Skip to content

Commit 271ece4

Browse files
fix(desktop): Cmd/Ctrl+F searches rendered HTML in the file preview
A workspace HTML file renders in a sandboxed opaque-origin iframe, so the renderer can neither read its text nor see a Cmd/Ctrl+F pressed inside it, and Electron has no page find to fall back on. The renderer now names that iframe. The desktop shell catches Cmd/Ctrl+F when focus is inside a frame with that name and asks the renderer to open the file find bar. Typing in the bar runs the search inside the frame through the main process, which paints highlights there and returns the match count. Browsers keep their native page find, which already reaches the frame. AI-assisted; verified with the tests and tools listed above.
1 parent 1a719dd commit 271ece4

10 files changed

Lines changed: 315 additions & 60 deletions

File tree

‎apps/desktop/src/ipc/DesktopIpcHandlers.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import {
4848
pasteAsText,
4949
probeRemoteEditors,
5050
revealWindow,
51+
findInFrame,
5152
pickFolder,
5253
pickProjectFavicon,
5354
pickThemeFiles,
@@ -155,6 +156,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
155156
yield* ipc.handle(checkSystemPermission);
156157
yield* ipc.handle(pasteAsText);
157158
yield* ipc.handle(revealWindow);
159+
yield* ipc.handle(findInFrame);
158160
yield* ipc.handle(syncHtmlFullscreen);
159161
yield* ipc.handle(probeRemoteEditors);
160162
yield* ipc.handle(getUpdateState);

‎apps/desktop/src/ipc/channels.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ export const SNAP_SHOT_EVENT_CHANNEL = "desktop:snap-shot-event";
1515
export const WEB_LINK_OPEN_CHANNEL = "desktop:web-link-open";
1616
export const WEB_LINK_READY_CHANNEL = "desktop:web-link-ready";
1717
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
18+
export const FRAME_FIND_REQUEST_CHANNEL = "desktop:frame-find-request";
19+
export const FIND_IN_FRAME_CHANNEL = "desktop:find-in-frame";
1820
export const TRACKPAD_SCROLL_BEGIN_CHANNEL = "desktop:trackpad-scroll-begin";
1921
export const TRACKPAD_SCROLL_END_CHANNEL = "desktop:trackpad-scroll-end";
2022
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";

‎apps/desktop/src/ipc/methods/window.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import * as Electron from "electron";
4242
import * as MacPermissions from "../../permissions/MacPermissions.ts";
4343
import { safariPermissionCheck } from "../../preview/BrowserImport/SafariPermission.ts";
4444
import * as IpcChannels from "../channels.ts";
45+
import { findFrameByName, frameFindScript } from "../../window/FrameFind.ts";
4546
import * as DesktopIpc from "../DesktopIpc.ts";
4647
import {
4748
extractDistroFromUncPath,
@@ -451,6 +452,35 @@ export const revealWindow = DesktopIpc.makeIpcMethod({
451452
}),
452453
});
453454

455+
export const findInFrame = DesktopIpc.makeIpcMethod({
456+
channel: IpcChannels.FIND_IN_FRAME_CHANNEL,
457+
payload: Schema.Struct({
458+
frameName: Schema.String,
459+
query: Schema.String.check(Schema.isMaxLength(200)),
460+
index: Schema.Number,
461+
}),
462+
result: Schema.Number,
463+
handler: Effect.fn("desktop.ipc.window.findInFrame")(function* (input, event) {
464+
const electronWindow = yield* ElectronWindow.ElectronWindow;
465+
const window = yield* electronWindow.main;
466+
if (
467+
event === undefined ||
468+
Option.isNone(window) ||
469+
window.value.isDestroyed() ||
470+
window.value.webContents.id !== event.sender.id
471+
) {
472+
return 0;
473+
}
474+
const frame = findFrameByName(window.value.webContents, input.frameName);
475+
if (frame === undefined) return 0;
476+
const count: unknown = yield* Effect.promise(() =>
477+
frame.executeJavaScript(frameFindScript(input.query, input.index)).catch(() => 0),
478+
);
479+
// The page can replace the globals the script uses, so the count is untrusted.
480+
return typeof count === "number" && Number.isSafeInteger(count) && count > 0 ? count : 0;
481+
}),
482+
});
483+
454484
const htmlFullscreenStates = new WeakMap<
455485
Electron.BrowserWindow,
456486
{ owned: boolean; leaving: boolean }

‎apps/desktop/src/preload.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,15 @@ contextBridge.exposeInMainWorld("desktopBridge", {
115115
return () => ipcRenderer.removeListener(IpcChannels.TRACKPAD_SCROLL_END_CHANNEL, handler);
116116
},
117117
revealWindow: () => ipcRenderer.invoke(IpcChannels.REVEAL_WINDOW_CHANNEL),
118+
findInFrame: (frameName, query, index) =>
119+
ipcRenderer.invoke(IpcChannels.FIND_IN_FRAME_CHANNEL, { frameName, query, index }),
120+
onFrameFindRequest: (listener) => {
121+
const handler = (_event: Electron.IpcRendererEvent, frameName: unknown) => {
122+
if (typeof frameName === "string") listener(frameName);
123+
};
124+
ipcRenderer.on(IpcChannels.FRAME_FIND_REQUEST_CHANNEL, handler);
125+
return () => ipcRenderer.removeListener(IpcChannels.FRAME_FIND_REQUEST_CHANNEL, handler);
126+
},
118127
getSystemLocale: () => {
119128
const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL);
120129
return typeof result === "string" ? result : null;

‎apps/desktop/src/window/DesktopWindow.test.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ import * as ElectronMenu from "../electron/ElectronMenu.ts";
4545
import * as ElectronShell from "../electron/ElectronShell.ts";
4646
import * as ElectronTheme from "../electron/ElectronTheme.ts";
4747
import * as ElectronWindow from "../electron/ElectronWindow.ts";
48-
import { SNAP_SHOT_EVENT_CHANNEL } from "../ipc/channels.ts";
48+
import { FRAME_FIND_REQUEST_CHANNEL, SNAP_SHOT_EVENT_CHANNEL } from "../ipc/channels.ts";
4949
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
5050
import * as DesktopWindow from "./DesktopWindow.ts";
5151
import * as PreviewManager from "../preview/Manager.ts";
@@ -67,7 +67,10 @@ function makeFakeBrowserWindow() {
6767
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
6868
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
6969
let zoomLevel = 0;
70+
const mainFrame = { name: "", parent: null };
7071
const webContents = {
72+
mainFrame,
73+
focusedFrame: mainFrame as { name: string; parent: unknown } | null,
7174
copyImageAt: vi.fn(),
7275
focus: vi.fn(),
7376
isDestroyed: vi.fn(() => false),
@@ -152,6 +155,7 @@ function makeFakeBrowserWindow() {
152155
setAutoHideCursor: window.setAutoHideCursor,
153156
setFullScreen: window.setFullScreen,
154157
setOpacity: window.setOpacity,
158+
webContents,
155159
webContentsListeners,
156160
webContentsOnce: webContents.once,
157161
windowListeners,
@@ -697,6 +701,44 @@ describe("DesktopWindow", () => {
697701
}),
698702
);
699703

704+
it.effect("routes Cmd+F inside a named file-preview frame to the renderer", () =>
705+
Effect.gen(function* () {
706+
const fakeWindow = makeFakeBrowserWindow();
707+
const createCount = yield* Ref.make(0);
708+
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
709+
const layer = layerTest({ window: fakeWindow.window, createCount, mainWindow });
710+
711+
yield* Effect.gen(function* () {
712+
const desktopWindow = yield* DesktopWindow.DesktopWindow;
713+
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
714+
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
715+
if (!beforeInput) {
716+
return yield* Effect.die("before-input-event listener was not registered");
717+
}
718+
const { webContents } = fakeWindow;
719+
const preview = { name: "t3-file-find-r1", parent: webContents.mainFrame };
720+
const press = (frame: typeof webContents.focusedFrame, meta = true) => {
721+
let prevented = false;
722+
webContents.focusedFrame = frame;
723+
beforeInput(
724+
{ preventDefault: () => (prevented = true) },
725+
{ type: "keyDown", key: "f", meta, control: false, alt: false, shift: false },
726+
);
727+
return prevented;
728+
};
729+
730+
assert.isFalse(press(webContents.mainFrame));
731+
assert.isFalse(press({ name: "page-frame", parent: webContents.mainFrame }));
732+
assert.isFalse(press(preview, false));
733+
assert.isTrue(press({ name: "", parent: preview }));
734+
assert.deepEqual(
735+
fakeWindow.send.mock.calls.filter(([channel]) => channel === FRAME_FIND_REQUEST_CHANNEL),
736+
[[FRAME_FIND_REQUEST_CHANNEL, "t3-file-find-r1"]],
737+
);
738+
}).pipe(Effect.provide(layer));
739+
}),
740+
);
741+
700742
// Chromium hands the main window's zoom level down to embedded preview
701743
// guests, so every app zoom has to put the preview browser back at its own
702744
// zoom or zooming the UI drags the previewed page with it.

‎apps/desktop/src/window/DesktopWindow.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import * as ElectronShell from "../electron/ElectronShell.ts";
2222
import * as ElectronTheme from "../electron/ElectronTheme.ts";
2323
import * as ElectronWindow from "../electron/ElectronWindow.ts";
2424
import {
25+
FRAME_FIND_REQUEST_CHANNEL,
2526
MENU_ACTION_CHANNEL,
2627
QUIT_SHORTCUT_CHANNEL,
2728
SNAP_SHOT_EVENT_CHANNEL,
@@ -38,6 +39,7 @@ import * as ElectronApp from "../electron/ElectronApp.ts";
3839
import * as DesktopRendererHistory from "../telemetry/DesktopRendererHistory.ts";
3940
import { makeQuitShortcutHandler } from "./QuitHold.ts";
4041
import { copyContextMenuImage } from "./ContextMenuImage.ts";
42+
import { FIND_FRAME_NAME_PREFIX, isFindShortcut } from "./FrameFind.ts";
4143

4244
const TITLEBAR_HEIGHT = 40;
4345

@@ -705,6 +707,18 @@ export const make = Effect.gen(function* () {
705707
});
706708
window.webContents.on("before-input-event", (event, input) => {
707709
quitShortcutHandler(event, input);
710+
// Opaque-origin file previews cannot forward Cmd/Ctrl+F, and Electron has no page find.
711+
if (isFindShortcut(input, environment.platform)) {
712+
const main = window.webContents.mainFrame;
713+
for (let frame = window.webContents.focusedFrame; frame && frame !== main;) {
714+
if (frame.name.startsWith(FIND_FRAME_NAME_PREFIX)) {
715+
event.preventDefault();
716+
window.webContents.send(FRAME_FIND_REQUEST_CHANNEL, frame.name);
717+
break;
718+
}
719+
frame = frame.parent;
720+
}
721+
}
708722
// Cmd/Ctrl+W reaches the renderer; DevTools uses the native menu shortcut.
709723
window.webContents.setIgnoreMenuShortcuts(
710724
(environment.platform === "darwin" ? input.meta : input.control) &&
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import type * as Electron from "electron";
2+
3+
/** Names the renderer gives iframes it searches, so a page cannot opt the app shell in. */
4+
export const FIND_FRAME_NAME_PREFIX = "t3-file-find-";
5+
6+
export const isFindShortcut = (input: Electron.Input, platform: NodeJS.Platform): boolean =>
7+
input.type === "keyDown" &&
8+
(platform === "darwin" ? input.meta : input.control) &&
9+
!input.alt &&
10+
!input.shift &&
11+
input.key.toLowerCase() === "f";
12+
13+
// Runs inside the opaque-origin frame, which the renderer cannot reach; an empty query clears it.
14+
export const frameFindScript = (query: string, index: number): string =>
15+
`(() => {
16+
const H = typeof CSS !== "undefined" && CSS.highlights;
17+
if (!H || typeof Highlight === "undefined") return 0;
18+
H.delete("t3-file-find");
19+
H.delete("t3-file-find-active");
20+
const q = ${JSON.stringify(query.toLowerCase())};
21+
if (q.length === 0) return 0;
22+
if (!document.getElementById("t3-file-find-style")) {
23+
const style = document.createElement("style");
24+
style.id = "t3-file-find-style";
25+
style.textContent = "::highlight(t3-file-find){background:oklch(0.915 0.11 85);color:oklch(0.216 0.028 77.4)}::highlight(t3-file-find-active){background:oklch(0.8 0.16 70);color:oklch(0.216 0.028 77.4)}";
26+
(document.head || document.documentElement).append(style);
27+
}
28+
const ranges = [];
29+
const walker = document.createTreeWalker(document.body || document.documentElement, NodeFilter.SHOW_TEXT, {
30+
acceptNode: (node) => /^(?:SCRIPT|STYLE|NOSCRIPT|TEMPLATE)$/.test(node.parentNode.nodeName) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT,
31+
});
32+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
33+
const text = node.data.toLowerCase();
34+
for (let at = text.indexOf(q); at >= 0; at = text.indexOf(q, at + q.length)) {
35+
const range = new Range();
36+
range.setStart(node, at);
37+
range.setEnd(node, at + q.length);
38+
ranges.push(range);
39+
}
40+
}
41+
if (ranges.length === 0) return 0;
42+
const active = ranges[Math.min(${Math.max(0, Math.trunc(index))}, ranges.length - 1)];
43+
H.set("t3-file-find", new Highlight(...ranges.filter((range) => range !== active)));
44+
H.set("t3-file-find-active", new Highlight(active));
45+
active.startContainer.parentElement?.scrollIntoView({ block: "nearest" });
46+
return ranges.length;
47+
})()`;
48+
49+
export const findFrameByName = (
50+
contents: Electron.WebContents,
51+
frameName: string,
52+
): Electron.WebFrameMain | undefined => {
53+
if (!frameName.startsWith(FIND_FRAME_NAME_PREFIX)) return undefined;
54+
const main = contents.mainFrame;
55+
return main.framesInSubtree.find((frame) => frame !== main && frame.name === frameName);
56+
};

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

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
} from "react";
3434
import { isElectron } from "~/env";
3535
import { FileSurfaceLoading } from "./fileSurfaceChrome";
36+
import { FrameFileFind } from "./RenderedFileFind";
3637
import type { PdfViewState } from "./PdfViewer";
3738

3839
import { useOpenLink } from "~/browser/useOpenLink";
@@ -165,12 +166,17 @@ export function BrowserDocumentFrame(props: {
165166
function FileDocument(props: { readonly src: string; readonly title: string }) {
166167
const [src] = useState(props.src);
167168
return (
168-
<iframe
169-
src={src}
170-
title={props.title}
171-
className="min-h-0 flex-1 border-0 bg-white"
172-
sandbox="allow-scripts allow-forms allow-popups allow-downloads"
173-
/>
169+
<FrameFileFind>
170+
{(frameName) => (
171+
<iframe
172+
src={src}
173+
name={frameName}
174+
title={props.title}
175+
className="min-h-0 flex-1 border-0 bg-white"
176+
sandbox="allow-scripts allow-forms allow-popups allow-downloads"
177+
/>
178+
)}
179+
</FrameFileFind>
174180
);
175181
}
176182

0 commit comments

Comments
 (0)