Repository navigation
fix: keep URL on postponed browser back/forward with vaadin-router - #27141
Conversation
Asserts that the URL stays while a back navigation is postponed and that forward history still works after proceeding. Fails with vaadin-router (reactEnable=false), passes with the React router. Part of #9551
When a BeforeLeaveObserver postponed a navigation started with the browser back or forward button, the address bar already showed the target URL while the old view stayed. Cancelling then replaced the target history entry with the current URL, losing that entry. When the server reports the navigation as postponed, the client now pushes the URL of the still active view on top of the target entry. Proceeding steps back to the target entry without starting a new navigation, so forward history is kept. Cancelling leaves history as it was before the back/forward navigation. Only affects reactEnable=false; the React router already restores the URL itself. Fixes #9551
Pushing the active URL on top of the target entry dropped all entries ahead of it and put the entry in the wrong order on forward navigation. Instead, the target entry shows the active URL while the navigation is postponed and gets its own URL and state back when the server answers, so proceeding leaves history exactly as the browser made it, for back and forward alike. Only cancelling adds an entry for the active view, so that the cancelled target can still be reached with back. The back/forward detection is tied to the URL of the popstate, so a popstate to a client route no longer marks a later navigation.
Postpone now restores the browser-back entry instead of overwriting itsequenceDiagram
participant H as Browser history API
participant F as Flow.ts
participant S as UI.serverPaused / serverConnected
H->>F: popstate fires, URL already moved to target
F->>F: onPopstate records popstateUrl (new, capture phase)
F->>S: sends ui-navigate for the target route
S->>S: BeforeLeaveObserver calls event.postpone()
S->>F: serverPaused(activeLocation) (new argument)
F->>H: showActiveUrl() replaceState back to active view's URL (new)
Note over F,H: entry the browser moved to now shows the active view again
S->>F: serverConnected(cancel)
F->>H: restorePostponedEntry() replaceState entry.url to target (new)
alt cancelled
F->>H: pushState for active view on top of target (new)
Note over H: back still reaches the postponed target
else proceeded
Note over H: target entry keeps its own URL, forward history intact
end
In vaadin-router mode, Diagram Bot draws the mechanism this pull request touches; it does not review the change. Verify it against the diff.
|
vaadin-review-bot
left a comment
There was a problem hiding this comment.
Reviewed the changes — left 2 comments.
| Finding | |
|---|---|
| The "URL already matches" guard compares a re-serialized server location against the literal browser URL, so views with query parameters take the back/forward branch even when they should not. | |
| If another navigation starts while a navigation is postponed, the rewritten history entry keeps the active view's URL forever. |
| private showActiveUrl(activeLocation: string): PostponedHistoryEntry | undefined { | ||
| const url = new URL(activeLocation, document.baseURI); | ||
| const { pathname, search, hash } = window.location; | ||
| if (url.pathname === pathname && url.search === search) { |
There was a problem hiding this comment.
getPathWithQueryParameters() rebuilds the query from a HashMap and re-encodes every value with encodeURIComponent, so the browser's ?q=a+b&p=1 comes back as ?p=1&q=a%20b. The guard then sees a difference that does not exist.
This guard is what keeps the new code out of React mode, where React Router has already restored the URL. With query parameters on the active view, a postponed back now:
- rewrites the URL of the entry the user is already on, and
- on cancel pushes an extra entry carrying
state: null, which React Router did not create and whoseidxit cannot read.
In vaadin-router mode the effect is milder: the active view's query string comes back normalized.
Flow.ts:332 · correctness
There was a problem hiding this comment.
@vaadin-review-bot Good catch. The check no longer uses the server's location: it now compares the browser URL with the back/forward target, both read from the browser. If the router has already moved the URL away from the target (React Router), nothing is rewritten. The server's location is only used for the URL shown while postponed, so in vaadin-router mode its query string can come back reordered or re-encoded. That limitation is now listed in the description.
| if (this.response) { | ||
| const fromPopstate = this.popstateUrl !== undefined && this.popstateUrl === ctx.pathname + (ctx.search ?? ''); | ||
| this.popstateUrl = undefined; | ||
| let postponedEntry: PostponedHistoryEntry | undefined; |
There was a problem hiding this comment.
postponedEntry lives in the flowNavigate closure and is only read from the serverConnected that the same call installed. The next flowNavigate or flowLeave overwrites container.serverConnected, and nothing else restores the entry.
Pressing back a second time while the confirm buttons are up, or clicking another link, therefore leaves the entry the browser first moved to pointing at the active view's URL. Navigating back to it later lands on the wrong view, and the original target is unreachable.
Flow.ts:273 · correctness
There was a problem hiding this comment.
@vaadin-review-bot Fixed. The rewritten entry is now marked in history.state instead of being tracked in the closure. A new navigation that starts from that entry (e.g. a link click) handles the postponed one like a cancel: the entry gets its own URL back and the active view gets an entry on top. If the browser leaves the entry first (back/forward or a server-side navigation), the entry gets its own URL and state back as soon as the browser returns to it, before the router reads the URL. New browser tests cover a link click and a forward while a back is postponed.
Decide whether the router already restored the URL by comparing the browser URL with the back/forward target, both taken from the browser. Comparing with the location from the server reported a difference for query strings the server serializes differently. When a new navigation starts while a back/forward navigation is postponed, treat the postponed one as cancelled: give its entry its own URL back and add an entry for the active view, so its target can still be reached with back.
The entry that shows the active view's URL while a back/forward navigation is postponed is now marked in its history state. When the browser leaves it before the server answers, e.g. with another back or forward, or a server-side navigation, the entry gets its own URL and state back once the browser returns to it, before the router reads the URL. Before, it kept the active view's URL for good. The entry is left alone when the target URL equals the active view's URL, and cancelling keeps the hash of the current URL.
|
The SonarCloud finding on |
Bundle sizeCompared with the base commit 07b92e0.
Size by module, before minification
The production bundle of |
vaadin-review-bot
left a comment
There was a problem hiding this comment.
Reviewed the changes — left 1 comment.
| Finding | |
|---|---|
| 🧪 | Nothing tests the guard that keeps the history rewriting out of React Router mode. |
| private showActiveUrl(activeLocation: string, targetUrl: string): PostponedHistoryEntry | undefined { | ||
| const { pathname, search, hash } = window.location; | ||
| const url = new URL(activeLocation, document.baseURI); | ||
| if (pathname + search !== targetUrl || url.pathname + url.search === targetUrl) { |
There was a problem hiding this comment.
🧪 Nothing tests the guard that keeps the history rewriting out of React Router mode.
pathname + search !== targetUrl is the only thing that stops the new code from running in React mode — fromPopstate is true there too, because the blocker effect runs before the revert popstate from React Router's history.go(-delta) lands.
If that condition is weakened, a postponed back in React mode replaces React Router's {usr, key, idx} state with the mark, and a cancel pushes an entry with state: null, so React Router can no longer compute a delta for that entry. The React-mode IT added here only compares URLs and would still pass.
This is client-only decision logic, and CONVENTIONS.md points it at flow-client/src/test/frontend/: the existing harness can call container.serverPaused(...) directly and assert that history.state and the URL are untouched when the browser URL no longer matches the navigation target.
Flow.ts:355 · tests
There was a problem hiding this comment.
Added client unit tests in FlowTests.ts that call serverPaused directly after a simulated popstate. One sets React Router-style state and moves the URL back to the active view before the pause, then checks that history.state, the URL and history.length are untouched through pause and cancel. It fails if the pathname + search !== targetUrl check is removed. Two more cover the other paths: the rewrite when the browser still shows the target (including back reaching the target with its own state after cancel), and the skip when the active location already is the target.
Check that a postponed back navigation leaves history state and URL untouched when the router already restored the active URL, as React Router does, and that the URL is rewritten when the browser still shows the target.
vaadin-review-bot
left a comment
There was a problem hiding this comment.
Reviewed the changes — left 1 comment.
| Finding | |
|---|---|
| The capture flag does not make Flow see popstate before the router, as the comment claims. |
| this.appShellTitle = document.title; | ||
|
|
||
| // Capture phase, so that Flow sees the event before the router does | ||
| window.addEventListener('popstate', (event) => this.onPopstate(event), { capture: true }); |
There was a problem hiding this comment.
popstate is dispatched at window, so every window listener runs in the AT_TARGET phase and capture vs. bubble has no effect on ordering — registration order decides. Restoring a marked entry before the router reads window.location works only because the generated index.ts constructs Flow before new Router(...).
In an entry point that creates the router first (applications may replace index.ts), vaadin-router's popstate trigger reads the active view's URL out of the marked entry and navigates there, while the address bar ends up showing the restored target URL.
Flow.ts:157 · correctness
There was a problem hiding this comment.
Fixed. Flow now adds its popstate listener once, when Flow.ts loads, and hands the event to the Flow instance created last. vaadin-router adds its listener in the Router constructor, so Flow's listener now comes first however the entry point orders the two. I checked in Chromium that a capture listener on window still runs after a plain listener added before it, so registration order is what counts here. A new client test adds a "router" listener before Flow is created. It checks that the router sees the entry's own URL when the browser returns to a postponed entry, and it fails with the old registration in the constructor.
caalador
left a comment
There was a problem hiding this comment.
- Cancelling a forward navigation reverses the history and drops later entries (
Flow.ts,restorePostponedEntry, thepushStatewhencancelis true). The new IT confirms this.
- On cancel, the code puts the target entry's own URL back and then pushes a new entry for the active view. That is only correct for a single step back.
- Forward: history
A(active), B, CbecomesA, B, A'. C is gone, forward is disabled, and back leads to B, the target the user just cancelled. - Jumping several entries back (
go(-n)from the back-button dropdown): historyZ, A, B(active), jump to Z and cancel →Z, B'. A is gone. - A suggested fix: record each entry's position in
history.state(as React Router does withidx). On cancel, callhistory.go(-delta)to return to the original entry, and ignore the popstate that causes.
- Postponed entries are tracked only in memory, so a reload breaks them (
postponedEntries/lastPostponedEntryId)
- If the user reloads while a back navigation is postponed, entry A keeps B's URL and
{vaadinPostponedEntry: 1}as its state permanently. A can no longer be reached in that tab. - Ids restart at 1 after a reload, so a leftover entry can match a new entry with the same id.
onPopstatewould then restore the wrong URL. - A suggested fix: store the original
{state, url}directly inhistory.state, plus a per-page-load nonce, instead of using the map.
Window listeners for popstate run in the order they were added, and the capture flag has no effect on that. Add Flow's listener when its module loads, so that it restores a postponed entry before vaadin-router reads the URL even when an entry point creates the router before Flow.
|
@caalador Thanks, both points are right. I haven't changed this part yet, because the fix you suggest replaces the whole mechanism and comes with its own trade-offs: Option A: keep rewriting the entry and fix the reload problem. Store the entry's own Option B: return to the active entry with I lean towards B because it fixes the forward case. It is a bigger rewrite, though, so tell me which one you prefer. |
vaadin-review-bot
left a comment
There was a problem hiding this comment.
Reviewed the changes — left 1 comment.
| Finding | |
|---|---|
| The active view's URL is rebuilt from the server's location, and on cancel that rebuilt URL becomes the view's permanent history entry. |
| id: this.lastPostponedEntryId, | ||
| state: window.history.state, | ||
| url: pathname + search + hash, | ||
| activeUrl: url.pathname + url.search |
There was a problem hiding this comment.
getPathWithQueryParameters() re-encodes every query value with encodeURIComponent, which escapes /, : and spaces, so ?return=/home comes back as ?return=%2Fhome. It also appends the fragment, which url.pathname + url.search then drops.
The description lists the re-encoding as a limitation of the URL shown while postponed, but it does not stop there: on cancel, restorePostponedEntry pushes the current (rewritten) location, so the active view keeps the escaped, fragment-less URL in its own history entry afterwards. Where that string differs from what vaadin-router holds as its location, the router's history update after prevent() is likely to add a second entry for the same view.
No IT or client test uses a view with query parameters, so none of this would show up.
Flow.ts:374 · correctness
There was a problem hiding this comment.
You're right. It also goes beyond what is shown while postponed: on cancel, the active view keeps the rebuilt URL in its own history entry. I've corrected the limitation in the PR description to say so, but haven't changed the code yet, because the fix depends on the open choice between the two designs in my earlier PR comment:
- With B (return to the active entry with
history.go(-delta)), no URL is ever rebuilt. The browser goes back to the real entry, so the query string, fragment and entry stay exactly as the user had them, and the server no longer needs to send the location. - With A, I'd stop using the server's location and use the URL the browser showed before the back/forward instead. I'd also add a test with a view that has query parameters and a fragment.
Once that's decided, I'll fix this the matching way.
|
Let's go with B. It fixes the forward and multi-step cases, gets rid of the in-memory map, and it also settles the newest review-bot finding: the view's rebuilt URL becoming its permanent entry on cancel. With B, Flow never writes a URL of its own into history. On the push vs replace problem: rather than guessing from the A few things I'd like covered:
IT for cancelling a forward navigation (test-vaadin-router |
|
@caalador Fixed. Flow now records the position of the active view's entry when a navigation completes, and always returns to that entry. For two quick backs it computes the steps from the active entry to where the browser is now, so several presses in a row return to the view that is shown, and a second answer from the server doesn't move the browser again. Your IT is in On the smaller points:
|
|
@caalador Done: React mode now behaves as on main. Flow wraps |
|
Looks ok, but one small thing: |
The React Router integration now passes trackHistory: false when it creates Flow, instead of Flow recognizing vaadin-router by the next() of its route context. Tracking starts when Flow is created, so entries created before the first server-side route get positions too. A browser test in a React Router application checks that a postponed back keeps the URL and leaves React Router's history state as it is.
|
@caalador Switched to an explicit option. A correction to my earlier reply: |
…-url-reproduction # Conflicts: # flow-client/src/main/frontend/Flow.ts
|
|
I don't think this needs
Could you change the title to |
|
@caalador Done. The title is now |
|
Documentation Bot: No documentation needed for this change. This is a BEHAVIOR_CHANGE (bug fix) and an API_CHANGE restricted to the deprecated Nothing was opened in vaadin/docs. If you disagree, the change has to be documented by hand there.
|
…27141) (CP: 25.4) (#27569) This PR cherry-picks changes from the original PR #27141 to branch 25.4. --- > ## Summary > With `reactEnable=false` (vaadin-router), when a `BeforeLeaveObserver` postpones a navigation started with the browser back or forward button, the address bar already showed the target URL while the old view stayed. Cancelling then overwrote the target history entry, so it could no longer be reached with back. Now, while the navigation is postponed, Flow moves the browser back to the history entry of the active view. On proceed it moves on to the target entry. On cancel it leaves the history as it is. React router mode is unchanged. > > Fixes #9551 > > ## What changed > - **Entry positions (vaadin-router mode only).** When Flow is created, it wraps `history.pushState` and `history.replaceState` and records the position of every entry created through them in the entry's `history.state`. This lets Flow tell how many steps a back/forward navigation moved, which the history API does not say. > - **New `FlowConfig.trackHistory` option**, `true` by default. The generated React Router integration (`Flow.tsx`) passes `trackHistory: false`, because React Router returns the browser to the active entry itself; in React mode Flow never wraps the history API or stamps an entry. A vaadin-router application with its own `index.ts` can pass it too, to turn the handling off. > - **While postponed.** If the navigation came from back/forward and the positions are known, Flow calls `history.go()` back to the entry of the active view. That entry is recorded when a navigation completes, so several quick back/forward presses before the server answers still return to the view that is shown. The `popstate` from Flow's own move is kept from the router, so it is not a navigation and sends no second `ui-navigate`. > - **On proceed.** Flow calls `history.go()` on to the target entry, which keeps its own URL and state. History API calls made while Flow moves the browser, such as a server-side forward in the same round trip, are held until the browser has arrived, so they apply to the target entry. The `vaadin-navigated` event the server fires after such a call is held with it, so its listeners see the new URL. > - **On cancel.** Nothing changes in the history: the URL, the entries ahead and behind, and the cancelled target all stay where they were. This holds for back, forward and multi-step jumps (e.g. `history.go(-2)` from the back button's menu). > - **Reload.** Positions live in the entries themselves, so a reload while a navigation is postponed leaves nothing to repair, and later back/forward navigations still work. > - **If the browser does not arrive.** If no `popstate` reports the arrival within a second, Flow stops holding the history calls and completes the navigation. If the `popstate` comes later, it is still kept from the router. > - **State sent to the server.** Flow removes its keys before sending `history.state` with `ui-navigate`, so `HistoryStateChangeEvent.getState()` is unchanged. > - **Fallback.** When the target entry or the active view's entry has no position, the behaviour is the same as before this change: the address bar shows the target URL while the navigation is postponed, and on cancel vaadin-router writes the active view's URL into the target entry. An entry has no position when its state is neither `null` nor a plain object (e.g. an application stores a string). An entry the browser creates without the history API, such as a fragment navigation, gets a position in a new segment. Positions only compare within one segment, so the fallback applies when a back/forward crosses into another segment. > - The server no longer needs to send the active view's location when it postpones, so `UI` is back to what it was. > > ## Risks > Everything listed here applies only to applications with `reactEnable=false`. React Router mode, the default, is not affected: the generated `Flow.tsx` passes `trackHistory: false`. An application with `reactEnable=false` turns all of it off by passing `trackHistory: false` when it creates Flow in its `index.ts`, e.g. `new Flow({ imports: ..., trackHistory: false })`. > - **The History API is patched as soon as Flow is created**, also in an application that only uses client-side routes. `history.pushState` and `history.replaceState` are replaced on `window.history`, and the state of the current entry is rewritten to carry its position. Code that captured the original functions before Flow was created makes entries without a position, which falls back as described above. > - **`history.state` changes for application code.** A plain-object state gets a `vaadinHistoryPosition` key. A `null` state becomes `{vaadinHistoryPosition, vaadinNullState: true}`, so code that checks `history.state === null` behaves differently. vaadin-router stores `null` for its entries, so this applies to most entries. The state the server receives is unchanged. > - **Flow keeps the `popstate` of its own moves from later listeners** with `stopImmediatePropagation`. Flow's listener is added when its module loads, so it runs before the router's. If the user presses back/forward while Flow's own move is in flight, the event is passed on as a normal navigation. > - **`vaadin-navigated` can come later.** While Flow holds history calls, the event is dispatched again once the held call has run, after the browser arrived. > > ## Test summary > - Browser tests (vaadin-router mode): > - the URL stays while a back or forward navigation is postponed; proceeding completes it and forward history still works; > - after cancelling a postponed back, back still reaches the cancelled target; > - cancelling a postponed forward keeps the URL, forward reaches the target again, and back reaches the initial view; > - cancelling a postponed `history.go(-2)` keeps the URL and both entries in between; > - two quick backs before the server answers keep the active URL, also after cancelling; > - a reload while a back is postponed keeps the history working; > - a link click while a back is postponed, then cancelled, still lets back reach the original target. > - Browser tests in a second vaadin-router application: the URL stays while a back or forward navigation is postponed, and proceeding completes it. > - Browser test (React router mode): a postponed back keeps the URL, cancelling keeps it, React Router's history state carries no Flow keys, and back then proceeds as before. > - Client unit tests: > - back, forward and two-step back, each for cancel and proceed: where the browser ends, that the router sees only the user's `popstate`, and that one `ui-navigate` is sent; > - two quick backs, for cancel and for proceed; > - the server answering before Flow's move ends; a history change and its `vaadin-navigated` event during the move; a redirect after proceed; > - a move the browser never reports, and its late arrival; > - entries created after a fragment navigation; a reload while postponed; a target entry without a position; the browser having left the target entry already; the state sent to the server without Flow's keys; > - with `trackHistory: false` the history API is not wrapped and entries keep a `null` state, also after back; by default entries get a position. > - Without the fix, the vaadin-router browser tests fail. The navigation, history and postpone browser tests of both router modes and all client unit tests pass. > > Working on behalf of Artur > > Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com> Co-authored-by: caalador <mikael.grankvist@vaadin.com>
…27141) (CP: 25.3) (#27571) This PR cherry-picks changes from the original PR #27141 to branch 25.3. The original commit conflicts on 25.3, so this PR picks the 25.4 pick #27569 instead, which already adapted the change to an older branch. > [!WARNING] > The cherry-pick had merge conflicts that were resolved automatically by Claude Code. Please review the changes carefully. **Resolution notes from Claude:** - Flow.ts: 25.3 lacks #27058 (settleRoundTrip/navigationAnswered wrapper around serverConnected), so the pick's serverConnected bodies were assigned directly to this.container.serverConnected as on 25.3, with the settleRoundTrip resets dropped; the history-position logic is unchanged. - tsconfig.json (test): kept 25.3's version. The 25.4 version lists suites from #26714/#26866 (missing on 25.3); adding FlowRouterModeTests.ts there clashes with 25.3's eslint allowDefaultProject glob 'src/test/frontend/*', so the new suite stays in the default project like the other root-level suites. - FlowRouterModeTests.ts: imports ConnectionState/ConnectionStateStore from @vaadin/common-frontend, as ConnectionState was moved into flow-client only by #26714 (missing on 25.3). - Verified: spotless, mvn install -DskipTests for flow-client, flow-server and the three flow-tests modules (incl. tsc, test typecheck, eslint). Client unit tests and the ITs (NavigationIT, both PostponeUpdateIT) were not run. --- > ## Summary > With `reactEnable=false` (vaadin-router), when a `BeforeLeaveObserver` postpones a navigation started with the browser back or forward button, the address bar already showed the target URL while the old view stayed. Cancelling then overwrote the target history entry, so it could no longer be reached with back. Now, while the navigation is postponed, Flow moves the browser back to the history entry of the active view. On proceed it moves on to the target entry. On cancel it leaves the history as it is. React router mode is unchanged. > > Fixes #9551 > > ## What changed > - **Entry positions (vaadin-router mode only).** When Flow is created, it wraps `history.pushState` and `history.replaceState` and records the position of every entry created through them in the entry's `history.state`. This lets Flow tell how many steps a back/forward navigation moved, which the history API does not say. > - **New `FlowConfig.trackHistory` option**, `true` by default. The generated React Router integration (`Flow.tsx`) passes `trackHistory: false`, because React Router returns the browser to the active entry itself; in React mode Flow never wraps the history API or stamps an entry. A vaadin-router application with its own `index.ts` can pass it too, to turn the handling off. > - **While postponed.** If the navigation came from back/forward and the positions are known, Flow calls `history.go()` back to the entry of the active view. That entry is recorded when a navigation completes, so several quick back/forward presses before the server answers still return to the view that is shown. The `popstate` from Flow's own move is kept from the router, so it is not a navigation and sends no second `ui-navigate`. > - **On proceed.** Flow calls `history.go()` on to the target entry, which keeps its own URL and state. History API calls made while Flow moves the browser, such as a server-side forward in the same round trip, are held until the browser has arrived, so they apply to the target entry. The `vaadin-navigated` event the server fires after such a call is held with it, so its listeners see the new URL. > - **On cancel.** Nothing changes in the history: the URL, the entries ahead and behind, and the cancelled target all stay where they were. This holds for back, forward and multi-step jumps (e.g. `history.go(-2)` from the back button's menu). > - **Reload.** Positions live in the entries themselves, so a reload while a navigation is postponed leaves nothing to repair, and later back/forward navigations still work. > - **If the browser does not arrive.** If no `popstate` reports the arrival within a second, Flow stops holding the history calls and completes the navigation. If the `popstate` comes later, it is still kept from the router. > - **State sent to the server.** Flow removes its keys before sending `history.state` with `ui-navigate`, so `HistoryStateChangeEvent.getState()` is unchanged. > - **Fallback.** When the target entry or the active view's entry has no position, the behaviour is the same as before this change: the address bar shows the target URL while the navigation is postponed, and on cancel vaadin-router writes the active view's URL into the target entry. An entry has no position when its state is neither `null` nor a plain object (e.g. an application stores a string). An entry the browser creates without the history API, such as a fragment navigation, gets a position in a new segment. Positions only compare within one segment, so the fallback applies when a back/forward crosses into another segment. > - The server no longer needs to send the active view's location when it postpones, so `UI` is back to what it was. > > ## Risks > Everything listed here applies only to applications with `reactEnable=false`. React Router mode, the default, is not affected: the generated `Flow.tsx` passes `trackHistory: false`. An application with `reactEnable=false` turns all of it off by passing `trackHistory: false` when it creates Flow in its `index.ts`, e.g. `new Flow({ imports: ..., trackHistory: false })`. > - **The History API is patched as soon as Flow is created**, also in an application that only uses client-side routes. `history.pushState` and `history.replaceState` are replaced on `window.history`, and the state of the current entry is rewritten to carry its position. Code that captured the original functions before Flow was created makes entries without a position, which falls back as described above. > - **`history.state` changes for application code.** A plain-object state gets a `vaadinHistoryPosition` key. A `null` state becomes `{vaadinHistoryPosition, vaadinNullState: true}`, so code that checks `history.state === null` behaves differently. vaadin-router stores `null` for its entries, so this applies to most entries. The state the server receives is unchanged. > - **Flow keeps the `popstate` of its own moves from later listeners** with `stopImmediatePropagation`. Flow's listener is added when its module loads, so it runs before the router's. If the user presses back/forward while Flow's own move is in flight, the event is passed on as a normal navigation. > - **`vaadin-navigated` can come later.** While Flow holds history calls, the event is dispatched again once the held call has run, after the browser arrived. > > ## Test summary > - Browser tests (vaadin-router mode): > - the URL stays while a back or forward navigation is postponed; proceeding completes it and forward history still works; > - after cancelling a postponed back, back still reaches the cancelled target; > - cancelling a postponed forward keeps the URL, forward reaches the target again, and back reaches the initial view; > - cancelling a postponed `history.go(-2)` keeps the URL and both entries in between; > - two quick backs before the server answers keep the active URL, also after cancelling; > - a reload while a back is postponed keeps the history working; > - a link click while a back is postponed, then cancelled, still lets back reach the original target. > - Browser tests in a second vaadin-router application: the URL stays while a back or forward navigation is postponed, and proceeding completes it. > - Browser test (React router mode): a postponed back keeps the URL, cancelling keeps it, React Router's history state carries no Flow keys, and back then proceeds as before. > - Client unit tests: > - back, forward and two-step back, each for cancel and proceed: where the browser ends, that the router sees only the user's `popstate`, and that one `ui-navigate` is sent; > - two quick backs, for cancel and for proceed; > - the server answering before Flow's move ends; a history change and its `vaadin-navigated` event during the move; a redirect after proceed; > - a move the browser never reports, and its late arrival; > - entries created after a fragment navigation; a reload while postponed; a target entry without a position; the browser having left the target entry already; the state sent to the server without Flow's keys; > - with `trackHistory: false` the history API is not wrapped and entries keep a `null` state, also after back; by default entries get a position. > - Without the fix, the vaadin-router browser tests fail. The navigation, history and postpone browser tests of both router modes and all client unit tests pass. > > Working on behalf of Artur > > --------- Co-authored-by: totally-not-ai[bot] <290682512+totally-not-ai[bot]@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: caalador <mikael.grankvist@vaadin.com> Co-authored-by: Mikael Grankvist <mgrankvi@vaadin.com>



Summary
With
reactEnable=false(vaadin-router), when aBeforeLeaveObserverpostpones a navigation started with the browser back or forward button, the address bar already showed the target URL while the old view stayed. Cancelling then overwrote the target history entry, so it could no longer be reached with back. Now, while the navigation is postponed, Flow moves the browser back to the history entry of the active view. On proceed it moves on to the target entry. On cancel it leaves the history as it is. React router mode is unchanged.Fixes #9551
What changed
history.pushStateandhistory.replaceStateand records the position of every entry created through them in the entry'shistory.state. This lets Flow tell how many steps a back/forward navigation moved, which the history API does not say.FlowConfig.trackHistoryoption,trueby default. The generated React Router integration (Flow.tsx) passestrackHistory: false, because React Router returns the browser to the active entry itself; in React mode Flow never wraps the history API or stamps an entry. A vaadin-router application with its ownindex.tscan pass it too, to turn the handling off.history.go()back to the entry of the active view. That entry is recorded when a navigation completes, so several quick back/forward presses before the server answers still return to the view that is shown. Thepopstatefrom Flow's own move is kept from the router, so it is not a navigation and sends no secondui-navigate.history.go()on to the target entry, which keeps its own URL and state. History API calls made while Flow moves the browser, such as a server-side forward in the same round trip, are held until the browser has arrived, so they apply to the target entry. Thevaadin-navigatedevent the server fires after such a call is held with it, so its listeners see the new URL.history.go(-2)from the back button's menu).popstatereports the arrival within a second, Flow stops holding the history calls and completes the navigation. If thepopstatecomes later, it is still kept from the router.history.statewithui-navigate, soHistoryStateChangeEvent.getState()is unchanged.nullnor a plain object (e.g. an application stores a string). An entry the browser creates without the history API, such as a fragment navigation, gets a position in a new segment. Positions only compare within one segment, so the fallback applies when a back/forward crosses into another segment.UIis back to what it was.Risks
Everything listed here applies only to applications with
reactEnable=false. React Router mode, the default, is not affected: the generatedFlow.tsxpassestrackHistory: false. An application withreactEnable=falseturns all of it off by passingtrackHistory: falsewhen it creates Flow in itsindex.ts, e.g.new Flow({ imports: ..., trackHistory: false }).history.pushStateandhistory.replaceStateare replaced onwindow.history, and the state of the current entry is rewritten to carry its position. Code that captured the original functions before Flow was created makes entries without a position, which falls back as described above.history.statechanges for application code. A plain-object state gets avaadinHistoryPositionkey. Anullstate becomes{vaadinHistoryPosition, vaadinNullState: true}, so code that checkshistory.state === nullbehaves differently. vaadin-router storesnullfor its entries, so this applies to most entries. The state the server receives is unchanged.popstateof its own moves from later listeners withstopImmediatePropagation. Flow's listener is added when its module loads, so it runs before the router's. If the user presses back/forward while Flow's own move is in flight, the event is passed on as a normal navigation.vaadin-navigatedcan come later. While Flow holds history calls, the event is dispatched again once the held call has run, after the browser arrived.Test summary
history.go(-2)keeps the URL and both entries in between;popstate, and that oneui-navigateis sent;vaadin-navigatedevent during the move; a redirect after proceed;trackHistory: falsethe history API is not wrapped and entries keep anullstate, also after back; by default entries get a position.Working on behalf of Artur