Skip to content

Commit

Permalink
fix: browser url not updated with form partials
Browse files Browse the repository at this point in the history
  • Loading branch information
marvinhagemeister committed Jan 10, 2024
1 parent 6f6f551 commit 30ba00a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 19 deletions.
43 changes: 24 additions & 19 deletions src/runtime/entrypoints/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -885,6 +885,28 @@ if (!history.state) {
history.replaceState(state, document.title);
}

function maybeUpdateHistory(nextUrl: URL) {
// Only add history entry when URL is new. Still apply
// the partials because sometimes users click a link to
// "refresh" the current page.
if (nextUrl.href !== window.location.href) {
const state: FreshHistoryState = {
index,
scrollX: window.scrollX,
scrollY: window.scrollY,
};

// Store current scroll position
history.replaceState({ ...state }, "", location.href);

// Now store the new position
index++;
state.scrollX = 0;
state.scrollY = 0;
history.pushState(state, "", nextUrl.href);
}
}

document.addEventListener("click", async (e) => {
let el = e.target;
if (el && el instanceof HTMLElement) {
Expand Down Expand Up @@ -930,25 +952,7 @@ document.addEventListener("click", async (e) => {

const nextUrl = new URL(el.href);
try {
// Only add history entry when URL is new. Still apply
// the partials because sometimes users click a link to
// "refresh" the current page.
if (el.href !== window.location.href) {
const state: FreshHistoryState = {
index,
scrollX: window.scrollX,
scrollY: window.scrollY,
};

// Store current scroll position
history.replaceState({ ...state }, "", location.href);

// Now store the new position
index++;
state.scrollX = 0;
state.scrollY = 0;
history.pushState(state, "", nextUrl.href);
}
maybeUpdateHistory(nextUrl);

const partialUrl = new URL(
partial ? partial : nextUrl.href,
Expand Down Expand Up @@ -1084,6 +1088,7 @@ document.addEventListener("submit", async (e) => {
init = { body: new FormData(el), method: lowerMethod };
}

maybeUpdateHistory(url);
await fetchPartials(url, init);
}
}
Expand Down
3 changes: 3 additions & 0 deletions tests/partials_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1033,6 +1033,9 @@ Deno.test("submit form GET", async () => {
const url = await page.$eval(".url", (el) => el.textContent);
assertEquals(url, `${address}/form_get?name=foobar&fresh-partial=true`);

const pageUrl = page.url();
assertEquals(pageUrl, `${address}/form_get?name=foobar`);

// Server can update form value
const value = await page.$eval("input", (el) => el.value);
assertEquals(value, "foobar_foo");
Expand Down

0 comments on commit 30ba00a

Please sign in to comment.