Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ProjectContentSearchDialog.browser.test.tsx

153 lines4.9 KB

1import { scopeThreadRef } from "@t3tools/client-runtime/environment";
2import { AuthFilesystemReadScope, EnvironmentId, ThreadId } from "@t3tools/contracts";
3import { act } from "react";
4import { createRoot, type Root } from "react-dom/client";
5import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";
6​
7const state = vi.hoisted(() => ({
8 readScope: vi.fn(),
9 // The real query hands back the same result array until the search changes.
10 matches: [
11 {
12 resultIndex: 0,
13 path: "src/index.ts",
14 lineNumber: 3,
15 lineContent: "match",
16 matchRanges: [],
17 },
18 ],
19 noMatches: [],
20 access: { canReadFiles: true, isCheckingAccess: false },
21 listeners: new Set<() => void>(),
22}));
23​
24// The real query is subscription-backed, so access changes reach the dialog without a parent render.
25function setAccess(access: { canReadFiles: boolean; isCheckingAccess: boolean }) {
26 state.access = access;
27 for (const listener of state.listeners) listener();
29​
30const target = {
31 environmentId: EnvironmentId.make("content-search-secondary"),
32 cwd: "/project",
33 projectName: "Project",
34 threadRef: scopeThreadRef(
35 EnvironmentId.make("content-search-secondary"),
36 ThreadId.make("content-search-thread"),
37 ),
38};
39​
40vi.mock(import("~/hooks/useActiveProjectTarget"), async (original) => ({
41 ...(await original()),
42 useActiveProjectTarget: () => target,
43}));
44vi.mock(import("~/state/session"), async (original) => ({
45 ...(await original()),
46 readEnvironmentScope: state.readScope,
47}));
48vi.mock(import("~/state/queries"), async (original) => {
49 const { useSyncExternalStore } = await import("react");
50 const subscribe = (listener: () => void) => {
51 state.listeners.add(listener);
52 return () => state.listeners.delete(listener);
53 };
54 return {
55 ...(await original()),
56 useProjectContentSearch: (({ query }: { query: string }) => {
57 const { canReadFiles, isCheckingAccess } = useSyncExternalStore(
58 subscribe,
59 () => state.access,
60 );
61 return {
62 canReadFiles,
63 isCheckingAccess,
64 error: null,
65 isPending: isCheckingAccess,
66 hasQuery: query.length > 0,
67 truncated: false,
68 invalidRegex: false,
69 matches: canReadFiles && query.length > 0 ? state.matches : state.noMatches,
70 };
71 }) as never,
72 };
73});
74​
75import { useRightPanelStore } from "~/rightPanelStore";
76import { ProjectContentSearchDialog } from "./ProjectContentSearchDialog";
77​
78let root: Root;
79let container: HTMLDivElement;
80const onOpenChange = vi.fn();
81const openFile = vi.fn();
82​
83beforeEach(() => {
84 state.access = { canReadFiles: true, isCheckingAccess: false };
85 state.listeners.clear();
86 state.readScope.mockReset().mockReturnValue(true);
87 openFile.mockClear();
88 onOpenChange.mockClear();
89 vi.spyOn(useRightPanelStore.getState(), "openFile").mockImplementation(openFile);
90 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
91 container = document.createElement("div");
92 document.body.append(container);
93 root = createRoot(container);
94});
95​
96afterEach(async () => {
97 await act(() => root.unmount());
98 container.remove();
99 vi.restoreAllMocks();
100 vi.unstubAllGlobals();
101});
102​
103const input = () => container.querySelector("input")!;
104const result = () => container.querySelector<HTMLButtonElement>("[data-content-search-result]");
105​
106async function openSearch() {
107 await act(() => root.render(<ProjectContentSearchDialog onOpenChange={onOpenChange} />));
109​
110async function type(text: string) {
111 await act(async () => {
112 const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!;
113 setValue.call(input(), text);
114 input().dispatchEvent(new Event("input", { bubbles: true }));
115 });
117​
118it("enables search after access resolves and opens a result in its own environment", async () => {
119 state.access = { canReadFiles: false, isCheckingAccess: true };
120 await openSearch();
121 expect(input().disabled).toBe(true);
122 expect(container.textContent).toContain("Checking file access…");
123​
124 await act(() => setAccess({ canReadFiles: true, isCheckingAccess: false }));
125 expect(input().disabled).toBe(false);
126 await type("match");
127 await act(async () => result()!.click());
128​
129 expect(state.readScope).toHaveBeenCalledWith(target.environmentId, AuthFilesystemReadScope);
130 expect(openFile).toHaveBeenCalledWith(target.threadRef, "src/index.ts", 3);
131 expect(onOpenChange).toHaveBeenCalledWith(false);
132});
133​
134it.each(["pointer", "keyboard"])(
135 "rechecks access before a retained %s action opens a result",
136 async (action) => {
137 await openSearch();
138 await type("match");
139​
140 state.readScope.mockReturnValue(false);
141 await act(async () => {
142 if (action === "pointer") result()!.click();
143 else
144 input().dispatchEvent(
145 new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }),
146 );
147 });
148​
149 expect(state.readScope).toHaveBeenCalled();
150 expect(openFile).not.toHaveBeenCalled();
151 expect(onOpenChange).not.toHaveBeenCalled();
152 },
153);