@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
tsx 925 lines 27.9 KB
Raw
1 // <reference types="@testing-library/jest-dom" />
2 import { assert } from "@effect/vitest"
3 import { act, render, screen, waitFor } from "@testing-library/react"
4 import { Cause, Context, Effect, Latch, Layer } from "effect"
5 import * as AsyncResult from "effect/reactivity/AsyncResult"
6 import * as Atom from "effect/reactivity/Atom"
7 import * as AtomRef from "effect/reactivity/AtomRef"
8 import * as AtomRegistry from "effect/reactivity/AtomRegistry"
9 import * as Hydration from "effect/reactivity/Hydration"
10 import * as Schema from "effect/Schema"
11 import * as React from "react"
12 import { Suspense } from "react"
13 import * as ReactDOMClient from "react-dom/client"
14 import { renderToString } from "react-dom/server"
15 import { ErrorBoundary } from "react-error-boundary"
16 import { beforeEach, describe, expect, it, test, vi } from "vitest"
17 import {
18 HydrationBoundary,
19 RegistryContext,
20 RegistryProvider,
21 useAtomRef,
22 useAtomSuspense,
23 useAtomValue
24 } from "../src/index.ts"
25 import * as ScopedAtom from "../src/ScopedAtom.ts"
26
27 // Tests share the DOM and registry.
28 describe("atom-react", { concurrent: false }, () => {
29 let registry: AtomRegistry.AtomRegistry
30
31 beforeEach(() => {
32 registry = AtomRegistry.make()
33 })
34
35 describe("runtime", () => {
36 test("can inject test layers", () => {
37 class TheNumber extends Context.Service<TheNumber>()("TheNumber", {
38 make: Effect.succeed({ n: 42 as number })
39 }) {
40 static readonly layer = Layer.effect(this, this.make)
41 }
42 const runtime = Atom.runtime(TheNumber.layer)
43 const numberAtom = runtime.atom(TheNumber.use((_) => Effect.succeed(_.n)))
44
45 function TestComponent() {
46 const value = useAtomValue(numberAtom, AsyncResult.getOrThrow)
47 return <div data-testid="value">{value}</div>
48 }
49
50 render(
51 <RegistryProvider
52 initialValues={[
53 Atom.initialValue(
54 runtime.layer,
55 Layer.succeed(TheNumber, { n: 69 })
56 )
57 ]}
58 >
59 <TestComponent />
60 </RegistryProvider>
61 )
62
63 expect(screen.getByTestId("value")).toHaveTextContent("69")
64 })
65 })
66
67 describe("useAtomValue", () => {
68 test("should read value from simple Atom", () => {
69 const atom = Atom.make(42)
70
71 function TestComponent() {
72 const value = useAtomValue(atom)
73 return <div data-testid="value">{value}</div>
74 }
75
76 render(<TestComponent />)
77
78 expect(screen.getByTestId("value")).toHaveTextContent("42")
79 })
80
81 test("should read value with transform function", () => {
82 const atom = Atom.make(42)
83
84 function TestComponent() {
85 const value = useAtomValue(atom, (x) => x * 2)
86 return <div data-testid="value">{value}</div>
87 }
88
89 render(<TestComponent />)
90
91 expect(screen.getByTestId("value")).toHaveTextContent("84")
92 })
93
94 test("should update when Atom value changes", async () => {
95 const atom = Atom.make("initial")
96
97 function TestComponent() {
98 const value = useAtomValue(atom)
99 return <div data-testid="value">{value}</div>
100 }
101
102 render(
103 <RegistryContext.Provider value={registry}>
104 <TestComponent />
105 </RegistryContext.Provider>
106 )
107
108 expect(screen.getByTestId("value")).toHaveTextContent("initial")
109
110 act(() => {
111 registry.set(atom, "updated")
112 })
113
114 await waitFor(() => {
115 expect(screen.getByTestId("value")).toHaveTextContent("updated")
116 })
117 })
118
119 test("should work with computed Atom", () => {
120 const baseAtom = Atom.make(10)
121 const computedAtom = Atom.make((get) => get(baseAtom) * 2)
122
123 function TestComponent() {
124 const value = useAtomValue(computedAtom)
125 return <div data-testid="value">{value}</div>
126 }
127
128 render(<TestComponent />)
129
130 expect(screen.getByTestId("value")).toHaveTextContent("20")
131 })
132
133 test("initializing an atom that sets another atom does not update other components during render", () => {
134 const count = Atom.make(0)
135 const resource = Atom.make((get) =>
136 Effect.sync(() => {
137 get.set(count, 1)
138 return "ready"
139 })
140 )
141 const errors = vi.spyOn(console, "error").mockImplementation(() => {})
142
143 function Observer() {
144 return <div data-testid="count">{useAtomValue(count)}</div>
145 }
146 function Initializer() {
147 const result = useAtomValue(resource)
148 return <div data-testid="resource">{AsyncResult.getOrElse(result, () => "")}</div>
149 }
150
151 try {
152 const { rerender } = render(
153 <RegistryContext.Provider value={registry}>
154 <Observer />
155 </RegistryContext.Provider>
156 )
157 assert.strictEqual(screen.getByTestId("count").textContent, "0")
158
159 rerender(
160 <RegistryContext.Provider value={registry}>
161 <Observer />
162 <Initializer />
163 </RegistryContext.Provider>
164 )
165
166 assert.strictEqual(screen.getByTestId("count").textContent, "1")
167 assert.strictEqual(screen.getByTestId("resource").textContent, "ready")
168 assert.deepStrictEqual(errors.mock.calls, [])
169 } finally {
170 errors.mockRestore()
171 }
172 })
173
174 test("suspense success", () => {
175 const atom = Atom.make(Effect.never)
176
177 function TestComponent() {
178 const value = useAtomSuspense(atom).value
179 return <div data-testid="value">{value}</div>
180 }
181
182 render(
183 <Suspense fallback={<div data-testid="loading">Loading...</div>}>
184 <TestComponent />
185 </Suspense>
186 )
187
188 expect(screen.getByTestId("loading")).toBeInTheDocument()
189 })
190
191 test("suspense subscriptions are isolated per registry", async () => {
192 const atom = Atom.make(AsyncResult.initial<string>())
193 const firstRegistry = AtomRegistry.make()
194 const secondRegistry = AtomRegistry.make()
195
196 function TestComponent({ id }: { readonly id: string }) {
197 const value = useAtomSuspense(atom).value
198 return <div data-testid={`${id}-value`}>{value}</div>
199 }
200
201 render(
202 <RegistryContext.Provider value={firstRegistry}>
203 <Suspense fallback={<div data-testid="first-loading">Loading...</div>}>
204 <TestComponent id="first" />
205 </Suspense>
206 </RegistryContext.Provider>
207 )
208 render(
209 <RegistryContext.Provider value={secondRegistry}>
210 <Suspense fallback={<div data-testid="second-loading">Loading...</div>}>
211 <TestComponent id="second" />
212 </Suspense>
213 </RegistryContext.Provider>
214 )
215
216 act(() => {
217 secondRegistry.set(atom, AsyncResult.success("second"))
218 })
219
220 await waitFor(() => {
221 expect(screen.getByTestId("second-value")).toHaveTextContent("second")
222 })
223 expect(screen.getByTestId("first-loading")).toBeInTheDocument()
224
225 act(() => {
226 firstRegistry.set(atom, AsyncResult.success("first"))
227 })
228
229 await waitFor(() => {
230 expect(screen.getByTestId("first-value")).toHaveTextContent("first")
231 })
232 })
233 })
234
235 test("useAtomRef updates after switching refs", () => {
236 const first = AtomRef.make(0)
237 const second = AtomRef.make(1)
238
239 function TestComponent({ source }: { readonly source: AtomRef.ReadonlyRef<number> }) {
240 return <div data-testid="value">{useAtomRef(source)}</div>
241 }
242
243 const { rerender } = render(<TestComponent source={first} />)
244 rerender(<TestComponent source={second} />)
245
246 act(() => {
247 second.set(0)
248 })
249
250 expect(screen.getByTestId("value")).toHaveTextContent("0")
251 })
252
253 describe("ScopedAtom", () => {
254 test("throws when used outside Provider", () => {
255 const counter = ScopedAtom.make(() => Atom.make(0))
256
257 function TestComponent() {
258 counter.use()
259 return <div>ok</div>
260 }
261
262 expect(() => render(<TestComponent />)).toThrow("ScopedAtom used outside of its Provider")
263 })
264
265 test("scopes atom instances per Provider", async () => {
266 const counter = ScopedAtom.make(() => Atom.make(0))
267
268 function Count() {
269 const atom = counter.use()
270 const value = useAtomValue(atom)
271 return <div data-testid="value">{value}</div>
272 }
273
274 function SetTo({ value }: { readonly value: number }) {
275 const atom = counter.use()
276 const registry = React.useContext(RegistryContext)
277 React.useEffect(() => {
278 registry.set(atom, value)
279 }, [registry, atom, value])
280 return null
281 }
282
283 render(
284 <div>
285 <counter.Provider>
286 <SetTo value={1} />
287 <Count />
288 </counter.Provider>
289 <counter.Provider>
290 <SetTo value={2} />
291 <Count />
292 </counter.Provider>
293 </div>
294 )
295
296 await waitFor(() => {
297 const values = screen.getAllByTestId("value")
298 expect(values[0]).toHaveTextContent("1")
299 expect(values[1]).toHaveTextContent("2")
300 })
301 })
302
303 test("input factory uses provider value once", () => {
304 const makeAtom = vi.fn((value: number) => Atom.make(value))
305 const scoped = ScopedAtom.make(makeAtom)
306
307 function Count() {
308 const atom = scoped.use()
309 const value = useAtomValue(atom)
310 return <div data-testid="value">{value}</div>
311 }
312
313 const { rerender } = render(
314 <scoped.Provider value={10}>
315 <Count />
316 </scoped.Provider>
317 )
318
319 expect(screen.getByTestId("value")).toHaveTextContent("10")
320 expect(makeAtom).toHaveBeenCalledTimes(1)
321 expect(makeAtom).toHaveBeenCalledWith(10)
322
323 rerender(
324 <scoped.Provider value={99}>
325 <Count />
326 </scoped.Provider>
327 )
328
329 expect(screen.getByTestId("value")).toHaveTextContent("10")
330 expect(makeAtom).toHaveBeenCalledTimes(1)
331 })
332
333 test("integrates with useAtomValue", async () => {
334 const scoped = ScopedAtom.make(() => Atom.make(0))
335
336 function Counter() {
337 const atom = scoped.use()
338 const value = useAtomValue(atom)
339 return <div data-testid="value">{value}</div>
340 }
341
342 function IncrementOnce() {
343 const atom = scoped.use()
344 const registry = React.useContext(RegistryContext)
345 React.useEffect(() => {
346 registry.set(atom, 1)
347 }, [registry, atom])
348 return null
349 }
350
351 render(
352 <scoped.Provider>
353 <IncrementOnce />
354 <Counter />
355 </scoped.Provider>
356 )
357
358 await waitFor(() => {
359 expect(screen.getByTestId("value")).toHaveTextContent("1")
360 })
361 })
362 })
363
364 test("suspense error", () => {
365 const atom = Atom.make(Effect.fail(new Error("test")))
366 function TestComponent() {
367 const value = useAtomSuspense(atom).value
368 return <div data-testid="value">{value}</div>
369 }
370
371 render(
372 <ErrorBoundary fallback={<div data-testid="error">Error</div>}>
373 <Suspense fallback={<div data-testid="loading">Loading...</div>}>
374 <TestComponent />
375 </Suspense>
376 </ErrorBoundary>,
377 {
378 onCaughtError: ((error: unknown) => {
379 if (error instanceof Error && error.message === "test") {
380 return
381 }
382 // eslint-disable-next-line no-console
383 console.error(error)
384 }) as unknown as undefined // todo: fix idk why the types are weird
385 }
386 )
387
388 expect(screen.getByTestId("error")).toBeInTheDocument()
389 })
390
391 describe("hydration", () => {
392 test("basic hydration with number atom and result atoms", () => {
393 const atomBasic = Atom.make(0).pipe(
394 Atom.serializable({
395 key: "basic",
396 schema: Schema.Number
397 })
398 )
399 const e: Effect.Effect<number, string> = Effect.never
400 const makeAtomResult = (key: string) =>
401 Atom.make(e).pipe(
402 Atom.serializable({
403 key,
404 schema: AsyncResult.Schema({
405 success: Schema.Number,
406 error: Schema.String
407 })
408 })
409 )
410
411 const atomResult1 = makeAtomResult("success")
412 const atomResult2 = makeAtomResult("errored")
413 const atomResult3 = makeAtomResult("pending")
414
415 // Use a server-side registry to generate properly encoded dehydrated state
416 const serverRegistry = AtomRegistry.make()
417 serverRegistry.mount(atomBasic)
418 serverRegistry.set(atomBasic, 1)
419 serverRegistry.mount(atomResult1)
420 ;(serverRegistry.getNodes().get("success") as any).setValue(
421 AsyncResult.success(123)
422 )
423 serverRegistry.mount(atomResult2)
424 ;(serverRegistry.getNodes().get("errored") as any).setValue(
425 AsyncResult.failure(Cause.fail("error"))
426 )
427 serverRegistry.mount(atomResult3)
428 // atomResult3 stays Initial (just mounted, effect is Effect.never)
429
430 const dehydratedState = Hydration.dehydrate(serverRegistry, {
431 encodeInitialAs: "value-only"
432 })
433
434 function Basic() {
435 const value = useAtomValue(atomBasic)
436 return <div data-testid="hydration-basic-value">{value}</div>
437 }
438
439 function Result1() {
440 const value = useAtomValue(atomResult1)
441 return AsyncResult.match(value, {
442 onSuccess: (result) => <div data-testid="value-1">{result.value}</div>,
443 onFailure: () => <div data-testid="error-1">Error</div>,
444 onInitial: () => <div data-testid="loading-1">Loading...</div>
445 })
446 }
447
448 function Result2() {
449 const value = useAtomValue(atomResult2)
450 return AsyncResult.match(value, {
451 onSuccess: (result) => <div data-testid="value-2">{result.value}</div>,
452 onFailure: () => <div data-testid="error-2">Error</div>,
453 onInitial: () => <div data-testid="loading-2">Loading...</div>
454 })
455 }
456
457 function Result3() {
458 const value = useAtomValue(atomResult3)
459 return AsyncResult.match(value, {
460 onSuccess: (result) => <div data-testid="value-3">{result.value}</div>,
461 onFailure: () => <div data-testid="error-3">Error</div>,
462 onInitial: () => <div data-testid="loading-3">Loading...</div>
463 })
464 }
465
466 render(
467 <RegistryContext.Provider value={AtomRegistry.make()}>
468 <HydrationBoundary state={dehydratedState}>
469 <Basic />
470 <Result1 />
471 <Result2 />
472 <Result3 />
473 </HydrationBoundary>
474 </RegistryContext.Provider>
475 )
476
477 expect(screen.getByTestId("hydration-basic-value")).toHaveTextContent("1")
478 expect(screen.getByTestId("value-1")).toHaveTextContent("123")
479 expect(screen.getByTestId("error-2")).toBeInTheDocument()
480 expect(screen.getByTestId("loading-3")).toBeInTheDocument()
481 })
482
483 test("hydration streaming with resultPromise", async () => {
484 const latch = Latch.makeUnsafe()
485 let start = 0
486 let stop = 0
487 const atom = Atom.make(
488 Effect.gen(function*() {
489 start = start + 1
490 yield* latch.await
491 stop = stop + 1
492 return 1
493 })
494 ).pipe(
495 Atom.serializable({
496 key: "test",
497 schema: AsyncResult.Schema({
498 success: Schema.Number
499 })
500 })
501 )
502
503 registry.mount(atom)
504
505 expect(start).toBe(1)
506 expect(stop).toBe(0)
507
508 const dehydratedState = Hydration.dehydrate(registry, {
509 encodeInitialAs: "promise"
510 })
511
512 function TestComponent() {
513 const value = useAtomValue(atom)
514 return <div data-testid="value">{value._tag}</div>
515 }
516
517 render(
518 // provide a fresh registry each time to simulate hydration
519 <RegistryContext.Provider value={AtomRegistry.make()}>
520 <HydrationBoundary state={dehydratedState}>
521 <TestComponent />
522 </HydrationBoundary>
523 </RegistryContext.Provider>
524 )
525
526 expect(screen.getByTestId("value")).toHaveTextContent("Initial")
527 // Hydration starts a client effect while the server effect is still pending.
528 expect(start).toBe(2)
529 expect(stop).toBe(0)
530
531 act(() => {
532 Effect.runSync(latch.open)
533 })
534 await Effect.runPromise(latch.await)
535
536 const result = registry.get(atom)
537 expect(result._tag).toBe("Success")
538 if (result._tag === "Success") {
539 expect(result.value).toBe(1)
540 }
541
542 expect(screen.getByTestId("value")).toHaveTextContent("Success")
543 expect(start).toBe(2)
544 expect(stop).toBe(2)
545 })
546
547 test("HydrationBoundary updates existing readers after commit", () => {
548 const count = Atom.make(0).pipe(
549 Atom.serializable({ key: "existing-count", schema: Schema.Number })
550 )
551 const server = AtomRegistry.make()
552 try {
553 server.set(count, 5)
554 const state = Hydration.dehydrate(server)
555
556 function Count({ id }: { id: string }) {
557 return <div data-testid={id}>{useAtomValue(count)}</div>
558 }
559
560 const { rerender } = render(
561 <RegistryContext.Provider value={registry}>
562 <Count id="header" />
563 </RegistryContext.Provider>
564 )
565 assert.strictEqual(screen.getByTestId("header").textContent, "0")
566
567 rerender(
568 <RegistryContext.Provider value={registry}>
569 <Count id="header" />
570 <HydrationBoundary state={state}>
571 <Count id="page" />
572 </HydrationBoundary>
573 </RegistryContext.Provider>
574 )
575
576 assert.strictEqual(screen.getByTestId("header").textContent, "5")
577 assert.strictEqual(screen.getByTestId("page").textContent, "5")
578 } finally {
579 server.dispose()
580 }
581 })
582
583 test("HydrationBoundary splits new vs existing atoms", () => {
584 const newAtom = Atom.make(0).pipe(
585 Atom.serializable({ key: "new-atom", schema: Schema.Number })
586 )
587
588 // Use a server registry to generate dehydrated state
589 const serverRegistry = AtomRegistry.make()
590 serverRegistry.mount(newAtom)
591 serverRegistry.set(newAtom, 99)
592 const dehydratedState = Hydration.dehydrate(serverRegistry)
593
594 function NewValue() {
595 const value = useAtomValue(newAtom)
596 return <div data-testid="new">{value}</div>
597 }
598
599 // Render with a fresh client registry (no pre-existing atoms)
600 render(
601 <RegistryContext.Provider value={AtomRegistry.make()}>
602 <HydrationBoundary state={dehydratedState}>
603 <NewValue />
604 </HydrationBoundary>
605 </RegistryContext.Provider>
606 )
607
608 // New atom should be hydrated immediately during render
609 expect(screen.getByTestId("new")).toHaveTextContent("99")
610 })
611
612 test("dehydrate with encodeInitialAs ignore (default)", () => {
613 const atom = Atom.make(Effect.never as Effect.Effect<number>).pipe(
614 Atom.serializable({
615 key: "initial-atom",
616 schema: AsyncResult.Schema({ success: Schema.Number })
617 })
618 )
619
620 registry.mount(atom)
621
622 // Default behavior: Initial values should be ignored
623 const state = Hydration.dehydrate(registry)
624 const values = Hydration.toValues(state)
625
626 expect(values.length).toBe(0)
627 })
628
629 test("dehydrate with encodeInitialAs value-only", () => {
630 const atom = Atom.make(Effect.never as Effect.Effect<number>).pipe(
631 Atom.serializable({
632 key: "initial-atom",
633 schema: AsyncResult.Schema({ success: Schema.Number })
634 })
635 )
636
637 registry.mount(atom)
638
639 // value-only: should encode the Initial value without a resultPromise
640 const state = Hydration.dehydrate(registry, {
641 encodeInitialAs: "value-only"
642 })
643 const values = Hydration.toValues(state)
644
645 expect(values.length).toBe(1)
646 expect(values[0].key).toBe("initial-atom")
647 expect(values[0].resultPromise).toBeUndefined()
648 })
649
650 test("serializable encode/decode survives JSON roundtrip (wire transfer)", () => {
651 const atom = Atom.make(0 as never).pipe(
652 Atom.serializable({
653 key: "wire-test",
654 schema: AsyncResult.Schema({
655 success: Schema.Struct({ name: Schema.String }),
656 error: Schema.String
657 })
658 })
659 )
660
661 const original = AsyncResult.success({ name: "hello" })
662
663 // Encode using the atom's serializable encode
664 const encoded = atom[Atom.SerializableTypeId].encode(original)
665
666 // Simulate wire transfer (seroval / JSON serialization roundtrip)
667 const wireTransferred = JSON.parse(JSON.stringify(encoded))
668
669 // Decode after wire transfer — this was the bug: decode would fail
670 // because the encoded value lost its AsyncResult prototype
671 const decoded = atom[Atom.SerializableTypeId].decode(wireTransferred)
672
673 expect(AsyncResult.isAsyncResult(decoded)).toBe(true)
674 expect(decoded._tag).toBe("Success")
675 if (AsyncResult.isSuccess(decoded)) {
676 expect(decoded.value).toEqual({ name: "hello" })
677 }
678 })
679
680 test("dehydrate + JSON roundtrip + hydrate works (SSR simulation)", () => {
681 const atom = Atom.make(Effect.never as Effect.Effect<number>).pipe(
682 Atom.serializable({
683 key: "ssr-wire",
684 schema: AsyncResult.Schema({ success: Schema.Number })
685 })
686 )
687
688 // Server: dehydrate
689 const serverRegistry = AtomRegistry.make()
690 serverRegistry.mount(atom)
691 ;(serverRegistry.getNodes().get("ssr-wire") as any).setValue(
692 AsyncResult.success(42)
693 )
694 const dehydratedState = Hydration.dehydrate(serverRegistry)
695
696 // Simulate wire transfer (seroval / JSON)
697 const wireTransferred = JSON.parse(JSON.stringify(dehydratedState))
698
699 // Client: hydrate from wire-transferred state
700 function TestComponent() {
701 const value = useAtomValue(atom)
702 return (
703 <div data-testid="ssr-wire-value">
704 {AsyncResult.isSuccess(value) ? value.value : "not-success"}
705 </div>
706 )
707 }
708
709 render(
710 <RegistryContext.Provider value={AtomRegistry.make()}>
711 <HydrationBoundary state={wireTransferred}>
712 <TestComponent />
713 </HydrationBoundary>
714 </RegistryContext.Provider>
715 )
716
717 expect(screen.getByTestId("ssr-wire-value")).toHaveTextContent("42")
718 })
719
720 test("empty state is a no-op", () => {
721 function TestComponent() {
722 return <div data-testid="hydration-empty-state">OK</div>
723 }
724
725 render(
726 <HydrationBoundary state={[]}>
727 <TestComponent />
728 </HydrationBoundary>
729 )
730
731 expect(screen.getByTestId("hydration-empty-state")).toHaveTextContent("OK")
732 })
733
734 test("hydrate with no state is a no-op", () => {
735 function TestComponent() {
736 return <div data-testid="hydration-no-state">OK</div>
737 }
738
739 render(
740 <HydrationBoundary>
741 <TestComponent />
742 </HydrationBoundary>
743 )
744
745 expect(screen.getByTestId("hydration-no-state")).toHaveTextContent("OK")
746 })
747 })
748
749 describe("SSR", () => {
750 it("should run atom's during SSR by default", () => {
751 const getCount = vi.fn(() => 0)
752 const counterAtom = Atom.make(getCount)
753
754 function TestComponent() {
755 const count = useAtomValue(counterAtom)
756 return <div>{count}</div>
757 }
758
759 function App() {
760 return <TestComponent />
761 }
762
763 const ssrHtml = renderToString(<App />)
764
765 expect(getCount).toHaveBeenCalled()
766 expect(ssrHtml).toContain("0")
767
768 render(<App />)
769
770 expect(getCount).toHaveBeenCalled()
771 expect(screen.getByText("0")).toBeInTheDocument()
772 })
773
774 it("hydrates a delayed Suspense boundary after the atom changes", async () => {
775 const userAtom = Atom.make("loading")
776
777 // Reading through a selector also covers the selector's server snapshot.
778 // It is inline and returns a new object, so its result must be memoized.
779 function Name({ id }: { id: string }) {
780 const user = useAtomValue(userAtom, (name) => ({ name: name.toUpperCase() }))
781 return <span id={id}>{user.name}</span>
782 }
783
784 const Passthrough = ({ children }: { children?: React.ReactNode }) => <>{children}</>
785
786 function App({ Panel }: { Panel: React.ComponentType<{ children?: React.ReactNode }> }) {
787 return (
788 <div>
789 <Name id="header" />
790 <Suspense fallback={<span>...</span>}>
791 <Panel>
792 <Name id="panel" />
793 </Panel>
794 </Suspense>
795 </div>
796 )
797 }
798
799 const container = document.createElement("div")
800 container.innerHTML = renderToString(
801 <RegistryContext.Provider value={AtomRegistry.make()}>
802 <App Panel={Passthrough} />
803 </RegistryContext.Provider>
804 )
805 document.body.append(container)
806
807 // The panel stays dehydrated until its lazy chunk loads.
808 let loadPanel!: (mod: { default: typeof Passthrough }) => void
809 const LazyPanel = React.lazy(() =>
810 new Promise<{ default: typeof Passthrough }>((resolve) => {
811 loadPanel = resolve
812 })
813 )
814 const recoverableErrors: Array<unknown> = []
815
816 let root!: ReactDOMClient.Root
817 await act(async () => {
818 root = ReactDOMClient.hydrateRoot(
819 container,
820 <RegistryContext.Provider value={registry}>
821 <App Panel={LazyPanel} />
822 </RegistryContext.Provider>,
823 { onRecoverableError: (error) => recoverableErrors.push(error) }
824 )
825 })
826 await act(async () => {
827 registry.set(userAtom, "Alice")
828 })
829 await act(async () => {
830 loadPanel({ default: Passthrough })
831 })
832
833 expect(recoverableErrors).toEqual([])
834 expect(container.innerHTML).toBe(
835 `<div><span id="header">ALICE</span><!--$--><span id="panel">ALICE</span><!--/$--></div>`
836 )
837
838 act(() => root.unmount())
839 container.remove()
840 })
841
842 it("keeps the hydrated value until the last reader unmounts", async () => {
843 const userAtom = Atom.make("loading").pipe(Atom.keepAlive)
844
845 function Name() {
846 return <span>{useAtomValue(userAtom)}</span>
847 }
848
849 const app = (
850 <RegistryContext.Provider value={registry}>
851 <Name />
852 </RegistryContext.Provider>
853 )
854 const html = renderToString(app)
855 const containers = [0, 1, 2].map(() => {
856 const container = document.createElement("div")
857 container.innerHTML = html
858 document.body.append(container)
859 return container
860 })
861 const recoverableErrors: Array<unknown> = []
862 const hydrate = (container: HTMLElement) =>
863 ReactDOMClient.hydrateRoot(container, app, {
864 onRecoverableError: (error) => recoverableErrors.push(error)
865 })
866
867 let first!: ReactDOMClient.Root
868 let second!: ReactDOMClient.Root
869 await act(async () => {
870 first = hydrate(containers[0])
871 second = hydrate(containers[1])
872 })
873 await act(async () => {
874 registry.set(userAtom, "Alice")
875 })
876
877 // The second reader keeps the snapshot locked after the first unmounts.
878 act(() => first.unmount())
879 let third!: ReactDOMClient.Root
880 await act(async () => {
881 third = hydrate(containers[2])
882 })
883
884 expect(recoverableErrors).toEqual([])
885 expect(containers[2].innerHTML).toBe("<span>Alice</span>")
886
887 // Once no reader is subscribed, server renders read the registry again.
888 act(() => {
889 second.unmount()
890 third.unmount()
891 })
892 containers.forEach((container) => container.remove())
893
894 expect(renderToString(app)).toBe("<span>Alice</span>")
895 })
896 })
897
898 it("should not execute Atom effects during SSR when using withServerSnapshot", () => {
899 const mockFetchData = vi.fn(() => 0)
900
901 const userDataAtom = Atom.make(Effect.sync(() => mockFetchData())).pipe(
902 Atom.withServerValueInitial
903 )
904
905 function TestComponent() {
906 const result = useAtomValue(userDataAtom)
907
908 return <div>{result._tag}</div>
909 }
910
911 function App() {
912 return <TestComponent />
913 }
914
915 const ssrHtml = renderToString(<App />)
916
917 expect(mockFetchData).not.toHaveBeenCalled()
918 expect(ssrHtml).toContain("Initial")
919
920 render(<App />)
921
922 expect(mockFetchData).toHaveBeenCalled()
923 expect(screen.getByText("Success")).toBeInTheDocument()
924 })
925 })