Open History to see the last commit
1import { DEFAULT_THEMES, preloadHighlighter } from "@pierre/diffs";
2import { EnvironmentId, ThreadId, type ProjectReadFileResult } from "@t3tools/contracts";
3import { AsyncResult } from "effect/reactivity";
4import type { ReactNode } from "react";
5import { describe, expect, it, vi } from "vite-plus/test";
6import { userEvent } from "vite-plus/test/browser";
7import { act, fakeTimers, render } from "../../../test/render";
8import appCss from "~/index.css?inline";
9import { isMacPlatform } from "~/lib/utils";
10import {
11 createWorkspaceFocusController,
12 startWorkspaceFocus,
13 workspaceAreaProps,
14} from "~/lib/workspaceFocus";
15
16const state = vi.hoisted(() => ({
17 file: null as ProjectReadFileResult | null,
18 optimistic: null as ProjectReadFileResult | null,
19 writeFile: vi.fn(),
20}));
21
22vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({
23 ...(await original()),
24 runAtomCommand: ((_registry: unknown, _command: unknown, request: unknown) =>
25 state.writeFile(request)) as never,
26}));
27vi.mock(import("~/state/session"), async (original) => ({
28 ...(await original()),
29 readEnvironmentScope: () => true,
30 useEnvironmentScope: () => true,
31}));
32vi.mock(import("~/state/filesystem"), async (original) => ({
33 ...(await original()),
34 useFilesystemReadAccess: () => ({ canReadFiles: true, isPending: false, error: null }),
35}));
36vi.mock(import("~/state/use-atom-command"), async (original) => ({
37 ...(await original()),
38 useAtomCommand: (() => state.writeFile) as never,
39}));
40vi.mock(import("~/state/server"), async (original) => {
41 const actual = await original();
42 const { Atom } = await import("effect/reactivity");
43 const noConfig = Atom.make(null);
44 return {
45 ...actual,
46 serverEnvironment: { ...actual.serverEnvironment, configValueAtom: (() => noConfig) as never },
47 };
48});
49vi.mock(import("~/remoteOpen"), async (original) => ({
50 ...(await original()),
51 useRemoteOpenState: () => ({ mode: "local-exec" }) as never,
52 useRemoteOpenResolution: () => ({ state: { mode: "local-exec" }, isResolved: true }) as never,
53}));
54vi.mock(import("~/hooks/useTheme"), async (original) => ({
55 ...(await original()),
56 useTheme: () => ({ resolvedTheme: "dark" }) as never,
57}));
58vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({
59 useWorkspaceMutationRefresh: vi.fn(),
60}));
61vi.mock(import("./FileBreadcrumbs"), () => ({ FileBreadcrumbs: () => <></> }));
62vi.mock(import("./FileBrowserPanel"), () => ({
63 default: () => (
64 <div role="tree">
65 <button type="button" role="treeitem" data-item-path="src/">
66 src
67 </button>
68 <button type="button" role="treeitem" data-item-path="server.ts">
69 server.ts
70 </button>
71 </div>
72 ),
73}));
74vi.mock(import("../DiffWorkerPoolProvider"), () => ({
75 DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,
76}));
77vi.mock(import("./projectFilesQueryState"), async (original) => ({
78 ...(await original()),
79 useProjectFileQuery: () => ({
80 data: state.file,
81 error: null,
82 isPending: false,
83 readError: null,
84 isNotFile: false,
85 isFile: true,
86 refresh: vi.fn(),
87 }),
88 getOptimisticProjectFileQueryData: () => state.optimistic,
89 getUnsavedProjectFileQueryData: () => null,
90 setProjectFileQueryData: (
91 _environmentId: EnvironmentId,
92 _cwd: string,
93 relativePath: string,
94 contents: string,
95 ) => {
96 state.optimistic = { relativePath, contents, truncated: false, byteLength: contents.length };
97 },
98 confirmProjectFileQueryData: () => true,
99}));
100
101import FilePreviewPanel from "./FilePreviewPanel";
102
103const environmentId = EnvironmentId.make("markdown-preview-test");
104const threadRef = { environmentId, threadId: ThreadId.make("thread") };
105function setup() {
106 const keys = ["t3code.fileExplorerOpen", "t3code.renderMarkdown"];
107 const previous = keys.map((key) => localStorage.getItem(key));
108 localStorage.setItem(keys[0]!, "false");
109 localStorage.setItem(keys[1]!, "true");
110 state.file = null;
111 state.optimistic = null;
112 state.writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
113 return {
114 [Symbol.dispose]() {
115 for (const [index, key] of keys.entries()) {
116 const value = previous[index];
117 if (value == null) localStorage.removeItem(key);
118 else localStorage.setItem(key, value);
119 }
120 },
121 };
122}
123
124function markdownPreview(truncated: boolean, contents = "- [ ] Keep the rest of this file\n") {
125 state.file = {
126 relativePath: "tasks.md",
127 contents,
128 byteLength: truncated ? 1_200_000 : contents.length,
129 truncated,
130 };
131 return filePreview("tasks.md");
132}
133
134function filePreview(relativePath: string) {
135 return (
136 <FilePreviewPanel
137 environmentId={environmentId}
138 cwd="/workspace"
139 projectName="Project"
140 relativePath={relativePath}
141 threadRef={threadRef}
142 composerDraftTarget={threadRef}
143 keybindings={[]}
144 availableEditors={[]}
145 openInShortcutEnabled={false}
146 revealLine={null}
147 revealRequestId={0}
148 onOpenFile={vi.fn()}
149 onNavigateFolder={vi.fn()}
150 folderTrail={undefined}
151 onPendingChange={vi.fn()}
152 selectedFilePending={false}
153 workspaceMutationId={null}
154 />
155 );
156}
157
158function deepActiveElement() {
159 let active = document.activeElement;
160 while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
161 return active;
162}
163
164describe("source file focus", () => {
165 it("hands panel focus to the file's editor, which owns mod+f", async () => {
166 using _settings = setup();
167 const style = document.createElement("style");
168 style.textContent = appCss;
169 document.head.append(style);
170 using _style = { [Symbol.dispose]: () => style.remove() };
171 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
172 const panel = () => (
173 <div {...workspaceAreaProps("panel", 1, "Workspace panel")}>
174 <div data-right-panel-surface-content>{filePreview("server.ts")}</div>
175 </div>
176 );
177 const editorHasFocus = () => expect(deepActiveElement()?.matches("[data-content]")).toBe(true);
178
179 await using screen = await render(panel());
180 const focus = createWorkspaceFocusController(document);
181 using _focus = { [Symbol.dispose]: focus.dispose };
182 expect(focus.focus("panel")).toBe(true);
183 state.file = {
184 relativePath: "server.ts",
185 contents: "const server = 1;\n",
186 byteLength: 18,
187 truncated: false,
188 };
189 await screen.rerender(panel());
190 await vi.waitFor(editorHasFocus);
191 await userEvent.keyboard("x");
192 await vi.waitFor(() => expect(deepActiveElement()?.textContent).toContain("xconst server"));
193
194 (deepActiveElement() as HTMLElement).blur();
195 expect(focus.focus("panel", false)).toBe(true);
196 await vi.waitFor(editorHasFocus);
197 await userEvent.keyboard(
198 isMacPlatform(navigator.platform) ? "{Meta>}f{/Meta}" : "{Control>}f{/Control}",
199 );
200 await vi.waitFor(() => expect(deepActiveElement()).toBeInstanceOf(HTMLInputElement));
201 });
202
203 it("focuses the editor when a file row is clicked or activated with Enter", async () => {
204 using _settings = setup();
205 localStorage.setItem("t3code.fileExplorerOpen", "true");
206 const style = document.createElement("style");
207 style.textContent = appCss;
208 document.head.append(style);
209 using _style = { [Symbol.dispose]: () => style.remove() };
210 await preloadHighlighter({ themes: Object.values(DEFAULT_THEMES), langs: ["typescript"] });
211 state.file = {
212 relativePath: "server.ts",
213 contents: "const server = 1;\n",
214 byteLength: 18,
215 truncated: false,
216 };
217 await using screen = await render(
218 <div {...workspaceAreaProps("panel", 1, "Workspace panel")} style={{ width: 900 }}>
219 <div data-right-panel-surface-content>{filePreview("server.ts")}</div>
220 </div>,
221 );
222 using _focus = {
223 [Symbol.dispose]: startWorkspaceFocus({ subscribe: () => () => {} } as never),
224 };
225 const editorHasFocus = () => expect(deepActiveElement()?.matches("[data-content]")).toBe(true);
226 // The explorer measures its parent row; a wrapper without a box would cap it at the minimum.
227 await expect
228 .element(screen.getByRole("separator", { name: "Resize file explorer" }))
229 .toHaveAttribute("aria-valuemax", "560");
230 const folderRow = screen.getByRole("treeitem", { name: "src" });
231 const fileRow = screen.getByRole("treeitem", { name: "server.ts" });
232
233 (folderRow.element() as HTMLElement).focus();
234 await userEvent.keyboard("{Enter}");
235 expect(document.activeElement).toBe(folderRow.element());
236
237 await userEvent.click(fileRow);
238 await vi.waitFor(editorHasFocus);
239
240 (fileRow.element() as HTMLElement).focus();
241 await userEvent.keyboard("{Enter}");
242 await vi.waitFor(editorHasFocus);
243 });
244});
245
246describe("rendered Markdown task saves", () => {
247 it("keeps a truncated read read-only without queuing a replacement", async () => {
248 using _settings = setup();
249 await using screen = await render(markdownPreview(true));
250 using _timers = fakeTimers();
251 const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
252 expect(checkbox).not.toBeNull();
253 expect(checkbox.disabled).toBe(true);
254 expect(checkbox.readOnly).toBe(true);
255 await act(async () => checkbox.click());
256 await vi.advanceTimersByTimeAsync(500);
257 expect(checkbox.checked).toBe(false);
258 expect(state.optimistic).toBeNull();
259 expect(state.writeFile).not.toHaveBeenCalled();
260 });
261
262 it("still toggles and saves tasks from a complete read", async () => {
263 using _settings = setup();
264 await using screen = await render(markdownPreview(false));
265 using _timers = fakeTimers();
266 const checkbox = screen.container.querySelector<HTMLInputElement>('input[type="checkbox"]')!;
267 expect(checkbox).not.toBeNull();
268 expect(checkbox.disabled).toBe(false);
269 await act(async () => checkbox.click());
270 await vi.advanceTimersByTimeAsync(500);
271 expect(state.writeFile).toHaveBeenCalledExactlyOnceWith({
272 environmentId,
273 input: {
274 cwd: "/workspace",
275 relativePath: "tasks.md",
276 contents: "- [x] Keep the rest of this file\n",
277 },
278 });
279 });
280});
281
282describe("rendered Markdown select all", () => {
283 it("selects only the rendered file, including after a task toggle", async () => {
284 using _settings = setup();
285 await using screen = await render(
286 <>
287 <p>Transcript text from the chat thread.</p>
288 {markdownPreview(false, "- [ ] Task item\n\nRendered file body.\n")}
289 </>,
290 );
291 const expectFileOnlySelection = async () => {
292 await userEvent.keyboard(
293 isMacPlatform(navigator.platform) ? "{Meta>}a{/Meta}" : "{Control>}a{/Control}",
294 );
295 const selection = window.getSelection()?.toString() ?? "";
296 expect(selection).toContain("Rendered file body.");
297 expect(selection).not.toContain("Transcript text from the chat thread.");
298 };
299
300 await userEvent.click(screen.getByText("Rendered file body."));
301 await expectFileOnlySelection();
302 // A toggled checkbox keeps focus on an input inside the preview.
303 await userEvent.click(screen.getByRole("checkbox"));
304 await expectFileOnlySelection();
305 });
306});