From 12d75f00e75435baceafafaf4866ac942e39bdc8 Mon Sep 17 00:00:00 2001 From: David Wilde Date: Thu, 5 Sep 2024 22:27:49 +0100 Subject: [PATCH] Add view transitions on navigating history The view transitions are added when the user navigates back and forth through the history for configs that have enabled globalViewTransitions. --- src/htmx.js | 40 +++++++++++++++++++++++++++------------- 1 file changed, 27 insertions(+), 13 deletions(-) diff --git a/src/htmx.js b/src/htmx.js index 41ae9b382..eb935eda9 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -3205,19 +3205,33 @@ var htmx = (function() { path = path || location.pathname + location.search const cached = getCachedHistory(path) if (cached) { - const fragment = makeFragment(cached.content) - const historyElement = getHistoryElement() - const settleInfo = makeSettleInfo(historyElement) - handleTitle(cached.title) - handlePreservedElements(fragment) - swapInnerHTML(historyElement, fragment, settleInfo) - restorePreservedElements() - settleImmediately(settleInfo.tasks) - getWindow().setTimeout(function() { - window.scrollTo(0, cached.scroll) - }, 0) // next 'tick', so browser has time to render layout - currentPathForHistory = path - triggerEvent(getDocument().body, 'htmx:historyRestore', { path, item: cached }) + let restoreHistoryFromCache = function() { + const fragment = makeFragment(cached.content) + const historyElement = getHistoryElement() + const settleInfo = makeSettleInfo(historyElement) + handleTitle(cached.title) + handlePreservedElements(fragment) + swapInnerHTML(historyElement, fragment, settleInfo) + restorePreservedElements() + settleImmediately(settleInfo.tasks) + getWindow().setTimeout(function() { + window.scrollTo(0, cached.scroll) + }, 0) // next 'tick', so browser has time to render layout + currentPathForHistory = path + triggerEvent(getDocument().body, 'htmx:historyRestore', { path, item: cached }) + } + const shouldTransition = htmx.config.globalViewTransitions + if (shouldTransition && + // @ts-ignore experimental feature atm + document.startViewTransition) { + const innerRestoreHistoryFromCache = restoreHistoryFromCache + // wrap the original doRestoreHistory() in a call to startViewTransition() + // @ts-ignore experimental feature atm + restoreHistoryFromCache = document.startViewTransition( + () => innerRestoreHistoryFromCache() + ) + } + restoreHistoryFromCache() } else { if (htmx.config.refreshOnHistoryMiss) { // @ts-ignore: optional parameter in reload() function throws error