Skip to content

Commit 1ab3afe

Browse files
fix(web): opening a file focuses its editor so Cmd+F searches it (pingdotgg#34360)
Co-authored-by: Julius Marminge <[email protected]>
1 parent c230078 commit 1ab3afe

2 files changed

Lines changed: 223 additions & 25 deletions

File tree

‎apps/web/src/components/files/FilePreviewPanel.browser.test.tsx‎

Lines changed: 119 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,17 @@
1+
import { DEFAULT_THEMES, preloadHighlighter } from "@pierre/diffs";
12
import { EnvironmentId, ThreadId, type ProjectReadFileResult } from "@t3tools/contracts";
23
import { AsyncResult } from "effect/reactivity";
4+
import type { ReactNode } from "react";
35
import { describe, expect, it, vi } from "vite-plus/test";
6+
import { userEvent } from "vite-plus/test/browser";
47
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";
515

616
const state = vi.hoisted(() => ({
717
file: null as ProjectReadFileResult | null,
@@ -49,6 +59,21 @@ vi.mock(import("~/hooks/useWorkspaceMutationRefresh"), () => ({
4959
useWorkspaceMutationRefresh: vi.fn(),
5060
}));
5161
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+
}));
5277
vi.mock(import("./projectFilesQueryState"), async (original) => ({
5378
...(await original()),
5479
useProjectFileQuery: () => ({
@@ -82,6 +107,7 @@ function setup() {
82107
const previous = keys.map((key) => localStorage.getItem(key));
83108
localStorage.setItem(keys[0]!, "false");
84109
localStorage.setItem(keys[1]!, "true");
110+
state.file = null;
85111
state.optimistic = null;
86112
state.writeFile.mockReset().mockResolvedValue(AsyncResult.success(undefined));
87113
return {
@@ -102,12 +128,16 @@ function markdownPreview(truncated: boolean) {
102128
byteLength: truncated ? 1_200_000 : 32,
103129
truncated,
104130
};
131+
return filePreview("tasks.md");
132+
}
133+
134+
function filePreview(relativePath: string) {
105135
return (
106136
<FilePreviewPanel
107137
environmentId={environmentId}
108138
cwd="/workspace"
109139
projectName="Project"
110-
relativePath="tasks.md"
140+
relativePath={relativePath}
111141
threadRef={threadRef}
112142
composerDraftTarget={threadRef}
113143
keybindings={[]}
@@ -125,6 +155,94 @@ function markdownPreview(truncated: boolean) {
125155
);
126156
}
127157

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+
128246
describe("rendered Markdown task saves", () => {
129247
it("keeps a truncated read read-only without queuing a replacement", async () => {
130248
using _settings = setup();

‎apps/web/src/components/files/FilePreviewPanel.tsx‎

Lines changed: 104 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -57,10 +57,12 @@ import { MediaActions, type MediaActionSource } from "~/components/media/MediaAc
5757
import { useRemoteOpenState } from "~/remoteOpen";
5858
import { useClientSettings } from "~/hooks/useSettings";
5959
import { useTheme } from "~/hooks/useTheme";
60+
import { useStableCallback } from "~/hooks/useStableCallback";
6061
import { getLocalStorageItem, setLocalStorageItem, useLocalStorage } from "~/hooks/useLocalStorage";
6162
import { resolveDiffThemeName } from "~/lib/diffRendering";
6263
import { PREFERRED_HIGHLIGHTER } from "~/lib/syntaxHighlighting";
6364
import { cn } from "~/lib/utils";
65+
import { requestWorkspaceFocus } from "~/lib/workspaceFocus";
6466
import type { ChatFileAttachment } from "~/types";
6567
import { isHostPath } from "@t3tools/shared/path";
6668
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
@@ -598,6 +600,7 @@ const createFileEditor: EditorFactory<FileCommentAnnotationGroup, undefined> = (
598600
options,
599601
editStateKey,
600602
) => new Editor(editorType, options, editStateKey);
603+
type FileEditor = Editor<"file", FileCommentAnnotationGroup, undefined>;
601604

602605
function editableFileContents(
603606
environmentId: EnvironmentId,
@@ -661,6 +664,7 @@ interface EditableFileSurfaceProps {
661664
wordWrap: boolean;
662665
onPostRender: FilePostRender;
663666
onPendingChange: (relativePath: string, pending: boolean) => void;
667+
onEditorChange: (editor: FileEditor | null) => void;
664668
}
665669

666670
interface FileSelectionOverride {
@@ -680,6 +684,7 @@ function EditableFileSurface({
680684
wordWrap,
681685
onPostRender,
682686
onPendingChange,
687+
onEditorChange,
683688
}: EditableFileSurfaceProps) {
684689
const addReviewComment = useComposerDraftStore((store) => store.addReviewComment);
685690
const removeReviewComment = useComposerDraftStore((store) => store.removeReviewComment);
@@ -705,13 +710,15 @@ function EditableFileSurface({
705710
}
706711
const { ready: editable, onPostRender: onEditablePostRender } =
707712
useEditableAfterHighlight(externalFile);
708-
const editorRef = useRef<Editor<"file", FileCommentAnnotationGroup, undefined> | null>(null);
713+
const editorRef = useRef<FileEditor | null>(null);
709714
const editorOptions: EditorOptions<"file", FileCommentAnnotationGroup, undefined> = {
710715
onAttach: (editor) => {
711716
editorRef.current = editor;
717+
onEditorChange(editor);
712718
},
713719
onComplete: () => {
714720
editorRef.current = null;
721+
onEditorChange(null);
715722
},
716723
};
717724

@@ -943,6 +950,7 @@ function RenderedMarkdownSurface({
943950
| "revealRequestId"
944951
| "wordWrap"
945952
| "onPostRender"
953+
| "onEditorChange"
946954
> & {
947955
threadRef: ScopedThreadRef;
948956
readOnly: boolean;
@@ -1142,6 +1150,55 @@ export default function FilePreviewPanel({
11421150
!(tableDelimiter && renderTable) &&
11431151
!renderBrowserFile &&
11441152
!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+
};
11451202
const rendered = isMermaid
11461203
? renderMermaid
11471204
: isMarkdown
@@ -1364,6 +1421,20 @@ export default function FilePreviewPanel({
13641421
<div
13651422
className={cn("min-w-0 flex-1 flex-col overflow-hidden", previewPath ? "flex" : "hidden")}
13661423
>
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}
13671438
{isFolder ? null : relativePath && attachment ? (
13681439
<AttachmentFilePreview
13691440
key={`${environmentId}:${attachment.id}`}
@@ -1539,36 +1610,45 @@ export default function FilePreviewPanel({
15391610
wordWrap={wordWrap}
15401611
onPostRender={onFilePostRender}
15411612
onPendingChange={onPendingChange}
1613+
onEditorChange={handleEditorChangeStable}
15421614
/>
15431615
</DiffWorkerPoolProvider>
15441616
)
15451617
) : null}
15461618
</div>
15471619
{showExplorer ? (
15481620
<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>
15721652
</FileExplorerPane>
15731653
) : null}
15741654
</div>

0 commit comments

Comments
 (0)