|
| 1 | +// @vitest-environment jsdom |
| 2 | + |
| 3 | +import { act, memo, useRef } from "react"; |
| 4 | +import { createRoot, type Root } from "react-dom/client"; |
| 5 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; |
| 6 | +import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts"; |
| 7 | + |
| 8 | +import { THREAD_CONTEXT_DROP_EVENT, useThreadContextDrop } from "./threadContextDrag"; |
| 9 | + |
| 10 | +const ENVIRONMENT_ID = "environment-local" as EnvironmentId; |
| 11 | + |
| 12 | +let root: Root; |
| 13 | +let container: HTMLDivElement; |
| 14 | + |
| 15 | +beforeEach(() => { |
| 16 | + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); |
| 17 | + container = document.createElement("div"); |
| 18 | + document.body.append(container); |
| 19 | + root = createRoot(container); |
| 20 | +}); |
| 21 | + |
| 22 | +afterEach(async () => { |
| 23 | + await act(() => root.unmount()); |
| 24 | + container.remove(); |
| 25 | + vi.unstubAllGlobals(); |
| 26 | +}); |
| 27 | + |
| 28 | +// ChatComposer is memoized and reused across thread navigation; each render's |
| 29 | +// drop callback must write into the draft of the thread it last rendered. |
| 30 | +const ComposerDropTarget = memo(function ComposerDropTarget({ |
| 31 | + draftKey, |
| 32 | + drafts, |
| 33 | +}: { |
| 34 | + draftKey: string; |
| 35 | + drafts: Map<string, Array<ThreadId>>; |
| 36 | +}) { |
| 37 | + const targetRef = useRef<HTMLDivElement | null>(null); |
| 38 | + useThreadContextDrop(targetRef, ENVIRONMENT_ID, draftKey, (refs, isActive) => { |
| 39 | + if (!isActive()) return; |
| 40 | + drafts.get(draftKey)?.push(...refs.map((ref) => ref.threadId)); |
| 41 | + }); |
| 42 | + return <div data-drop-target ref={targetRef} />; |
| 43 | +}); |
| 44 | + |
| 45 | +describe("useThreadContextDrop", () => { |
| 46 | + it("drops into the last rendered thread's draft when the memoized target is reused", async () => { |
| 47 | + const drafts = new Map<string, Array<ThreadId>>([ |
| 48 | + ["thread-a", []], |
| 49 | + ["thread-b", []], |
| 50 | + ]); |
| 51 | + |
| 52 | + await act(() => root.render(<ComposerDropTarget draftKey="thread-a" drafts={drafts} />)); |
| 53 | + await act(() => root.render(<ComposerDropTarget draftKey="thread-b" drafts={drafts} />)); |
| 54 | + |
| 55 | + const dropped: ScopedThreadRef = { |
| 56 | + environmentId: ENVIRONMENT_ID, |
| 57 | + threadId: "thread-dropped" as ThreadId, |
| 58 | + }; |
| 59 | + const target = container.querySelector("[data-drop-target]"); |
| 60 | + expect(target).not.toBeNull(); |
| 61 | + act(() => { |
| 62 | + target!.dispatchEvent(new CustomEvent(THREAD_CONTEXT_DROP_EVENT, { detail: [dropped] })); |
| 63 | + }); |
| 64 | + |
| 65 | + expect(drafts.get("thread-b")).toEqual(["thread-dropped"]); |
| 66 | + expect(drafts.get("thread-a")).toEqual([]); |
| 67 | + }); |
| 68 | +}); |
0 commit comments