@devries-cameron20 / t3code Mirror · read-only / commits / 1ab3afe892
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, 22:15 UTC

fix(web): opening a file focuses its editor so Cmd+F searches it (#34360)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Arman Arutiunov committed Nov 11, 2026 at 21:23 UTC 1ab3afe892baf7ee7f64076d63f1c2358f8068c1
2 files changed +223 -25
apps/web/src/components/files/FilePreviewPanel.browser.test.tsx
+119 -1
@@ -1,7 +1,17 @@
1 +import { DEFAULT_THEMES, preloadHighlighter } from "@pierre/diffs";
2 import { EnvironmentId, ThreadId, type ProjectReadFileResult } from "@t3tools/contracts";
3 import { AsyncResult } from "effect/reactivity";
4 +import type { ReactNode } from "react";
5 import { describe, expect, it, vi } from "vite-plus/test";
6 +import { userEvent } from "vite-plus/test/browser";
7 import { act, fakeTimers, render } from "../../../test/render";
8 +import appCss from "~/index.css?inline";
9 +import { isMacPlatform } from "~/lib/utils";
10 +import {
11 + createWorkspaceFocusController,
12 + startWorkspaceFocus,
13 + workspaceAreaProps,
14 +} from "~/lib/workspaceFocus";
15
16 const state = vi.hoisted(() => ({
17 file: null as ProjectReadFileResult | null,
@@ -49,6 +59,21 @@ vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({
59 useWorkspaceMutationRefresh: vi.fn(),
60 }));
61 vi.mock(import("./FileBreadcrumbs"), () => ({ FileBreadcrumbs: () => <></> }));
62 +vi.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 +}));
74 +vi.mock(import("../DiffWorkerPoolProvider"), () => ({
75 + DiffWorkerPoolProvider: ({ children }: { children?: ReactNode }) => <>{children}</>,
76 +}));
77 vi.mock(import("./projectFilesQueryState"), async (original) => ({
78 ...(await original()),
79 useProjectFileQuery: () => ({
@@ -82,6 +107,7 @@ function setup() {
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 {
@@ -102,12 +128,16 @@ function markdownPreview(truncated: boolean) {
128 byteLength: truncated ? 1_200_000 : 32,
129 truncated,
130 };
131 + return filePreview("tasks.md");
132 +}
133 +
134 +function filePreview(relativePath: string) {
135 return (
136 <FilePreviewPanel
137 environmentId={environmentId}
138 cwd="/workspace"
139 projectName="Project"
110 - relativePath="tasks.md"
140 + relativePath={relativePath}
141 threadRef={threadRef}
142 composerDraftTarget={threadRef}
143 keybindings={[]}
@@ -125,6 +155,94 @@ function markdownPreview(truncated: boolean) {
155 );
156 }
157
158 +function deepActiveElement() {
159 + let active = document.activeElement;
160 + while (active?.shadowRoot?.activeElement) active = active.shadowRoot.activeElement;
161 + return active;
162 +}
163 +
164 +describe("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 +
246 describe("rendered Markdown task saves", () => {
247 it("keeps a truncated read read-only without queuing a replacement", async () => {
248 using _settings = setup();
apps/web/src/components/files/FilePreviewPanel.tsx
+104 -24
@@ -57,10 +57,12 @@ import { MediaActions, type MediaActionSource } from "~/components/media/MediaAc
57 import { useRemoteOpenState } from "~/remoteOpen";
58 import { useClientSettings } from "~/hooks/useSettings";
59 import { useTheme } from "~/hooks/useTheme";
60 +import { useStableCallback } from "~/hooks/useStableCallback";
61 import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
62 import { resolveDiffThemeName } from "~/lib/diffRendering";
63 import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
64 import { cn } from "~/lib/utils";
65 +import { requestWorkspaceFocus } from "~/lib/workspaceFocus";
66 import type { ChatFileAttachment } from "~/types";
67 import { isHostPath } from "@t3tools/shared/path";
68 import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
@@ -598,6 +600,7 @@ const createFileEditor: EditorFactory<FileCommentAnnotationGroup, undefined> = (
600 options,
601 editStateKey,
602 ) => new Editor(editorType, options, editStateKey);
603 +type FileEditor = Editor<"file", FileCommentAnnotationGroup, undefined>;
604
605 function editableFileContents(
606 environmentId: EnvironmentId,
@@ -661,6 +664,7 @@ interface EditableFileSurfaceProps {
664 wordWrap: boolean;
665 onPostRender: FilePostRender;
666 onPendingChange: (relativePath: string, pending: boolean) => void;
667 + onEditorChange: (editor: FileEditor | null) => void;
668 }
669
670 interface FileSelectionOverride {
@@ -680,6 +684,7 @@ function EditableFileSurface({
684 wordWrap,
685 onPostRender,
686 onPendingChange,
687 + onEditorChange,
688 }: EditableFileSurfaceProps) {
689 const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
690 const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
@@ -705,13 +710,15 @@ function EditableFileSurface({
710 }
711 const { ready: editable, onPostRender: onEditablePostRender } =
712 useEditableAfterHighlight(externalFile);
708 - const editorRef = useRef<Editor<"file", FileCommentAnnotationGroup, undefined> | null>(null);
713 + const editorRef = useRef<FileEditor | null>(null);
714 const editorOptions: EditorOptions<"file", FileCommentAnnotationGroup, undefined> = {
715 onAttach: (editor) => {
716 editorRef.current = editor;
717 + onEditorChange(editor);
718 },
719 onComplete: () => {
720 editorRef.current = null;
721 + onEditorChange(null);
722 },
723 };
724
@@ -943,6 +950,7 @@ function RenderedMarkdownSurface({
950 | "revealRequestId"
951 | "wordWrap"
952 | "onPostRender"
953 + | "onEditorChange"
954 > & {
955 threadRef: ScopedThreadRef;
956 readOnly: boolean;
@@ -1142,6 +1150,55 @@ export default function FilePreviewPanel({
1150 !(tableDelimiter && renderTable) &&
1151 !renderBrowserFile &&
1152 !isDocument;
1153 + const mayOpenEditor =
1154 + previewPath !== null &&
1155 + !isHostFile &&
1156 + canWriteFiles &&
1157 + file.error === null &&
1158 + !file.data?.truncated &&
1159 + !isMedia &&
1160 + !isDocument &&
1161 + !renderBrowserFile &&
1162 + !renderMermaid &&
1163 + !(isMarkdown && renderMarkdown) &&
1164 + !(tableDelimiter && renderTable);
1165 + const contentFocusRef = useRef<HTMLDivElement>(null);
1166 + const fileEditorRef = useRef<FileEditor | null>(null);
1167 + const focusEditorFromContent = () => {
1168 + const editor = fileEditorRef.current;
1169 + if (!editor || document.activeElement !== contentFocusRef.current) return;
1170 + // Without a caret the editor focuses with no selection, so no caret shows and typing
1171 + // lands on whatever the browser selection held.
1172 + const hasCaret = Boolean(editor.getViewState().selections?.length);
1173 + editor.focus(
1174 + hasCaret
1175 + ? { preventScroll: true }
1176 + : { preventScroll: true, lineNumber: revealLine ?? "first-visible" },
1177 + );
1178 + };
1179 + const handleEditorChange = (editor: FileEditor | null) => {
1180 + fileEditorRef.current = editor;
1181 + focusEditorFromContent();
1182 + };
1183 + const handleEditorChangeStable = useStableCallback(handleEditorChange);
1184 + const focusEditorOnTreeRowClickOrEnter = (event: {
1185 + nativeEvent: Event;
1186 + altKey: boolean;
1187 + ctrlKey: boolean;
1188 + metaKey: boolean;
1189 + shiftKey: boolean;
1190 + }) => {
1191 + if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
1192 + const row = event.nativeEvent
1193 + .composedPath()
1194 + .find(
1195 + (node): node is Element =>
1196 + node instanceof Element && node.matches('[role="treeitem"][data-item-path]'),
1197 + );
1198 + const path = row?.getAttribute("data-item-path");
1199 + if (!path || path.endsWith("/")) return;
1200 + requestWorkspaceFocus({ area: "panel", selector: "[data-file-content-focus]" });
1201 + };
1202 const rendered = isMermaid
1203 ? renderMermaid
1204 : isMarkdown
@@ -1364,6 +1421,20 @@ export default function FilePreviewPanel({
1421 <div
1422 className={cn("min-w-0 flex-1 flex-col overflow-hidden", previewPath ? "flex" : "hidden")}
1423 >
1424 + {mayOpenEditor ? (
1425 + // Panel focus lands here and passes to the editor once it attaches. sr-only keeps the
1426 + // 1px box workspace focus needs, and clips it so clicks in the file never reach it.
1427 + // The hand-off waits a microtask: workspace focus checks that focus stayed here.
1428 + <div
1429 + ref={contentFocusRef}
1430 + tabIndex={-1}
1431 + data-workspace-focus-default
1432 + data-file-content-focus
1433 + aria-label="File contents"
1434 + className="sr-only"
1435 + onFocus={() => queueMicrotask(focusEditorFromContent)}
1436 + />
1437 + ) : null}
1438 {isFolder ? null : relativePath && attachment ? (
1439 <AttachmentFilePreview
1440 key={`${environmentId}:${attachment.id}`}
@@ -1539,6 +1610,7 @@ export default function FilePreviewPanel({
1610 wordWrap={wordWrap}
1611 onPostRender={onFilePostRender}
1612 onPendingChange={onPendingChange}
1613 + onEditorChange={handleEditorChangeStable}
1614 />
1615 </DiffWorkerPoolProvider>
1616 )
@@ -1546,29 +1618,37 @@ export default function FilePreviewPanel({
1618 </div>
1619 {showExplorer ? (
1620 <FileExplorerPane resizable={Boolean(previewPath)}>
1549 - <FileBrowserPanel
1550 - key={`${environmentId}:${hostFolderPath ?? cwd}`}
1551 - environmentId={environmentId}
1552 - cwd={hostFolderPath ?? cwd}
1553 - projectName={hostFolderPath ?? projectName}
1554 - hostFolder={hostFolderPath !== null}
1555 - selectedPath={
1556 - hostFolderPath === null
1557 - ? relativePath
1558 - : trailChildOf(hostFolderPath, breadcrumbTrail ?? hostFolderPath)
1559 - }
1560 - selectedPathRevealId={revealRequestId}
1561 - onOpenFile={onOpenFile}
1562 - workspaceMutationId={workspaceMutationId}
1563 - {...(previewPath && !isMedia && !isPdf
1564 - ? {
1565 - onRefreshSelectedFile: () => {
1566 - if (!isDocument) file.refresh();
1567 - setFileRefreshRevision((value) => value + 1);
1568 - },
1569 - }
1570 - : {})}
1571 - />
1621 + <div
1622 + className="contents"
1623 + onClick={focusEditorOnTreeRowClickOrEnter}
1624 + onKeyDown={(event) => {
1625 + if (event.key === "Enter") focusEditorOnTreeRowClickOrEnter(event);
1626 + }}
1627 + >
1628 + <FileBrowserPanel
1629 + key={`${environmentId}:${hostFolderPath ?? cwd}`}
1630 + environmentId={environmentId}
1631 + cwd={hostFolderPath ?? cwd}
1632 + projectName={hostFolderPath ?? projectName}
1633 + hostFolder={hostFolderPath !== null}
1634 + selectedPath={
1635 + hostFolderPath === null
1636 + ? relativePath
1637 + : trailChildOf(hostFolderPath, breadcrumbTrail ?? hostFolderPath)
1638 + }
1639 + selectedPathRevealId={revealRequestId}
1640 + onOpenFile={onOpenFile}
1641 + workspaceMutationId={workspaceMutationId}
1642 + {...(previewPath && !isMedia && !isPdf
1643 + ? {
1644 + onRefreshSelectedFile: () => {
1645 + if (!isDocument) file.refresh();
1646 + setFileRefreshRevision((value) => value + 1);
1647 + },
1648 + }
1649 + : {})}
1650 + />
1651 + </div>
1652 </FileExplorerPane>
1653 ) : null}
1654 </div>