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