]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
fix: wip discussion/1219-incorrect-state
authorEduardo San Martin Morote <posva13@gmail.com>
Fri, 17 Dec 2021 07:26:23 +0000 (08:26 +0100)
committerEduardo San Martin Morote <posva13@gmail.com>
Fri, 17 Dec 2021 07:26:23 +0000 (08:26 +0100)
__tests__/history/html5.spec.ts
src/history/html5.ts

index 4eb446a3677c6ee7fe27c40822eab0d8aa2b8d17..75cc1375e20feb6203b765eea9131a3c21ec5796 100644 (file)
@@ -1,6 +1,6 @@
 import { JSDOM } from 'jsdom'
 import { createWebHistory } from '../../src/history/html5'
-import { createDom } from '../utils'
+import { createDom, tick } from '../utils'
 
 // override the value of isBrowser because the variable is created before JSDOM
 // is created
@@ -40,6 +40,26 @@ describe('History HTMl5', () => {
     expect(createWebHistory('#other').base).toBe('#other')
   })
 
+  it('grecefully handles an invalid state', async () => {
+    const history = createWebHistory()
+    const spy = jest.fn()
+    history.listen(spy)
+
+    // null state
+    window.history.pushState(null, '')
+    window.history.back()
+    await tick(2)
+    expect(spy).toHaveBeenCalled()
+    expect(spy).toHaveBeenCalledWith('', '', 'https://example.com/foo')
+
+    // invalid state but not empty
+    window.history.pushState({}, '')
+    window.history.back()
+    await tick()
+    expect(spy).toHaveBeenCalled()
+    expect(spy).toHaveBeenCalledWith('', '', 'https://example.com/foo')
+  })
+
   it('handles a base tag', () => {
     const baseEl = document.createElement('base')
     baseEl.href = '/foo/'
index 017edef1e3752a301c4d53528ead51a2066d652c..7ad31bc4f7e17eb9685212492eeda434d303d9eb 100644 (file)
@@ -69,7 +69,9 @@ function useHistoryListeners(
   const popStateHandler: PopStateListener = ({
     state,
   }: {
-    state: StateEntry | null
+    // use an empty object to accomodate for other kind of invalid states
+    // https://github.com/vuejs/vue-router-next/pull/1219
+    state: StateEntry | null | { current: never }
   }) => {
     const to = createCurrentLocation(base, location)
     const from: HistoryLocation = currentLocation.value
@@ -77,6 +79,14 @@ function useHistoryListeners(
     let delta = 0
 
     if (state) {
+      if (!state.current) {
+        state = assign({}, historyState.value, {
+          back: historyState.value.current,
+          current: to,
+          position: historyState.value.position + 1,
+        })
+      }
+
       currentLocation.value = to
       historyState.value = state