Skip to content

Commit

Permalink
[experimental] fix: safer history patching (#2181)
Browse files Browse the repository at this point in the history
* fix: safer history patching

* fix tests

---------

Co-authored-by: Manuel Schiller <manuel.schiller@caligano.de>
  • Loading branch information
tannerlinsley and schiller-manuel committed Aug 23, 2024
1 parent 23cbb9a commit 333efe0
Show file tree
Hide file tree
Showing 2 changed files with 131 additions and 74 deletions.
21 changes: 15 additions & 6 deletions packages/history/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export interface RouterHistory {
flush: () => void
destroy: () => void
notify: () => void
_ignoreSubscribers?: boolean
}

export interface HistoryLocation extends ParsedPath {
Expand Down Expand Up @@ -238,10 +239,18 @@ export function createBrowserHistory(opts?: {
return
}

// We use the original push/replace calls here to ensure that
// we do not notify subscribers about this push/replace call
const caller = next.isPush ? originalPushState : originalReplaceState
caller.call(win.history, next.state, '', next.href)
// We need to ignore any updates to the subscribers while we update the browser history
history._ignoreSubscribers = true

// Update the browser history
;(next.isPush ? win.history.pushState : win.history.replaceState)(
next.state,
'',
next.href,
)

history._ignoreSubscribers = false

// Reset the nextIsPush flag and clear the scheduled update
next = undefined
scheduled = undefined
Expand Down Expand Up @@ -316,13 +325,13 @@ export function createBrowserHistory(opts?: {

win.history.pushState = function (...args: Array<any>) {
const res = originalPushState.apply(win.history, args)
onPushPop()
if (!history._ignoreSubscribers) onPushPop()
return res
}

win.history.replaceState = function (...args: Array<any>) {
const res = originalReplaceState.apply(win.history, args)
onPushPop()
if (!history._ignoreSubscribers) onPushPop()
return res
}

Expand Down
Loading

0 comments on commit 333efe0

Please sign in to comment.