Skip to content
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

chore(router): reverting sticky params whilst issue with presentation exists #7489

Merged
merged 1 commit into from
Sep 10, 2024
Merged
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
77 changes: 4 additions & 73 deletions packages/sanity/src/router/IntentLink.test.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
import {describe, expect, it, jest} from '@jest/globals'
import {describe, expect, it} from '@jest/globals'
import {render} from '@testing-library/react'
import {noop} from 'lodash'

import {IntentLink} from './IntentLink'
import {route} from './route'
import {RouterProvider} from './RouterProvider'

jest.mock('./stickyParams', () => ({
STICKY_PARAMS: ['aTestStickyParam'],
}))

describe('IntentLink', () => {
it('should resolve intent link with query params', () => {
const router = route.create('/test', [route.intents('/intent')])
Expand All @@ -20,83 +15,19 @@ describe('IntentLink', () => {
id: 'document-id-123',
type: 'document-type',
}}
searchParams={[['aTestStickyParam', `aStickyParam.value`]]}
/>,
{
wrapper: ({children}) => (
<RouterProvider onNavigate={noop} router={router} state={{}}>
{children}
</RouterProvider>
),
},
)
// Component should render the query param in the href
expect(component.container.querySelector('a')?.href).toContain(
'/test/intent/edit/id=document-id-123;type=document-type/?aTestStickyParam=aStickyParam.value',
)
})

it('should preserve sticky parameters when resolving intent link', () => {
const router = route.create('/test', [route.intents('/intent')])
const component = render(
<IntentLink
intent="edit"
params={{
id: 'document-id-123',
type: 'document-type',
}}
searchParams={[['perspective', `bundle.summer-drop`]]}
/>,
{
wrapper: ({children}) => (
<RouterProvider
onNavigate={noop}
router={router}
state={{
_searchParams: [['aTestStickyParam', 'aStickyParam.value']],
}}
>
<RouterProvider onNavigate={() => null} router={router} state={{}}>
{children}
</RouterProvider>
),
},
)
// Component should render the query param in the href
expect(component.container.querySelector('a')?.href).toContain(
'/test/intent/edit/id=document-id-123;type=document-type/?aTestStickyParam=aStickyParam.value',
)
})

it('should allow sticky parameters to be overridden when resolving intent link', () => {
const router = route.create('/test', [route.intents('/intent')])
const component = render(
<IntentLink
intent="edit"
params={{
id: 'document-id-123',
type: 'document-type',
}}
searchParams={[['aTestStickyParam', `aStickyParam.value.to-be-defined`]]}
/>,
{
wrapper: ({children}) => (
<RouterProvider
onNavigate={noop}
router={router}
state={{
_searchParams: [['aTestStickyParam', 'aStickyParam.value.to-be-overridden']],
}}
>
{children}
</RouterProvider>
),
},
)
// Component should render the query param in the href
expect(component.container.querySelector('a')?.href).toContain(
'/test/intent/edit/id=document-id-123;type=document-type/?aTestStickyParam=aStickyParam.value.to-be-defined',
)
expect(component.container.querySelector('a')?.href).not.toContain(
'aTestStickyParam=aStickyParam.value.to-be-overridden',
'/test/intent/edit/id=document-id-123;type=document-type/?perspective=bundle.summer-drop',
)
})
})
85 changes: 7 additions & 78 deletions packages/sanity/src/router/RouterProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import {fromPairs, partition, toPairs} from 'lodash'
import {type ReactElement, type ReactNode, useCallback, useMemo} from 'react'
import {RouterContext} from 'sanity/_singletons'

import {STICKY_PARAMS} from './stickyParams'
import {
type IntentParameters,
type NavigateOptions,
Expand Down Expand Up @@ -89,49 +87,17 @@ export function RouterProvider(props: RouterProviderProps): ReactElement {
intent: intentName,
params,
payload,
_searchParams: toPairs({
...fromPairs((state._searchParams ?? []).filter(([key]) => STICKY_PARAMS.includes(key))),
...fromPairs(_searchParams ?? []),
}),
_searchParams,
})
},
[routerProp, state._searchParams],
[routerProp],
)

const resolvePathFromState = useCallback(
(nextState: RouterState): string => {
const currentStateParams = state._searchParams || []
const nextStateParams = nextState._searchParams || []
const nextParams = STICKY_PARAMS.reduce((acc, param) => {
return replaceStickyParam(
acc,
param,
findParam(nextStateParams, param) ?? findParam(currentStateParams, param),
)
}, nextStateParams || [])

return routerProp.encode({
...nextState,
_searchParams: nextParams,
})
},
[routerProp, state],
)

const handleNavigateStickyParam = useCallback(
(param: string, value: string | undefined, options: NavigateOptions = {}) => {
if (!STICKY_PARAMS.includes(param)) {
throw new Error('Parameter is not sticky')
}
onNavigate({
path: resolvePathFromState({
...state,
_searchParams: [[param, value || '']],
}),
replace: options.replace,
})
(nextState: Record<string, unknown>): string => {
return routerProp.encode(nextState)
},
[onNavigate, resolvePathFromState, state],
[routerProp],
)

const navigate = useCallback(
Expand All @@ -148,54 +114,17 @@ export function RouterProvider(props: RouterProviderProps): ReactElement {
[onNavigate, resolveIntentLink],
)

const [routerState, stickyParams] = useMemo(() => {
if (!state._searchParams) {
return [state, null]
}
const {_searchParams, ...rest} = state
const [sticky, restParams] = partition(_searchParams, ([key]) => STICKY_PARAMS.includes(key))
if (sticky.length === 0) {
return [state, null]
}
return [{...rest, _searchParams: restParams}, sticky]
}, [state])

const router: RouterContextValue = useMemo(
() => ({
navigate,
navigateIntent,
navigateStickyParam: handleNavigateStickyParam,
navigateUrl: onNavigate,
resolveIntentLink,
resolvePathFromState,
state: routerState,
stickyParams: Object.fromEntries(stickyParams || []),
state,
}),
[
handleNavigateStickyParam,
navigate,
navigateIntent,
onNavigate,
resolveIntentLink,
resolvePathFromState,
routerState,
stickyParams,
],
[navigate, navigateIntent, onNavigate, resolveIntentLink, resolvePathFromState, state],
)

return <RouterContext.Provider value={router}>{props.children}</RouterContext.Provider>
}

function replaceStickyParam(
current: SearchParam[],
param: string,
value: string | undefined,
): SearchParam[] {
const filtered = current.filter(([key]) => key !== param)
return value === undefined || value == '' ? filtered : [...filtered, [param, value]]
}

function findParam(searchParams: SearchParam[], key: string): string | undefined {
const entry = searchParams.find(([k]) => k === key)
return entry ? entry[1] : undefined
}
1 change: 0 additions & 1 deletion packages/sanity/src/router/stickyParams.ts

This file was deleted.

10 changes: 0 additions & 10 deletions packages/sanity/src/router/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -264,11 +264,6 @@ export interface RouterContextValue {
*/
navigateUrl: (opts: {path: string; replace?: boolean}) => void

/**
* Navigates to the current URL with the sticky url search param set to the given value
*/
navigateStickyParam: (param: string, value: string, options?: NavigateOptions) => void

/**
* Navigates to the given router state.
* See {@link RouterState} and {@link NavigateOptions}
Expand All @@ -285,9 +280,4 @@ export interface RouterContextValue {
* The current router state. See {@link RouterState}
*/
state: RouterState

/**
* The current router state. See {@link RouterState}
*/
stickyParams: Record<string, string | undefined>
}
8 changes: 1 addition & 7 deletions packages/sanity/src/structure/components/IntentButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,7 @@ export const IntentButton = forwardRef(function IntentButton(
linkRef: ForwardedRef<HTMLAnchorElement>,
) {
return (
<IntentLink
{...linkProps}
intent={intent.type}
params={intent.params}
ref={linkRef}
searchParams={intent.searchParams}
/>
<IntentLink {...linkProps} intent={intent.type} params={intent.params} ref={linkRef} />
)
}),
[intent],
Expand Down
4 changes: 0 additions & 4 deletions packages/sanity/src/structure/structureBuilder/Intent.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import {type SearchParam} from 'sanity/router'

import {getTypeNamesFromFilter, type PartialDocumentList} from './DocumentList'
import {type StructureNode} from './StructureNodes'

Expand Down Expand Up @@ -77,8 +75,6 @@ export interface Intent {
/** Intent parameters. See {@link IntentParams}
*/
params?: IntentParams

searchParams?: SearchParam[]
}

/**
Expand Down
Loading