Skip to content

Commit d2e9ee9

Browse files
fix: browser url not updated with form partials (#2236)
Fixes #2173
1 parent 6f6f551 commit d2e9ee9

File tree

2 files changed

+27
-19
lines changed

2 files changed

+27
-19
lines changed

src/runtime/entrypoints/main.ts

+24-19
Original file line numberDiff line numberDiff line change
@@ -885,6 +885,28 @@ if (!history.state) {
885885
history.replaceState(state, document.title);
886886
}
887887

888+
function maybeUpdateHistory(nextUrl: URL) {
889+
// Only add history entry when URL is new. Still apply
890+
// the partials because sometimes users click a link to
891+
// "refresh" the current page.
892+
if (nextUrl.href !== window.location.href) {
893+
const state: FreshHistoryState = {
894+
index,
895+
scrollX: window.scrollX,
896+
scrollY: window.scrollY,
897+
};
898+
899+
// Store current scroll position
900+
history.replaceState({ ...state }, "", location.href);
901+
902+
// Now store the new position
903+
index++;
904+
state.scrollX = 0;
905+
state.scrollY = 0;
906+
history.pushState(state, "", nextUrl.href);
907+
}
908+
}
909+
888910
document.addEventListener("click", async (e) => {
889911
let el = e.target;
890912
if (el && el instanceof HTMLElement) {
@@ -930,25 +952,7 @@ document.addEventListener("click", async (e) => {
930952

931953
const nextUrl = new URL(el.href);
932954
try {
933-
// Only add history entry when URL is new. Still apply
934-
// the partials because sometimes users click a link to
935-
// "refresh" the current page.
936-
if (el.href !== window.location.href) {
937-
const state: FreshHistoryState = {
938-
index,
939-
scrollX: window.scrollX,
940-
scrollY: window.scrollY,
941-
};
942-
943-
// Store current scroll position
944-
history.replaceState({ ...state }, "", location.href);
945-
946-
// Now store the new position
947-
index++;
948-
state.scrollX = 0;
949-
state.scrollY = 0;
950-
history.pushState(state, "", nextUrl.href);
951-
}
955+
maybeUpdateHistory(nextUrl);
952956

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

1091+
maybeUpdateHistory(url);
10871092
await fetchPartials(url, init);
10881093
}
10891094
}

tests/partials_test.ts

+3
Original file line numberDiff line numberDiff line change
@@ -1033,6 +1033,9 @@ Deno.test("submit form GET", async () => {
10331033
const url = await page.$eval(".url", (el) => el.textContent);
10341034
assertEquals(url, `${address}/form_get?name=foobar&fresh-partial=true`);
10351035

1036+
const pageUrl = page.url();
1037+
assertEquals(pageUrl, `${address}/form_get?name=foobar`);
1038+
10361039
// Server can update form value
10371040
const value = await page.$eval("input", (el) => el.value);
10381041
assertEquals(value, "foobar_foo");

0 commit comments

Comments
 (0)