Skip to content
Myr

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

6 files+126 added−30 removed

modified:deno_dist/jsx/dom/render.ts+7 added-2 removed
80 unmodified lines
81 | [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 lines
573574export 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 render581582 const fragment = document.createDocumentFragment()583 apply(node, fragment)584 replaceContainer(node, fragment, container)
27 unmodified lines
modified:deno_dist/jsx/hooks/index.ts+20 added-13 removed
386 unmodified lines
387 }388 }, deps)389}390391let useSyncExternalStoreGetServerSnapshotNotified = false391export 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 )405406 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 }404405 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 }, [])417418 return state419}
modified:src/jsx/dom/render.ts+7 added-2 removed
80 unmodified lines
81 | [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 lines
573574export 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 render581582 const fragment = document.createDocumentFragment()583 apply(node, fragment)584 replaceContainer(node, fragment, container)
27 unmodified lines
modified:src/jsx/hooks/dom.test.tsx+32 added
561 unmodified lines
562 root.querySelector('button')?.click()563 await new Promise((r) => setTimeout(r))564 expect(root.innerHTML).toBe('<div>1</div><button>toggle</button>')565 })566567 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 lines
387 }388 }, deps)389}390391let useSyncExternalStoreGetServerSnapshotNotified = false391export 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 )405406 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 }404405 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 }, [])417418 return state419}
added:src/jsx/hooks/string.test.tsx+40 added