Skip to content

Commit

Permalink
Handle history navigation after page refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
bartblast committed Oct 28, 2024
1 parent 475f0bf commit 6956988
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
1 change: 1 addition & 0 deletions assets/js/config.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"use strict";

export default class Config {
static clientFetchTimeoutMs = 3000;
static fetchPageTimeoutMs = 3000;
}
41 changes: 33 additions & 8 deletions assets/js/hologram.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export default class Hologram {
static #pageModule = null;
static #pageParams = null;
static #registeredPageModules = new Set();
static #scrollPosition = null;
static #shouldLoadMountData = true;
static #shouldReplaceHistoryState = true;

Expand Down Expand Up @@ -515,11 +516,24 @@ export default class Hologram {
$.#shouldLoadMountData = false;
$.#shouldReplaceHistoryState = false;

const toParam = Type.tuple([pageModule, pageParams]);
await $.#navigateToPage(toParam, window.location.pathname, false);
await Client.fetchPageBundlePath(
pageModule,
(resp) => {
const script = document.createElement("script");
script.src = resp;
script.fetchpriority = "high";
document.head.appendChild(script);

$.#shouldLoadMountData = true;
$.#shouldReplaceHistoryState = true;
// TODO: use scroll position from page snapshot
$.#scrollPosition = [0, 0];
},
(_resp) => {
throw new HologramRuntimeError(
"Failed to fetch page bundle path for: " +
Interpreter.inspect(pageModule),
);
},
);
}

// Executed only once, on the initial page load.
Expand Down Expand Up @@ -582,6 +596,8 @@ export default class Hologram {

if ($.#shouldLoadMountData) {
Hologram.#loadMountData();
} else {
$.#shouldLoadMountData = true;
}

$.#registerPageModule($.#pageModule);
Expand All @@ -590,11 +606,20 @@ export default class Hologram {

Hologram.prefetchedPages.clear();

Hologram.render();
window.requestAnimationFrame(() => {
$.render();

if ($.#shouldReplaceHistoryState) {
Hologram.#replaceHistoryState();
}
if ($.#scrollPosition) {
window.scrollTo($.#scrollPosition[0], $.#scrollPosition[1]);
$.#scrollPosition = null;
}

if ($.#shouldReplaceHistoryState) {
$.#replaceHistoryState();
} else {
$.#shouldReplaceHistoryState = true;
}
});
}

// Tested implicitely in feature tests
Expand Down

0 comments on commit 6956988

Please sign in to comment.