Open History to see the last commit
1// @effect-diagnostics globalDate:off globalTimers:off - This isolated Electron preload does not run inside an Effect runtime.
2import { ipcRenderer } from "electron";
3import { getElementContext } from "react-grab/primitives";
4import type {
5 DesktopPreviewAnnotationTheme,
6 PickedElementPayload,
7 PickedElementStackFrame,
8 PreviewAnnotationPayload,
9 PreviewAnnotationPoint,
10 PreviewAnnotationRect,
11 PreviewAnnotationRegionTarget,
12 PreviewAnnotationStrokeTarget,
13 PreviewAnnotationStyleChange,
14 PreviewAnnotationSubmission,
15} from "@t3tools/contracts";
16
17import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
18import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
19import {
20 ANNOTATION_CAPTURED_CHANNEL,
21 ANNOTATION_THEME_CHANNEL,
22 CANCEL_PICK_CHANNEL,
23 ELEMENT_PICKED_CHANNEL,
24 HUMAN_INPUT_CHANNEL,
25 MOUSE_NAVIGATE_CHANNEL,
26 START_PICK_CHANNEL,
27} from "./GuestProtocol.ts";
28const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui";
29const Z_INDEX_OVERLAY = 2147483646;
30const PRIMARY = "var(--t3-primary)";
31const PRIMARY_FILL = "color-mix(in srgb, var(--t3-primary) 10%, transparent)";
32const MAX_MARQUEE_ELEMENTS = 20;
33/** Upper bound on one element's React context lookup during submit. */
34const ELEMENT_CONTEXT_TIMEOUT_MS = 5_000;
35const CONTENT_LAYER_Z_INDEX = 1;
36const CHROME_LAYER_Z_INDEX = 10;
37
38type AnnotationTool = "select" | "marquee" | "draw" | "erase";
39
40interface SelectedElement {
41 id: string;
42 element: Element;
43 outline: HTMLDivElement;
44 label: HTMLDivElement;
45 baselineStyles: Map<string, string>;
46}
47
48interface AnnotationSession {
49 teardown: (notifyMain: boolean) => void;
50 applyTheme: (theme: DesktopPreviewAnnotationTheme) => void;
51}
52
53let activeSession: AnnotationSession | null = null;
54let idSequence = 0;
55let annotationTheme: DesktopPreviewAnnotationTheme | null = null;
56
57const applyAnnotationTheme = (
58 host: HTMLElement,
59 theme: DesktopPreviewAnnotationTheme | null,
60): void => {
61 if (!theme) return;
62 host.style.colorScheme = theme.colorScheme;
63 const variables = {
64 "--t3-radius": theme.radius,
65 "--t3-background": theme.background,
66 "--t3-foreground": theme.foreground,
67 "--t3-popover": theme.popover,
68 "--t3-popover-foreground": theme.popoverForeground,
69 "--t3-primary": theme.primary,
70 "--t3-primary-foreground": theme.primaryForeground,
71 "--t3-muted": theme.muted,
72 "--t3-muted-foreground": theme.mutedForeground,
73 "--t3-accent": theme.accent,
74 "--t3-accent-foreground": theme.accentForeground,
75 "--t3-border": theme.border,
76 "--t3-input": theme.input,
77 "--t3-ring": theme.ring,
78 "--t3-font-sans": theme.fontSans,
79 "--t3-font-mono": theme.fontMono,
80 };
81 for (const [name, value] of Object.entries(variables)) {
82 host.style.setProperty(name, value);
83 }
84};
85
86const reportHumanPointerInput = (event: PointerEvent): void => {
87 if (!event.isTrusted) return;
88 ipcRenderer.send(HUMAN_INPUT_CHANNEL, {
89 kind: "pointer",
90 x: event.clientX,
91 y: event.clientY,
92 button: event.button,
93 });
94};
95
96const reportHumanKeyInput = (event: KeyboardEvent): void => {
97 if (!event.isTrusted) return;
98 ipcRenderer.send(HUMAN_INPUT_CHANNEL, {
99 kind: "key",
100 key: event.key,
101 code: event.code,
102 });
103};
104
105window.addEventListener("pointerdown", reportHumanPointerInput, true);
106window.addEventListener("keydown", reportHumanKeyInput, true);
107
108// Mouse thumb buttons: `button === 3` is Back, `button === 4` is Forward.
109const MOUSE_BUTTON_BACK = 3;
110const MOUSE_BUTTON_FORWARD = 4;
111
112const navigationDirectionForButton = (button: number): "back" | "forward" | null => {
113 if (button === MOUSE_BUTTON_BACK) return "back";
114 if (button === MOUSE_BUTTON_FORWARD) return "forward";
115 return null;
116};
117
118// Chromium routes thumb-button history navigation to the *focused* WebContents,
119// so hovering this guest without focusing it sends the host app's router back
120// instead of the preview. Suppress Chromium's default here and drive this tab's
121// history explicitly so the buttons always navigate the browser the pointer is
122// over — never the host app.
123const suppressNavigationButton = (event: MouseEvent): void => {
124 if (!event.isTrusted || navigationDirectionForButton(event.button) === null) return;
125 event.preventDefault();
126 event.stopImmediatePropagation();
127};
128
129const requestNavigationForButton = (event: MouseEvent): void => {
130 if (!event.isTrusted) return;
131 const direction = navigationDirectionForButton(event.button);
132 if (direction === null) return;
133 event.preventDefault();
134 event.stopImmediatePropagation();
135 ipcRenderer.send(MOUSE_NAVIGATE_CHANNEL, { direction });
136};
137
138window.addEventListener("mousedown", suppressNavigationButton, true);
139window.addEventListener("mouseup", requestNavigationForButton, true);
140window.addEventListener("auxclick", suppressNavigationButton, true);
141
142const nextId = (prefix: string): string => {
143 idSequence += 1;
144 return `${prefix}_${idSequence.toString(36)}`;
145};
146
147const rectFromDomRect = (rect: DOMRect): PreviewAnnotationRect => ({
148 x: rect.left,
149 y: rect.top,
150 width: rect.width,
151 height: rect.height,
152});
153
154const normalizeRect = (
155 startX: number,
156 startY: number,
157 endX: number,
158 endY: number,
159): PreviewAnnotationRect => ({
160 x: Math.min(startX, endX),
161 y: Math.min(startY, endY),
162 width: Math.abs(endX - startX),
163 height: Math.abs(endY - startY),
164});
165
166const isUsableRect = (rect: PreviewAnnotationRect): boolean => rect.width >= 3 && rect.height >= 3;
167
168function unionRects(
169 rects: ReadonlyArray<PreviewAnnotationRect>,
170 padding = 20,
171): PreviewAnnotationRect | null {
172 if (rects.length === 0) return null;
173 const left = Math.min(...rects.map((rect) => rect.x));
174 const top = Math.min(...rects.map((rect) => rect.y));
175 const right = Math.max(...rects.map((rect) => rect.x + rect.width));
176 const bottom = Math.max(...rects.map((rect) => rect.y + rect.height));
177 const x = Math.max(0, left - padding);
178 const y = Math.max(0, top - padding);
179 const maxWidth = Math.max(1, window.innerWidth - x);
180 const maxHeight = Math.max(1, window.innerHeight - y);
181 return {
182 x,
183 y,
184 width: Math.min(maxWidth, right - left + padding * 2),
185 height: Math.min(maxHeight, bottom - top + padding * 2),
186 };
187}
188
189function isAnnotationNode(element: Element): boolean {
190 return element instanceof Element && element.closest(`[${OVERLAY_ATTRIBUTE}]`) !== null;
191}
192
193function pickFromPoint(clientX: number, clientY: number): Element | null {
194 for (const candidate of document.elementsFromPoint(clientX, clientY)) {
195 if (!(candidate instanceof Element)) continue;
196 if (isAnnotationNode(candidate)) continue;
197 if (candidate === document.documentElement || candidate === document.body) continue;
198 return candidate;
199 }
200 return null;
201}
202
203function describeRawElement(element: Element): string {
204 const tag = element.tagName.toLowerCase();
205 const id = element.id ? `#${element.id}` : "";
206 const classes =
207 element instanceof HTMLElement && typeof element.className === "string"
208 ? element.className
209 .trim()
210 .split(/\s+/)
211 .filter(Boolean)
212 .slice(0, 2)
213 .map((name) => `.${name}`)
214 .join("")
215 : "";
216 return `${tag}${id}${classes}`;
217}
218
219function createBox(color: string, fill: string): HTMLDivElement {
220 const node = document.createElement("div");
221 node.setAttribute(OVERLAY_ATTRIBUTE, "");
222 node.style.cssText = [
223 "position:fixed",
224 "pointer-events:none",
225 `border:2px solid ${color}`,
226 `background:${fill}`,
227 "border-radius:3px",
228 "box-sizing:border-box",
229 "display:none",
230 `z-index:${CONTENT_LAYER_Z_INDEX}`,
231 ].join(";");
232 return node;
233}
234
235function positionBox(node: HTMLElement, rect: PreviewAnnotationRect): void {
236 node.style.display = "block";
237 node.style.transform = `translate(${rect.x}px, ${rect.y}px)`;
238 node.style.width = `${rect.width}px`;
239 node.style.height = `${rect.height}px`;
240}
241
242function createLabel(): HTMLDivElement {
243 const label = document.createElement("div");
244 label.setAttribute(OVERLAY_ATTRIBUTE, "");
245 label.className =
246 "fixed z-1 max-w-70 overflow-hidden rounded-md bg-primary px-2 py-1 font-sans text-xs font-semibold text-primary-foreground shadow-md";
247 label.style.cssText = [
248 "position:fixed",
249 "pointer-events:none",
250 "white-space:nowrap",
251 "text-overflow:ellipsis",
252 `z-index:${CONTENT_LAYER_Z_INDEX}`,
253 ].join(";");
254 return label;
255}
256
257function updateSelectedVisual(target: SelectedElement): void {
258 if (!target.element.isConnected) {
259 target.outline.style.display = "none";
260 target.label.style.display = "none";
261 return;
262 }
263 const rect = target.element.getBoundingClientRect();
264 positionBox(target.outline, rectFromDomRect(rect));
265 target.label.textContent = describeRawElement(target.element);
266 target.label.style.display = "block";
267 target.label.style.transform = `translate(${Math.max(4, rect.left)}px, ${Math.max(4, rect.top - 22)}px)`;
268}
269
270function toStackFrame(frame: {
271 functionName?: string;
272 fileName?: string;
273 lineNumber?: number;
274 columnNumber?: number;
275}): PickedElementStackFrame {
276 return {
277 functionName: frame.functionName ?? null,
278 fileName: frame.fileName ?? null,
279 lineNumber: frame.lineNumber ?? null,
280 columnNumber: frame.columnNumber ?? null,
281 };
282}
283
284/**
285 * Resolves to `null` instead of hanging when `promise` outlives `millis`.
286 * `getElementContext` walks the inspected page's React internals, and some
287 * pages leave it pending forever. Without a bound, the whole submit chain
288 * stalls and the overlay sits on "Capturing…".
289 */
290function withCaptureTimeout<A>(promise: Promise<A>, millis: number): Promise<A | null> {
291 let timer: ReturnType<typeof setTimeout> | undefined;
292 return Promise.race([
293 promise,
294 new Promise<null>((resolve) => {
295 timer = setTimeout(() => resolve(null), millis);
296 }),
297 ]).finally(() => clearTimeout(timer));
298}
299
300/** Truncation for the DOM-only preview used when React context is unavailable. */
301const HTML_PREVIEW_MAX_CHARS = 500;
302
303/**
304 * Describes a picked element. The React context lookup can stall or throw on
305 * some pages, so the element is never dropped: without context it still
306 * carries its tag, a short HTML preview, and its rect so the crop stays on the
307 * pick instead of falling back to the whole viewport.
308 */
309async function captureElement(element: Element): Promise<PickedElementPayload> {
310 const base = {
311 pageUrl: location.href,
312 pageTitle: document.title?.trim() || null,
313 tagName: element.tagName.toLowerCase(),
314 pickedAt: new Date().toISOString(),
315 };
316 try {
317 const context = await withCaptureTimeout(
318 Promise.resolve(getElementContext(element)),
319 ELEMENT_CONTEXT_TIMEOUT_MS,
320 );
321 if (context) {
322 const stack = (context.stack ?? []).map(toStackFrame);
323 return {
324 ...base,
325 selector: context.selector,
326 htmlPreview: context.htmlPreview ?? "",
327 componentName: context.componentName,
328 source: stack[0] ?? null,
329 stack,
330 styles: context.styles ?? "",
331 };
332 }
333 } catch {
334 // Fall through to the DOM-only payload.
335 }
336 return {
337 ...base,
338 selector: null,
339 htmlPreview: element.outerHTML.slice(0, HTML_PREVIEW_MAX_CHARS),
340 componentName: null,
341 source: null,
342 stack: [],
343 styles: "",
344 };
345}
346
347function createButton(label: string, title: string): HTMLButtonElement {
348 const button = document.createElement("button");
349 button.type = "button";
350 button.textContent = label;
351 button.title = title;
352 button.className =
353 "inline-flex h-7 cursor-pointer items-center justify-center rounded-md border border-transparent px-2 font-sans text-xs font-medium text-foreground outline-none hover:bg-accent disabled:pointer-events-none disabled:opacity-60";
354 return button;
355}
356
357function styleControl(input: HTMLInputElement | HTMLSelectElement): void {
358 input.setAttribute("aria-label", input.getAttribute("aria-label") ?? "Style value");
359 input.className =
360 "h-7 min-w-0 w-full appearance-none rounded-md border border-input bg-background px-2 font-mono text-xs text-foreground shadow-xs outline-none";
361}
362
363function createUnitControl(input: HTMLInputElement): HTMLElement {
364 const wrapper = document.createElement("div");
365 wrapper.style.cssText = "position:relative;min-width:0";
366 const unit = document.createElement("span");
367 unit.textContent = input.dataset.unit ?? "";
368 unit.className =
369 "pointer-events-none absolute top-1/2 right-2 -translate-y-1/2 font-mono text-xs text-muted-foreground";
370 wrapper.append(input, unit);
371 return wrapper;
372}
373
374function createField(
375 labelText: string,
376 input: HTMLInputElement | HTMLSelectElement,
377): HTMLLabelElement {
378 const label = document.createElement("label");
379 label.className =
380 "grid min-h-7 grid-cols-[82px_minmax(0,1fr)] items-center gap-2 font-sans text-xs font-medium text-muted-foreground";
381 const text = document.createElement("span");
382 text.textContent = labelText;
383 styleControl(input);
384 label.append(
385 text,
386 input instanceof HTMLInputElement && input.dataset.unit ? createUnitControl(input) : input,
387 );
388 return label;
389}
390
391function createStyleSection(): HTMLElement {
392 const section = document.createElement("section");
393 section.className = "grid gap-1 border-t border-border py-2";
394 return section;
395}
396
397function createUnitInput(unit: string, placeholder = "0"): HTMLInputElement {
398 const input = document.createElement("input");
399 input.type = "number";
400 input.placeholder = placeholder;
401 input.style.paddingRight = "30px";
402 input.dataset.unit = unit;
403 return input;
404}
405
406function pathFromPoints(points: ReadonlyArray<PreviewAnnotationPoint>): string {
407 if (points.length === 0) return "";
408 if (points.length === 1) return `M ${points[0]!.x} ${points[0]!.y} l 0.01 0.01`;
409 let path = `M ${points[0]!.x} ${points[0]!.y}`;
410 for (let index = 1; index < points.length - 1; index += 1) {
411 const current = points[index]!;
412 const next = points[index + 1]!;
413 path += ` Q ${current.x} ${current.y} ${(current.x + next.x) / 2} ${(current.y + next.y) / 2}`;
414 }
415 const last = points[points.length - 1]!;
416 path += ` L ${last.x} ${last.y}`;
417 return path;
418}
419
420function strokeBounds(
421 points: ReadonlyArray<PreviewAnnotationPoint>,
422 width: number,
423): PreviewAnnotationRect {
424 const xs = points.map((point) => point.x);
425 const ys = points.map((point) => point.y);
426 const padding = width + 3;
427 const left = Math.min(...xs) - padding;
428 const top = Math.min(...ys) - padding;
429 const right = Math.max(...xs) + padding;
430 const bottom = Math.max(...ys) + padding;
431 return { x: left, y: top, width: right - left, height: bottom - top };
432}
433
434function startAnnotation(): void {
435 activeSession?.teardown(false);
436 let finished = false;
437 const host = document.createElement("div");
438 host.setAttribute(OVERLAY_ATTRIBUTE, "");
439 host.style.cssText = `position:fixed;inset:0;z-index:${Z_INDEX_OVERLAY};pointer-events:none`;
440 applyAnnotationTheme(host, annotationTheme);
441 const shadowRoot = host.attachShadow({ mode: "closed" });
442 const themeStyle = document.createElement("style");
443 themeStyle.textContent = previewAnnotationStyles;
444 shadowRoot.appendChild(themeStyle);
445
446 const root = document.createElement("div");
447 root.setAttribute(OVERLAY_ATTRIBUTE, "");
448 root.className = "fixed inset-0 font-sans text-foreground";
449 root.style.cssText = "pointer-events:none";
450 const cursorStyle = document.createElement("style");
451 cursorStyle.setAttribute(OVERLAY_ATTRIBUTE, "");
452 cursorStyle.textContent = `html[data-t3code-annotation-tool] body, html[data-t3code-annotation-tool] body * { cursor: crosshair !important; } [${OVERLAY_ATTRIBUTE}], [${OVERLAY_ATTRIBUTE}] * { cursor: default !important; } [${OVERLAY_ATTRIBUTE}] input[type=number]::-webkit-inner-spin-button, [${OVERLAY_ATTRIBUTE}] input[type=number]::-webkit-outer-spin-button { appearance:none; margin:0; }`;
453 document.documentElement.appendChild(cursorStyle);
454 shadowRoot.appendChild(root);
455
456 const hoverOutline = createBox(PRIMARY, PRIMARY_FILL);
457 const marqueeBox = createBox(PRIMARY, PRIMARY_FILL);
458 root.append(hoverOutline, marqueeBox);
459
460 const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
461 svg.setAttribute(OVERLAY_ATTRIBUTE, "");
462 svg.setAttribute("width", "100%");
463 svg.setAttribute("height", "100%");
464 svg.setAttribute("viewBox", `0 0 ${window.innerWidth} ${window.innerHeight}`);
465 svg.style.cssText = "position:fixed;inset:0;overflow:visible;pointer-events:none";
466 svg.style.zIndex = String(CONTENT_LAYER_Z_INDEX);
467 root.appendChild(svg);
468
469 const toolbar = document.createElement("div");
470 toolbar.setAttribute(OVERLAY_ATTRIBUTE, "");
471 toolbar.className =
472 "pointer-events-auto fixed top-2.5 left-1/2 flex -translate-x-1/2 gap-0.5 rounded-lg border border-border bg-popover/95 p-1 text-popover-foreground shadow-lg backdrop-blur-xl";
473 toolbar.style.zIndex = String(CHROME_LAYER_Z_INDEX);
474 root.appendChild(toolbar);
475
476 const editor = document.createElement("div");
477 editor.setAttribute(OVERLAY_ATTRIBUTE, "");
478 editor.className =
479 "pointer-events-auto fixed hidden max-h-[calc(100vh-16px)] w-[min(360px,calc(100vw-16px))] flex-col overflow-hidden rounded-xl border border-border bg-popover/96 text-popover-foreground shadow-2xl backdrop-blur-xl";
480 editor.style.zIndex = String(CHROME_LAYER_Z_INDEX);
481 root.appendChild(editor);
482
483 const composerRow = document.createElement("div");
484 composerRow.className = "flex items-start gap-2 p-2";
485
486 const adjust = createButton("", "Expand annotation editor");
487 adjust.setAttribute("aria-label", "Expand annotation editor");
488 adjust.setAttribute("aria-expanded", "false");
489 adjust.className +=
490 " h-8 w-8 shrink-0 bg-muted p-0 text-muted-foreground hover:bg-accent hover:text-accent-foreground";
491 adjust.innerHTML =
492 '<svg viewBox="0 0 20 20" width="15" height="15" aria-hidden="true"><path d="M4 5h12M4 10h12M4 15h12M7 3v4M13 8v4M9 13v4" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>';
493 composerRow.appendChild(adjust);
494
495 const comment = document.createElement("textarea");
496 comment.placeholder = "Describe the change…";
497 comment.rows = 1;
498 comment.className =
499 "min-h-8 max-h-24 min-w-0 flex-1 resize-none overflow-y-hidden border-0 border-b border-b-transparent bg-transparent px-0 py-1.5 font-sans text-sm leading-5 text-foreground outline-none ring-0 placeholder:text-muted-foreground focus:border-b-primary focus:outline-none focus:ring-0";
500 composerRow.appendChild(comment);
501
502 const dragHandle = document.createElement("button");
503 dragHandle.type = "button";
504 dragHandle.textContent = "⠿";
505 dragHandle.title = "Drag annotation editor";
506 dragHandle.className =
507 "hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
508 composerRow.appendChild(dragHandle);
509
510 const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
511 submit.className +=
512 " h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
513 composerRow.appendChild(submit);
514 editor.appendChild(composerRow);
515
516 const stylePanel = document.createElement("div");
517 stylePanel.className =
518 "hidden max-h-[min(176px,calc(100vh-180px))] overflow-auto border-t border-border bg-muted/40 px-3";
519 editor.appendChild(stylePanel);
520
521 const selected = new Map<Element, SelectedElement>();
522 const regions: PreviewAnnotationRegionTarget[] = [];
523 const strokes: PreviewAnnotationStrokeTarget[] = [];
524 const styleChanges = new Map<string, PreviewAnnotationStyleChange>();
525 const toolButtons = new Map<AnnotationTool, HTMLButtonElement>();
526 let tool: AnnotationTool = "select";
527 let dragStart: PreviewAnnotationPoint | null = null;
528 let activeStroke: { target: PreviewAnnotationStrokeTarget; path: SVGPathElement } | null = null;
529 let pendingCapture = false;
530 let editorExpanded = false;
531 let editorWasShown = false;
532 let editorPosition: { left: number; top: number } | null = null;
533 let editorDrag: { pointerId: number; offsetX: number; offsetY: number } | null = null;
534 let editorLayoutFrame: number | null = null;
535
536 const resizeComment = (): void => {
537 const maxHeight = 96;
538 comment.style.height = "auto";
539 const nextHeight = Math.min(comment.scrollHeight, maxHeight);
540 comment.style.height = `${nextHeight}px`;
541 comment.style.overflowY = comment.scrollHeight > maxHeight ? "auto" : "hidden";
542 queueEditorLayout();
543 };
544 comment.addEventListener("input", resizeComment);
545
546 const updateStatus = (): void => {
547 const hasTargets = selected.size > 0 || regions.length > 0 || strokes.length > 0;
548 editor.style.display = hasTargets ? "flex" : "none";
549 submit.disabled = !hasTargets;
550 submit.style.opacity = hasTargets ? "1" : "0.45";
551 adjust.disabled = !hasTargets;
552 stylePanel.style.display = editorExpanded && selected.size > 0 ? "grid" : "none";
553 queueEditorLayout();
554 if (hasTargets && !editorWasShown) {
555 editorWasShown = true;
556 window.setTimeout(() => comment.focus({ preventScroll: true }), 0);
557 }
558 };
559
560 const refreshToolButtons = (): void => {
561 for (const [candidate, button] of toolButtons) {
562 const active = candidate === tool;
563 button.classList.toggle("bg-primary/10", active);
564 button.classList.toggle("text-primary", active);
565 button.classList.toggle("text-foreground", !active);
566 }
567 if (tool !== "select") hoverOutline.style.display = "none";
568 if (tool !== "marquee") marqueeBox.style.display = "none";
569 document.documentElement.setAttribute("data-t3code-annotation-tool", tool);
570 };
571
572 const removeSelected = (target: SelectedElement): void => {
573 if (target.element instanceof HTMLElement || target.element instanceof SVGElement) {
574 for (const [property, baseline] of target.baselineStyles) {
575 if (baseline) target.element.style.setProperty(property, baseline);
576 else target.element.style.removeProperty(property);
577 }
578 }
579 selected.delete(target.element);
580 target.outline.remove();
581 target.label.remove();
582 for (const [key, change] of styleChanges) {
583 if (change.targetId === target.id) styleChanges.delete(key);
584 }
585 updateStatus();
586 };
587
588 const addSelected = (element: Element): void => {
589 if (selected.has(element)) return;
590 const target: SelectedElement = {
591 id: nextId("element"),
592 element,
593 outline: createBox(PRIMARY, PRIMARY_FILL),
594 label: createLabel(),
595 baselineStyles: new Map(),
596 };
597 selected.set(element, target);
598 root.append(target.outline, target.label);
599 updateSelectedVisual(target);
600 updateStatus();
601 if (editorExpanded) {
602 stylePanel.style.display = "grid";
603 syncStyleControls();
604 }
605 };
606
607 const toggleSelected = (element: Element, additive: boolean): void => {
608 const existing = selected.get(element);
609 if (existing) {
610 removeSelected(existing);
611 return;
612 }
613 if (!additive) {
614 for (const target of Array.from(selected.values())) removeSelected(target);
615 }
616 addSelected(element);
617 };
618
619 const setStyleForSelected = (property: string, value: string): void => {
620 for (const target of selected.values()) {
621 if (!(target.element instanceof HTMLElement || target.element instanceof SVGElement))
622 continue;
623 if (!target.baselineStyles.has(property)) {
624 target.baselineStyles.set(property, target.element.style.getPropertyValue(property));
625 }
626 const key = `${target.id}:${property}`;
627 const previousValue =
628 styleChanges.get(key)?.previousValue ??
629 getComputedStyle(target.element).getPropertyValue(property).trim();
630 target.element.style.setProperty(property, value, "important");
631 styleChanges.set(key, {
632 targetId: target.id,
633 selector: null,
634 property,
635 previousValue,
636 value,
637 });
638 updateSelectedVisual(target);
639 }
640 };
641
642 const textSection = createStyleSection();
643 const colorsSection = createStyleSection();
644 const bordersSection = createStyleSection();
645 const sizingSection = createStyleSection();
646 stylePanel.append(textSection, colorsSection, bordersSection, sizingSection);
647
648 const fontFamily = document.createElement("select");
649 for (const value of ["inherit", "system-ui", "sans-serif", "serif", "monospace"]) {
650 const option = document.createElement("option");
651 option.value = value;
652 option.textContent = value;
653 fontFamily.appendChild(option);
654 }
655 fontFamily.addEventListener("change", () => setStyleForSelected("font-family", fontFamily.value));
656 textSection.appendChild(createField("Font", fontFamily));
657
658 const fontSize = createUnitInput("px", "16");
659 fontSize.min = "1";
660 fontSize.max = "300";
661 fontSize.addEventListener("input", () => {
662 if (fontSize.value) setStyleForSelected("font-size", `${fontSize.value}px`);
663 });
664 textSection.appendChild(createField("Font size", fontSize));
665
666 const fontWeight = document.createElement("select");
667 for (const value of ["300", "400", "500", "600", "700", "800", "900"]) {
668 const option = document.createElement("option");
669 option.value = value;
670 option.textContent = value;
671 fontWeight.appendChild(option);
672 }
673 fontWeight.addEventListener("change", () => setStyleForSelected("font-weight", fontWeight.value));
674 textSection.appendChild(createField("Font weight", fontWeight));
675
676 const lineHeight = document.createElement("input");
677 lineHeight.type = "text";
678 lineHeight.placeholder = "normal / 1.4";
679 lineHeight.addEventListener("change", () => {
680 if (lineHeight.value.trim()) setStyleForSelected("line-height", lineHeight.value.trim());
681 });
682 textSection.appendChild(createField("Line height", lineHeight));
683
684 const createColorRow = (
685 labelText: string,
686 property: string,
687 section: HTMLElement,
688 ): { row: HTMLLabelElement; color: HTMLInputElement; text: HTMLInputElement } => {
689 const row = document.createElement("label");
690 row.className =
691 "grid min-h-7 grid-cols-[82px_minmax(0,1fr)] items-center gap-2 font-sans text-xs font-medium text-muted-foreground";
692 const label = document.createElement("span");
693 label.textContent = labelText;
694 const control = document.createElement("div");
695 control.className =
696 "grid h-7 grid-cols-[22px_minmax(0,1fr)] items-center gap-1 rounded-md border border-input bg-background px-1 shadow-xs";
697 const color = document.createElement("input");
698 color.type = "color";
699 color.setAttribute("aria-label", labelText);
700 color.style.cssText =
701 "width:20px;height:20px;padding:0;border:0;border-radius:5px;overflow:hidden;background:transparent;cursor:pointer";
702 const text = document.createElement("input");
703 text.type = "text";
704 text.setAttribute("aria-label", `${labelText} value`);
705 text.className =
706 "min-w-0 w-full border-0 bg-transparent font-mono text-xs text-foreground outline-none";
707 color.addEventListener("input", () => {
708 text.value = color.value;
709 setStyleForSelected(property, color.value);
710 });
711 text.addEventListener("change", () => {
712 const value = text.value.trim();
713 if (!value) return;
714 setStyleForSelected(property, value);
715 if (/^#[0-9a-f]{6}$/i.test(value)) color.value = value;
716 });
717 control.append(color, text);
718 row.append(label, control);
719 section.appendChild(row);
720 return { row, color, text };
721 };
722
723 const textColor = createColorRow("Text color", "color", colorsSection);
724 const backgroundColor = createColorRow("Background", "background-color", colorsSection);
725
726 const opacity = document.createElement("input");
727 opacity.type = "range";
728 opacity.min = "0";
729 opacity.max = "1";
730 opacity.step = "0.05";
731 opacity.value = "1";
732 opacity.style.accentColor = PRIMARY;
733 opacity.addEventListener("input", () => setStyleForSelected("opacity", opacity.value));
734 colorsSection.appendChild(createField("Opacity", opacity));
735
736 const radius = createUnitInput("px", "0");
737 radius.min = "0";
738 radius.max = "300";
739 radius.addEventListener("input", () => {
740 if (radius.value) setStyleForSelected("border-radius", `${radius.value}px`);
741 });
742 bordersSection.appendChild(createField("Radius", radius));
743
744 const borderColor = createColorRow("Border color", "border-color", bordersSection);
745
746 const borderWidth = createUnitInput("px", "0");
747 borderWidth.min = "0";
748 borderWidth.max = "100";
749 borderWidth.addEventListener("input", () => {
750 if (borderWidth.value) {
751 setStyleForSelected("border-style", "solid");
752 setStyleForSelected("border-width", `${borderWidth.value}px`);
753 }
754 });
755 bordersSection.appendChild(createField("Border width", borderWidth));
756
757 const dimensions = document.createElement("div");
758 dimensions.style.cssText =
759 "display:grid;grid-template-columns:82px minmax(0,1fr);gap:8px;align-items:center";
760 const dimensionLabel = document.createElement("div");
761 dimensionLabel.className = "grid gap-2 font-sans text-xs font-medium text-muted-foreground";
762 dimensionLabel.innerHTML = "<span>Width</span><span>Height</span>";
763 const dimensionControls = document.createElement("div");
764 dimensionControls.style.cssText = "position:relative;display:grid;gap:3px;padding-left:22px";
765 const widthInput = createUnitInput("px", "auto");
766 const heightInput = createUnitInput("px", "auto");
767 styleControl(widthInput);
768 styleControl(heightInput);
769 const aspectLock = createButton("", "Lock aspect ratio");
770 aspectLock.setAttribute("aria-pressed", "true");
771 aspectLock.style.cssText +=
772 ";position:absolute;left:0;top:50%;transform:translateY(-50%);width:18px;height:38px;padding:0";
773 aspectLock.className += " bg-primary/10 text-primary";
774 dimensionControls.append(
775 createUnitControl(widthInput),
776 createUnitControl(heightInput),
777 aspectLock,
778 );
779 dimensions.append(dimensionLabel, dimensionControls);
780 sizingSection.appendChild(dimensions);
781
782 let aspectLocked = true;
783 let aspectRatio = 1;
784 const refreshAspectButton = (): void => {
785 aspectLock.innerHTML = aspectLocked
786 ? '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="M8 6.5 9.5 5A3.5 3.5 0 0 1 14.5 10l-1.5 1.5M12 13.5 10.5 15A3.5 3.5 0 0 1 5.5 10L7 8.5M7.5 12.5l5-5" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>'
787 : '<svg viewBox="0 0 20 20" width="14" height="14" aria-hidden="true"><path d="m6 6 8 8M8 6.5 9.5 5A3.5 3.5 0 0 1 14 9M12 13.5 10.5 15A3.5 3.5 0 0 1 6 11" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/></svg>';
788 aspectLock.setAttribute("aria-pressed", String(aspectLocked));
789 aspectLock.classList.toggle("bg-primary/10", aspectLocked);
790 aspectLock.classList.toggle("text-primary", aspectLocked);
791 aspectLock.classList.toggle("bg-muted", !aspectLocked);
792 aspectLock.classList.toggle("text-muted-foreground", !aspectLocked);
793 };
794 aspectLock.addEventListener("click", () => {
795 aspectLocked = !aspectLocked;
796 refreshAspectButton();
797 });
798 widthInput.addEventListener("input", () => {
799 const width = Number(widthInput.value);
800 if (!Number.isFinite(width) || width <= 0) return;
801 setStyleForSelected("width", `${width}px`);
802 if (aspectLocked && aspectRatio > 0) {
803 const height = Math.max(1, Math.round(width / aspectRatio));
804 heightInput.value = String(height);
805 setStyleForSelected("height", `${height}px`);
806 }
807 });
808 heightInput.addEventListener("input", () => {
809 const height = Number(heightInput.value);
810 if (!Number.isFinite(height) || height <= 0) return;
811 setStyleForSelected("height", `${height}px`);
812 if (aspectLocked && aspectRatio > 0) {
813 const width = Math.max(1, Math.round(height * aspectRatio));
814 widthInput.value = String(width);
815 setStyleForSelected("width", `${width}px`);
816 }
817 });
818 refreshAspectButton();
819
820 const addSpacingField = (
821 label: string,
822 property: string,
823 placeholder: string,
824 ): HTMLInputElement => {
825 const input = document.createElement("input");
826 input.type = "text";
827 input.placeholder = placeholder;
828 input.addEventListener("change", () => {
829 if (input.value.trim()) setStyleForSelected(property, input.value.trim());
830 });
831 sizingSection.appendChild(createField(label, input));
832 return input;
833 };
834 const padding = addSpacingField("Padding", "padding", "0 0 0 0");
835 const margin = addSpacingField("Margin", "margin", "0 0 0 0");
836 const gap = addSpacingField("Gap", "gap", "0px");
837
838 const syncStyleControls = (): void => {
839 const first = selected.values().next().value as SelectedElement | undefined;
840 if (!first) return;
841 const computed = getComputedStyle(first.element);
842 const rect = first.element.getBoundingClientRect();
843 aspectRatio = rect.height > 0 ? rect.width / rect.height : 1;
844 widthInput.value = String(Math.round(rect.width));
845 heightInput.value = String(Math.round(rect.height));
846 fontSize.value = String(Math.round(Number.parseFloat(computed.fontSize) || 16));
847 fontWeight.value = computed.fontWeight.match(/^[0-9]+$/) ? computed.fontWeight : "400";
848 lineHeight.value = computed.lineHeight;
849 fontFamily.value = Array.from(fontFamily.options).some(
850 (option) => option.value === computed.fontFamily,
851 )
852 ? computed.fontFamily
853 : "inherit";
854 textColor.text.value = computed.color;
855 backgroundColor.text.value = computed.backgroundColor;
856 borderColor.text.value = computed.borderColor;
857 opacity.value = computed.opacity;
858 radius.value = String(Math.round(Number.parseFloat(computed.borderRadius) || 0));
859 borderWidth.value = String(Math.round(Number.parseFloat(computed.borderWidth) || 0));
860 padding.value = computed.padding;
861 margin.value = computed.margin;
862 gap.value = computed.gap === "normal" ? "0px" : computed.gap;
863 };
864
865 const tools: ReadonlyArray<[AnnotationTool, string, string]> = [
866 ["select", "Select", "Select elements (V)"],
867 ["marquee", "Region", "Draw a region or marquee-select elements (R)"],
868 ["draw", "Draw", "Draw freehand (D)"],
869 ["erase", "Erase", "Remove an annotation target (E)"],
870 ];
871 for (const [candidate, label, title] of tools) {
872 const button = createButton(label, title);
873 button.className += " h-8 px-2.5 text-sm";
874 button.addEventListener("click", () => {
875 tool = candidate;
876 refreshToolButtons();
877 });
878 toolButtons.set(candidate, button);
879 toolbar.appendChild(button);
880 }
881
882 const clampEditorPosition = (left: number, top: number): { left: number; top: number } => {
883 const margin = 8;
884 const rect = editor.getBoundingClientRect();
885 return {
886 left: Math.min(
887 Math.max(margin, left),
888 Math.max(margin, window.innerWidth - rect.width - margin),
889 ),
890 top: Math.min(
891 Math.max(margin, top),
892 Math.max(margin, window.innerHeight - rect.height - margin),
893 ),
894 };
895 };
896
897 const applyEditorPosition = (position: { left: number; top: number }): void => {
898 const clamped = clampEditorPosition(position.left, position.top);
899 editor.style.left = `${clamped.left}px`;
900 editor.style.top = `${clamped.top}px`;
901 editor.style.right = "auto";
902 editor.style.bottom = "auto";
903 if (editorExpanded) editorPosition = clamped;
904 };
905
906 const getAnnotationBounds = (): PreviewAnnotationRect | null =>
907 unionRects(
908 [
909 ...Array.from(selected.values(), (target) =>
910 rectFromDomRect(target.element.getBoundingClientRect()),
911 ),
912 ...regions.map((region) => region.rect),
913 ...strokes.map((stroke) => stroke.bounds),
914 ],
915 0,
916 );
917
918 const positionCompactEditor = (): void => {
919 const bounds = getAnnotationBounds();
920 if (!bounds) return;
921 const editorRect = editor.getBoundingClientRect();
922 const gap = 8;
923 const candidates = [
924 { left: bounds.x + bounds.width + gap, top: bounds.y },
925 { left: bounds.x - editorRect.width - gap, top: bounds.y },
926 {
927 left: bounds.x + bounds.width - editorRect.width,
928 top: bounds.y + bounds.height + gap,
929 },
930 {
931 left: bounds.x + bounds.width - editorRect.width,
932 top: bounds.y - editorRect.height - gap,
933 },
934 ];
935 const overflow = (position: { left: number; top: number }): number =>
936 Math.max(0, -position.left) +
937 Math.max(0, -position.top) +
938 Math.max(0, position.left + editorRect.width - window.innerWidth) +
939 Math.max(0, position.top + editorRect.height - window.innerHeight);
940 const best = candidates.reduce((current, candidate) =>
941 overflow(candidate) < overflow(current) ? candidate : current,
942 );
943 applyEditorPosition(best);
944 };
945
946 function queueEditorLayout(): void {
947 if (editorLayoutFrame !== null) window.cancelAnimationFrame(editorLayoutFrame);
948 editorLayoutFrame = window.requestAnimationFrame(() => {
949 editorLayoutFrame = null;
950 if (editor.style.display === "none") return;
951 if (editorExpanded && editorPosition) applyEditorPosition(editorPosition);
952 else positionCompactEditor();
953 });
954 }
955
956 adjust.addEventListener("click", () => {
957 if (selected.size === 0) return;
958 if (!editorExpanded) {
959 const rect = editor.getBoundingClientRect();
960 editorExpanded = true;
961 editorPosition = { left: rect.left, top: rect.top };
962 stylePanel.style.display = selected.size > 0 ? "grid" : "none";
963 dragHandle.style.display = "block";
964 adjust.setAttribute("aria-expanded", "true");
965 adjust.title = "Collapse annotation editor";
966 adjust.setAttribute("aria-label", "Collapse annotation editor");
967 if (selected.size > 0) syncStyleControls();
968 } else {
969 editorExpanded = false;
970 editorPosition = null;
971 stylePanel.style.display = "none";
972 dragHandle.style.display = "none";
973 adjust.setAttribute("aria-expanded", "false");
974 adjust.title = "Expand annotation editor";
975 adjust.setAttribute("aria-label", "Expand annotation editor");
976 }
977 queueEditorLayout();
978 });
979
980 const onEditorPointerDown = (event: PointerEvent): void => {
981 if (event.button !== 0 || !editorExpanded) return;
982 const rect = editor.getBoundingClientRect();
983 editorDrag = {
984 pointerId: event.pointerId,
985 offsetX: event.clientX - rect.left,
986 offsetY: event.clientY - rect.top,
987 };
988 dragHandle.setPointerCapture(event.pointerId);
989 dragHandle.style.cursor = "grabbing";
990 event.preventDefault();
991 event.stopPropagation();
992 };
993
994 const onEditorPointerMove = (event: PointerEvent): void => {
995 if (!editorDrag || editorDrag.pointerId !== event.pointerId) return;
996 applyEditorPosition({
997 left: event.clientX - editorDrag.offsetX,
998 top: event.clientY - editorDrag.offsetY,
999 });
1000 event.preventDefault();
1001 event.stopPropagation();
1002 };
1003
1004 const onEditorPointerUp = (event: PointerEvent): void => {
1005 if (!editorDrag || editorDrag.pointerId !== event.pointerId) return;
1006 editorDrag = null;
1007 dragHandle.style.cursor = "grab";
1008 if (dragHandle.hasPointerCapture(event.pointerId))
1009 dragHandle.releasePointerCapture(event.pointerId);
1010 event.preventDefault();
1011 event.stopPropagation();
1012 };
1013 dragHandle.addEventListener("pointerdown", onEditorPointerDown);
1014 dragHandle.addEventListener("pointermove", onEditorPointerMove);
1015 dragHandle.addEventListener("pointerup", onEditorPointerUp);
1016 dragHandle.addEventListener("pointercancel", onEditorPointerUp);
1017
1018 const repaint = (): void => {
1019 for (const target of selected.values()) updateSelectedVisual(target);
1020 queueEditorLayout();
1021 };
1022
1023 const removeTargetAtPoint = (x: number, y: number): boolean => {
1024 for (const target of Array.from(selected.values()).toReversed()) {
1025 const rect = target.element.getBoundingClientRect();
1026 if (x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom) {
1027 removeSelected(target);
1028 return true;
1029 }
1030 }
1031 const regionIndex = regions.findIndex(
1032 (region) =>
1033 x >= region.rect.x &&
1034 x <= region.rect.x + region.rect.width &&
1035 y >= region.rect.y &&
1036 y <= region.rect.y + region.rect.height,
1037 );
1038 if (regionIndex >= 0) {
1039 const [removed] = regions.splice(regionIndex, 1);
1040 root.querySelector(`[data-region-id="${removed?.id}"]`)?.remove();
1041 updateStatus();
1042 return true;
1043 }
1044 const strokeIndex = strokes.findIndex(
1045 (stroke) =>
1046 x >= stroke.bounds.x &&
1047 x <= stroke.bounds.x + stroke.bounds.width &&
1048 y >= stroke.bounds.y &&
1049 y <= stroke.bounds.y + stroke.bounds.height,
1050 );
1051 if (strokeIndex >= 0) {
1052 const [removed] = strokes.splice(strokeIndex, 1);
1053 svg.querySelector(`[data-stroke-id="${removed?.id}"]`)?.remove();
1054 updateStatus();
1055 return true;
1056 }
1057 return false;
1058 };
1059
1060 const selectElementsInRect = (rect: PreviewAnnotationRect): number => {
1061 const candidates = Array.from(document.querySelectorAll("body *"))
1062 .filter((element) => !isAnnotationNode(element))
1063 .map((element) => ({ element, rect: element.getBoundingClientRect() }))
1064 .filter(({ rect: candidate }) => {
1065 if (candidate.width < 2 || candidate.height < 2) return false;
1066 return !(
1067 candidate.right < rect.x ||
1068 candidate.left > rect.x + rect.width ||
1069 candidate.bottom < rect.y ||
1070 candidate.top > rect.y + rect.height
1071 );
1072 })
1073 .filter(({ element, rect: candidate }) => {
1074 const centerX = candidate.left + candidate.width / 2;
1075 const centerY = candidate.top + candidate.height / 2;
1076 return (
1077 centerX >= rect.x &&
1078 centerX <= rect.x + rect.width &&
1079 centerY >= rect.y &&
1080 centerY <= rect.y + rect.height &&
1081 (element.children.length === 0 ||
1082 element instanceof HTMLButtonElement ||
1083 element instanceof HTMLAnchorElement ||
1084 element.getAttribute("role") === "button")
1085 );
1086 })
1087 .sort(
1088 (left, right) => left.rect.width * left.rect.height - right.rect.width * right.rect.height,
1089 )
1090 .slice(0, MAX_MARQUEE_ELEMENTS);
1091 for (const candidate of candidates) addSelected(candidate.element);
1092 return candidates.length;
1093 };
1094
1095 const clearHoverOutline = (): void => {
1096 hoverOutline.style.display = "none";
1097 };
1098
1099 const onPointerMove = (event: PointerEvent): void => {
1100 if (isAnnotationNode(event.target as Element)) {
1101 clearHoverOutline();
1102 return;
1103 }
1104 if (tool === "select" && dragStart === null) {
1105 const target = pickFromPoint(event.clientX, event.clientY);
1106 if (target) positionBox(hoverOutline, rectFromDomRect(target.getBoundingClientRect()));
1107 else clearHoverOutline();
1108 return;
1109 }
1110 clearHoverOutline();
1111 if (tool === "marquee" && dragStart) {
1112 positionBox(
1113 marqueeBox,
1114 normalizeRect(dragStart.x, dragStart.y, event.clientX, event.clientY),
1115 );
1116 return;
1117 }
1118 if (tool === "draw" && activeStroke) {
1119 activeStroke.target.points = [
1120 ...activeStroke.target.points,
1121 { x: event.clientX, y: event.clientY },
1122 ];
1123 activeStroke.target.bounds = strokeBounds(
1124 activeStroke.target.points,
1125 activeStroke.target.width,
1126 );
1127 activeStroke.path.setAttribute("d", pathFromPoints(activeStroke.target.points));
1128 }
1129 };
1130
1131 const onPointerDown = (event: PointerEvent): void => {
1132 if (event.button !== 0 || isAnnotationNode(event.target as Element)) return;
1133 event.preventDefault();
1134 event.stopPropagation();
1135 if (tool === "select") {
1136 const target = pickFromPoint(event.clientX, event.clientY);
1137 if (target) toggleSelected(target, event.shiftKey);
1138 return;
1139 }
1140 if (tool === "erase") {
1141 removeTargetAtPoint(event.clientX, event.clientY);
1142 return;
1143 }
1144 dragStart = { x: event.clientX, y: event.clientY };
1145 if (tool === "draw") {
1146 const stroke: PreviewAnnotationStrokeTarget = {
1147 id: nextId("stroke"),
1148 color: annotationTheme?.primary ?? "#2563eb",
1149 width: 4,
1150 points: [dragStart],
1151 bounds: { x: dragStart.x, y: dragStart.y, width: 1, height: 1 },
1152 };
1153 const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
1154 path.setAttribute(OVERLAY_ATTRIBUTE, "");
1155 path.setAttribute("data-stroke-id", stroke.id);
1156 path.setAttribute("fill", "none");
1157 path.setAttribute("stroke", stroke.color);
1158 path.setAttribute("stroke-width", String(stroke.width));
1159 path.setAttribute("stroke-linecap", "round");
1160 path.setAttribute("stroke-linejoin", "round");
1161 svg.appendChild(path);
1162 activeStroke = { target: stroke, path };
1163 }
1164 };
1165
1166 const onPointerUp = (event: PointerEvent): void => {
1167 if (!dragStart) return;
1168 event.preventDefault();
1169 event.stopPropagation();
1170 if (tool === "marquee") {
1171 const rect = normalizeRect(dragStart.x, dragStart.y, event.clientX, event.clientY);
1172 marqueeBox.style.display = "none";
1173 if (isUsableRect(rect)) {
1174 const found = selectElementsInRect(rect);
1175 if (found === 0) {
1176 const region: PreviewAnnotationRegionTarget = { id: nextId("region"), rect };
1177 regions.push(region);
1178 const regionBox = createBox(
1179 PRIMARY,
1180 "color-mix(in srgb, var(--t3-primary) 6%, transparent)",
1181 );
1182 regionBox.setAttribute("data-region-id", region.id);
1183 positionBox(regionBox, rect);
1184 root.appendChild(regionBox);
1185 }
1186 }
1187 } else if (tool === "draw" && activeStroke) {
1188 if (activeStroke.target.points.length > 1) strokes.push(activeStroke.target);
1189 else activeStroke.path.remove();
1190 activeStroke = null;
1191 }
1192 dragStart = null;
1193 updateStatus();
1194 };
1195
1196 const onClick = (event: MouseEvent): void => {
1197 if (isAnnotationNode(event.target as Element)) return;
1198 event.preventDefault();
1199 event.stopPropagation();
1200 };
1201
1202 const onPointerOut = (event: PointerEvent): void => {
1203 if (event.relatedTarget === null) clearHoverOutline();
1204 };
1205
1206 const onWindowBlur = (): void => {
1207 clearHoverOutline();
1208 };
1209
1210 const restoreStyles = (): void => {
1211 for (const target of selected.values()) {
1212 if (!(target.element instanceof HTMLElement || target.element instanceof SVGElement))
1213 continue;
1214 for (const [property, baseline] of target.baselineStyles) {
1215 if (baseline) target.element.style.setProperty(property, baseline);
1216 else target.element.style.removeProperty(property);
1217 }
1218 }
1219 };
1220
1221 const teardown = (notifyMain: boolean): void => {
1222 if (finished) return;
1223 finished = true;
1224 restoreStyles();
1225 window.removeEventListener("pointermove", onPointerMove, true);
1226 window.removeEventListener("pointerdown", onPointerDown, true);
1227 window.removeEventListener("pointerup", onPointerUp, true);
1228 window.removeEventListener("pointerout", onPointerOut, true);
1229 window.removeEventListener("click", onClick, true);
1230 window.removeEventListener("blur", onWindowBlur);
1231 window.removeEventListener("keydown", onKeyDown, true);
1232 window.removeEventListener("scroll", repaint, true);
1233 window.removeEventListener("resize", repaint);
1234 dragHandle.removeEventListener("pointerdown", onEditorPointerDown);
1235 dragHandle.removeEventListener("pointermove", onEditorPointerMove);
1236 dragHandle.removeEventListener("pointerup", onEditorPointerUp);
1237 dragHandle.removeEventListener("pointercancel", onEditorPointerUp);
1238 if (editorLayoutFrame !== null) window.cancelAnimationFrame(editorLayoutFrame);
1239 ipcRenderer.off(CANCEL_PICK_CHANNEL, onCancel);
1240 ipcRenderer.off(ANNOTATION_CAPTURED_CHANNEL, onCaptured);
1241 document.documentElement.removeAttribute("data-t3code-annotation-tool");
1242 cursorStyle.remove();
1243 host.remove();
1244 activeSession = null;
1245 if (notifyMain) ipcRenderer.send(ELEMENT_PICKED_CHANNEL, null);
1246 };
1247
1248 const onCancel = (): void => teardown(false);
1249 const onCaptured = (): void => teardown(false);
1250 const onKeyDown = (event: KeyboardEvent): void => {
1251 if (isAnnotationNode(event.target as Element) && event.key !== "Escape") return;
1252 if (event.key === "Escape") {
1253 event.preventDefault();
1254 event.stopPropagation();
1255 teardown(true);
1256 return;
1257 }
1258 if (event.key === "v") tool = "select";
1259 else if (event.key === "r") tool = "marquee";
1260 else if (event.key === "d") tool = "draw";
1261 else if (event.key === "e") tool = "erase";
1262 else return;
1263 refreshToolButtons();
1264 };
1265
1266 const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
1267 if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
1268 return;
1269 pendingCapture = true;
1270 submit.disabled = true;
1271 submit.textContent = "Capturing…";
1272 // Snapshot everything the annotation will carry before the capture runs.
1273 // The element context lookup can take up to its timeout, and the user can
1274 // keep editing meanwhile; the annotation must describe what they submitted.
1275 const submittedComment = comment.value.trim();
1276 const submittedRegions = [...regions];
1277 const submittedStrokes = [...strokes];
1278 const submittedStyleChanges = Array.from(styleChanges.values(), (change) => ({ ...change }));
1279 void Promise.all(
1280 Array.from(selected.values()).map(async (target) => {
1281 const element = await captureElement(target.element);
1282 for (const change of submittedStyleChanges) {
1283 if (change.targetId === target.id && element.selector !== null) {
1284 change.selector = element.selector;
1285 }
1286 }
1287 return {
1288 id: target.id,
1289 element,
1290 rect: rectFromDomRect(target.element.getBoundingClientRect()),
1291 };
1292 }),
1293 )
1294 .then((elements) => {
1295 // The overlay may have been cancelled or replaced while the capture
1296 // ran. A late submit must not deliver into the next pick's listener.
1297 if (finished) return;
1298 const annotation: PreviewAnnotationPayload = {
1299 id: nextId("annotation"),
1300 pageUrl: location.href,
1301 pageTitle: document.title?.trim() || null,
1302 comment: submittedComment,
1303 elements,
1304 regions: submittedRegions,
1305 strokes: submittedStrokes,
1306 styleChanges: submittedStyleChanges,
1307 screenshot: null,
1308 createdAt: new Date().toISOString(),
1309 };
1310 editor.style.display = "none";
1311 toolbar.style.display = "none";
1312 hoverOutline.style.display = "none";
1313 const screenshotRect = unionRects([
1314 ...elements.map((target) => target.rect),
1315 ...submittedRegions.map((region) => region.rect),
1316 ...submittedStrokes.map((stroke) => stroke.bounds),
1317 ]);
1318 ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
1319 })
1320 .catch(() => {
1321 // Last resort. Main is waiting on this message, so hand it an empty
1322 // pick rather than leaving the button stuck on "Capturing…" and the
1323 // renderer's pick promise pending. teardown is a no-op once finished.
1324 teardown(true);
1325 });
1326 };
1327 submit.addEventListener("click", () => submitAnnotation("attach"));
1328 root.addEventListener("keydown", (event) => {
1329 const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
1330 // Keep this in the bubble phase so editor inputs receive the event before
1331 // it is isolated from listeners installed by the inspected page.
1332 event.stopImmediatePropagation();
1333 if (!submission) return;
1334 event.preventDefault();
1335 submitAnnotation(submission);
1336 });
1337
1338 window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
1339 window.addEventListener("pointerdown", onPointerDown, { capture: true, passive: false });
1340 window.addEventListener("pointerup", onPointerUp, { capture: true, passive: false });
1341 window.addEventListener("pointerout", onPointerOut, { capture: true, passive: true });
1342 window.addEventListener("click", onClick, { capture: true, passive: false });
1343 window.addEventListener("blur", onWindowBlur);
1344 window.addEventListener("keydown", onKeyDown, { capture: true });
1345 window.addEventListener("scroll", repaint, { capture: true, passive: true });
1346 window.addEventListener("resize", repaint, { passive: true });
1347 ipcRenderer.on(CANCEL_PICK_CHANNEL, onCancel);
1348 ipcRenderer.on(ANNOTATION_CAPTURED_CHANNEL, onCaptured);
1349 document.documentElement.appendChild(host);
1350 refreshToolButtons();
1351 updateStatus();
1352 activeSession = {
1353 teardown,
1354 applyTheme: (theme) => applyAnnotationTheme(host, theme),
1355 };
1356}
1357
1358ipcRenderer.on(START_PICK_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme | undefined) => {
1359 if (theme) annotationTheme = theme;
1360 startAnnotation();
1361});
1362ipcRenderer.on(ANNOTATION_THEME_CHANNEL, (_event, theme: DesktopPreviewAnnotationTheme) => {
1363 annotationTheme = theme;
1364 activeSession?.applyTheme(theme);
1365});
1366ipcRenderer.on(CANCEL_PICK_CHANNEL, () => activeSession?.teardown(false));