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

feat: Key isolation #855

Open
wants to merge 4 commits into
base: next
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { testKeyIsolation } from 'e2e-shared/specs/key-isolation.cy'

testKeyIsolation({
path: '/key-isolation/useQueryState',
hook: 'useQueryState'
})

testKeyIsolation({
path: '/key-isolation/useQueryStates',
hook: 'useQueryStates'
})
2 changes: 2 additions & 0 deletions packages/e2e/react-router/v6/src/react-router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ const router = createBrowserRouter(
<Route path="form/useQueryStates" lazy={load(import('./routes/form.useQueryStates'))} />
<Route path="referential-stability/useQueryState" lazy={load(import('./routes/referential-stability.useQueryState'))} />
<Route path="referential-stability/useQueryStates" lazy={load(import('./routes/referential-stability.useQueryStates'))} />
<Route path="key-isolation/useQueryState" lazy={load(import('./routes/key-isolation.useQueryState'))} />
<Route path="key-isolation/useQueryStates" lazy={load(import('./routes/key-isolation.useQueryStates'))} />

<Route path="render-count/:hook/:shallow/:history/:startTransition/no-loader" lazy={load(import('./routes/render-count.$hook.$shallow.$history.$startTransition.no-loader'))} />
<Route path="render-count/:hook/:shallow/:history/:startTransition/sync-loader" lazy={load(import('./routes/render-count.$hook.$shallow.$history.$startTransition.sync-loader'))} />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { KeyIsolationUseQueryState } from 'e2e-shared/specs/key-isolation'

export default KeyIsolationUseQueryState
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { KeyIsolationUseQueryStates } from 'e2e-shared/specs/key-isolation'

export default KeyIsolationUseQueryStates
2 changes: 2 additions & 0 deletions packages/e2e/react-router/v7/app/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ export default [
route('/form/useQueryStates', './routes/form.useQueryStates.tsx'),
route('/referential-stability/useQueryState', './routes/referential-stability.useQueryState.tsx'),
route('/referential-stability/useQueryStates', './routes/referential-stability.useQueryStates.tsx'),
route('/key-isolation/useQueryState', './routes/key-isolation.useQueryState.tsx'),
route('/key-isolation/useQueryStates', './routes/key-isolation.useQueryStates.tsx'),
route('/render-count/:hook/:shallow/:history/:startTransition/no-loader', './routes/render-count.$hook.$shallow.$history.$startTransition.no-loader.tsx'),
route('/render-count/:hook/:shallow/:history/:startTransition/sync-loader', './routes/render-count.$hook.$shallow.$history.$startTransition.sync-loader.tsx'),
route('/render-count/:hook/:shallow/:history/:startTransition/async-loader', './routes/render-count.$hook.$shallow.$history.$startTransition.async-loader.tsx'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { KeyIsolationUseQueryState } from 'e2e-shared/specs/key-isolation'

export default KeyIsolationUseQueryState
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { KeyIsolationUseQueryStates } from 'e2e-shared/specs/key-isolation'

export default KeyIsolationUseQueryStates
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { testKeyIsolation } from 'e2e-shared/specs/key-isolation.cy'

testKeyIsolation({
path: '/key-isolation/useQueryState',
hook: 'useQueryState'
})

testKeyIsolation({
path: '/key-isolation/useQueryStates',
hook: 'useQueryStates'
})
11 changes: 11 additions & 0 deletions packages/e2e/react/cypress/e2e/shared/key-isolation.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { testKeyIsolation } from 'e2e-shared/specs/key-isolation.cy'

testKeyIsolation({
path: '/key-isolation/useQueryState',
hook: 'useQueryState'
})

testKeyIsolation({
path: '/key-isolation/useQueryStates',
hook: 'useQueryStates'
})
2 changes: 2 additions & 0 deletions packages/e2e/react/src/routes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ const routes: Record<string, React.LazyExoticComponent<() => JSX.Element>> = {
'/form/useQueryStates': lazy(() => import('./routes/form.useQueryStates')),
'/referential-stability/useQueryState': lazy(() => import('./routes/referential-stability.useQueryState')),
'/referential-stability/useQueryStates': lazy(() => import('./routes/referential-stability.useQueryStates')),
'/key-isolation/useQueryState': lazy(() => import('./routes/key-isolation.useQueryState')),
'/key-isolation/useQueryStates': lazy(() => import('./routes/key-isolation.useQueryStates')),

'/render-count/useQueryState/true/replace/false': lazy(() => import('./routes/render-count')),
'/render-count/useQueryState/true/replace/true': lazy(() => import('./routes/render-count')),
Expand Down
3 changes: 3 additions & 0 deletions packages/e2e/react/src/routes/key-isolation.useQueryState.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { KeyIsolationUseQueryState } from 'e2e-shared/specs/key-isolation'

export default KeyIsolationUseQueryState
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { KeyIsolationUseQueryStates } from 'e2e-shared/specs/key-isolation'

export default KeyIsolationUseQueryStates
3 changes: 3 additions & 0 deletions packages/e2e/remix/app/routes/key-isolation.useQueryState.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { KeyIsolationUseQueryState } from 'e2e-shared/specs/key-isolation'

export default KeyIsolationUseQueryState
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { KeyIsolationUseQueryStates } from 'e2e-shared/specs/key-isolation'

export default KeyIsolationUseQueryStates
11 changes: 11 additions & 0 deletions packages/e2e/remix/cypress/e2e/shared/key-isolation.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { testKeyIsolation } from 'e2e-shared/specs/key-isolation.cy'

testKeyIsolation({
path: '/key-isolation/useQueryState',
hook: 'useQueryState'
})

testKeyIsolation({
path: '/key-isolation/useQueryStates',
hook: 'useQueryStates'
})
13 changes: 13 additions & 0 deletions packages/e2e/shared/cypress/support/log-spy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export const stubConsoleLog = {
onBeforeLoad(window: any) {
cy.stub(window.console, 'log').as('consoleLog')
}
}

export function assertLogCount(message: string, expectedCount: number) {
cy.get('@consoleLog').then(spy => {
// @ts-ignore
const matchingLogs = spy.args.filter(args => args[0] === message)
expect(matchingLogs.length).to.equal(expectedCount)
})
}
34 changes: 34 additions & 0 deletions packages/e2e/shared/specs/key-isolation.cy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createTest } from '../create-test'
import { assertLogCount, stubConsoleLog } from '../cypress/support/log-spy'

export const testKeyIsolation = createTest('Key isolation', ({ path }) => {
it('does not render b when updating a', () => {
cy.visit(path, stubConsoleLog)
cy.contains('#hydration-marker', 'hydrated').should('be.hidden')
cy.get('#trigger-a').click()
cy.get('#state-a').should('have.text', 'pass')
cy.location('search').should('eq', '?a=pass')
assertLogCount('render a', 3) // 1 at mount + 2 at update
assertLogCount('render b', 1) // only 1 at mount
})
it('does not render a when updating b', () => {
cy.visit(path, stubConsoleLog)
cy.contains('#hydration-marker', 'hydrated').should('be.hidden')
cy.get('#trigger-b').click()
cy.get('#state-b').should('have.text', 'pass')
cy.location('search').should('eq', '?b=pass')
assertLogCount('render b', 3) // 1 at mount + 2 at update
assertLogCount('render a', 1) // only 1 at mount
})
it('does not render a again when updating b after a', () => {
cy.visit(path, stubConsoleLog)
cy.contains('#hydration-marker', 'hydrated').should('be.hidden')
cy.get('#trigger-a').click()
cy.get('#state-a').should('have.text', 'pass')
cy.get('#trigger-b').click()
cy.get('#state-b').should('have.text', 'pass')
cy.location('search').should('eq', '?a=pass&b=pass')
assertLogCount('render a', 3) // 1 at mount + 2 at update
assertLogCount('render b', 3) // 1 at mount + 2 at update
})
})
51 changes: 51 additions & 0 deletions packages/e2e/shared/specs/key-isolation.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import { parseAsString, useQueryState, useQueryStates } from 'nuqs'

type TestComponentProps = {
id: string
}

export function KeyIsolationUseQueryState() {
return (
<>
<TestComponentUseQueryState id="a" />
<TestComponentUseQueryState id="b" />
</>
)
}

export function KeyIsolationUseQueryStates() {
return (
<>
<TestComponentUseQueryStates id="a" />
<TestComponentUseQueryStates id="b" />
</>
)
}

function TestComponentUseQueryState({ id }: TestComponentProps) {
const [state, setState] = useQueryState(id)
console.log(`render ${id}`)
return (
<>
<button id={`trigger-${id}`} onClick={() => setState('pass')}>
Test {id}
</button>
<pre id={`state-${id}`}>{state}</pre>
</>
)
}

function TestComponentUseQueryStates({ id }: TestComponentProps) {
const [state, setState] = useQueryStates({
[id]: parseAsString
})
console.log(`render ${id}`)
return (
<>
<button id={`trigger-${id}`} onClick={() => setState({ [id]: 'pass' })}>
Test {id}
</button>
<pre id={`state-${id}`}>{state[id]}</pre>
</>
)
}
17 changes: 2 additions & 15 deletions packages/e2e/shared/specs/render-count.cy.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createTest, type TestConfig } from '../create-test'
import { assertLogCount, stubConsoleLog } from '../cypress/support/log-spy'

type TestRenderCountConfig = TestConfig & {
props: {
Expand All @@ -13,20 +14,6 @@ type TestRenderCountConfig = TestConfig & {
}
}

const stubConsoleLog = {
onBeforeLoad(window: any) {
cy.stub(window.console, 'log').as('consoleLog')
}
}

function assertLogCount(message: string, expectedCount: number) {
cy.get('@consoleLog').then(spy => {
// @ts-ignore
const matchingLogs = spy.args.filter(args => args[0] === message)
expect(matchingLogs.length).to.equal(expectedCount)
})
}

export function testRenderCount({
props,
expected,
Expand Down Expand Up @@ -63,9 +50,9 @@ export function testRenderCount({
if (props.delay) {
cy.wait(props.delay)
}
assertLogCount('render', expected.mount + expected.update)
cy.get('#state').should('have.text', 'pass')
cy.location('search').should('contain', 'test=pass')
assertLogCount('render', expected.mount + expected.update)
Copy link
Member Author

@franky47 franky47 Jan 9, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

note: Unrelated change to help the render count test be less flaky: by asserting the log count after testing for correctness, Cypress will wait for the URL to be correct (and give logs time to flush) before testing.

}
)
}
Expand Down
4 changes: 2 additions & 2 deletions packages/nuqs/src/adapters/lib/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,10 @@ export function createAdapterProvider(useAdapter: UseAdapterHook) {
)
}

export function useAdapter() {
export function useAdapter(watchKeys: string[]) {
const value = useContext(context)
if (!('useAdapter' in value)) {
throw new Error(error(404))
}
return value.useAdapter()
return value.useAdapter(watchKeys)
}
2 changes: 1 addition & 1 deletion packages/nuqs/src/adapters/lib/defs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export type UpdateUrlFunction = (
options: Required<AdapterOptions>
) => void

export type UseAdapterHook = () => AdapterInterface
export type UseAdapterHook = (watchKeys: string[]) => AdapterInterface

export type AdapterInterface = {
searchParams: URLSearchParams
Expand Down
49 changes: 49 additions & 0 deletions packages/nuqs/src/adapters/lib/key-isolation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { debug } from '../../debug'

export function applyChange(
newValue: URLSearchParams,
keys: string[],
copy: boolean
) {
return (oldValue: URLSearchParams) => {
const hasChanged =
keys.length === 0
? true
: keys.some(key => oldValue.get(key) !== newValue.get(key))
if (!hasChanged) {
debug(
'[nuqs `%s`] no change, returning previous',
keys.join(','),
oldValue
)
return oldValue
}
const filtered = filterSearchParams(newValue, keys, copy)
debug(
`[nuqs \`%s\`] subbed search params change
from %O
to %O`,
keys.join(','),
oldValue,
filtered
)
return filtered
}
}

export function filterSearchParams(
search: URLSearchParams,
keys: string[],
copy: boolean
) {
if (keys.length === 0) {
return search
}
const filtered = copy ? new URLSearchParams(search) : search
for (const key of search.keys()) {
if (!keys.includes(key)) {
filtered.delete(key)
}
}
return filtered
}
22 changes: 15 additions & 7 deletions packages/nuqs/src/adapters/lib/react-router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import mitt from 'mitt'
import { startTransition, useCallback, useEffect, useState } from 'react'
import { renderQueryString } from '../../url-encoding'
import type { AdapterInterface, AdapterOptions } from './defs'
import { applyChange, filterSearchParams } from './key-isolation'
import {
historyUpdateMarker,
patchHistory,
Expand All @@ -20,7 +21,6 @@ type NavigateOptions = {
}
type NavigateFn = (url: NavigateUrl, options: NavigateOptions) => void
type UseNavigate = () => NavigateFn

type UseSearchParams = () => [URLSearchParams, {}]

// --
Expand All @@ -31,9 +31,11 @@ export function createReactRouterBasedAdapter(
useSearchParams: UseSearchParams
) {
const emitter: SearchParamsSyncEmitter = mitt()
function useNuqsReactRouterBasedAdapter(): AdapterInterface {
function useNuqsReactRouterBasedAdapter(
watchKeys: string[]
): AdapterInterface {
const navigate = useNavigate()
const searchParams = useOptimisticSearchParams()
const searchParams = useOptimisticSearchParams(watchKeys)
const updateUrl = useCallback(
(search: URLSearchParams, options: AdapterOptions) => {
startTransition(() => {
Expand Down Expand Up @@ -77,15 +79,21 @@ export function createReactRouterBasedAdapter(
updateUrl
}
}
function useOptimisticSearchParams() {
function useOptimisticSearchParams(watchKeys: string[] = []) {
const [serverSearchParams] = useSearchParams()
const [searchParams, setSearchParams] = useState(serverSearchParams)
const [searchParams, setSearchParams] = useState(() => {
// Make a copy to avoid modifying the original search params
return filterSearchParams(serverSearchParams, watchKeys, true)
})

useEffect(() => {
function onPopState() {
setSearchParams(new URLSearchParams(location.search))
setSearchParams(
applyChange(new URLSearchParams(location.search), watchKeys, false)
)
}
function onEmitterUpdate(search: URLSearchParams) {
setSearchParams(search)
setSearchParams(applyChange(search, watchKeys, true))
}
emitter.on('update', onEmitterUpdate)
window.addEventListener('popstate', onPopState)
Expand Down
Loading
Loading