1
+/**
2
+ * Preview pick preload — runs in the isolated world of the Chromium
3
+ * `<webview>` that hosts the in-app browser. Loaded via the
4
+ * `<webview preload="...">` attribute set by the renderer.
5
+ *
6
+ * Responsibilities:
7
+ *
8
+ * 1. Listen for `preview:start-pick` from main (sent through
9
+ * `WebContents.send`, received here via `ipcRenderer.on`).
10
+ * 2. Mount a minimal blue-highlight element picker on the page.
11
+ * 3. On click → call `react-grab/primitives.getElementContext` and bubble
12
+ * a `PickedElementPayload` to main via `ipcRenderer.send`. Main resolves
13
+ * the in-flight `pickElement(tabId)` promise via its per-WebContents
14
+ * `wc.ipc.on(...)` listener.
15
+ * 4. Tear down the picker on Escape, blur, navigation, or explicit cancel.
16
+ *
17
+ * Design notes:
18
+ *
19
+ * - We never modify the page's DOM tree — the highlight + crosshair cursor
20
+ * live on a single fixed-position overlay layer that we own. This keeps
21
+ * us safe against pages that reset DOM or do MutationObserver tracking.
22
+ * - The overlay uses `pointer-events: none` so clicks fall through to the
23
+ * real element behind it; we do hit-testing with `elementFromPoint`.
24
+ * - Only a single pick session is ever active per webview; re-activating
25
+ * silently replaces the previous session.
26
+ * - Cancellations triggered BY MAIN (CANCEL_PICK_CHANNEL, or a follow-up
27
+ * START_PICK_CHANNEL that supersedes the current session) tear down
28
+ * silently — they do NOT echo a `null` ELEMENT_PICKED back, because main
29
+ * already knows it cancelled and would otherwise resolve the freshly-
30
+ * registered next-pick listener with that stale `null`. Cancellations
31
+ * triggered by the USER (Escape, beforeunload, click on empty) DO send
32
+ * `null` back so main can resolve the in-flight pick promise.
33
+ */
34
+import { ipcRenderer } from "electron";
35
+import { getElementContext } from "react-grab/primitives";
36
+import type { PickedElementPayload, PickedElementStackFrame } from "@t3tools/contracts";
37
+
38
+import { computeLabelPosition } from "./preview-pick-label-position.ts";
39
+
40
+const START_PICK_CHANNEL = "preview:start-pick";
41
+const CANCEL_PICK_CHANNEL = "preview:cancel-pick";
42
+const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
43
+
44
+const HIGHLIGHT_COLOR = "rgba(37, 99, 235, 0.9)"; // blue-600
45
+const HIGHLIGHT_FILL = "rgba(37, 99, 235, 0.16)";
46
+const LABEL_BG = "rgba(37, 99, 235, 0.96)";
47
+const Z_INDEX_OVERLAY = 2147483646;
48
+
49
+interface PickSession {
50
+ readonly overlay: HTMLDivElement;
51
+ readonly outline: HTMLDivElement;
52
+ readonly label: HTMLDivElement;
53
+ /**
54
+ * Tear down listeners + DOM WITHOUT notifying main. Used when main itself
55
+ * initiated the cancel (CANCEL_PICK_CHANNEL) or when a follow-up startPick
56
+ * supersedes us — main is already waiting on a fresh listener and would
57
+ * otherwise resolve it with the stale `null` we'd send.
58
+ */
59
+ readonly teardownSilent: () => void;
60
+}
61
+
62
+let activeSession: PickSession | null = null;
63
+
64
+function endActiveSession(): void {
65
+ if (!activeSession) return;
66
+ const session = activeSession;
67
+ activeSession = null;
68
+ // Supersession from a new startPick is a main-initiated transition: tear
69
+ // down silently so the new pick's main-side listener doesn't receive a
70
+ // ghost `null` from the old session.
71
+ session.teardownSilent();
72
+}
73
+
74
+interface OverlayHandles {
75
+ readonly overlay: HTMLDivElement;
76
+ readonly outline: HTMLDivElement;
77
+ readonly label: HTMLDivElement;
78
+ readonly destroyDom: () => void;
79
+}
80
+
81
+function createOverlay(): OverlayHandles {
82
+ const overlay = document.createElement("div");
83
+ overlay.setAttribute("data-t3code-pick-overlay", "");
84
+ overlay.style.cssText = [
85
+ "position:fixed",
86
+ "inset:0",
87
+ "z-index:" + String(Z_INDEX_OVERLAY),
88
+ "pointer-events:none",
89
+ "cursor:crosshair",
90
+ // Some apps register `pointer-events: auto !important` on body — using a
91
+ // dedicated overlay element ensures we don't fight with that.
92
+ ].join(";");
93
+
94
+ const outline = document.createElement("div");
95
+ outline.setAttribute("data-t3code-pick-outline", "");
96
+ outline.style.cssText = [
97
+ "position:absolute",
98
+ "left:0",
99
+ "top:0",
100
+ "width:0",
101
+ "height:0",
102
+ "border:2px solid " + HIGHLIGHT_COLOR,
103
+ "background:" + HIGHLIGHT_FILL,
104
+ "border-radius:2px",
105
+ "box-shadow:0 0 0 1px rgba(255,255,255,0.6) inset",
106
+ "transition:none",
107
+ "display:none",
108
+ "pointer-events:none",
109
+ ].join(";");
110
+
111
+ const label = document.createElement("div");
112
+ label.setAttribute("data-t3code-pick-label", "");
113
+ // `top:0; left:0` so transform translate() positions are absolute viewport
114
+ // coordinates (we re-anchor the label every paint via a single transform).
115
+ // `max-width: calc(100vw - 8px)` + ellipsis prevents an overly long
116
+ // tag#id.class string from overflowing the viewport horizontally before we
117
+ // even get to the clamp logic.
118
+ label.style.cssText = [
119
+ "position:absolute",
120
+ "left:0",
121
+ "top:0",
122
+ "padding:2px 6px",
123
+ "background:" + LABEL_BG,
124
+ "color:white",
125
+ "font:600 11px/1.2 ui-sans-serif,system-ui,-apple-system,sans-serif",
126
+ "border-radius:3px",
127
+ "pointer-events:none",
128
+ "white-space:nowrap",
129
+ "max-width:calc(100vw - 8px)",
130
+ "overflow:hidden",
131
+ "text-overflow:ellipsis",
132
+ "box-shadow:0 1px 2px rgba(0,0,0,0.25)",
133
+ "display:none",
134
+ ].join(";");
135
+
136
+ overlay.appendChild(outline);
137
+ overlay.appendChild(label);
138
+ document.documentElement.appendChild(overlay);
139
+
140
+ // Force the crosshair cursor across the whole page even though we set it
141
+ // on the overlay (because pointer-events: none means it's never the
142
+ // cursor target). We add a stylesheet rule and revert on cleanup.
143
+ const styleEl = document.createElement("style");
144
+ styleEl.textContent = `html[data-t3code-picking="1"], html[data-t3code-picking="1"] *, html[data-t3code-picking="1"] *::before, html[data-t3code-picking="1"] *::after { cursor: crosshair !important; }`;
145
+ document.documentElement.appendChild(styleEl);
146
+ document.documentElement.setAttribute("data-t3code-picking", "1");
147
+
148
+ const destroyDom = (): void => {
149
+ overlay.remove();
150
+ styleEl.remove();
151
+ document.documentElement.removeAttribute("data-t3code-picking");
152
+ };
153
+
154
+ return { overlay, outline, label, destroyDom };
155
+}
156
+
157
+/**
158
+ * Resolve the element under the cursor while ignoring our own overlay.
159
+ * We render at z-index 2147483646 with `pointer-events: none`, which means
160
+ * `elementFromPoint` already skips the overlay — but we double-guard against
161
+ * pages that mutate `pointer-events` via MutationObservers.
162
+ */
163
+function pickFromPoint(clientX: number, clientY: number): Element | null {
164
+ const candidates = document.elementsFromPoint(clientX, clientY);
165
+ for (const candidate of candidates) {
166
+ if (!(candidate instanceof Element)) continue;
167
+ if (candidate.hasAttribute("data-t3code-pick-overlay")) continue;
168
+ if (candidate.hasAttribute("data-t3code-pick-outline")) continue;
169
+ if (candidate.hasAttribute("data-t3code-pick-label")) continue;
170
+ if (candidate === document.documentElement) continue;
171
+ if (candidate === document.body) continue;
172
+ return candidate;
173
+ }
174
+ return null;
175
+}
176
+
177
+function describeRawElement(element: Element): string {
178
+ const tag = element.tagName.toLowerCase();
179
+ const id = element.id ? `#${element.id}` : "";
180
+ const className =
181
+ element instanceof HTMLElement && typeof element.className === "string"
182
+ ? element.className
183
+ .trim()
184
+ .split(/\s+/)
185
+ .filter((token) => token.length > 0)
186
+ .slice(0, 2)
187
+ .map((token) => `.${token}`)
188
+ .join("")
189
+ : "";
190
+ return `${tag}${id}${className}`;
191
+}
192
+
193
+/**
194
+ * Per-session cache of the resolved React component name for elements we've
195
+ * already inspected. Stores `null` when react-grab couldn't find a component
196
+ * (raw HTML / unmounted) so repeat hovers don't re-pay the async lookup.
197
+ */
198
+const componentNameCache = new WeakMap<Element, string | null>();
199
+const componentNameInFlight = new WeakSet<Element>();
200
+
201
+function describeElement(element: Element): string {
202
+ const cached = componentNameCache.get(element);
203
+ if (cached) return `<${cached}> ${describeRawElement(element)}`;
204
+ return describeRawElement(element);
205
+}
206
+
207
+function paintOutline(handles: OverlayHandles, element: Element): void {
208
+ const rect = element.getBoundingClientRect();
209
+ if (rect.width === 0 && rect.height === 0) {
210
+ handles.outline.style.display = "none";
211
+ handles.label.style.display = "none";
212
+ return;
213
+ }
214
+ handles.outline.style.display = "block";
215
+ handles.outline.style.transform = `translate(${rect.left}px, ${rect.top}px)`;
216
+ handles.outline.style.width = `${rect.width}px`;
217
+ handles.outline.style.height = `${rect.height}px`;
218
+
219
+ // Two-pass label paint: first apply the new text and force-block display
220
+ // so we can measure the rendered size, then clamp to the viewport and
221
+ // flip below the element when there isn't room above.
222
+ const text = describeElement(element);
223
+ if (handles.label.textContent !== text) {
224
+ handles.label.textContent = text;
225
+ }
226
+ handles.label.style.display = "block";
227
+
228
+ const labelRect = handles.label.getBoundingClientRect();
229
+ const { x, y } = computeLabelPosition({
230
+ targetLeft: rect.left,
231
+ targetTop: rect.top,
232
+ targetBottom: rect.bottom,
233
+ labelWidth: labelRect.width,
234
+ labelHeight: labelRect.height,
235
+ viewportWidth: document.documentElement.clientWidth || window.innerWidth || labelRect.width,
236
+ viewportHeight: document.documentElement.clientHeight || window.innerHeight || labelRect.height,
237
+ });
238
+ handles.label.style.transform = `translate(${x}px, ${y}px)`;
239
+}
240
+
241
+/**
242
+ * Kick off (at most once per element) an async react-grab lookup for the
243
+ * component name. When the answer arrives, repaint the label iff the element
244
+ * is still under the cursor — otherwise the user has moved on and a stale
245
+ * paint would clobber the next element's label.
246
+ */
247
+function ensureComponentName(element: Element, onResolve: (resolvedFor: Element) => void): void {
248
+ if (componentNameCache.has(element)) return;
249
+ if (componentNameInFlight.has(element)) return;
250
+ componentNameInFlight.add(element);
251
+ void getElementContext(element)
252
+ .then((context) => {
253
+ const trimmed = context.componentName?.trim();
254
+ componentNameCache.set(element, trimmed && trimmed.length > 0 ? trimmed : null);
255
+ })
256
+ .catch(() => {
257
+ componentNameCache.set(element, null);
258
+ })
259
+ .finally(() => {
260
+ componentNameInFlight.delete(element);
261
+ onResolve(element);
262
+ });
263
+}
264
+
265
+function clearOutline(handles: OverlayHandles): void {
266
+ handles.outline.style.display = "none";
267
+ handles.label.style.display = "none";
268
+}
269
+
270
+function toStackFrame(frame: {
271
+ functionName?: string;
272
+ fileName?: string;
273
+ lineNumber?: number;
274
+ columnNumber?: number;
275
+}): PickedElementStackFrame {
276
+ return {
277
+ functionName: frame.functionName ?? null,
278
+ fileName: frame.fileName ?? null,
279
+ lineNumber: frame.lineNumber ?? null,
280
+ columnNumber: frame.columnNumber ?? null,
281
+ };
282
+}
283
+
284
+async function captureElement(element: Element): Promise<PickedElementPayload | null> {
285
+ try {
286
+ const context = await getElementContext(element);
287
+ const stack = (context.stack ?? []).map((frame) => toStackFrame(frame));
288
+ return {
289
+ pageUrl: location.href,
290
+ pageTitle: document.title?.trim() ? document.title.trim() : null,
291
+ tagName: element.tagName.toLowerCase(),
292
+ selector: context.selector,
293
+ htmlPreview: context.htmlPreview ?? "",
294
+ componentName: context.componentName,
295
+ source: stack[0] ?? null,
296
+ stack,
297
+ styles: context.styles ?? "",
298
+ pickedAt: new Date().toISOString(),
299
+ };
300
+ } catch {
301
+ return null;
302
+ }
303
+}
304
+
305
+function startPick(): void {
306
+ endActiveSession();
307
+ if (typeof document === "undefined" || !document.body) {
308
+ ipcRenderer.send(ELEMENT_PICKED_CHANNEL, null);
309
+ return;
310
+ }
311
+
312
+ const handles = createOverlay();
313
+ let lastTarget: Element | null = null;
314
+ let resolved = false;
315
+
316
+ // Tear down listeners + DOM. Does NOT notify main. `notifyMain` controls
317
+ // whether we additionally bubble a `null` ELEMENT_PICKED back so main can
318
+ // resolve the in-flight pick promise (only true for USER-initiated cancels;
319
+ // main already knows about its own cancellations).
320
+ const teardown = (notifyMain: boolean, payload: PickedElementPayload | null): void => {
321
+ if (resolved) return;
322
+ resolved = true;
323
+ window.removeEventListener("mousemove", onMove, { capture: true } as EventListenerOptions);
324
+ window.removeEventListener("click", onClick, { capture: true } as EventListenerOptions);
325
+ window.removeEventListener("keydown", onKey, { capture: true } as EventListenerOptions);
326
+ window.removeEventListener("scroll", onScrollOrResize, {
327
+ capture: true,
328
+ } as EventListenerOptions);
329
+ window.removeEventListener("resize", onScrollOrResize);
330
+ window.removeEventListener("beforeunload", onBeforeUnload);
331
+ ipcRenderer.off(CANCEL_PICK_CHANNEL, onMainCancel);
332
+ handles.destroyDom();
333
+ if (notifyMain) {
334
+ // `ipcRenderer.send` (NOT `sendToHost`) reaches main, where the
335
+ // PreviewViewManager's per-WebContents `wc.ipc.on(...)` listener
336
+ // resolves the in-flight pick promise.
337
+ ipcRenderer.send(ELEMENT_PICKED_CHANNEL, payload);
338
+ }
339
+ };
340
+
341
+ // Re-paint when an in-flight component-name lookup resolves, but only if
342
+ // the same element is still under the cursor — otherwise the user moved on
343
+ // and we'd clobber the next element's label.
344
+ const onComponentNameResolved = (resolvedFor: Element): void => {
345
+ if (lastTarget !== resolvedFor) return;
346
+ paintOutline(handles, resolvedFor);
347
+ };
348
+
349
+ const onMove = (event: MouseEvent): void => {
350
+ const target = pickFromPoint(event.clientX, event.clientY);
351
+ if (target === lastTarget) return;
352
+ lastTarget = target;
353
+ if (target) {
354
+ paintOutline(handles, target);
355
+ ensureComponentName(target, onComponentNameResolved);
356
+ } else {
357
+ clearOutline(handles);
358
+ }
359
+ };
360
+
361
+ const onScrollOrResize = (): void => {
362
+ if (lastTarget) paintOutline(handles, lastTarget);
363
+ };
364
+
365
+ const onClick = (event: MouseEvent): void => {
366
+ event.preventDefault();
367
+ event.stopPropagation();
368
+ const target = pickFromPoint(event.clientX, event.clientY);
369
+ if (!target) {
370
+ teardown(true, null);
371
+ return;
372
+ }
373
+ void captureElement(target).then((payload) => teardown(true, payload));
374
+ };
375
+
376
+ const onKey = (event: KeyboardEvent): void => {
377
+ if (event.key === "Escape") {
378
+ event.preventDefault();
379
+ event.stopPropagation();
380
+ teardown(true, null);
381
+ }
382
+ };
383
+
384
+ const onBeforeUnload = (): void => {
385
+ teardown(true, null);
386
+ };
387
+
388
+ // Cancellation initiated by main (CANCEL_PICK_CHANNEL). Tear down silently
389
+ // — main already knows it cancelled and is either done waiting or about to
390
+ // register a fresh listener for a new pick. If we sent `null` here, that
391
+ // fresh listener would receive it and resolve the new pick instantly (the
392
+ // C1 race we previously hit).
393
+ const onMainCancel = (): void => {
394
+ teardown(false, null);
395
+ };
396
+
397
+ // Capture-phase listeners on `window` to outrun page handlers that
398
+ // `stopPropagation()` early. `passive: false` because we need preventDefault.
399
+ window.addEventListener("mousemove", onMove, { capture: true, passive: true });
400
+ window.addEventListener("click", onClick, { capture: true });
401
+ window.addEventListener("keydown", onKey, { capture: true });
402
+ window.addEventListener("scroll", onScrollOrResize, { capture: true, passive: true });
403
+ window.addEventListener("resize", onScrollOrResize, { passive: true });
404
+ window.addEventListener("beforeunload", onBeforeUnload);
405
+ ipcRenderer.on(CANCEL_PICK_CHANNEL, onMainCancel);
406
+
407
+ // Hand a "silent teardown" to `activeSession` so that a follow-up
408
+ // `startPick()` can supersede us without echoing `null` back to main.
409
+ activeSession = {
410
+ overlay: handles.overlay,
411
+ outline: handles.outline,
412
+ label: handles.label,
413
+ teardownSilent: () => teardown(false, null),
414
+ };
415
+}
416
+
417
+ipcRenderer.on(START_PICK_CHANNEL, () => {
418
+ startPick();
419
+});