| 1 | import React, { act, Suspense, startTransition } from "react"; |
| 2 | import { createRoot } from "react-dom/client"; |
| 3 | import { JSDOM } from "jsdom"; |
| 4 | import assert from "node:assert/strict"; |
| 5 | import { useTranscriptCommand } from "../lib/useTranscriptCommand"; |
| 6 | |
| 7 | const dom = new JSDOM("<div id='root'></div>"); |
| 8 | globalThis.window = dom.window as unknown as Window & typeof globalThis; |
| 9 | globalThis.document = dom.window.document; |
| 10 | Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); |
| 11 | const root = createRoot(document.getElementById("root")!); |
| 12 | let latest!: (offset: number) => number; |
| 13 | const suspended = new Promise<void>(() => {}); |
| 14 | function Probe({ revision, suspend = false }: { revision: number; suspend?: boolean }) { |
| 15 | latest = useTranscriptCommand((offset: number) => revision + offset); |
| 16 | if (suspend) throw suspended; |
| 17 | return null; |
| 18 | } |
| 19 | |
| 20 | try { |
| 21 | await act(async () => root.render(<Suspense><Probe revision={1} /></Suspense>)); |
| 22 | const retainedCommand = latest; |
| 23 | assert.equal(retainedCommand(10), 11); |
| 24 | for (let revision = 2; revision <= 100; revision += 1) { |
| 25 | await act(async () => root.render(<Suspense><Probe revision={revision} /></Suspense>)); |
| 26 | assert.equal(latest, retainedCommand, "commands retain identity across presentation commits"); |
| 27 | assert.equal(retainedCommand(10), revision + 10, "old holders dispatch to only the latest committed presentation"); |
| 28 | } |
| 29 | await act(async () => startTransition(() => root.render(<Suspense><Probe revision={999} suspend /></Suspense>))); |
| 30 | assert.equal(retainedCommand(10), 110, "an abandoned/suspended render cannot acquire command authority"); |
| 31 | console.log("PASS stable Transcript commands use committed state without cross-render callback chains"); |
| 32 | } finally { |
| 33 | await act(async () => root.unmount()); |
| 34 | dom.window.close(); |
| 35 | } |
| 36 |