diff --git a/apps/desktop/src/preview/FramePickAgent.ts b/apps/desktop/src/preview/FramePickAgent.ts new file mode 100644 index 0000000000000..bce983d95ce07 --- /dev/null +++ b/apps/desktop/src/preview/FramePickAgent.ts @@ -0,0 +1,628 @@ +export const FRAME_PICK_MESSAGE_KEY = "__t3codeFramePick"; +export const FRAME_PICK_COMMAND_CHANNEL = "preview:frame-pick-command"; +export const FRAME_PICK_ESCAPE_CHANNEL = "preview:frame-pick-escape"; + +export interface FramePickRect { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; +} + +export interface FramePickSize { + readonly width: number; + readonly height: number; +} + +export interface FramePickHit { + readonly id: string | null; + readonly label: string; + readonly visibleRect: FramePickRect; + readonly unclippedSize: FramePickSize; +} + +export interface FramePickCapture { + readonly selector: string; + readonly htmlPreview: string; + readonly tagName: string; +} + +export type FramePickCommand = + | { readonly kind: "capture"; readonly id: string } + | { readonly kind: "describe"; readonly id: string } + | { + readonly kind: "style"; + readonly id: string; + readonly property: string; + readonly value: string; + } + | { readonly kind: "restore"; readonly id: string }; + +export type FramePickPointerType = "pointermove" | "pointerdown" | "pointerup" | "pointerout"; + +export interface FramePickElementBox { + readonly id: string; + readonly visibleRect: FramePickRect; + readonly unclippedSize: FramePickSize; +} + +export type FramePickUp = + | { readonly kind: "hello" } + | { + readonly kind: "pointer"; + readonly type: FramePickPointerType; + readonly x: number; + readonly y: number; + readonly button: number; + readonly shiftKey: boolean; + readonly hit: FramePickHit | null; + } + | { readonly kind: "key"; readonly key: string } + | { readonly kind: "rects"; readonly rects: ReadonlyArray }; + +export type FramePickDown = + | { readonly kind: "start" } + | { readonly kind: "stop" } + | { readonly kind: "refresh" }; + +export interface FramePickDelivery { + readonly up: FramePickUp; + readonly framePathsOutermostFirst: ReadonlyArray; + readonly senderDocumentToken: string | null; +} + +export interface FramePickRelay { + readonly send: (down: FramePickDown) => void; + readonly dispose: () => void; + readonly runCommandForDocument: (documentToken: string, command: FramePickCommand) => unknown; +} + +// Main injects this function's source text into subframes, so it must not reference anything +// outside its own body. +export function installFramePickAgent( + key: string, + deliver?: (delivery: FramePickDelivery) => void, + documentToken: string | null = null, +): FramePickRelay { + const registry = window as unknown as Record; + const replaceAgentWhoseStopIsStillInFlight = (): void => registry[key]?.dispose(); + if (!deliver) replaceAgentWhoseStopIsStillInFlight(); + + const styleProperties = [ + "font-family", + "font-size", + "font-weight", + "line-height", + "color", + "background-color", + "border-color", + "border-width", + "border-style", + "border-radius", + "opacity", + "padding", + "margin", + "gap", + "width", + "height", + ]; + const toolKeys = new Set(["Escape", "v", "r", "d", "e"]); + const elementsById = new Map(); + let idsByElement = new WeakMap(); + const styleAttributeBeforeFirstEdit = new Map(); + let lastId = 0; + let active = false; + let cursorStyle: HTMLStyleElement | null = null; + + // Frames inside open shadow roots count too. The walk is cached and redone on a lookup miss + // so per-pointermove relays do not rescan the whole document. + let frameCache: HTMLIFrameElement[] | null = null; + const scanFrames = (): HTMLIFrameElement[] => { + const found: HTMLIFrameElement[] = []; + const visit = (root: Document | ShadowRoot): void => { + for (const element of Array.from(root.querySelectorAll("*"))) { + if (element instanceof HTMLIFrameElement || element.tagName === "FRAME") + found.push(element as HTMLIFrameElement); + if (element.shadowRoot) visit(element.shadowRoot); + } + }; + visit(document); + frameCache = found; + return found; + }; + const childFrames = (): HTMLIFrameElement[] => frameCache ?? scanFrames(); + + const post = (target: Window | null | undefined, envelope: unknown): void => { + if (!target) return; + try { + target.postMessage({ [key]: envelope }, "*"); + } catch {} + }; + + const cssPath = (element: Element): string => { + const parts: string[] = []; + for ( + let node: Element | null = element; + node && node !== document.documentElement && node !== document.body; + node = node.parentElement + ) { + if (node.id) { + parts.unshift(`#${CSS.escape(node.id)}`); + break; + } + const tagName = node.tagName; + const siblings = node.parentElement + ? Array.from(node.parentElement.children).filter((child) => child.tagName === tagName) + : []; + const tag = tagName.toLowerCase(); + parts.unshift( + siblings.length > 1 ? `${tag}:nth-of-type(${siblings.indexOf(node) + 1})` : tag, + ); + } + return parts.join(" > "); + }; + + const describe = (element: Element): string => { + const id = element.id ? `#${element.id}` : ""; + const classes = + typeof element.className === "string" + ? element.className + .trim() + .split(/\s+/) + .filter(Boolean) + .slice(0, 2) + .map((name) => `.${name}`) + .join("") + : ""; + return `${element.tagName.toLowerCase()}${id}${classes}`; + }; + + const intersect = (rect: FramePickRect, bounds: FramePickRect): FramePickRect => { + const left = Math.max(rect.x, bounds.x); + const top = Math.max(rect.y, bounds.y); + const right = Math.min(rect.x + rect.width, bounds.x + bounds.width); + const bottom = Math.min(rect.y + rect.height, bounds.y + bounds.height); + return { x: left, y: top, width: Math.max(0, right - left), height: Math.max(0, bottom - top) }; + }; + + const isNumber = (value: unknown): value is number => + typeof value === "number" && Number.isFinite(value); + const isRect = (value: unknown): value is FramePickRect => { + const rect = value as Partial | null; + return ( + typeof rect === "object" && + rect !== null && + isNumber(rect.x) && + isNumber(rect.y) && + isNumber(rect.width) && + isNumber(rect.height) + ); + }; + const isSize = (value: unknown): value is FramePickSize => { + const size = value as Partial | null; + return ( + typeof size === "object" && size !== null && isNumber(size.width) && isNumber(size.height) + ); + }; + + const transformScale = (element: HTMLElement, box: DOMRect): { sx: number; sy: number } => ({ + sx: element.offsetWidth ? box.width / element.offsetWidth : 1, + sy: element.offsetHeight ? box.height / element.offsetHeight : 1, + }); + + const parentAcrossShadowRoots = (element: Element): Element | null => { + if (element.parentElement) return element.parentElement; + const root = element.getRootNode(); + return root instanceof ShadowRoot ? root.host : null; + }; + + const viewportRect = (): FramePickRect => ({ + x: 0, + y: 0, + width: document.documentElement.clientWidth, + height: document.documentElement.clientHeight, + }); + + const clipByOverflowAncestor = (clip: FramePickRect, ancestor: HTMLElement): FramePickRect => { + const style = getComputedStyle(ancestor); + const clipsX = style.overflowX !== "visible"; + const clipsY = style.overflowY !== "visible"; + if (!clipsX && !clipsY) return clip; + const box = ancestor.getBoundingClientRect(); + const { sx, sy } = transformScale(ancestor, box); + return intersect(clip, { + x: clipsX ? box.left + ancestor.clientLeft * sx : clip.x, + y: clipsY ? box.top + ancestor.clientTop * sy : clip.y, + width: clipsX ? ancestor.clientWidth * sx : clip.width, + height: clipsY ? ancestor.clientHeight * sy : clip.height, + }); + }; + + const visibleAreaFor = (element: Element): FramePickRect => { + let clip = viewportRect(); + for ( + let ancestor = parentAcrossShadowRoots(element); + ancestor && ancestor !== document.documentElement && ancestor !== document.body; + ancestor = parentAcrossShadowRoots(ancestor) + ) { + if (ancestor instanceof HTMLElement) clip = clipByOverflowAncestor(clip, ancestor); + } + return clip; + }; + + const elementBox = (element: Element): Omit => { + if (!element.isConnected) { + return { + visibleRect: { x: 0, y: 0, width: 0, height: 0 }, + unclippedSize: { width: 0, height: 0 }, + }; + } + const box = element.getBoundingClientRect(); + return { + visibleRect: intersect( + { x: box.left, y: box.top, width: box.width, height: box.height }, + visibleAreaFor(element), + ), + unclippedSize: { width: box.width, height: box.height }, + }; + }; + + interface ChildDocumentPlacement { + readonly originX: number; + readonly originY: number; + readonly scaleX: number; + readonly scaleY: number; + readonly visibleArea: FramePickRect; + } + + const childDocumentPlacement = (frame: HTMLIFrameElement): ChildDocumentPlacement => { + const box = frame.getBoundingClientRect(); + const style = getComputedStyle(frame); + const { sx, sy } = transformScale(frame, box); + const paddingLeft = Number.parseFloat(style.paddingLeft) || 0; + const paddingTop = Number.parseFloat(style.paddingTop) || 0; + const paddingRight = Number.parseFloat(style.paddingRight) || 0; + const paddingBottom = Number.parseFloat(style.paddingBottom) || 0; + const originX = box.left + (frame.clientLeft + paddingLeft) * sx; + const originY = box.top + (frame.clientTop + paddingTop) * sy; + const contentBox = { + x: originX, + y: originY, + width: (frame.clientWidth - paddingLeft - paddingRight) * sx, + height: (frame.clientHeight - paddingTop - paddingBottom) * sy, + }; + return { + originX, + originY, + scaleX: sx, + scaleY: sy, + visibleArea: intersect(contentBox, visibleAreaFor(frame)), + }; + }; + + const placeRect = (rect: FramePickRect, placement: ChildDocumentPlacement): FramePickRect => + intersect( + { + x: placement.originX + rect.x * placement.scaleX, + y: placement.originY + rect.y * placement.scaleY, + width: rect.width * placement.scaleX, + height: rect.height * placement.scaleY, + }, + placement.visibleArea, + ); + const placeSize = (size: FramePickSize, placement: ChildDocumentPlacement): FramePickSize => ({ + width: size.width * placement.scaleX, + height: size.height * placement.scaleY, + }); + + const placeValidHit = (hit: unknown, placement: ChildDocumentPlacement): FramePickHit | null => { + const candidate = hit as Partial | null; + if (!candidate || typeof candidate !== "object" || typeof candidate.label !== "string") + return null; + if (!isRect(candidate.visibleRect) || !isSize(candidate.unclippedSize)) return null; + return { + id: typeof candidate.id === "string" ? candidate.id : null, + label: candidate.label, + visibleRect: placeRect(candidate.visibleRect, placement), + unclippedSize: placeSize(candidate.unclippedSize, placement), + }; + }; + + const placeValidBoxes = ( + boxes: unknown, + placement: ChildDocumentPlacement, + ): FramePickElementBox[] | null => { + if (!Array.isArray(boxes)) return null; + return boxes.flatMap((entry: unknown) => { + const candidate = entry as Partial | null; + if (!candidate || typeof candidate.id !== "string") return []; + if (!isRect(candidate.visibleRect) || !isSize(candidate.unclippedSize)) return []; + return [ + { + id: candidate.id, + visibleRect: placeRect(candidate.visibleRect, placement), + unclippedSize: placeSize(candidate.unclippedSize, placement), + }, + ]; + }); + }; + + const placeChildMessage = ( + up: FramePickUp, + placement: ChildDocumentPlacement, + ): FramePickUp | null => { + if (up.kind === "pointer") { + if (!isNumber(up.x) || !isNumber(up.y)) return null; + return { + ...up, + x: placement.originX + up.x * placement.scaleX, + y: placement.originY + up.y * placement.scaleY, + hit: placeValidHit(up.hit, placement), + }; + } + if (up.kind === "rects") { + const rects = placeValidBoxes(up.rects, placement); + return rects ? { kind: "rects", rects } : null; + } + return up; + }; + + const sendUp = ( + up: FramePickUp, + framePathsOutermostFirst: ReadonlyArray = [], + senderDocumentToken: string | null = documentToken, + ): void => { + const delivery = { up, framePathsOutermostFirst, senderDocumentToken }; + if (deliver) deliver(delivery); + else post(window.parent, delivery); + }; + + const sendDown = (frame: HTMLIFrameElement, down: FramePickDown): void => + post(frame.contentWindow, { down }); + + const broadcast = (down: FramePickDown): void => { + for (const frame of down.kind === "refresh" ? childFrames() : scanFrames()) + sendDown(frame, down); + }; + + const register = (element: Element): string => { + const known = idsByElement.get(element); + if (known && elementsById.get(known) === element) return known; + lastId += 1; + const id = String(lastId); + idsByElement.set(element, id); + elementsById.set(id, element); + return id; + }; + + const hitAt = (x: number, y: number, selecting: boolean): FramePickHit | null => { + const element = document + .elementsFromPoint(x, y) + .find((candidate) => candidate !== document.documentElement && candidate !== document.body); + if (!element) return null; + return { + id: selecting ? register(element) : null, + label: describe(element), + ...elementBox(element), + }; + }; + + const reportRects = (): void => { + if (elementsById.size === 0) return; + sendUp({ + kind: "rects", + rects: Array.from(elementsById, ([id, element]) => ({ id, ...elementBox(element) })), + }); + }; + + const styleTarget = (id: string): HTMLElement | SVGElement | null => { + const element = elementsById.get(id); + return element instanceof HTMLElement || element instanceof SVGElement ? element : null; + }; + + const restore = (id: string): void => { + const element = styleTarget(id); + if (!element || !styleAttributeBeforeFirstEdit.has(id)) return; + const original = styleAttributeBeforeFirstEdit.get(id) ?? null; + if (original === null) element.removeAttribute("style"); + else element.setAttribute("style", original); + styleAttributeBeforeFirstEdit.delete(id); + reportRects(); + }; + + const applyStyle = (id: string, property: string, value: string): void => { + const element = styleTarget(id); + if (!element) return; + if (!styleAttributeBeforeFirstEdit.has(id)) + styleAttributeBeforeFirstEdit.set(id, element.getAttribute("style")); + element.style.setProperty(property, value, "important"); + reportRects(); + }; + + const computedStyles = (element: Element): Record => { + const computed = getComputedStyle(element); + return Object.fromEntries( + styleProperties.map((property) => [property, computed.getPropertyValue(property)]), + ); + }; + + const captureWithFreshRect = (element: Element): FramePickCapture => { + reportRects(); + return { + selector: cssPath(element), + htmlPreview: element.outerHTML.slice(0, 500), + tagName: element.tagName.toLowerCase(), + }; + }; + + const runCommand = (command: FramePickCommand): unknown => { + if (command.kind === "style") { + applyStyle(command.id, command.property, command.value); + return null; + } + if (command.kind === "restore") { + restore(command.id); + return null; + } + const element = elementsById.get(command.id); + if (!element) return null; + return command.kind === "describe" ? computedStyles(element) : captureWithFreshRect(element); + }; + + const onPointer = (event: PointerEvent): void => { + if (!event.isTrusted) return; + const type = event.type as FramePickPointerType; + if (type === "pointerout" && event.relatedTarget !== null) return; + if ((type === "pointerdown" || type === "pointerup") && event.button === 0) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + sendUp({ + kind: "pointer", + type, + x: event.clientX, + y: event.clientY, + button: event.button, + shiftKey: event.shiftKey, + hit: + type === "pointerout" ? null : hitAt(event.clientX, event.clientY, type === "pointerdown"), + }); + }; + + const onClick = (event: MouseEvent): void => { + if (!event.isTrusted) return; + event.preventDefault(); + event.stopImmediatePropagation(); + }; + + const escapeEndsTheSessionThroughMainOnly = (pressed: string): boolean => pressed === "Escape"; + + const onKey = (event: KeyboardEvent): void => { + if (!event.isTrusted || event.isComposing || event.metaKey || event.ctrlKey || event.altKey) + return; + if (!toolKeys.has(event.key)) return; + event.preventDefault(); + event.stopImmediatePropagation(); + if (!escapeEndsTheSessionThroughMainOnly(event.key)) sendUp({ kind: "key", key: event.key }); + }; + + const onLayoutChange = (): void => { + reportRects(); + broadcast({ kind: "refresh" }); + }; + + const pointerTypes: ReadonlyArray = [ + "pointermove", + "pointerdown", + "pointerup", + "pointerout", + ]; + + const activate = (): void => { + if (active) return; + active = true; + for (const type of pointerTypes) window.addEventListener(type, onPointer, true); + window.addEventListener("click", onClick, true); + window.addEventListener("keydown", onKey, true); + window.addEventListener("scroll", onLayoutChange, { capture: true, passive: true }); + window.addEventListener("resize", onLayoutChange, { passive: true }); + cursorStyle = document.createElement("style"); + cursorStyle.textContent = "html, html * { cursor: crosshair !important; }"; + document.documentElement.appendChild(cursorStyle); + }; + + const deactivate = (): void => { + if (!active) return; + active = false; + for (const type of pointerTypes) window.removeEventListener(type, onPointer, true); + window.removeEventListener("click", onClick, true); + window.removeEventListener("keydown", onKey, true); + window.removeEventListener("scroll", onLayoutChange, true); + window.removeEventListener("resize", onLayoutChange); + cursorStyle?.remove(); + cursorStyle = null; + for (const id of Array.from(styleAttributeBeforeFirstEdit.keys())) restore(id); + elementsById.clear(); + idsByElement = new WeakMap(); + }; + + const route = (down: FramePickDown): void => { + if (!deliver) { + if (down.kind === "start") activate(); + else if (down.kind === "stop") deactivate(); + else reportRects(); + } + broadcast(down); + // Main injects a fresh agent into every frame when the next session starts. + if (down.kind === "stop") relay.dispose(); + }; + + const senderFrame = (source: MessageEventSource | null): HTMLIFrameElement | undefined => { + const isSender = (frame: HTMLIFrameElement): boolean => frame.contentWindow === source; + return childFrames().find(isSender) ?? scanFrames().find(isSender); + }; + + const relayChildMessage = ( + event: MessageEvent, + envelope: { + up: FramePickUp; + framePathsOutermostFirst?: unknown; + senderDocumentToken?: unknown; + }, + ): void => { + const frame = senderFrame(event.source); + if (!frame) return; + if (envelope.up.kind === "hello") { + if (deliver || active) sendDown(frame, { kind: "start" }); + return; + } + const placed = placeChildMessage(envelope.up, childDocumentPlacement(frame)); + if (!placed) return; + const innerPaths = Array.isArray(envelope.framePathsOutermostFirst) + ? envelope.framePathsOutermostFirst.filter((path): path is string => typeof path === "string") + : []; + sendUp( + placed, + [cssPath(frame), ...innerPaths], + typeof envelope.senderDocumentToken === "string" ? envelope.senderDocumentToken : null, + ); + }; + + const onMessage = (event: MessageEvent): void => { + const envelope = (event.data as Record | null)?.[key] as + | { + up?: FramePickUp; + down?: { kind?: unknown }; + framePathsOutermostFirst?: unknown; + senderDocumentToken?: unknown; + } + | undefined; + if (!envelope || typeof envelope !== "object") return; + if (envelope.up && typeof envelope.up === "object") { + relayChildMessage(event, { ...envelope, up: envelope.up }); + return; + } + if (envelope.down && !deliver && event.source === window.parent) { + const kind = envelope.down.kind; + if (kind === "start" || kind === "stop" || kind === "refresh") route({ kind }); + } + }; + + window.addEventListener("message", onMessage); + const relay: FramePickRelay = { + send: (down) => route(down), + dispose: () => { + window.removeEventListener("message", onMessage); + if (deliver) return; + deactivate(); + if (registry[key] === relay) delete registry[key]; + }, + runCommandForDocument: (token, command) => + documentToken !== null && token === documentToken && active ? runCommand(command) : null, + }; + if (!deliver) { + Object.defineProperty(registry, key, { value: relay, configurable: true }); + sendUp({ kind: "hello" }); + } + return relay; +} diff --git a/apps/desktop/src/preview/FramePickInjection.ts b/apps/desktop/src/preview/FramePickInjection.ts new file mode 100644 index 0000000000000..d9d094f42519b --- /dev/null +++ b/apps/desktop/src/preview/FramePickInjection.ts @@ -0,0 +1,96 @@ +import { webFrameMain, type WebContents, type WebFrameMain } from "electron"; + +import { + FRAME_PICK_COMMAND_CHANNEL, + FRAME_PICK_ESCAPE_CHANNEL, + FRAME_PICK_MESSAGE_KEY, + installFramePickAgent, + type FramePickCommand, +} from "./FramePickAgent.ts"; + +const agentSourceFor = (documentToken: string): string => + `(${installFramePickAgent.toString()})(${JSON.stringify(FRAME_PICK_MESSAGE_KEY)}, undefined, ${JSON.stringify(documentToken)});`; + +const commandSourceFor = (documentToken: string, command: FramePickCommand): string => + `(() => { const agent = window[${JSON.stringify(FRAME_PICK_MESSAGE_KEY)}]; return agent && typeof agent.runCommandForDocument === "function" ? agent.runCommandForDocument(${JSON.stringify(documentToken)}, ${JSON.stringify(command)}) ?? null : null; })()`; + +const CSS_PROPERTY = /^-?[a-z][a-z-]*$/; +const MAX_STYLE_VALUE_CHARS = 1_000; + +function parseFramePickCommand(value: unknown): FramePickCommand | null { + if (typeof value !== "object" || value === null) return null; + const { kind, id, property, value: styleValue } = value as Record; + if (typeof id !== "string" || id.length > 32) return null; + if (kind === "capture" || kind === "describe" || kind === "restore") return { kind, id }; + if ( + kind === "style" && + typeof property === "string" && + CSS_PROPERTY.test(property) && + typeof styleValue === "string" && + styleValue.length <= MAX_STYLE_VALUE_CHARS + ) { + return { kind, id, property, value: styleValue }; + } + return null; +} + +const commandOwnerByWebContents = new WeakMap(); +let injectedDocuments = 0; + +export function watchFramesForPick(wc: WebContents): () => void { + const owner = Symbol("frame-pick-session"); + const framesByDocumentToken = new Map(); + + const injectAgent = (frame: WebFrameMain | null | undefined): void => { + if (!frame || frame.detached) return; + injectedDocuments += 1; + const documentToken = `${frame.processId}.${frame.routingId}.${injectedDocuments}`; + framesByDocumentToken.set(documentToken, frame); + frame.executeJavaScript(agentSourceFor(documentToken)).catch(() => undefined); + }; + + const mainFrame = wc.mainFrame; + for (const frame of mainFrame?.framesInSubtree ?? []) { + if (frame !== mainFrame) injectAgent(frame); + } + const onFrameLoaded = ( + _event: Electron.Event, + isMainFrame: boolean, + processId: number, + routingId: number, + ): void => { + if (!isMainFrame) injectAgent(webFrameMain.fromId(processId, routingId)); + }; + + const runCommand = async ( + _event: Electron.IpcMainInvokeEvent, + documentToken: unknown, + rawCommand: unknown, + ): Promise => { + const command = parseFramePickCommand(rawCommand); + if (typeof documentToken !== "string" || !command) return null; + const frame = framesByDocumentToken.get(documentToken); + if (!frame || frame.detached) return null; + return frame.executeJavaScript(commandSourceFor(documentToken, command)).catch(() => null); + }; + + const onInput = (_event: Electron.Event, input: Electron.Input): void => { + if (input.type !== "keyDown" || input.key !== "Escape" || input.isAutoRepeat) return; + wc.send(FRAME_PICK_ESCAPE_CHANNEL); + }; + + wc.on("did-frame-finish-load", onFrameLoaded); + wc.on("before-input-event", onInput); + wc.ipc.removeHandler(FRAME_PICK_COMMAND_CHANNEL); + wc.ipc.handle(FRAME_PICK_COMMAND_CHANNEL, runCommand); + commandOwnerByWebContents.set(wc, owner); + return () => { + wc.off("did-frame-finish-load", onFrameLoaded); + wc.off("before-input-event", onInput); + if (commandOwnerByWebContents.get(wc) === owner) { + wc.ipc.removeHandler(FRAME_PICK_COMMAND_CHANNEL); + commandOwnerByWebContents.delete(wc); + } + framesByDocumentToken.clear(); + }; +} diff --git a/apps/desktop/src/preview/Manager.test.ts b/apps/desktop/src/preview/Manager.test.ts index c8e75e841d7c8..0432484cc13aa 100644 --- a/apps/desktop/src/preview/Manager.test.ts +++ b/apps/desktop/src/preview/Manager.test.ts @@ -333,7 +333,7 @@ const makeTestPreviewWebContents = ( isCurrentlyAudible: () => false, on: vi.fn(), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -493,7 +493,7 @@ const makeFaviconWebContents = (options?: { listeners.set(event, listener); }), off, - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, session: { fetch }, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, @@ -1246,7 +1246,7 @@ describe("PreviewManager", () => { listeners.set(event, listener); }), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -1419,7 +1419,7 @@ describe("PreviewManager", () => { loadURL: vi.fn(async () => undefined), on: vi.fn(), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -1691,7 +1691,7 @@ describe("PreviewManager", () => { once: (event: string, listener: () => void) => { listeners.set(event, listener); }, - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -1837,7 +1837,7 @@ describe("PreviewManager", () => { off: vi.fn((event: string) => { listeners.delete(event); }), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -2804,7 +2804,7 @@ describe("PreviewManager", () => { isCurrentlyAudible: () => false, on: vi.fn(), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn() }, + ipc: { on: vi.fn(), off: vi.fn(), handle: vi.fn(), removeHandler: vi.fn() }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -3406,7 +3406,13 @@ describe("PreviewManager", () => { }); }), off: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() }, + ipc: { + on: vi.fn(), + off: vi.fn(), + removeListener: vi.fn(), + handle: vi.fn(), + removeHandler: vi.fn(), + }, send: webviewSend, navigationHistory: { canGoBack: () => false, canGoForward: () => false }, setIgnoreMenuShortcuts: vi.fn(), @@ -3467,7 +3473,13 @@ describe("PreviewManager", () => { Deferred.doneUnsafe(registrations++ === 0 ? firstReady : secondReady, Effect.void); }, once: vi.fn(), - ipc: { on: vi.fn(), off: vi.fn(), removeListener: vi.fn() }, + ipc: { + on: vi.fn(), + off: vi.fn(), + removeListener: vi.fn(), + handle: vi.fn(), + removeHandler: vi.fn(), + }, }; fromId.mockReturnValue(guest as never); yield* manager.createTab("tab_1"); @@ -3536,6 +3548,8 @@ describe("PreviewManager", () => { ), off: vi.fn(), removeListener: vi.fn(), + handle: vi.fn(), + removeHandler: vi.fn(), }, }), ] as const, @@ -3625,6 +3639,8 @@ describe("PreviewManager", () => { }), off: vi.fn(), removeListener: vi.fn(), + handle: vi.fn(), + removeHandler: vi.fn(), }, }), ); diff --git a/apps/desktop/src/preview/Manager.ts b/apps/desktop/src/preview/Manager.ts index 9ca560b87e6c3..bbe7b42c5b7da 100644 --- a/apps/desktop/src/preview/Manager.ts +++ b/apps/desktop/src/preview/Manager.ts @@ -91,6 +91,7 @@ import { START_PICK_CHANNEL, THUMB_PRESS_CHANNEL, } from "./GuestProtocol.ts"; +import { watchFramesForPick } from "./FramePickInjection.ts"; import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts"; import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts"; import { DEFAULT_RECORDING_INPUT_OPTIONS, type RecordingInputOptions } from "./RecordingInput.ts"; @@ -2357,6 +2358,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function wc.ipc.removeListener(ANNOTATION_VOICE_EVENT_CHANNEL, onVoiceEvent); wc.off("destroyed", onDestroyed); wc.off("did-start-navigation", onNavigated); + stopWatchingFrames(); }).pipe(Effect.ignore); // A newer session may already own the slot when this one is cancelled. yield* Ref.update(pickSessionsRef, (sessions) => @@ -2367,6 +2369,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function : sessions, ); }); + let stopWatchingFrames = (): void => undefined; let settled = false; const claimSettle = (): boolean => { if (settled) return false; @@ -2510,6 +2513,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function annotationSendEnabled.get(tabId) === true, voice, ); + stopWatchingFrames = watchFramesForPick(wc); }); }); runFork( diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts index 9c7c2901b1085..96890dea70286 100644 --- a/apps/desktop/src/preview/PickPreload.ts +++ b/apps/desktop/src/preview/PickPreload.ts @@ -18,6 +18,22 @@ import type { } from "@t3tools/contracts"; import { createAnnotationIdSource } from "./AnnotationIds.ts"; +import { + FRAME_PICK_COMMAND_CHANNEL, + FRAME_PICK_ESCAPE_CHANNEL, + FRAME_PICK_MESSAGE_KEY, + installFramePickAgent, + type FramePickCapture, + type FramePickCommand, + type FramePickDelivery, + type FramePickElementBox, + type FramePickHit, + type FramePickPointerType, + type FramePickRect, + type FramePickRelay, + type FramePickSize, + type FramePickUp, +} from "./FramePickAgent.ts"; import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts"; import { addStrokePoint, @@ -163,6 +179,19 @@ interface AnnotationSession { handleOverlayKey: (event: KeyboardEvent) => void; } +interface RemoteTarget { + readonly label: string; + readonly styles: CSSStyleDeclaration; + readonly stylesWhenPicked: CSSStyleDeclaration; + readonly reloadStyles: () => void; + readonly unclippedSize: () => FramePickSize; + readonly capture: () => Promise; + readonly setStyle: (property: string, value: string) => void; + readonly restoreStyles: () => void; +} + +const remoteTargets = new WeakMap(); + let activeSession: AnnotationSession | null = null; let annotationTheme: DesktopPreviewAnnotationTheme | null = null; @@ -334,6 +363,8 @@ function pickFromPoint(clientX: number, clientY: number): Element | null { } function describeRawElement(element: Element): string { + const remote = remoteTargets.get(element); + if (remote) return remote.label; const tag = element.tagName.toLowerCase(); const id = element.id ? `#${element.id}` : ""; const classes = @@ -447,6 +478,114 @@ const pageNumber = (source: unknown, key: string): number | null => { return typeof value === "number" && Number.isFinite(value) ? value : null; }; +const pageRect = (source: unknown): FramePickRect | null => { + const x = pageNumber(source, "x"); + const y = pageNumber(source, "y"); + const width = pageNumber(source, "width"); + const height = pageNumber(source, "height"); + return x === null || y === null || width === null || height === null + ? null + : { x, y, width, height }; +}; + +const pageSize = (source: unknown): FramePickSize | null => { + const width = pageNumber(source, "width"); + const height = pageNumber(source, "height"); + return width === null || height === null ? null : { width, height }; +}; + +const pageHit = (source: unknown): FramePickHit | null => { + const label = pageString(source, "label"); + const visibleRect = pageRect(pageField(source, "visibleRect")); + const unclippedSize = pageSize(pageField(source, "unclippedSize")); + if (label === null || visibleRect === null || unclippedSize === null) return null; + return { id: pageString(source, "id"), label, visibleRect, unclippedSize }; +}; + +const pageElementBox = (source: unknown): FramePickElementBox | null => { + const id = pageString(source, "id"); + const visibleRect = pageRect(pageField(source, "visibleRect")); + const unclippedSize = pageSize(pageField(source, "unclippedSize")); + return id === null || visibleRect === null || unclippedSize === null + ? null + : { id, visibleRect, unclippedSize }; +}; + +const pageCapture = (source: unknown): FramePickCapture | null => { + const selector = pageString(source, "selector"); + const htmlPreview = pageString(source, "htmlPreview"); + const tagName = pageString(source, "tagName"); + return selector === null || htmlPreview === null || tagName === null + ? null + : { selector, htmlPreview: htmlPreview.slice(0, HTML_PREVIEW_MAX_CHARS), tagName }; +}; + +const pageStyles = (source: unknown): Record => + typeof source === "object" && source !== null + ? Object.fromEntries( + Object.entries(source).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ), + ) + : {}; + +const FRAME_POINTER_TYPES: ReadonlySet = new Set([ + "pointermove", + "pointerdown", + "pointerup", + "pointerout", +]); + +/** Subframe agents run in the page's world, so a relayed message is checked field by field. */ +function parseFrameDelivery(delivery: FramePickDelivery): FramePickDelivery | null { + const { up, framePathsOutermostFirst, senderDocumentToken } = delivery as { + up: unknown; + framePathsOutermostFirst: unknown; + senderDocumentToken: unknown; + }; + if ( + !Array.isArray(framePathsOutermostFirst) || + !framePathsOutermostFirst.every((path) => typeof path === "string") + ) + return null; + if (typeof senderDocumentToken !== "string") return null; + const relayed = (parsed: FramePickUp | null): FramePickDelivery | null => + parsed && { up: parsed, framePathsOutermostFirst, senderDocumentToken }; + const kind = pageField(up, "kind"); + if (kind === "pointer") { + const type = pageField(up, "type"); + const x = pageNumber(up, "x"); + const y = pageNumber(up, "y"); + const button = pageNumber(up, "button"); + if (!FRAME_POINTER_TYPES.has(type) || x === null || y === null || button === null) return null; + return relayed({ + kind, + type: type as FramePickPointerType, + x, + y, + button, + shiftKey: pageField(up, "shiftKey") === true, + hit: pageHit(pageField(up, "hit")), + }); + } + if (kind === "key") { + const key = pageString(up, "key"); + return relayed(key === null ? null : { kind, key }); + } + if (kind === "rects") { + const entries = pageField(up, "rects"); + if (!Array.isArray(entries)) return null; + return relayed({ + kind, + rects: entries.flatMap((entry) => { + const box = pageElementBox(entry); + return box ? [box] : []; + }), + }); + } + return null; +} + const toStackFrame = (frame: unknown): PickedElementStackFrame => ({ functionName: pageString(frame, "functionName"), fileName: pageString(frame, "fileName"), @@ -466,9 +605,12 @@ function withCaptureTimeout(promise: Promise, millis: number): Promise { + const remote = remoteTargets.get(element); + if (remote) return remote.capture(); const base = { pageUrl: location.href, pageTitle: document.title?.trim() || null, @@ -959,6 +1101,7 @@ function startAnnotation( }; const removeSelected = (target: SelectedElement): void => { + remoteTargets.get(target.element)?.restoreStyles(); if (target.element instanceof HTMLElement || target.element instanceof SVGElement) { for (const [property, baseline] of target.baselineStyles) { if (baseline) target.element.style.setProperty(property, baseline); @@ -1007,6 +1150,21 @@ function startAnnotation( const setStyleForSelected = (property: string, value: string): void => { for (const target of selected.values()) { + const remote = remoteTargets.get(target.element); + if (remote) { + const key = `${target.id}:${property}`; + styleChanges.set(key, { + targetId: target.id, + selector: null, + property, + previousValue: + styleChanges.get(key)?.previousValue ?? + remote.stylesWhenPicked.getPropertyValue(property).trim(), + value, + }); + remote.setStyle(property, value); + continue; + } if (!(target.element instanceof HTMLElement || target.element instanceof SVGElement)) continue; if (!target.baselineStyles.has(property)) { @@ -1227,8 +1385,9 @@ function startAnnotation( const syncStyleControls = (): void => { const first = selected.values().next().value as SelectedElement | undefined; if (!first) return; - const computed = getComputedStyle(first.element); - const rect = first.element.getBoundingClientRect(); + const remote = remoteTargets.get(first.element); + const computed = remote?.styles ?? getComputedStyle(first.element); + const rect = remote?.unclippedSize() ?? first.element.getBoundingClientRect(); aspectRatio = rect.height > 0 ? rect.width / rect.height : 1; widthInput.value = String(Math.round(rect.width)); heightInput.value = String(Math.round(rect.height)); @@ -1353,7 +1512,10 @@ function startAnnotation( adjust.setAttribute("aria-expanded", "true"); adjust.title = "Collapse annotation editor"; adjust.setAttribute("aria-label", "Collapse annotation editor"); - if (selected.size > 0) syncStyleControls(); + if (selected.size > 0) { + syncStyleControls(); + for (const target of selected.values()) remoteTargets.get(target.element)?.reloadStyles(); + } } else { editorExpanded = false; editorPosition = null; @@ -1404,7 +1566,7 @@ function startAnnotation( dragHandle.addEventListener("pointerup", onEditorPointerUp); dragHandle.addEventListener("pointercancel", onEditorPointerUp); - const repaint = (): void => { + const repaintSelection = (): void => { for (const target of selected.values()) updateSelectedVisual(target); queueEditorLayout(); }; @@ -1415,6 +1577,11 @@ function startAnnotation( } repaint(); }; + let frameRelay: FramePickRelay | null = null; + const repaint = (): void => { + repaintSelection(); + frameRelay?.send({ kind: "refresh" }); + }; // A scrollbar appearing narrows the viewport without a window resize. const rootResizeObserver = new ResizeObserver(repaint); @@ -1491,6 +1658,11 @@ function startAnnotation( return candidates.length; }; + let forwardedHit: Element | null | undefined; + let dragStartedInFrame = false; + const pickAt = (clientX: number, clientY: number): Element | null => + forwardedHit === undefined ? pickFromPoint(clientX, clientY) : forwardedHit; + const clearHoverOutline = (): void => { hoverOutline.style.display = "none"; }; @@ -1501,7 +1673,7 @@ function startAnnotation( return; } if (tool === "select" && dragStart === null) { - const target = pickFromPoint(event.clientX, event.clientY); + const target = pickAt(event.clientX, event.clientY); if (target) positionBox(hoverOutline, visibleElementRect(target)); else clearHoverOutline(); return; @@ -1535,7 +1707,7 @@ function startAnnotation( event.preventDefault(); event.stopPropagation(); if (tool === "select") { - const target = pickFromPoint(event.clientX, event.clientY); + const target = pickAt(event.clientX, event.clientY); if (target) toggleSelected(target, event.shiftKey); return; } @@ -1544,6 +1716,7 @@ function startAnnotation( return; } dragStart = { x: event.clientX, y: event.clientY }; + dragStartedInFrame = forwardedHit !== undefined; if (tool === "draw") { const geometry = startStroke(dragStart); const stroke: PreviewAnnotationStrokeTarget = { @@ -1577,7 +1750,7 @@ function startAnnotation( const rect = normalizeRect(dragStart.x, dragStart.y, event.clientX, event.clientY); marqueeBox.style.display = "none"; if (isUsableRect(rect)) { - const found = selectElementsInRect(rect); + const found = dragStartedInFrame ? 0 : selectElementsInRect(rect); if (found === 0) { const region: PreviewAnnotationRegionTarget = { id: nextId("region"), rect }; regions.push(region); @@ -1672,6 +1845,12 @@ function startAnnotation( finished = true; rootResizeObserver.disconnect(); restoreStyles(); + frameRelay?.send({ kind: "stop" }); + frameRelay?.dispose(); + frameRelay = null; + for (const settle of rectWaiters.values()) settle(); + rectWaiters.clear(); + ipcRenderer.off(FRAME_PICK_ESCAPE_CHANNEL, onFrameEscape); window.removeEventListener("pointermove", onPointerMove, true); window.removeEventListener("pointerdown", onPointerDown, true); window.removeEventListener("pointerup", onPointerUp, true); @@ -1705,6 +1884,14 @@ function startAnnotation( }; const onCancel = (): void => teardown(false); + const focusIsInsideAFrame = (): boolean => { + let focused = document.activeElement; + while (focused?.shadowRoot?.activeElement) focused = focused.shadowRoot.activeElement; + return focused instanceof HTMLIFrameElement || focused?.tagName === "FRAME"; + }; + const onFrameEscape = (): void => { + if (focusIsInsideAFrame()) teardown(true); + }; const onCaptured = (): void => teardown(false); const onVoiceKeyUp = (event: KeyboardEvent): void => { if (!event.isTrusted || (event.code || event.key) !== voiceKeyCode) return; @@ -1732,7 +1919,7 @@ function startAnnotation( return; } } - if (event.key === "Escape" && !event.isComposing) { + if (event.key === "Escape" && event.isTrusted && !event.isComposing) { event.preventDefault(); event.stopPropagation(); teardown(true); @@ -1837,6 +2024,191 @@ function startAnnotation( submitAnnotation(submission); }; + const mirrors = new Map(); + const mirrorSizes = new WeakMap(); + const rectWaiters = new Map void>(); + const mirrorKey = (documentToken: string, id: string | null): string => + `${documentToken}#${id ?? "hover"}`; + + const commandFrame = (documentToken: string, command: FramePickCommand): Promise => + ipcRenderer.invoke(FRAME_PICK_COMMAND_CHANNEL, documentToken, command).catch(() => null); + + const nextRectsFrom = (documentToken: string): Promise => + withCaptureTimeout( + new Promise((resolve) => { + rectWaiters.get(documentToken)?.(); + const settle = (): void => { + if (rectWaiters.get(documentToken) === settle) rectWaiters.delete(documentToken); + resolve(); + }; + rectWaiters.set(documentToken, settle); + }), + FRESH_RECT_TIMEOUT_MS, + ).then(() => undefined); + + const captureRemote = async ( + documentToken: string, + framePaths: ReadonlyArray, + id: string, + label: string, + ): Promise => { + const freshRect = nextRectsFrom(documentToken); + const capture = pageCapture( + await withCaptureTimeout( + commandFrame(documentToken, { kind: "capture", id }), + ELEMENT_CONTEXT_TIMEOUT_MS, + ), + ); + if (capture) await freshRect; + return { + pageUrl: location.href, + pageTitle: document.title?.trim() || null, + tagName: capture?.tagName ?? label.split(/[#.]/)[0] ?? "", + pickedAt: new Date().toISOString(), + selector: capture ? [...framePaths, capture.selector].join(" >>> ") : null, + htmlPreview: capture?.htmlPreview ?? "", + componentName: null, + source: null, + stack: [], + styles: "", + }; + }; + + const placeMirror = (mirror: HTMLDivElement, box: Omit): void => { + positionBox(mirror, box.visibleRect); + mirrorSizes.set(mirror, box.unclippedSize); + }; + + const loadRemoteStyles = ( + mirror: HTMLDivElement, + targets: ReadonlyArray, + documentToken: string, + id: string, + ): void => { + void commandFrame(documentToken, { kind: "describe", id }).then((described) => { + for (const [property, value] of Object.entries(pageStyles(described))) + for (const styles of targets) styles.setProperty(property, value); + if (selected.values().next().value?.element === mirror && editorExpanded) syncStyleControls(); + }); + }; + + const hoverTarget = (label: string): RemoteTarget => ({ + label, + styles: document.createElement("div").style, + stylesWhenPicked: document.createElement("div").style, + reloadStyles: () => undefined, + unclippedSize: () => ({ width: 0, height: 0 }), + capture: () => Promise.reject(new Error("hover outline only")), + setStyle: () => undefined, + restoreStyles: () => undefined, + }); + + const mirrorFor = ( + documentToken: string, + framePaths: ReadonlyArray, + hit: FramePickHit, + ): Element => { + const key = mirrorKey(documentToken, hit.id); + let mirror = mirrors.get(key); + if (!mirror) { + mirror = document.createElement("div"); + mirror.setAttribute(OVERLAY_ATTRIBUTE, ""); + mirror.style.cssText = "position:fixed;left:0;top:0;visibility:hidden;pointer-events:none"; + root.appendChild(mirror); + mirrors.set(key, mirror); + } + placeMirror(mirror, hit); + const id = hit.id; + if (id === null) { + remoteTargets.set(mirror, hoverTarget(hit.label)); + return mirror; + } + if (remoteTargets.has(mirror)) return mirror; + const styles = document.createElement("div").style; + const stylesWhenPicked = document.createElement("div").style; + const sizedMirror = mirror; + remoteTargets.set(mirror, { + label: hit.label, + styles, + stylesWhenPicked, + reloadStyles: () => loadRemoteStyles(sizedMirror, [styles], documentToken, id), + unclippedSize: () => mirrorSizes.get(sizedMirror) ?? hit.unclippedSize, + capture: () => captureRemote(documentToken, framePaths, id, hit.label), + setStyle: (property, value) => { + void commandFrame(documentToken, { kind: "style", id, property, value }); + }, + restoreStyles: () => { + void commandFrame(documentToken, { kind: "restore", id }); + }, + }); + loadRemoteStyles(mirror, [styles, stylesWhenPicked], documentToken, id); + return mirror; + }; + + const forwardedPointerHandlers = { + pointermove: onPointerMove, + pointerdown: onPointerDown, + pointerup: onPointerUp, + pointerout: onPointerOut, + }; + + const forwardPointer = ( + up: Extract, + documentToken: string, + framePaths: ReadonlyArray, + ): void => { + const handler = forwardedPointerHandlers[up.type]; + const forwarded = { + type: up.type, + clientX: up.x, + clientY: up.y, + button: up.button, + shiftKey: up.shiftKey, + target: document.documentElement, + relatedTarget: null, + preventDefault: () => undefined, + stopPropagation: () => undefined, + } as unknown as PointerEvent; + forwardedHit = up.hit ? mirrorFor(documentToken, framePaths, up.hit) : null; + try { + handler(forwarded); + } finally { + forwardedHit = undefined; + } + }; + + const forwardKey = (key: string): void => { + onKeyDown({ + key, + code: key, + isTrusted: false, + isComposing: false, + keyCode: 0, + preventDefault: () => undefined, + stopPropagation: () => undefined, + stopImmediatePropagation: () => undefined, + } as unknown as KeyboardEvent); + }; + + const onFrameDelivery = (delivery: FramePickDelivery): void => { + const parsed = parseFrameDelivery(delivery); + if (finished || !parsed || parsed.senderDocumentToken === null) return; + const { up, framePathsOutermostFirst, senderDocumentToken } = parsed; + if (up.kind === "pointer") forwardPointer(up, senderDocumentToken, framePathsOutermostFirst); + else if (up.kind === "key") forwardKey(up.key); + else if (up.kind === "rects") { + for (const entry of up.rects) { + const mirror = mirrors.get(mirrorKey(senderDocumentToken, entry.id)); + if (mirror) placeMirror(mirror, entry); + } + repaintSelection(); + rectWaiters.get(senderDocumentToken)?.(); + } + }; + + frameRelay = installFramePickAgent(FRAME_PICK_MESSAGE_KEY, onFrameDelivery); + frameRelay.send({ kind: "start" }); + window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false }); window.addEventListener("pointerdown", onPointerDown, { capture: true, passive: false }); window.addEventListener("pointerup", onPointerUp, { capture: true, passive: false }); @@ -1853,6 +2225,7 @@ function startAnnotation( host.addEventListener(type, stopAtOverlay, { passive: true }); document.documentElement.addEventListener("focusout", onFocusOutToOverlay); ipcRenderer.on(CANCEL_PICK_CHANNEL, onCancel); + ipcRenderer.on(FRAME_PICK_ESCAPE_CHANNEL, onFrameEscape); ipcRenderer.on(ANNOTATION_CAPTURED_CHANNEL, onCaptured); if (voice) ipcRenderer.on(ANNOTATION_VOICE_STATE_CHANNEL, onVoiceState); if (inputLayer) {