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