feat(jsx/dom): support getServerSnapshot in useSyncExternalStore (#2646)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(jsx/dom): support getServerSnapshot in useSyncExternalStore * chore: denoify * test: add tests for hooks with `.toString()` * test: fix typo. * refactor: set the flag to false at the end of top level render * chore: denoify
authored by Taku Amano · committed by GitHub · parent aebaa28 · Browse files · 6 files·+126 added−30 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+126 added−30 removed
- tests:+72 added−0 removed
- other:+54 added−30 removed
Provenance
- Commit
cd35af7- Tree
f7e4993- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
aebaa28
6 files changed+126 added−30 removed
modified:deno_dist/jsx/dom/render.ts+7 added-2 removed
80 unmodified lines81 | [82 PendingType, // PendingType83 boolean, // got an error84 UpdateHook, // update hook85- boolean // is in view transition85+ boolean, // is in view transition86+ boolean // is in top level render87 ]88+ | [PendingType, boolean, UpdateHook, boolean]89 | [PendingType, boolean, UpdateHook]90 | [PendingType, boolean]91 | [PendingType]92 | []480 unmodified lines573 574 export const render = (jsxNode: unknown, container: Container) => {575 // eslint-disable-next-line @typescript-eslint/no-explicit-any576 const node = buildNode({ tag: '', props: { children: jsxNode } } as any) as NodeObject577+ const context: Context = []578+ ;(context as Context)[4] = true // start top level render575- build([], node, undefined)579+ build(context, node, undefined)580+ ;(context as Context)[4] = false // finish top level render581 582 const fragment = document.createDocumentFragment()583 apply(node, fragment)584 replaceContainer(node, fragment, container)27 unmodified linesmodified:deno_dist/jsx/hooks/index.ts+20 added-13 removed
386 unmodified lines387 }388 }, deps)389 }390 391-let useSyncExternalStoreGetServerSnapshotNotified = false391 export const useSyncExternalStore = <T>(392 subscribe: (callback: (value: T) => void) => () => void,393 getSnapshot: () => T,394 getServerSnapshot?: () => T395 ): T => {397- const [state, setState] = useState(getSnapshot())398- useEffect(399- () =>400- subscribe(() => {401- setState(getSnapshot())402- }),403- []404- )405-406- if (getServerSnapshot && !useSyncExternalStoreGetServerSnapshotNotified) {407- useSyncExternalStoreGetServerSnapshotNotified = true408- console.info('`getServerSnapshot` is not supported yet.')396+ const buildData = buildDataStack.at(-1) as [Context, unknown]397+ if (!buildData) {398+ // now a stringify process, maybe in server side399+ if (!getServerSnapshot) {400+ throw new Error('getServerSnapshot is required for server side rendering')401+ }402+ return getServerSnapshot()403 }404 405+ const [serverSnapshotIsUsed] = useState<boolean>(!!(buildData[0][4] && getServerSnapshot))406+ const [state, setState] = useState(() =>407+ serverSnapshotIsUsed ? (getServerSnapshot as () => T)() : getSnapshot()408+ )409+ useEffect(() => {410+ if (serverSnapshotIsUsed) {411+ setState(getSnapshot())412+ }413+ return subscribe(() => {414+ setState(getSnapshot())415+ })416+ }, [])417+418 return state419 }modified:src/jsx/dom/render.ts+7 added-2 removed
80 unmodified lines81 | [82 PendingType, // PendingType83 boolean, // got an error84 UpdateHook, // update hook85- boolean // is in view transition85+ boolean, // is in view transition86+ boolean // is in top level render87 ]88+ | [PendingType, boolean, UpdateHook, boolean]89 | [PendingType, boolean, UpdateHook]90 | [PendingType, boolean]91 | [PendingType]92 | []480 unmodified lines573 574 export const render = (jsxNode: unknown, container: Container) => {575 // eslint-disable-next-line @typescript-eslint/no-explicit-any576 const node = buildNode({ tag: '', props: { children: jsxNode } } as any) as NodeObject577+ const context: Context = []578+ ;(context as Context)[4] = true // start top level render575- build([], node, undefined)579+ build(context, node, undefined)580+ ;(context as Context)[4] = false // finish top level render581 582 const fragment = document.createDocumentFragment()583 apply(node, fragment)584 replaceContainer(node, fragment, container)27 unmodified linesmodified:src/jsx/hooks/dom.test.tsx+32 added
561 unmodified lines562 root.querySelector('button')?.click()563 await new Promise((r) => setTimeout(r))564 expect(root.innerHTML).toBe('<div>1</div><button>toggle</button>')565 })566+567+ it('with getServerSnapshot', async () => {568+ let count = 0569+ const unsubscribe = vi.fn()570+ const subscribe = vi.fn(() => unsubscribe)571+ const getSnapshot = vi.fn(() => count++)572+ const getServerSnapshot = vi.fn(() => 100)573+ const SubApp = () => {574+ const count = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)575+ return <div>{count}</div>576+ }577+ const App = () => {578+ const [show, setShow] = useState(true)579+ return (580+ <>581+ {show && <SubApp />}582+ <button onClick={() => setShow((s) => !s)}>toggle</button>583+ </>584+ )585+ }586+ render(<App />, root)587+ expect(root.innerHTML).toBe('<div>100</div><button>toggle</button>')588+ await new Promise((r) => setTimeout(r))589+ expect(root.innerHTML).toBe('<div>0</div><button>toggle</button>')590+ root.querySelector('button')?.click()591+ await new Promise((r) => setTimeout(r))592+ expect(root.innerHTML).toBe('<button>toggle</button>')593+ expect(unsubscribe).toBeCalled()594+ root.querySelector('button')?.click()595+ await new Promise((r) => setTimeout(r))596+ expect(root.innerHTML).toBe('<div>1</div><button>toggle</button>')597+ })598 })599 })modified:src/jsx/hooks/index.ts+20 added-13 removed
386 unmodified lines387 }388 }, deps)389 }390 391-let useSyncExternalStoreGetServerSnapshotNotified = false391 export const useSyncExternalStore = <T>(392 subscribe: (callback: (value: T) => void) => () => void,393 getSnapshot: () => T,394 getServerSnapshot?: () => T395 ): T => {397- const [state, setState] = useState(getSnapshot())398- useEffect(399- () =>400- subscribe(() => {401- setState(getSnapshot())402- }),403- []404- )405-406- if (getServerSnapshot && !useSyncExternalStoreGetServerSnapshotNotified) {407- useSyncExternalStoreGetServerSnapshotNotified = true408- console.info('`getServerSnapshot` is not supported yet.')396+ const buildData = buildDataStack.at(-1) as [Context, unknown]397+ if (!buildData) {398+ // now a stringify process, maybe in server side399+ if (!getServerSnapshot) {400+ throw new Error('getServerSnapshot is required for server side rendering')401+ }402+ return getServerSnapshot()403 }404 405+ const [serverSnapshotIsUsed] = useState<boolean>(!!(buildData[0][4] && getServerSnapshot))406+ const [state, setState] = useState(() =>407+ serverSnapshotIsUsed ? (getServerSnapshot as () => T)() : getSnapshot()408+ )409+ useEffect(() => {410+ if (serverSnapshotIsUsed) {411+ setState(getSnapshot())412+ }413+ return subscribe(() => {414+ setState(getSnapshot())415+ })416+ }, [])417+418 return state419 }added:src/jsx/hooks/string.test.tsx+40 added
12345678910111213141516171819202122232425262728293031323334353637383940/* eslint-disable @typescript-eslint/no-explicit-any */import { jsx, useState, useSyncExternalStore } from '..'
describe('useState', () => { it('should be rendered with initial state', () => { const Component = () => { const [state] = useState('hello') return <span>{state}</span> } const template = <Component /> expect(template.toString()).toBe('<span>hello</span>') })})
describe('useSyncExternalStore', () => { it('should be rendered with result of getServerSnapshot()', () => { const unsubscribe = vi.fn() const subscribe = vi.fn(() => unsubscribe) const getSnapshot = vi.fn() const getServerSnapshot = vi.fn(() => 100) const App = () => { const count = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) return <div>{count}</div> } const template = <App /> expect(template.toString()).toBe('<div>100</div>') expect(unsubscribe).not.toBeCalled() expect(subscribe).not.toBeCalled() expect(getSnapshot).not.toBeCalled() })
it('should raise an error if getServerShot() is not provided', () => { const App = () => { const count = useSyncExternalStore(vi.fn(), vi.fn()) return <div>{count}</div> } const template = <App /> expect(() => template.toString()).toThrowError() })})