Skip to content

Add optimistic navigation for navigateTo #137

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: fix-scroll-restoration
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions superglue/lib/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,13 @@ export const copyPage = createAction<{ from: PageKey; to: PageKey }>(
'@@superglue/COPY_PAGE'
)

/**
* A redux action you can dispatch to move a page from one pageKey to another.
*/
export const movePage = createAction<{ from: PageKey; to: PageKey }>(
'@@superglue/MOVE_PAGE'
)

/**
* A redux action you can dispatch to remove a page from your store.
*
Expand Down
43 changes: 26 additions & 17 deletions superglue/lib/components/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import React, {
useImperativeHandle,
ForwardedRef,
} from 'react'
import { urlToPageKey, pathWithoutBZParams } from '../utils'
import { removePage, setActivePage } from '../actions'
import { urlToPageKey, pathWithoutBZParams, mergeQuery } from '../utils'
import { removePage, setActivePage, movePage, copyPage } from '../actions'
import {
HistoryState,
RootState,
Expand Down Expand Up @@ -153,29 +153,31 @@ const NavigationProvider = forwardRef(function NavigationProvider(
}
}
}
const navigateTo: NavigateTo = (path, { action, search } = {}) => {
action ||= 'push'
search ||= {}

const navigateTo: NavigateTo = (
path,
{ action } = {
action: 'push',
}
) => {
if (action === 'none') {
return false
}

path = pathWithoutBZParams(path)
const nextPageKey = urlToPageKey(path)
const hasPage = Object.prototype.hasOwnProperty.call(
store.getState().pages,
nextPageKey
)
let nextPath = pathWithoutBZParams(path)
const originalPageKey = urlToPageKey(nextPath)
let nextPageKey = urlToPageKey(originalPageKey)
// store is untyped?
const page = store.getState().pages[nextPageKey]

if (page) {
const isOptimisticNav = Object.keys(search).length > 0
if (isOptimisticNav) {
nextPageKey = mergeQuery(nextPageKey, search)
nextPath = mergeQuery(nextPath, search)
}

if (hasPage) {
const location = history.location
const state = location.state as HistoryState
const historyArgs = [
path,
nextPath,
{
pageKey: nextPageKey,
superglue: true,
Expand All @@ -200,14 +202,21 @@ const NavigationProvider = forwardRef(function NavigationProvider(
)
}

if (isOptimisticNav) {
dispatch(copyPage({ from: originalPageKey, to: nextPageKey }))
}

history.push(...historyArgs)
dispatch(setActivePage({ pageKey: nextPageKey }))
}

if (action === 'replace') {
history.replace(...historyArgs)

if (currentPageKey !== nextPageKey) {
if (isOptimisticNav) {
dispatch(movePage({ from: originalPageKey, to: nextPageKey }))
dispatch(setActivePage({ pageKey: nextPageKey }))
} else if (currentPageKey !== nextPageKey) {
dispatch(setActivePage({ pageKey: nextPageKey }))
dispatch(removePage({ pageKey: currentPageKey }))
}
Expand Down
11 changes: 11 additions & 0 deletions superglue/lib/reducers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
handleGraft,
historyChange,
copyPage,
movePage,
setCSRFToken,
setActivePage,
removePage,
Expand Down Expand Up @@ -171,6 +172,16 @@ export function pageReducer(state: AllPages = {}, action: Action): AllPages {
return nextState
}

if (movePage.match(action)) {
const nextState = { ...state }
const { from, to } = action.payload

nextState[to] = nextState[from]
delete nextState[from]

return nextState
}

if (handleGraft.match(action)) {
const { pageKey, page } = action.payload

Expand Down
3 changes: 2 additions & 1 deletion superglue/lib/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,8 @@ export interface BasicRequestInit extends RequestInit {
export type NavigateTo = (
path: Keypath,
options: {
action: NavigationAction
action?: NavigationAction
search?: Record<string, string>
}
) => boolean

Expand Down
10 changes: 10 additions & 0 deletions superglue/lib/utils/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,13 @@ export function parsePageKey(pageKey: PageKey) {
search: query,
}
}

export function mergeQuery(pageKey: PageKey, search: Record<string, string>) {
const parsed = new parse(pageKey, {}, true)

Object.keys(search).forEach((key) => {
parsed.query[key] = search[key]
})

return parsed.toString()
}
112 changes: 112 additions & 0 deletions superglue/spec/lib/NavComponent.spec.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -355,6 +355,118 @@ describe('Nav', () => {
})
})

it('navigates using "push" to a copied page with new params', () => {
const history = createMemoryHistory({})
history.replace('/home', {
superglue: true,
pageKey: '/home',
posX: 5,
posY: 5,
})

vi.spyOn(window, 'scrollTo').mockImplementation(() => {})

const store = buildStore({
pages: {
'/home': {
componentIdentifier: 'home',
restoreStrategy: 'fromCacheOnly',
},
'/about': {
componentIdentifier: 'about',
restoreStrategy: 'fromCacheOnly',
},
},
superglue: {
csrfToken: 'abc',
currentPageKey: '/home',
},
})

let instance

render(
<Provider store={store}>
<NavigationProvider
store={store}
ref={(node) => (instance = node)}
mapping={{ home: Home, about: About }}
history={history}
/>
</Provider>
)

instance.navigateTo('/home', { search: { hello: 'world' } })

const pages = store.getState().pages
expect(pages['/home?hello=world']).toMatchObject(pages['/home'])
expect(pages['/home?hello=world']).not.toBe(pages['/home'])

expect(store.getState().superglue.currentPageKey).toEqual(
'/home?hello=world'
)
expect(history.location.pathname).toEqual('/home')
expect(history.location.search).toEqual('?hello=world')
})

it('navigates using "replace" to a moved page with new params', () => {
const history = createMemoryHistory({})
history.replace('/home', {
superglue: true,
pageKey: '/home',
posX: 5,
posY: 5,
})

vi.spyOn(window, 'scrollTo').mockImplementation(() => {})

const homeProps = {
componentIdentifier: 'home',
restoreStrategy: 'fromCacheOnly',
}

const store = buildStore({
pages: {
'/home': homeProps,
'/about': {
componentIdentifier: 'about',
restoreStrategy: 'fromCacheOnly',
},
},
superglue: {
csrfToken: 'abc',
currentPageKey: '/home',
},
})

let instance

render(
<Provider store={store}>
<NavigationProvider
store={store}
ref={(node) => (instance = node)}
mapping={{ home: Home, about: About }}
history={history}
/>
</Provider>
)

instance.navigateTo('/home', {
action: 'replace',
search: { hello: 'world' },
})

const pages = store.getState().pages
expect(pages['/home?hello=world']).toBe(homeProps)

expect(store.getState().superglue.currentPageKey).toEqual(
'/home?hello=world'
)
expect(history.location.pathname).toEqual('/home')
expect(history.location.search).toEqual('?hello=world')
})

describe('history pop', () => {
describe('when the previous page was set to "revisitOnly"', () => {
it('revisits the page and scrolls when finished', async () => {
Expand Down