@antone-io/render-picker 0.0.0-stage → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2587 @@
1
+ "use client";
2
+
3
+ // src/core/devpanel/console-capture.ts
4
+ var LEVELS = ["log", "info", "warn", "error", "debug"];
5
+ var MAX_LEN = 2e3;
6
+ function argToText(arg) {
7
+ if (typeof arg === "string") return arg;
8
+ if (arg instanceof Error) return `${arg.name}: ${arg.message}`;
9
+ if (arg === null) return "null";
10
+ if (arg === void 0) return "undefined";
11
+ if (typeof arg === "object") {
12
+ try {
13
+ return JSON.stringify(arg);
14
+ } catch {
15
+ return Object.prototype.toString.call(arg);
16
+ }
17
+ }
18
+ return String(arg);
19
+ }
20
+ function initConsoleCapture(onEntry) {
21
+ if (typeof console === "undefined") return () => {
22
+ };
23
+ const originals = /* @__PURE__ */ new Map();
24
+ for (const level of LEVELS) {
25
+ const original = console[level];
26
+ originals.set(level, original);
27
+ console[level] = (...args) => {
28
+ try {
29
+ const text = args.map(argToText).join(" ").slice(0, MAX_LEN);
30
+ onEntry({ level, text, ts: Date.now() });
31
+ } catch {
32
+ }
33
+ original.apply(console, args);
34
+ };
35
+ }
36
+ return () => {
37
+ for (const [level, original] of originals) console[level] = original;
38
+ };
39
+ }
40
+
41
+ // src/core/devpanel/network-capture.ts
42
+ var BODY_CAP = 1e4;
43
+ var STACK_CAP = 4e3;
44
+ function cap(s, n) {
45
+ return s.length > n ? `${s.slice(0, n)}\u2026` : s;
46
+ }
47
+ function urlOf(input) {
48
+ if (typeof input === "string") return input;
49
+ if (input instanceof URL) return input.href;
50
+ if (input && typeof input === "object" && "url" in input) {
51
+ return String(input.url);
52
+ }
53
+ return String(input);
54
+ }
55
+ function initiatorStack() {
56
+ const raw = new Error().stack ?? "";
57
+ const lines = raw.split("\n").slice(3).join("\n").trim();
58
+ return cap(lines, STACK_CAP);
59
+ }
60
+ function normalizeHeaders(h) {
61
+ if (!h) return void 0;
62
+ const out = {};
63
+ if (typeof Headers !== "undefined" && h instanceof Headers) {
64
+ h.forEach((v, k) => out[k] = v);
65
+ } else if (Array.isArray(h)) {
66
+ for (const [k, v] of h) out[k] = v;
67
+ } else {
68
+ Object.assign(out, h);
69
+ }
70
+ return Object.keys(out).length ? out : void 0;
71
+ }
72
+ function headersOf(h) {
73
+ const out = {};
74
+ h.forEach((v, k) => out[k] = v);
75
+ return out;
76
+ }
77
+ function parseRawHeaders(raw) {
78
+ const out = {};
79
+ for (const line of raw.trim().split(/[\r\n]+/)) {
80
+ const i = line.indexOf(":");
81
+ if (i > 0) out[line.slice(0, i).trim()] = line.slice(i + 1).trim();
82
+ }
83
+ return out;
84
+ }
85
+ function bodyToText(body) {
86
+ if (typeof body === "string") return cap(body, BODY_CAP);
87
+ if (body == null) return void 0;
88
+ return `[${Object.prototype.toString.call(body).slice(8, -1)}]`;
89
+ }
90
+ function initNetworkCapture(onEntry) {
91
+ if (typeof window === "undefined") return () => {
92
+ };
93
+ const cleanups = [];
94
+ if (typeof window.fetch === "function") {
95
+ const original = window.fetch;
96
+ window.fetch = ((input, init) => {
97
+ const start = Date.now();
98
+ const method = (init?.method || input?.method || "GET").toUpperCase();
99
+ const url = urlOf(input);
100
+ const initiator = initiatorStack();
101
+ const reqHeaders = normalizeHeaders(init?.headers);
102
+ const reqBody = bodyToText(init?.body);
103
+ const base = { method, url, ts: start, initiator, reqHeaders, reqBody };
104
+ return original.call(window, input, init).then(
105
+ (res) => {
106
+ const meta = {
107
+ ...base,
108
+ status: res.status,
109
+ ok: res.ok,
110
+ durationMs: Date.now() - start,
111
+ resHeaders: headersOf(res.headers),
112
+ type: res.headers.get("content-type") ?? void 0
113
+ };
114
+ res.clone().text().then(
115
+ (text) => onEntry({ ...meta, resBody: cap(text, BODY_CAP) }),
116
+ () => onEntry(meta)
117
+ );
118
+ return res;
119
+ },
120
+ (err) => {
121
+ onEntry({ ...base, status: 0, ok: false, durationMs: Date.now() - start });
122
+ throw err;
123
+ }
124
+ );
125
+ });
126
+ cleanups.push(() => {
127
+ window.fetch = original;
128
+ });
129
+ }
130
+ const XHR = window.XMLHttpRequest;
131
+ if (XHR) {
132
+ const open = XHR.prototype.open;
133
+ const send = XHR.prototype.send;
134
+ const setHeader = XHR.prototype.setRequestHeader;
135
+ XHR.prototype.open = function(method, url, ...rest) {
136
+ this.__rp = {
137
+ method: (method || "GET").toUpperCase(),
138
+ url: urlOf(url),
139
+ start: 0,
140
+ reqHeaders: {},
141
+ initiator: ""
142
+ };
143
+ return open.call(this, method, url, ...rest);
144
+ };
145
+ XHR.prototype.setRequestHeader = function(name, value) {
146
+ if (this.__rp) this.__rp.reqHeaders[name] = value;
147
+ return setHeader.call(this, name, value);
148
+ };
149
+ XHR.prototype.send = function(...args) {
150
+ const rp = this.__rp;
151
+ if (rp) {
152
+ rp.start = Date.now();
153
+ rp.reqBody = bodyToText(args[0]);
154
+ rp.initiator = initiatorStack();
155
+ this.addEventListener("loadend", () => {
156
+ let resBody;
157
+ try {
158
+ resBody = typeof this.responseText === "string" ? cap(this.responseText, BODY_CAP) : void 0;
159
+ } catch {
160
+ resBody = void 0;
161
+ }
162
+ onEntry({
163
+ method: rp.method,
164
+ url: rp.url,
165
+ status: this.status,
166
+ ok: this.status >= 200 && this.status < 400,
167
+ durationMs: Date.now() - rp.start,
168
+ ts: rp.start,
169
+ reqHeaders: Object.keys(rp.reqHeaders).length ? rp.reqHeaders : void 0,
170
+ reqBody: rp.reqBody,
171
+ resHeaders: parseRawHeaders(this.getAllResponseHeaders?.() ?? ""),
172
+ resBody,
173
+ type: this.getResponseHeader?.("content-type") ?? void 0,
174
+ initiator: rp.initiator
175
+ });
176
+ });
177
+ }
178
+ return send.apply(this, args);
179
+ };
180
+ cleanups.push(() => {
181
+ XHR.prototype.open = open;
182
+ XHR.prototype.send = send;
183
+ XHR.prototype.setRequestHeader = setHeader;
184
+ });
185
+ }
186
+ return () => {
187
+ for (const fn of cleanups) fn();
188
+ };
189
+ }
190
+
191
+ // src/core/devpanel/store.ts
192
+ var MAX = 500;
193
+ var logs = [];
194
+ var requests = [];
195
+ var listeners = /* @__PURE__ */ new Set();
196
+ function emit() {
197
+ for (const fn of listeners) fn();
198
+ }
199
+ function addLog(entry) {
200
+ logs.push(entry);
201
+ if (logs.length > MAX) logs.shift();
202
+ emit();
203
+ }
204
+ function addRequest(entry) {
205
+ requests.push(entry);
206
+ if (requests.length > MAX) requests.shift();
207
+ emit();
208
+ }
209
+ function getState() {
210
+ return { logs, requests };
211
+ }
212
+ function clearLogs() {
213
+ logs.length = 0;
214
+ emit();
215
+ }
216
+ function clearRequests() {
217
+ requests.length = 0;
218
+ emit();
219
+ }
220
+ function subscribe(fn) {
221
+ listeners.add(fn);
222
+ return () => listeners.delete(fn);
223
+ }
224
+
225
+ // src/core/devpanel/capture.ts
226
+ var started = false;
227
+ function startCapture() {
228
+ if (started || typeof window === "undefined") return () => {
229
+ };
230
+ started = true;
231
+ const stopConsole = initConsoleCapture(addLog);
232
+ const stopNetwork = initNetworkCapture(addRequest);
233
+ return () => {
234
+ stopConsole();
235
+ stopNetwork();
236
+ started = false;
237
+ };
238
+ }
239
+
240
+ // src/core/inspector/constants/behavior.ts
241
+ var IGNORE_ATTR = "data-pathpicker-ignore";
242
+ var NPM_MARKER_ATTR = "data-render-picker";
243
+ var MAX_DESCEND = 32;
244
+ var SWALLOW_MS = 700;
245
+ var DOUBLE_TAP_WINDOW = 400;
246
+ var PRESS_EVENTS = [
247
+ "pointerdown",
248
+ "mousedown",
249
+ "pointerup",
250
+ "mouseup",
251
+ "click",
252
+ "auxclick",
253
+ "dblclick",
254
+ "contextmenu"
255
+ ];
256
+ var CONTEXT_MENU_OPEN = { value: false };
257
+ var ARMED_WINDOW_KEY = "__renderPickerArmed";
258
+ var PICKER_ARMED = {
259
+ get value() {
260
+ return typeof window !== "undefined" && window[ARMED_WINDOW_KEY] === true;
261
+ },
262
+ set value(armed) {
263
+ if (typeof window === "undefined") return;
264
+ window[ARMED_WINDOW_KEY] = armed;
265
+ }
266
+ };
267
+ var hasPointer = typeof window !== "undefined" && "PointerEvent" in window;
268
+ var DOWN_TYPE = hasPointer ? "pointerdown" : "mousedown";
269
+
270
+ // src/core/dev/editors.ts
271
+ var EDITORS = [
272
+ { id: "vscode", label: "VS Code", scheme: "vscode", family: "vscode" },
273
+ { id: "vscode-insiders", label: "VS Code Insiders", scheme: "vscode-insiders", family: "vscode" },
274
+ { id: "cursor", label: "Cursor", scheme: "cursor", family: "vscode" },
275
+ { id: "windsurf", label: "Windsurf", scheme: "windsurf", family: "vscode" },
276
+ { id: "vscodium", label: "VSCodium", scheme: "vscodium", family: "vscode" },
277
+ { id: "zed", label: "Zed", scheme: "zed", family: "zed" },
278
+ { id: "webstorm", label: "WebStorm", scheme: "webstorm", family: "jetbrains" },
279
+ { id: "phpstorm", label: "PhpStorm", scheme: "phpstorm", family: "jetbrains" },
280
+ { id: "idea", label: "IntelliJ IDEA", scheme: "idea", family: "jetbrains" },
281
+ { id: "pycharm", label: "PyCharm", scheme: "pycharm", family: "jetbrains" }
282
+ ];
283
+ var DEFAULT_EDITOR = "vscode";
284
+ function isEditorId(value) {
285
+ return typeof value === "string" && EDITORS.some((e) => e.id === value);
286
+ }
287
+ function parseSource(source) {
288
+ const m = /^(.*?)(?::(\d+))?(?::(\d+))?$/.exec(source);
289
+ return { file: m?.[1] ?? source, line: m?.[2], col: m?.[3] };
290
+ }
291
+ function buildEditorUri(editor, root, source) {
292
+ if (!root || !source) return null;
293
+ const normalizedRoot = root.replace(/\\/g, "/").replace(/\/+$/, "");
294
+ if (!normalizedRoot) return null;
295
+ const rel = source.replace(/^\/+/, "");
296
+ if (!rel) return null;
297
+ const info = EDITORS.find((e) => e.id === editor) ?? EDITORS[0];
298
+ switch (info.family) {
299
+ case "vscode":
300
+ return `${info.scheme}://file/${normalizedRoot}/${rel}`;
301
+ case "zed":
302
+ return `zed://file/${normalizedRoot.replace(/^\/+/, "")}/${rel}`;
303
+ case "jetbrains": {
304
+ const { file, line, col } = parseSource(rel);
305
+ let uri = `${info.scheme}://open?file=${encodeURIComponent(`${normalizedRoot}/${file}`)}`;
306
+ if (line) uri += `&line=${line}`;
307
+ if (line && col) uri += `&column=${col}`;
308
+ return uri;
309
+ }
310
+ }
311
+ }
312
+
313
+ // src/core/settings.ts
314
+ var DEFAULT_SETTINGS = {
315
+ commands: {
316
+ arm: "shift shift",
317
+ copy: { modifier: "none", trigger: "click" },
318
+ copyHtml: { modifier: "none", trigger: "rightclick" },
319
+ multi: { modifier: "shift", trigger: "click" },
320
+ confirm: "enter",
321
+ cancel: "escape",
322
+ inspect: { modifier: "ctrl", key: "i", double: false },
323
+ search: { modifier: "ctrl", key: "f", double: true },
324
+ source: { modifier: "alt", trigger: "click" },
325
+ usage: { modifier: "ctrl", trigger: "click" },
326
+ editor: DEFAULT_EDITOR
327
+ },
328
+ panel: { width: 420, height: 320 },
329
+ showModuleOverlay: false
330
+ };
331
+ function modifierMatches(mod, e) {
332
+ switch (mod) {
333
+ case "ctrl":
334
+ return e.ctrlKey;
335
+ case "alt":
336
+ return e.altKey;
337
+ case "meta":
338
+ return e.metaKey;
339
+ case "shift":
340
+ return e.shiftKey;
341
+ case "none":
342
+ return !e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey;
343
+ case "off":
344
+ return false;
345
+ }
346
+ }
347
+ function gestureMatches(b, e, kind) {
348
+ return b.trigger === kind && modifierMatches(b.modifier, e);
349
+ }
350
+ var KEY_OF = {
351
+ enter: "Enter",
352
+ escape: "Escape",
353
+ space: " "
354
+ };
355
+ function keyMatches(choice, key) {
356
+ return KEY_OF[choice] === key;
357
+ }
358
+ var STORAGE_KEY = "render-picker:settings";
359
+ var ROUTE_ENDPOINT = "/api/render-picker";
360
+ var ENDPOINT = ROUTE_ENDPOINT;
361
+ function configSettings() {
362
+ try {
363
+ const raw = process.env.NEXT_PUBLIC_RENDER_PICKER_CONFIG;
364
+ if (!raw) return null;
365
+ return JSON.parse(raw);
366
+ } catch {
367
+ return null;
368
+ }
369
+ }
370
+ function sameBinding(a, b) {
371
+ return a.modifier === b.modifier && a.trigger === b.trigger;
372
+ }
373
+ function sameKeyBinding(a, b) {
374
+ return a.modifier === b.modifier && a.key === b.key && a.double === b.double;
375
+ }
376
+ function normalizeKeyBinding(raw, def) {
377
+ if (raw == null) return def;
378
+ if (typeof raw === "string") return { ...def, key: raw, double: false };
379
+ const o = raw;
380
+ return {
381
+ modifier: o.modifier ?? def.modifier,
382
+ key: o.key ?? def.key,
383
+ double: o.double ?? def.double
384
+ };
385
+ }
386
+ function settingsDelta(settings, base = DEFAULT_SETTINGS) {
387
+ const delta = {};
388
+ const commands = {};
389
+ const sc = settings.commands;
390
+ const bc = base.commands;
391
+ if (sc.arm !== bc.arm) commands.arm = sc.arm;
392
+ if (!sameBinding(sc.copy, bc.copy)) commands.copy = sc.copy;
393
+ if (!sameBinding(sc.copyHtml, bc.copyHtml)) commands.copyHtml = sc.copyHtml;
394
+ if (!sameBinding(sc.multi, bc.multi)) commands.multi = sc.multi;
395
+ if (sc.confirm !== bc.confirm) commands.confirm = sc.confirm;
396
+ if (sc.cancel !== bc.cancel) commands.cancel = sc.cancel;
397
+ if (!sameKeyBinding(sc.inspect, bc.inspect)) commands.inspect = sc.inspect;
398
+ if (!sameKeyBinding(sc.search, bc.search)) commands.search = sc.search;
399
+ if (!sameBinding(sc.source, bc.source)) commands.source = sc.source;
400
+ if (!sameBinding(sc.usage, bc.usage)) commands.usage = sc.usage;
401
+ if (sc.editor !== bc.editor) commands.editor = sc.editor;
402
+ if (Object.keys(commands).length > 0) delta.commands = commands;
403
+ if (settings.panel.width !== base.panel.width || settings.panel.height !== base.panel.height) {
404
+ delta.panel = { width: settings.panel.width, height: settings.panel.height };
405
+ }
406
+ if (settings.showModuleOverlay !== base.showModuleOverlay) {
407
+ delta.showModuleOverlay = settings.showModuleOverlay;
408
+ }
409
+ return delta;
410
+ }
411
+ function merge(base, patch) {
412
+ if (!patch) return base;
413
+ const patchCommands = patch.commands ?? {};
414
+ return {
415
+ ...base,
416
+ ...patch,
417
+ commands: {
418
+ arm: patchCommands.arm ?? base.commands.arm,
419
+ copy: { ...base.commands.copy, ...patchCommands.copy ?? {} },
420
+ copyHtml: { ...base.commands.copyHtml, ...patchCommands.copyHtml ?? {} },
421
+ multi: { ...base.commands.multi, ...patchCommands.multi ?? {} },
422
+ confirm: patchCommands.confirm ?? base.commands.confirm,
423
+ cancel: patchCommands.cancel ?? base.commands.cancel,
424
+ inspect: normalizeKeyBinding(patchCommands.inspect, base.commands.inspect),
425
+ search: normalizeKeyBinding(patchCommands.search, base.commands.search),
426
+ source: { ...base.commands.source, ...patchCommands.source ?? {} },
427
+ usage: { ...base.commands.usage, ...patchCommands.usage ?? {} },
428
+ // Valeur inconnue (config éditée à la main) → éditeur de base.
429
+ editor: isEditorId(patchCommands.editor) ? patchCommands.editor : base.commands.editor
430
+ },
431
+ panel: { ...base.panel, ...patch.panel ?? {} }
432
+ };
433
+ }
434
+ function loadSettings() {
435
+ if (routePatch !== void 0) return merge(DEFAULT_SETTINGS, routePatch);
436
+ const file = configSettings();
437
+ if (file) return merge(DEFAULT_SETTINGS, file);
438
+ if (typeof window === "undefined") return DEFAULT_SETTINGS;
439
+ try {
440
+ const raw = window.localStorage.getItem(STORAGE_KEY);
441
+ return raw ? merge(DEFAULT_SETTINGS, JSON.parse(raw)) : DEFAULT_SETTINGS;
442
+ } catch {
443
+ return DEFAULT_SETTINGS;
444
+ }
445
+ }
446
+ var warnedNoRoute = false;
447
+ function warnNoRoute(detail) {
448
+ if (warnedNoRoute) return;
449
+ warnedNoRoute = true;
450
+ console.warn(
451
+ `[render-picker] render-picker.config.json non \xE9crit (POST ${ENDPOINT} \u2192 ${detail}). Ajoute app/api/render-picker/route.ts : export { GET, POST } from "@antone-io/render-picker/next".`
452
+ );
453
+ }
454
+ function saveSettings(settings, useRoute = true) {
455
+ if (typeof window === "undefined") return;
456
+ const delta = settingsDelta(settings);
457
+ try {
458
+ if (Object.keys(delta).length === 0) {
459
+ window.localStorage.removeItem(STORAGE_KEY);
460
+ } else {
461
+ window.localStorage.setItem(STORAGE_KEY, JSON.stringify(delta));
462
+ }
463
+ } catch {
464
+ }
465
+ if (useRoute && typeof fetch !== "undefined") {
466
+ fetch(ENDPOINT, {
467
+ method: "POST",
468
+ headers: { "content-type": "application/json" },
469
+ body: JSON.stringify(delta)
470
+ }).then((res) => {
471
+ if (!res.ok) {
472
+ warnNoRoute(`status ${res.status}`);
473
+ return;
474
+ }
475
+ routePatch = delta;
476
+ }).catch((e) => warnNoRoute(String(e)));
477
+ }
478
+ }
479
+ var routePatch;
480
+ var refreshUsers = 0;
481
+ var stopRefresh = null;
482
+ async function fetchPatch() {
483
+ if (typeof fetch === "undefined") return null;
484
+ try {
485
+ const res = await fetch(ENDPOINT);
486
+ if (!res.ok) return null;
487
+ const data = await res.json();
488
+ if (!data || typeof data !== "object") return null;
489
+ if (Object.keys(data).length === 0) return null;
490
+ return data;
491
+ } catch {
492
+ return null;
493
+ }
494
+ }
495
+ async function refreshSettings() {
496
+ const patch = await fetchPatch();
497
+ if (patch) routePatch = patch;
498
+ }
499
+ function initSettingsRefresh() {
500
+ if (typeof window === "undefined") return () => {
501
+ };
502
+ if (refreshUsers === 0) {
503
+ void refreshSettings();
504
+ const onFocus = () => {
505
+ void refreshSettings();
506
+ };
507
+ const onVisibility = () => {
508
+ if (document.visibilityState === "visible") void refreshSettings();
509
+ };
510
+ window.addEventListener("focus", onFocus);
511
+ document.addEventListener("visibilitychange", onVisibility);
512
+ stopRefresh = () => {
513
+ window.removeEventListener("focus", onFocus);
514
+ document.removeEventListener("visibilitychange", onVisibility);
515
+ stopRefresh = null;
516
+ };
517
+ }
518
+ refreshUsers++;
519
+ return () => {
520
+ refreshUsers--;
521
+ if (refreshUsers === 0 && stopRefresh) stopRefresh();
522
+ };
523
+ }
524
+ async function fetchSettings() {
525
+ const patch = await fetchPatch();
526
+ if (!patch || !patch.commands) return null;
527
+ return merge(DEFAULT_SETTINGS, patch);
528
+ }
529
+
530
+ // src/core/dev/click-to-source.ts
531
+ function buildVscodeUri(root, source) {
532
+ return buildEditorUri("vscode", root, source);
533
+ }
534
+ var SWALLOWED_EVENTS = ["click", "auxclick", "pointerup", "mouseup"];
535
+ var ROUTE_TIMEOUT_MS = 3e3;
536
+ async function openViaRoute(editor, source) {
537
+ if (typeof fetch === "undefined") return false;
538
+ const ctrl = typeof AbortController !== "undefined" ? new AbortController() : null;
539
+ const timer = ctrl ? setTimeout(() => ctrl.abort(), ROUTE_TIMEOUT_MS) : null;
540
+ try {
541
+ const res = await fetch(ROUTE_ENDPOINT, {
542
+ method: "POST",
543
+ headers: { "content-type": "application/json" },
544
+ body: JSON.stringify({ open: { editor, source } }),
545
+ signal: ctrl?.signal
546
+ });
547
+ return res.ok;
548
+ } catch {
549
+ return false;
550
+ } finally {
551
+ if (timer) clearTimeout(timer);
552
+ }
553
+ }
554
+ function followUri(uri) {
555
+ const a = document.createElement("a");
556
+ a.href = uri;
557
+ a.click();
558
+ }
559
+ var vscodeOpenRef = null;
560
+ function vscodeActionFor(e, kind = "click") {
561
+ const { source, usage } = loadSettings().commands;
562
+ if (usage.trigger === kind && modifierMatches(usage.modifier, e)) return "usage";
563
+ if (source.trigger === kind && modifierMatches(source.modifier, e)) return "source";
564
+ return null;
565
+ }
566
+ function vscodeOpenFor(el, action) {
567
+ if (!vscodeOpenRef) return false;
568
+ vscodeOpenRef(el, action);
569
+ return true;
570
+ }
571
+ function initClickToSource(root, getCommands = () => loadSettings().commands, useRoute = true) {
572
+ if (!root) {
573
+ console.warn(
574
+ "[render-picker] projectRoot absent (NEXT_PUBLIC_PROJECT_ROOT non inject\xE9 ?) \u2014 ouverture dans l'\xE9diteur d\xE9sactiv\xE9e."
575
+ );
576
+ return () => {
577
+ };
578
+ }
579
+ let suppressNext = false;
580
+ let suppressTimer = null;
581
+ const swallow = (e) => {
582
+ if (!suppressNext) return;
583
+ e.preventDefault();
584
+ e.stopImmediatePropagation();
585
+ };
586
+ for (const type of SWALLOWED_EVENTS) {
587
+ window.addEventListener(type, swallow, { capture: true });
588
+ }
589
+ function resolveAction(e, kind) {
590
+ const { source, usage } = getCommands();
591
+ if (PICKER_ARMED.value && usage.trigger === kind && modifierMatches(usage.modifier, e)) {
592
+ return "usage";
593
+ }
594
+ if (source.trigger === kind && modifierMatches(source.modifier, e)) return "source";
595
+ return null;
596
+ }
597
+ function open(e, action) {
598
+ const target = e.target;
599
+ const el = target?.closest("[data-source]");
600
+ if (!el) return;
601
+ openEl(el, action);
602
+ e.preventDefault();
603
+ e.stopImmediatePropagation();
604
+ }
605
+ function openEl(el, action) {
606
+ const rel = action === "usage" ? el.getAttribute("data-owner-source") ?? el.getAttribute("data-source") : el.getAttribute("data-source");
607
+ const editor = getCommands().editor;
608
+ const uri = buildEditorUri(editor, root, rel);
609
+ if (!uri || !rel) return;
610
+ document.dispatchEvent(
611
+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true })
612
+ );
613
+ suppressNext = true;
614
+ if (suppressTimer) clearTimeout(suppressTimer);
615
+ suppressTimer = setTimeout(() => {
616
+ suppressNext = false;
617
+ }, 500);
618
+ const prevOutline = el.style.outline;
619
+ el.style.outline = "2px solid #3b82f6";
620
+ setTimeout(() => {
621
+ el.style.outline = prevOutline;
622
+ }, 400);
623
+ if (!useRoute) {
624
+ followUri(uri);
625
+ return;
626
+ }
627
+ void openViaRoute(editor, rel).then((ok) => {
628
+ if (!ok) followUri(uri);
629
+ });
630
+ }
631
+ vscodeOpenRef = openEl;
632
+ const onPointerDown = (e) => {
633
+ if (e.button !== 0) return;
634
+ const action = resolveAction(e, "click");
635
+ if (action) open(e, action);
636
+ };
637
+ const onContextMenu = (e) => {
638
+ const action = resolveAction(e, "rightclick");
639
+ if (action) open(e, action);
640
+ };
641
+ const onDblClick = (e) => {
642
+ const action = resolveAction(e, "dblclick");
643
+ if (action) open(e, action);
644
+ };
645
+ window.addEventListener("pointerdown", onPointerDown, { capture: true });
646
+ window.addEventListener("contextmenu", onContextMenu, { capture: true });
647
+ window.addEventListener("dblclick", onDblClick, { capture: true });
648
+ return () => {
649
+ window.removeEventListener("pointerdown", onPointerDown, { capture: true });
650
+ window.removeEventListener("contextmenu", onContextMenu, { capture: true });
651
+ window.removeEventListener("dblclick", onDblClick, { capture: true });
652
+ for (const type of SWALLOWED_EVENTS) {
653
+ window.removeEventListener(type, swallow, { capture: true });
654
+ }
655
+ if (suppressTimer) clearTimeout(suppressTimer);
656
+ };
657
+ }
658
+
659
+ // src/core/source/source-map-resolver.ts
660
+ var CHUNK_CACHE_KEY = "__rfComponentTraceChunkCache__";
661
+ var BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
662
+ var CHAR_TO_INT = {};
663
+ for (let i = 0; i < BASE64.length; i++) CHAR_TO_INT[BASE64[i]] = i;
664
+ function decodeVLQ(str, offset) {
665
+ let result = 0;
666
+ let shift = 0;
667
+ let index = offset;
668
+ let value;
669
+ do {
670
+ value = CHAR_TO_INT[str[index]] ?? -1;
671
+ index++;
672
+ result += (value & 31) << shift;
673
+ shift += 5;
674
+ } while (value >= 32);
675
+ const negated = result & 1;
676
+ result >>>= 1;
677
+ return [negated ? -result : result, index];
678
+ }
679
+ function isMappingContinued(char) {
680
+ return char !== "," && char !== ";" && char !== "";
681
+ }
682
+ function parsePlainMap(raw) {
683
+ const mappings = [];
684
+ let sourceIndex = 0;
685
+ let sourceLine = 0;
686
+ let sourceColumn = 0;
687
+ const lines = raw.mappings.split(";");
688
+ for (const line of lines) {
689
+ if (!line) {
690
+ mappings.push(null);
691
+ continue;
692
+ }
693
+ const columns = [];
694
+ let generatedColumn = 0;
695
+ let offset = 0;
696
+ while (offset < line.length) {
697
+ const [deltaCol, next] = decodeVLQ(line, offset);
698
+ generatedColumn += deltaCol;
699
+ offset = next;
700
+ let mapping = { generatedColumn };
701
+ if (offset < line.length && isMappingContinued(line[offset])) {
702
+ const [dSrcIdx, o2] = decodeVLQ(line, offset);
703
+ const [dSrcLine, o3] = decodeVLQ(line, o2);
704
+ const [dSrcCol, o4] = decodeVLQ(line, o3);
705
+ sourceIndex += dSrcIdx;
706
+ sourceLine += dSrcLine;
707
+ sourceColumn += dSrcCol;
708
+ mapping = {
709
+ generatedColumn,
710
+ sourceIndex,
711
+ sourceLine,
712
+ sourceColumn
713
+ };
714
+ offset = o4;
715
+ } else {
716
+ mapping = { generatedColumn };
717
+ }
718
+ columns.push(mapping);
719
+ while (offset < line.length && line[offset] === ",") offset++;
720
+ }
721
+ mappings.push(columns);
722
+ }
723
+ return { mappings, sources: raw.sources ?? [], sourcesContent: raw.sourcesContent ?? [] };
724
+ }
725
+ function parseChunkMap(json) {
726
+ const raw = json;
727
+ if (raw.sections) {
728
+ const sections = raw.sections.map((section) => ({
729
+ offset: section.offset,
730
+ parsed: parsePlainMap(section.map)
731
+ }));
732
+ return {
733
+ kind: "index",
734
+ spanSources: sections.map((s) => s.parsed.sources),
735
+ spanMappings: sections.map((s) => s.parsed.mappings),
736
+ spanContents: sections.map((s) => s.parsed.sourcesContent),
737
+ offsets: sections.map((s) => s.offset)
738
+ };
739
+ }
740
+ const plain = parsePlainMap(raw);
741
+ return { kind: "plain", ...plain };
742
+ }
743
+ async function getChunkMap(chunkUrl) {
744
+ const cache = chunkCache();
745
+ const cached = cache.get(chunkUrl);
746
+ if (cached) return cached;
747
+ const promise = (async () => {
748
+ try {
749
+ const scriptRes = await fetch(chunkUrl);
750
+ if (!scriptRes.ok) return null;
751
+ const source = await scriptRes.text();
752
+ const mapMatch = source.match(/\/\/#\s*sourceMappingURL=(\S+?\.map)\b/);
753
+ if (!mapMatch) return null;
754
+ const mapUrl = mapMatch[1];
755
+ const fullMapUrl = /^[a-z]+:\/\//i.test(mapUrl) ? mapUrl : `${chunkUrl.replace(/\/[^/]*$/, "/")}${mapUrl}`;
756
+ const res = await fetch(fullMapUrl);
757
+ if (!res.ok) return null;
758
+ return parseChunkMap(await res.json());
759
+ } catch {
760
+ return null;
761
+ }
762
+ })();
763
+ cache.set(chunkUrl, promise);
764
+ return promise;
765
+ }
766
+ function chunkCache() {
767
+ const g = globalThis;
768
+ const key = CHUNK_CACHE_KEY;
769
+ if (!g[key]) g[key] = /* @__PURE__ */ new Map();
770
+ return g[key];
771
+ }
772
+ function normalizeSourcePath(path) {
773
+ const normalized = path.replace(/\\/g, "/");
774
+ const match = normalized.match(
775
+ /(?:^|[\\/])((?:src|app)\/[^?#]*?\.(?:tsx?|jsx?|css))/
776
+ );
777
+ return match ? match[1] : normalized;
778
+ }
779
+ var resolvedByCache = /* @__PURE__ */ new WeakMap();
780
+ function resolvePosition(chunkUrl, line, column) {
781
+ const cache = chunkCache();
782
+ let resolvedPositions = resolvedByCache.get(cache);
783
+ if (!resolvedPositions) {
784
+ resolvedPositions = /* @__PURE__ */ new Map();
785
+ resolvedByCache.set(cache, resolvedPositions);
786
+ }
787
+ const key = `${chunkUrl}:${line}:${column}`;
788
+ let resolved = resolvedPositions.get(key);
789
+ if (!resolved) {
790
+ resolved = resolvePositionUncached(chunkUrl, line, column);
791
+ resolvedPositions.set(key, resolved);
792
+ }
793
+ return resolved;
794
+ }
795
+ async function resolvePositionUncached(chunkUrl, line, column) {
796
+ const sm = await getChunkMap(chunkUrl);
797
+ if (!sm) return null;
798
+ if (sm.kind === "plain") {
799
+ return resolveInPlain(sm.mappings, sm.sources, line, column, sm.sourcesContent);
800
+ }
801
+ for (let i = sm.offsets.length - 1; i >= 0; i--) {
802
+ const offset = sm.offsets[i];
803
+ if (line - 1 <= offset.line) {
804
+ continue;
805
+ }
806
+ if (line - 1 > offset.line) {
807
+ return resolveInPlain(
808
+ sm.spanMappings[i] ?? [],
809
+ sm.spanSources[i] ?? [],
810
+ line - offset.line,
811
+ column,
812
+ sm.spanContents[i] ?? []
813
+ );
814
+ }
815
+ }
816
+ return null;
817
+ }
818
+ var sourceLines = /* @__PURE__ */ new Map();
819
+ function linesOf(content) {
820
+ let lines = sourceLines.get(content);
821
+ if (!lines) {
822
+ lines = content.split("\n");
823
+ sourceLines.set(content, lines);
824
+ }
825
+ return lines;
826
+ }
827
+ function isNonCodeSourceLine(content, line) {
828
+ if (content == null) return false;
829
+ const raw = linesOf(content)[line - 1] ?? "";
830
+ const text = raw.trim();
831
+ return text === "" || /^(interface\b|type\b|import\b|export type\b|declare\b|export interface\b)/.test(
832
+ text
833
+ );
834
+ }
835
+ function resolveInPlain(mappings, sources, line, column, sourcesContent) {
836
+ const rows = mappings[line - 1];
837
+ if (!rows) return null;
838
+ let selected = rows[0] ?? { generatedColumn: 0 };
839
+ let selectedIndex = 0;
840
+ for (let i = 0; i < rows.length; i++) {
841
+ const m = rows[i];
842
+ if (m.generatedColumn <= column) {
843
+ selected = m;
844
+ selectedIndex = i;
845
+ } else break;
846
+ }
847
+ if (!("sourceIndex" in selected)) return null;
848
+ const source = sources[selected.sourceIndex];
849
+ if (source == null) return null;
850
+ const relative = normalizeSourcePath(source);
851
+ const base = {
852
+ source: relative,
853
+ line: selected.sourceLine + 1,
854
+ column: selected.sourceColumn
855
+ };
856
+ if (sourcesContent.length > 0 && isNonCodeSourceLine(
857
+ sourcesContent[selected.sourceIndex] ?? null,
858
+ base.line
859
+ )) {
860
+ for (let i = selectedIndex + 1; i < rows.length; i++) {
861
+ const m = rows[i];
862
+ if (!("sourceIndex" in m)) continue;
863
+ if (m.sourceIndex !== selected.sourceIndex) continue;
864
+ const altSource = sources[m.sourceIndex];
865
+ if (altSource == null) continue;
866
+ const altLine = m.sourceLine + 1;
867
+ if (isNonCodeSourceLine(sourcesContent[m.sourceIndex] ?? null, altLine)) {
868
+ continue;
869
+ }
870
+ return {
871
+ source: normalizeSourcePath(altSource),
872
+ line: altLine,
873
+ column: m.sourceColumn
874
+ };
875
+ }
876
+ }
877
+ return base;
878
+ }
879
+
880
+ // src/core/source/component-annotate.ts
881
+ var FIBER_KEY_PREFIX = "__reactFiber$";
882
+ var STACK_FRAME_RE = /(https?:\/\/[^\s()]+?\/_next\/static\/chunks\/[^\s()]+?\._\.js):(\d+):(\d+)/;
883
+ function componentInfo(el) {
884
+ const fiber = getFiber(el);
885
+ if (!fiber) return null;
886
+ let current2 = fiber;
887
+ while (current2) {
888
+ const name = fiberName(current2);
889
+ if (name) {
890
+ return { component: name, source: null };
891
+ }
892
+ current2 = current2.return;
893
+ }
894
+ return null;
895
+ }
896
+ function componentChain(el, max = 4) {
897
+ const fiber = getFiber(el);
898
+ if (!fiber) return [];
899
+ const names = [];
900
+ let owner = fiber._debugOwner;
901
+ while (owner && names.length < max) {
902
+ const name = displayNameOf(owner.type);
903
+ if (name && names[names.length - 1] !== name) names.push(name);
904
+ owner = owner._debugOwner;
905
+ }
906
+ if (names.length === 0) {
907
+ const single = fiberName(fiber);
908
+ return single ? [single] : [];
909
+ }
910
+ return names.reverse();
911
+ }
912
+ function displayNameOf(type) {
913
+ const fn = type;
914
+ return fn?.displayName || fn?.name || null;
915
+ }
916
+ function fiberName(fiber) {
917
+ const direct = displayNameOf(fiber.type);
918
+ if (direct) return direct;
919
+ let owner = fiber._debugOwner;
920
+ while (owner) {
921
+ const ownerName = displayNameOf(owner.type);
922
+ if (ownerName) return ownerName;
923
+ owner = owner._debugOwner;
924
+ }
925
+ if (fiber._debugInfo)
926
+ for (const entry of fiber._debugInfo) {
927
+ const name = entry?.name;
928
+ if (name) return name;
929
+ }
930
+ return null;
931
+ }
932
+ var DIRECT_SOURCE_RE = /(?:^|[\s(/])((?:src|app)\/.+?\.(?:tsx?|jsx?))(?:\?[^\s:)]*)?:(\d+):(\d+)/g;
933
+ var FRAMEWORK_INTERNAL_RE = /(?:^|\/)(?:node_modules|next\/dist)\/|^(?:src|app)\/(?:client|server|shared)\//;
934
+ function extractDirectSources(stackText) {
935
+ const text = stackText.replace(/\\/g, "/");
936
+ const out = [];
937
+ const re = new RegExp(DIRECT_SOURCE_RE.source, "g");
938
+ let m;
939
+ while (m = re.exec(text)) {
940
+ const source = m[1];
941
+ if (FRAMEWORK_INTERNAL_RE.test(source) || /node_modules|next\/dist/.test(m[0])) {
942
+ continue;
943
+ }
944
+ out.push({ source, line: Number(m[2]) });
945
+ }
946
+ return out;
947
+ }
948
+ function stackCandidates(stack) {
949
+ const text = stack?.stack;
950
+ if (!text) return [];
951
+ const frames = [];
952
+ const regex = new RegExp(STACK_FRAME_RE.source, "g");
953
+ let m;
954
+ while (m = regex.exec(text)) {
955
+ frames.push({ url: m[1], line: Number(m[2]), col: Number(m[3]) });
956
+ }
957
+ return frames;
958
+ }
959
+ function getFiber(el) {
960
+ for (const key in el) {
961
+ if (key.startsWith(FIBER_KEY_PREFIX)) {
962
+ return el[key];
963
+ }
964
+ }
965
+ return null;
966
+ }
967
+ var SOURCE_RE = /(?:^|)(?:src|app)\/[^?]*\.(?:tsx?|jsx?|css)$/;
968
+ var PROCESSED_KEY = "__rfComponentTraceDone__";
969
+ var SUSPENSE_TAG = 13;
970
+ function isDehydrated(f) {
971
+ const state = f?.memoizedState;
972
+ return !!state?.dehydrated;
973
+ }
974
+ function isCommittedFiber(fiber) {
975
+ let f = fiber.return;
976
+ while (f) {
977
+ if (f.tag === SUSPENSE_TAG && isDehydrated(f) && (!f.alternate || isDehydrated(f.alternate)))
978
+ return false;
979
+ f = f.return;
980
+ }
981
+ return true;
982
+ }
983
+ var pendingCount = 0;
984
+ function pendingAnnotations() {
985
+ return pendingCount;
986
+ }
987
+ function annotateTree(root) {
988
+ const els = root.querySelectorAll("*");
989
+ let count = 0;
990
+ pendingCount = 0;
991
+ for (const el of els) {
992
+ if (annotate(el)) count++;
993
+ }
994
+ return count;
995
+ }
996
+ function annotate(el) {
997
+ const done = el[PROCESSED_KEY];
998
+ if (done) return false;
999
+ const fiberNow = getFiber(el);
1000
+ if (fiberNow && !isCommittedFiber(fiberNow)) {
1001
+ pendingCount++;
1002
+ return false;
1003
+ }
1004
+ const info = componentInfo(el);
1005
+ if (!info) return false;
1006
+ el[PROCESSED_KEY] = true;
1007
+ el.setAttribute("data-component", info.component);
1008
+ const fiber = getFiber(el);
1009
+ if (!fiber || !fiber._debugStack) return true;
1010
+ resolveFirstSource(fiber._debugStack).then(async (source) => {
1011
+ if (source) el.setAttribute("data-source", source);
1012
+ const owner = await resolveOwnerSource(fiber, fileOf(source));
1013
+ if (owner) el.setAttribute("data-owner-source", owner);
1014
+ });
1015
+ return true;
1016
+ }
1017
+ function fileOf(source) {
1018
+ return source ? source.replace(/:\d+(?::\d+)?$/, "") : null;
1019
+ }
1020
+ async function resolveStackSources(stack) {
1021
+ const direct = [];
1022
+ for (const f of extractDirectSources(stack.stack ?? "")) {
1023
+ if (SOURCE_RE.test(f.source)) direct.push({ source: f.source, line: f.line });
1024
+ }
1025
+ if (direct.length > 0) return direct;
1026
+ const out = [];
1027
+ for (const frame of stackCandidates(stack)) {
1028
+ const resolved = await resolvePosition(frame.url, frame.line, frame.col);
1029
+ if (resolved && SOURCE_RE.test(resolved.source)) {
1030
+ out.push({ source: resolved.source, line: resolved.line });
1031
+ }
1032
+ }
1033
+ return out;
1034
+ }
1035
+ async function resolveFirstSource(stack) {
1036
+ const frames = await resolveStackSources(stack);
1037
+ return frames.length > 0 ? `${frames[0].source}:${frames[0].line}` : null;
1038
+ }
1039
+ async function resolveOwnerSource(fiber, sourceFile) {
1040
+ if (sourceFile && fiber._debugStack) {
1041
+ for (const f of await resolveStackSources(fiber._debugStack)) {
1042
+ if (fileOf(f.source) !== sourceFile) return `${f.source}:${f.line}`;
1043
+ }
1044
+ }
1045
+ let owner = fiber._debugOwner;
1046
+ let depth = 0;
1047
+ while (owner && depth < 12) {
1048
+ if (owner._debugStack) {
1049
+ const s = await resolveFirstSource(owner._debugStack);
1050
+ if (s && fileOf(s) !== sourceFile) return s;
1051
+ }
1052
+ owner = owner._debugOwner;
1053
+ depth++;
1054
+ }
1055
+ return null;
1056
+ }
1057
+ var PENDING_RETRY_MS = 300;
1058
+ var MAX_PENDING_RETRIES = 100;
1059
+ var SETTLE_MS = 1e4;
1060
+ function initComponentAnnotator() {
1061
+ let queued = false;
1062
+ let frame = null;
1063
+ let retryTimer = null;
1064
+ let retries = 0;
1065
+ const startedAt = Date.now();
1066
+ const run = () => {
1067
+ queued = false;
1068
+ frame = null;
1069
+ if (!document.body) return;
1070
+ const added = annotateTree(document.body);
1071
+ const settling = Date.now() - startedAt < SETTLE_MS;
1072
+ if ((pendingAnnotations() > 0 || added > 0 || settling) && retries < MAX_PENDING_RETRIES) {
1073
+ retries++;
1074
+ if (retryTimer === null)
1075
+ retryTimer = setTimeout(() => {
1076
+ retryTimer = null;
1077
+ queue();
1078
+ }, PENDING_RETRY_MS);
1079
+ } else {
1080
+ retries = 0;
1081
+ }
1082
+ };
1083
+ const queue = () => {
1084
+ if (queued) return;
1085
+ queued = true;
1086
+ frame = requestAnimationFrame(run);
1087
+ };
1088
+ const observer = new MutationObserver(queue);
1089
+ const start = () => {
1090
+ observer.observe(document.body, { childList: true, subtree: true });
1091
+ run();
1092
+ };
1093
+ if (document.readyState === "loading")
1094
+ document.addEventListener("DOMContentLoaded", start, { once: true });
1095
+ else start();
1096
+ return () => {
1097
+ document.removeEventListener("DOMContentLoaded", start);
1098
+ observer.disconnect();
1099
+ if (frame !== null) cancelAnimationFrame(frame);
1100
+ if (retryTimer !== null) clearTimeout(retryTimer);
1101
+ };
1102
+ }
1103
+
1104
+ // src/core/source/tpl-annotate.ts
1105
+ var PROCESSED_KEY2 = "__rpTplDone__";
1106
+ function parseTplMarker(text) {
1107
+ const m = /^rp@(.+):(\d+)$/.exec(text.trim());
1108
+ if (!m) return null;
1109
+ return { source: m[1], line: Number(m[2]) };
1110
+ }
1111
+ function basename(path) {
1112
+ const parts = path.split("/");
1113
+ return parts[parts.length - 1] || path;
1114
+ }
1115
+ function moduleNameFromSource(source) {
1116
+ const m = /(?:^|\/)modules\/([^/]+)\//.exec(source);
1117
+ return m ? m[1] : null;
1118
+ }
1119
+ function tplLabel(el) {
1120
+ const src = el.closest("[data-source]")?.getAttribute("data-source");
1121
+ if (!src) return null;
1122
+ const path = src.replace(/:\d+(?::\d+)?$/, "");
1123
+ const mod = moduleNameFromSource(path);
1124
+ if (mod) return mod;
1125
+ return /\.tpl$/.test(path) ? basename(path) : null;
1126
+ }
1127
+ function annotateEl(el, source, component) {
1128
+ if (el[PROCESSED_KEY2]) return 0;
1129
+ el[PROCESSED_KEY2] = true;
1130
+ el.setAttribute("data-source", source);
1131
+ if (component) el.setAttribute("data-component", component);
1132
+ return 1;
1133
+ }
1134
+ function annotateFromComments(root = document.body, seedSource = null, seedComponent = null) {
1135
+ if (!root) return 0;
1136
+ let currentSource = seedSource;
1137
+ let currentComponent = seedComponent;
1138
+ let count = 0;
1139
+ if (root.nodeType === Node.ELEMENT_NODE && currentSource) {
1140
+ count += annotateEl(root, currentSource, currentComponent);
1141
+ }
1142
+ const walker = document.createTreeWalker(
1143
+ root,
1144
+ NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT
1145
+ );
1146
+ let node = walker.nextNode();
1147
+ while (node) {
1148
+ if (node.nodeType === Node.COMMENT_NODE) {
1149
+ const marker = parseTplMarker(node.data);
1150
+ if (marker) {
1151
+ currentSource = `${marker.source}:${marker.line}`;
1152
+ currentComponent = basename(marker.source);
1153
+ }
1154
+ } else if (currentSource) {
1155
+ count += annotateEl(node, currentSource, currentComponent);
1156
+ }
1157
+ node = walker.nextNode();
1158
+ }
1159
+ return count;
1160
+ }
1161
+ function previousInDocOrder(node) {
1162
+ if (node.previousSibling) {
1163
+ let p = node.previousSibling;
1164
+ while (p.lastChild) p = p.lastChild;
1165
+ return p;
1166
+ }
1167
+ return node.parentNode;
1168
+ }
1169
+ function precedingSource(start) {
1170
+ let n = previousInDocOrder(start);
1171
+ for (let steps = 0; n && steps < 5e3; steps++) {
1172
+ if (n.nodeType === Node.COMMENT_NODE) {
1173
+ const m = parseTplMarker(n.data);
1174
+ if (m) return { source: `${m.source}:${m.line}`, component: basename(m.source) };
1175
+ }
1176
+ n = previousInDocOrder(n);
1177
+ }
1178
+ return null;
1179
+ }
1180
+ function annotateSubtree(el) {
1181
+ const pre = precedingSource(el);
1182
+ return annotateFromComments(el, pre?.source ?? null, pre?.component ?? null);
1183
+ }
1184
+ function initTplAnnotator() {
1185
+ const pending = /* @__PURE__ */ new Set();
1186
+ let frame = null;
1187
+ const flush = () => {
1188
+ frame = null;
1189
+ for (const el of pending) {
1190
+ if (el.isConnected) annotateSubtree(el);
1191
+ }
1192
+ pending.clear();
1193
+ };
1194
+ const observer = new MutationObserver((mutations) => {
1195
+ for (const m of mutations) {
1196
+ for (const added of m.addedNodes) {
1197
+ if (added.nodeType === Node.ELEMENT_NODE) pending.add(added);
1198
+ }
1199
+ }
1200
+ if (pending.size > 0 && frame === null) frame = requestAnimationFrame(flush);
1201
+ });
1202
+ const start = () => {
1203
+ annotateFromComments(document.body);
1204
+ observer.observe(document.body, { childList: true, subtree: true });
1205
+ };
1206
+ if (document.readyState === "loading")
1207
+ document.addEventListener("DOMContentLoaded", start, { once: true });
1208
+ else start();
1209
+ return () => {
1210
+ document.removeEventListener("DOMContentLoaded", start);
1211
+ observer.disconnect();
1212
+ if (frame !== null) cancelAnimationFrame(frame);
1213
+ };
1214
+ }
1215
+
1216
+ // src/core/inspector/css-selector.ts
1217
+ var HASH_CLASS_RE = /^css-[a-z0-9]+$/i;
1218
+ function retainedClasses(el) {
1219
+ return Array.from(el.classList).filter((c) => !HASH_CLASS_RE.test(c));
1220
+ }
1221
+ function isUnique(selector) {
1222
+ try {
1223
+ return document.querySelectorAll(selector).length === 1;
1224
+ } catch {
1225
+ return false;
1226
+ }
1227
+ }
1228
+ function getElementSelector(el) {
1229
+ if (el.id) return `#${el.id}`;
1230
+ const tag = el.tagName.toLowerCase();
1231
+ const classes = retainedClasses(el);
1232
+ let selector = tag + classes.map((c) => `.${c}`).join("");
1233
+ const parent = el.parentElement;
1234
+ if (parent) {
1235
+ const classKey = classes.join(" ");
1236
+ const twins = Array.from(parent.children).filter(
1237
+ (s) => s.tagName === el.tagName && retainedClasses(s).join(" ") === classKey
1238
+ );
1239
+ if (twins.length > 1) {
1240
+ const index = Array.from(parent.children).indexOf(el) + 1;
1241
+ selector += `:nth-child(${index})`;
1242
+ }
1243
+ }
1244
+ return selector;
1245
+ }
1246
+ function getCssSelector(el) {
1247
+ if (el.id) return `#${el.id}`;
1248
+ const parts = [];
1249
+ let current2 = el;
1250
+ let depth = 0;
1251
+ while (current2 && current2.nodeType === 1 && current2 !== document.body && depth < 5) {
1252
+ const segment = getElementSelector(current2);
1253
+ parts.unshift(segment);
1254
+ const combined = parts.join(" > ");
1255
+ if (isUnique(combined)) return combined;
1256
+ if (segment.startsWith("#")) break;
1257
+ current2 = current2.parentElement;
1258
+ depth++;
1259
+ }
1260
+ return parts.join(" > ");
1261
+ }
1262
+
1263
+ // src/core/inspector/xpath.ts
1264
+ function isUsableId(id) {
1265
+ return !!id && !id.includes(":") && // React 18 useId / radix (`:r3:`)
1266
+ !id.includes("\xAB") && // variantes useId
1267
+ !id.includes("_r_") && // React 19 useId / headlessui (`..._r_3b_`)
1268
+ !/^(headlessui|radix)-/.test(id);
1269
+ }
1270
+ function getXPath(el) {
1271
+ if (isUsableId(el.id)) return `//*[@id="${el.id}"]`;
1272
+ const parts = [];
1273
+ let current2 = el.closest("svg") ?? el;
1274
+ while (current2 && current2.nodeType === 1 && current2 !== document.documentElement) {
1275
+ const tag = current2.tagName.toLowerCase();
1276
+ if (current2 !== el && isUsableId(current2.id)) {
1277
+ parts.unshift(`*[@id="${current2.id}"]`);
1278
+ return `//${parts.join("/")}`;
1279
+ }
1280
+ const parent = current2.parentElement;
1281
+ let segment = tag;
1282
+ if (parent) {
1283
+ const sameTag = Array.from(parent.children).filter(
1284
+ (c) => c.tagName.toLowerCase() === tag
1285
+ );
1286
+ if (sameTag.length > 1) {
1287
+ segment = `${tag}[${sameTag.indexOf(current2) + 1}]`;
1288
+ }
1289
+ }
1290
+ parts.unshift(segment);
1291
+ current2 = parent;
1292
+ }
1293
+ return `/html/${parts.join("/")}`;
1294
+ }
1295
+
1296
+ // src/core/format.ts
1297
+ var OUTPUT_PREFIX = "[renderPicker]";
1298
+ function reactLines(r) {
1299
+ const out = [];
1300
+ if (r.reactSource) out.push(`Source: ${r.reactSource}`);
1301
+ if (r.reactComponent) out.push(`React: ${r.reactComponent}`);
1302
+ return out;
1303
+ }
1304
+ function formatResult(r) {
1305
+ return [
1306
+ OUTPUT_PREFIX,
1307
+ `Page: ${r.route}`,
1308
+ `XPath: ${r.xpath}`,
1309
+ `CSS: ${r.cssSelector}`,
1310
+ ...r.text ? [`Text: ${r.text}`] : [],
1311
+ ...reactLines(r)
1312
+ ].join("\n");
1313
+ }
1314
+ function elementText(el) {
1315
+ const t = (el.textContent ?? "").replace(/\s+/g, " ").trim();
1316
+ if (!t) return null;
1317
+ return t.length > 200 ? `${t.slice(0, 200)}\u2026` : t;
1318
+ }
1319
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
1320
+ "area",
1321
+ "base",
1322
+ "br",
1323
+ "col",
1324
+ "embed",
1325
+ "hr",
1326
+ "img",
1327
+ "input",
1328
+ "link",
1329
+ "meta",
1330
+ "param",
1331
+ "source",
1332
+ "track",
1333
+ "wbr"
1334
+ ]);
1335
+ function serializeAttrs(el) {
1336
+ let out = "";
1337
+ for (const attr of Array.from(el.attributes)) {
1338
+ out += ` ${attr.name}="${attr.value.replace(/"/g, "&quot;")}"`;
1339
+ }
1340
+ return out;
1341
+ }
1342
+ function printNode(node, depth, indent) {
1343
+ const pad = indent.repeat(depth);
1344
+ if (node.nodeType === 3) {
1345
+ const text = (node.textContent ?? "").trim();
1346
+ return text ? pad + text : "";
1347
+ }
1348
+ if (node.nodeType === 8) {
1349
+ return `${pad}<!--${node.textContent ?? ""}-->`;
1350
+ }
1351
+ if (node.nodeType !== 1) return "";
1352
+ const el = node;
1353
+ const tag = el.localName;
1354
+ const open = `<${tag}${serializeAttrs(el)}>`;
1355
+ if (VOID_ELEMENTS.has(tag)) return pad + open;
1356
+ const children = Array.from(el.childNodes);
1357
+ const hasBlockChild = children.some((c) => c.nodeType === 1 || c.nodeType === 8);
1358
+ if (!hasBlockChild) {
1359
+ const text = (el.textContent ?? "").trim();
1360
+ return text ? `${pad}${open}${text}</${tag}>` : `${pad}${open}</${tag}>`;
1361
+ }
1362
+ const lines = [pad + open];
1363
+ for (const child of children) {
1364
+ const line = printNode(child, depth + 1, indent);
1365
+ if (line) lines.push(line);
1366
+ }
1367
+ lines.push(`${pad}</${tag}>`);
1368
+ return lines.join("\n");
1369
+ }
1370
+ function formatHtml(html, indent = " ") {
1371
+ if (typeof document === "undefined") return html;
1372
+ const container = document.createElement("div");
1373
+ container.innerHTML = html.trim();
1374
+ return Array.from(container.childNodes).map((n) => printNode(n, 0, indent)).filter(Boolean).join("\n");
1375
+ }
1376
+ function formatResults(results) {
1377
+ if (results.length <= 1) {
1378
+ return results[0] ? formatResult(results[0]) : OUTPUT_PREFIX;
1379
+ }
1380
+ const head = [
1381
+ `${OUTPUT_PREFIX} ${results.length} elements`,
1382
+ `Page: ${results[0].route}`
1383
+ ];
1384
+ const blocks = results.map(
1385
+ (r, i) => [
1386
+ `#${i + 1}`,
1387
+ `XPath: ${r.xpath}`,
1388
+ `CSS: ${r.cssSelector}`,
1389
+ ...r.text ? [`Text: ${r.text}`] : [],
1390
+ ...reactLines(r)
1391
+ ].join("\n")
1392
+ );
1393
+ return [...head, "", blocks.join("\n\n")].join("\n");
1394
+ }
1395
+
1396
+ // src/core/search/element-search.ts
1397
+ var SEARCH_MAX_RESULTS = 50;
1398
+ var SEARCH_UI_ATTR = "data-rp-search-ui";
1399
+ var IGNORE_SELECTOR = "[data-pathpicker-ignore]";
1400
+ var WORD_RE = /^[a-zA-Z][\w-]*$/;
1401
+ var CLASS_TOKEN_RE = /^[A-Za-z][A-Za-z0-9_:/.-]*$/;
1402
+ var PARTIAL_RE = /^([a-zA-Z][\w-]*)?\.(\w*)$/;
1403
+ function searchElements(query, root = document) {
1404
+ const partial = PARTIAL_RE.exec(query.trim());
1405
+ if (partial) return searchPartial(partial[1] ?? null, partial[2] ?? "");
1406
+ const selector = toSelector(query);
1407
+ if (!selector) return [];
1408
+ let matches;
1409
+ try {
1410
+ matches = root.querySelectorAll(selector);
1411
+ } catch {
1412
+ return [];
1413
+ }
1414
+ return collect(matches);
1415
+ }
1416
+ function collect(matches) {
1417
+ const results = [];
1418
+ for (const el of matches) {
1419
+ if (results.length >= SEARCH_MAX_RESULTS) break;
1420
+ if (!el.isConnected) continue;
1421
+ if (el.closest(IGNORE_SELECTOR)) continue;
1422
+ results.push(el);
1423
+ }
1424
+ return results;
1425
+ }
1426
+ function searchPartial(tag, prefix, root = document) {
1427
+ let candidates;
1428
+ try {
1429
+ candidates = root.querySelectorAll(tag ?? "*");
1430
+ } catch {
1431
+ return [];
1432
+ }
1433
+ const results = [];
1434
+ const lower = prefix.toLowerCase();
1435
+ const anyClass = lower === "";
1436
+ for (const el of candidates) {
1437
+ if (results.length >= SEARCH_MAX_RESULTS) break;
1438
+ if (!el.isConnected) continue;
1439
+ if (el.closest(IGNORE_SELECTOR)) continue;
1440
+ const raw = el.getAttribute("class");
1441
+ if (!anyClass) {
1442
+ const hit = raw ? raw.trim().split(/\s+/).some((cls) => cls.toLowerCase().startsWith(lower)) : false;
1443
+ if (!hit) continue;
1444
+ }
1445
+ results.push(el);
1446
+ }
1447
+ return results;
1448
+ }
1449
+ function toSelector(query) {
1450
+ const q = query.trim();
1451
+ if (!q) return null;
1452
+ const tokens = q.split(/\s+/);
1453
+ if (tokens.length > 1 && tokens.every((t) => CLASS_TOKEN_RE.test(t))) {
1454
+ return tokens.map((t) => `.${escapeClassToken(t)}`).join("");
1455
+ }
1456
+ const isSimpleWord = WORD_RE.test(q);
1457
+ if (!isSimpleWord) {
1458
+ return q;
1459
+ }
1460
+ const escaped = typeof CSS !== "undefined" && CSS.escape ? CSS.escape(q) : q;
1461
+ return `${q}, .${escaped}, [data-component="${q}" i], [class^="${q}"], [class*=" ${q}"]`;
1462
+ }
1463
+ function pickResultFromElement(el, route) {
1464
+ return {
1465
+ route,
1466
+ xpath: getXPath(el),
1467
+ cssSelector: getCssSelector(el),
1468
+ text: elementText(el),
1469
+ tagName: el.tagName.toLowerCase(),
1470
+ id: el.id || null,
1471
+ reactComponent: null,
1472
+ reactSource: null
1473
+ };
1474
+ }
1475
+ function escapeClassToken(token) {
1476
+ if (WORD_RE.test(token)) return token;
1477
+ if (typeof CSS !== "undefined" && CSS.escape) return CSS.escape(token);
1478
+ if (/^[0-9]/.test(token)) return `\\3${token} `;
1479
+ return token.replace(/[^a-zA-Z0-9_-]/g, (c) => `\\${c}`);
1480
+ }
1481
+ function classPrefixOf(query) {
1482
+ const m = PARTIAL_RE.exec(query.trim());
1483
+ return m ? m[2] ?? "" : null;
1484
+ }
1485
+ function groupResults(elements, prefix = "") {
1486
+ const byKey = /* @__PURE__ */ new Map();
1487
+ const lower = prefix.toLowerCase();
1488
+ elements.forEach((el, i) => {
1489
+ const tag = el.tagName.toLowerCase();
1490
+ const attr = el.getAttribute("class");
1491
+ const rawTokens = attr && attr.trim() ? attr.trim().split(/\s+/) : [];
1492
+ const ordered = lower ? [...rawTokens].sort(
1493
+ (a, b) => Number(b.toLowerCase().startsWith(lower)) - Number(a.toLowerCase().startsWith(lower))
1494
+ ) : rawTokens;
1495
+ const shown = ordered.slice(0, 3);
1496
+ const cls = shown.length > 0 ? `.${shown.join(".")}` : "";
1497
+ const escaped = shown.map((t) => `.${escapeClassToken(t)}`).join("");
1498
+ const key = `${tag}${cls}`;
1499
+ let group = byKey.get(key);
1500
+ if (!group) {
1501
+ group = { key, selector: `${tag}${escaped}`, tag, cls, count: 0, indices: [] };
1502
+ byKey.set(key, group);
1503
+ }
1504
+ group.count++;
1505
+ group.indices.push(i);
1506
+ });
1507
+ return Array.from(byKey.values()).sort((a, b) => a.cls.length - b.cls.length);
1508
+ }
1509
+
1510
+ // src/core/source/enrich.ts
1511
+ function findPickedElement(result, doc = document) {
1512
+ if (result.xpath) {
1513
+ try {
1514
+ const node = doc.evaluate(
1515
+ result.xpath,
1516
+ doc,
1517
+ null,
1518
+ XPathResult.FIRST_ORDERED_NODE_TYPE,
1519
+ null
1520
+ ).singleNodeValue;
1521
+ if (node instanceof Element) return node;
1522
+ } catch {
1523
+ }
1524
+ }
1525
+ if (result.cssSelector) {
1526
+ try {
1527
+ return doc.querySelector(result.cssSelector);
1528
+ } catch {
1529
+ return null;
1530
+ }
1531
+ }
1532
+ return null;
1533
+ }
1534
+ function enrichResult(result, doc = document) {
1535
+ if (result.reactSource && result.reactComponent) return result;
1536
+ const el = findPickedElement(result, doc);
1537
+ const annotated = el?.closest("[data-source]");
1538
+ const source = annotated?.getAttribute("data-source") ?? null;
1539
+ const chain = el instanceof HTMLElement ? componentChain(el) : [];
1540
+ const component = chain.length > 0 ? chain.join(" > ") : el?.closest("[data-component]")?.getAttribute("data-component") ?? null;
1541
+ return {
1542
+ ...result,
1543
+ reactSource: result.reactSource ?? source,
1544
+ reactComponent: result.reactComponent ?? component
1545
+ };
1546
+ }
1547
+
1548
+ // src/core/devpanel/inspected.ts
1549
+ var current = null;
1550
+ var listeners2 = /* @__PURE__ */ new Set();
1551
+ function setInspected(el) {
1552
+ current = el;
1553
+ for (const fn of listeners2) fn(el);
1554
+ }
1555
+ function getInspected() {
1556
+ return current;
1557
+ }
1558
+ function subscribeInspected(fn) {
1559
+ listeners2.add(fn);
1560
+ return () => listeners2.delete(fn);
1561
+ }
1562
+ var treeSelectMode = false;
1563
+ function setTreeSelectMode(on) {
1564
+ treeSelectMode = on;
1565
+ }
1566
+ function isTreeSelectMode() {
1567
+ return treeSelectMode;
1568
+ }
1569
+ var selectListeners = /* @__PURE__ */ new Set();
1570
+ function requestSelect(el) {
1571
+ for (const fn of selectListeners) fn(el);
1572
+ }
1573
+ function onSelectRequest(fn) {
1574
+ selectListeners.add(fn);
1575
+ return () => selectListeners.delete(fn);
1576
+ }
1577
+ var ctxListeners = /* @__PURE__ */ new Set();
1578
+ function requestContextMenu(el, x, y) {
1579
+ for (const fn of ctxListeners) fn(el, x, y);
1580
+ }
1581
+ function onContextMenuRequest(fn) {
1582
+ ctxListeners.add(fn);
1583
+ return () => ctxListeners.delete(fn);
1584
+ }
1585
+ var disarmListeners = /* @__PURE__ */ new Set();
1586
+ function onDisarmRequest(fn) {
1587
+ disarmListeners.add(fn);
1588
+ return () => disarmListeners.delete(fn);
1589
+ }
1590
+
1591
+ // src/core/inspector/constants/picker.ts
1592
+ var ACCENT = "#3b82f6";
1593
+ var OVERLAY_Z = 2147482e3;
1594
+ var UI_Z = 2147483e3;
1595
+ var HIGHLIGHT_BG = "rgba(59,130,246,0.15)";
1596
+ var SELECTED_BG = "rgba(59,130,246,0.24)";
1597
+ var HIGHLIGHT_BORDER = `2px solid ${ACCENT}`;
1598
+ var OVERLAY_RADIUS = "3px";
1599
+ var OVERLAY_GLIDE = "top .2s cubic-bezier(.25,.1,.25,1), left .2s cubic-bezier(.25,.1,.25,1), width .2s cubic-bezier(.25,.1,.25,1), height .2s cubic-bezier(.25,.1,.25,1), opacity .12s ease-out";
1600
+ var PICKING_CSS = ':disabled,[disabled],[aria-disabled="true"]{pointer-events:none!important}';
1601
+
1602
+ // src/core/inspector/constants/theme.ts
1603
+ var SOLID_BG = "#18181b";
1604
+ var TOOLTIP_SHADOW = "inset 0 1px 0 rgba(255,255,255,0.12), inset 0 0 0 1px rgba(255,255,255,0.08), 0 6px 20px rgba(0,0,0,0.45)";
1605
+ var PANEL_BORDER = "1px solid rgba(255,255,255,0.1)";
1606
+ var ELEVATED_BG = "#272729";
1607
+ var HOVER_BG = "#2e2e31";
1608
+ var MUTED = "#c4c4c8";
1609
+ var PRIMARY = "#60a5fa";
1610
+ var SECONDARY_BG_HOVER = "rgba(255,255,255,0.08)";
1611
+ var SECONDARY_SURFACE = "linear-gradient(rgba(255,255,255,0.04), rgba(255,255,255,0.04)), #18181b";
1612
+ var SECONDARY_BORDER = "1px solid rgba(255,255,255,0.08)";
1613
+ var BTN_SHADOW = "0px -1px 0px 0px rgba(255,255,255,.06), 0px 0px 0px 1px rgba(255,255,255,.06), 0px 0px 0px 1px rgba(39,39,42,1), 0px 0px 1px 1.5px rgba(0,0,0,.24), 0px 2px 2px 0px rgba(0,0,0,.24)";
1614
+ var CARD_SHADOW = "0px 0px 0px 1px rgba(0,0,0,.08), 0px 1px 2px -1px rgba(0,0,0,.08), 0px 2px 4px 0px rgba(0,0,0,.04)";
1615
+
1616
+ // src/core/inspector/key-command.ts
1617
+ function createKeyCommandMatcher() {
1618
+ let tapAt = null;
1619
+ return {
1620
+ status(e, b) {
1621
+ if (b.key === "off") return null;
1622
+ if (!modifierMatches(b.modifier, e)) return null;
1623
+ if (e.key.toLowerCase() !== b.key) return null;
1624
+ if (!b.double) return "fire";
1625
+ if (e.repeat) return "wait";
1626
+ if (tapAt !== null && e.timeStamp - tapAt <= DOUBLE_TAP_WINDOW) {
1627
+ tapAt = null;
1628
+ return "fire";
1629
+ }
1630
+ tapAt = e.timeStamp;
1631
+ return "wait";
1632
+ },
1633
+ reset() {
1634
+ tapAt = null;
1635
+ }
1636
+ };
1637
+ }
1638
+
1639
+ // src/core/inspector/hit-test.ts
1640
+ function shouldIgnore(el) {
1641
+ return !!el?.closest?.(`[${IGNORE_ATTR}]`);
1642
+ }
1643
+ function containsPoint(el, x, y) {
1644
+ const rects = el.getClientRects?.();
1645
+ const list = rects && rects.length ? Array.from(rects) : [el.getBoundingClientRect()];
1646
+ return list.some(
1647
+ (r) => r.width > 0 && r.height > 0 && x >= r.left && x <= r.right && y >= r.top && y <= r.bottom
1648
+ );
1649
+ }
1650
+ function skippedChildAt(el, x, y) {
1651
+ const children = Array.from(el.children);
1652
+ for (let i = children.length - 1; i >= 0; i--) {
1653
+ const child = children[i];
1654
+ if (shouldIgnore(child)) continue;
1655
+ if (!containsPoint(child, x, y)) continue;
1656
+ const cs = getComputedStyle(child);
1657
+ if (cs.pointerEvents !== "none") continue;
1658
+ if (cs.visibility === "hidden" || cs.opacity === "0") continue;
1659
+ return child;
1660
+ }
1661
+ return null;
1662
+ }
1663
+ function isDisabled(el) {
1664
+ try {
1665
+ return el.matches(':disabled,[disabled],[aria-disabled="true"]');
1666
+ } catch {
1667
+ return false;
1668
+ }
1669
+ }
1670
+ function resolveTarget(x, y) {
1671
+ const hit = document.elementFromPoint(x, y);
1672
+ if (!hit || shouldIgnore(hit)) return null;
1673
+ let current2 = hit;
1674
+ for (let i = 0; i < MAX_DESCEND; i++) {
1675
+ if (isDisabled(current2)) break;
1676
+ const child = skippedChildAt(current2, x, y);
1677
+ if (!child) break;
1678
+ current2 = child;
1679
+ }
1680
+ return current2;
1681
+ }
1682
+
1683
+ // src/core/inspector/surfaces/dom.ts
1684
+ function assign(el, style) {
1685
+ Object.assign(el.style, style);
1686
+ }
1687
+
1688
+ // src/core/inspector/surfaces/create.ts
1689
+ var TOOLTIP_MAX_W = 420;
1690
+ function createSurfaces() {
1691
+ const container = document.createElement("div");
1692
+ container.setAttribute(IGNORE_ATTR, "");
1693
+ assign(container, {
1694
+ position: "fixed",
1695
+ inset: "0",
1696
+ pointerEvents: "none",
1697
+ zIndex: String(OVERLAY_Z)
1698
+ });
1699
+ const decorLayer = document.createElement("div");
1700
+ container.appendChild(decorLayer);
1701
+ const markerLayer = document.createElement("div");
1702
+ container.appendChild(markerLayer);
1703
+ const overlay = document.createElement("div");
1704
+ assign(overlay, {
1705
+ position: "fixed",
1706
+ display: "block",
1707
+ opacity: "0",
1708
+ background: "transparent",
1709
+ border: HIGHLIGHT_BORDER,
1710
+ borderRadius: OVERLAY_RADIUS,
1711
+ boxSizing: "border-box",
1712
+ pointerEvents: "none",
1713
+ transition: OVERLAY_GLIDE
1714
+ });
1715
+ container.appendChild(overlay);
1716
+ const tooltip = document.createElement("div");
1717
+ assign(tooltip, {
1718
+ position: "fixed",
1719
+ display: "none",
1720
+ zIndex: "2",
1721
+ maxWidth: `${TOOLTIP_MAX_W}px`,
1722
+ padding: "6px 6px 6px 10px",
1723
+ borderRadius: "6px",
1724
+ font: "12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace",
1725
+ color: "#fff",
1726
+ background: SECONDARY_SURFACE,
1727
+ border: SECONDARY_BORDER,
1728
+ boxShadow: BTN_SHADOW,
1729
+ pointerEvents: "none",
1730
+ alignItems: "flex-start",
1731
+ gap: "10px"
1732
+ });
1733
+ const tooltipCol = document.createElement("div");
1734
+ assign(tooltipCol, { display: "flex", flexDirection: "column", minWidth: "0" });
1735
+ const tooltipLabel = document.createElement("span");
1736
+ assign(tooltipLabel, { whiteSpace: "pre-line" });
1737
+ tooltipCol.appendChild(tooltipLabel);
1738
+ const tooltipDivider = document.createElement("div");
1739
+ assign(tooltipDivider, {
1740
+ display: "none",
1741
+ height: "1px",
1742
+ margin: "5px 0",
1743
+ alignSelf: "stretch",
1744
+ background: "rgba(255,255,255,0.14)"
1745
+ });
1746
+ tooltipCol.appendChild(tooltipDivider);
1747
+ const tooltipMetrics = document.createElement("span");
1748
+ assign(tooltipMetrics, {
1749
+ display: "none",
1750
+ whiteSpace: "pre-line",
1751
+ color: "#d4d4d8"
1752
+ });
1753
+ tooltipCol.appendChild(tooltipMetrics);
1754
+ tooltip.appendChild(tooltipCol);
1755
+ const dims = document.createElement("span");
1756
+ assign(dims, {
1757
+ marginLeft: "auto",
1758
+ flexShrink: "0",
1759
+ padding: "1px 5px",
1760
+ borderRadius: "4px",
1761
+ font: "600 10px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace",
1762
+ color: "#60a5fa",
1763
+ background: "rgba(59,130,246,0.15)",
1764
+ border: "1px solid rgba(59,130,246,0.3)",
1765
+ whiteSpace: "nowrap"
1766
+ });
1767
+ tooltip.appendChild(dims);
1768
+ container.appendChild(tooltip);
1769
+ return {
1770
+ container,
1771
+ overlay,
1772
+ tooltip,
1773
+ tooltipLabel,
1774
+ tooltipDivider,
1775
+ tooltipMetrics,
1776
+ dims,
1777
+ decorLayer,
1778
+ markerLayer
1779
+ };
1780
+ }
1781
+
1782
+ // src/core/inspector/constants/layout.ts
1783
+ var PADDING_FILL = "#B8C480";
1784
+ var GAP_STRIPES = "repeating-linear-gradient(-45deg, rgba(127,32,210,0.8) 0, rgba(127,32,210,0.8) 1px, rgba(127,32,210,0.3) 1px, rgba(127,32,210,0.3) 10px)";
1785
+ var GAP_DASH = "rgba(127,32,210,0.8)";
1786
+ var MARGIN_FILL = "#B08355";
1787
+ var MODULE_OVERLAY_BORDER = "1px solid rgba(217,119,6,0.9)";
1788
+ var MODULE_OVERLAY_BG = "rgba(217,119,6,0.08)";
1789
+ var MODULE_OVERLAY_LABEL_BG = "rgba(217,119,6,0.95)";
1790
+ var CMS_OVERLAY_BORDER = "1px solid rgba(13,148,136,0.9)";
1791
+ var CMS_OVERLAY_BG = "rgba(13,148,136,0.08)";
1792
+ var CMS_OVERLAY_LABEL_BG = "rgba(13,148,136,0.95)";
1793
+
1794
+ // src/core/inspector/surfaces/decorations.ts
1795
+ function clearDecorations(layer) {
1796
+ layer.textContent = "";
1797
+ }
1798
+ function fillRect(layer, x, y, w, h, color) {
1799
+ if (w <= 0 || h <= 0) return;
1800
+ const box = document.createElement("div");
1801
+ assign(box, {
1802
+ position: "fixed",
1803
+ top: `${y}px`,
1804
+ left: `${x}px`,
1805
+ width: `${w}px`,
1806
+ height: `${h}px`,
1807
+ background: color,
1808
+ pointerEvents: "none"
1809
+ });
1810
+ layer.appendChild(box);
1811
+ }
1812
+ var SVG_NS = "http://www.w3.org/2000/svg";
1813
+ function dashedRect(layer, x, y, w, h, color, radius) {
1814
+ if (w <= 0 || h <= 0) return;
1815
+ const svg = document.createElementNS(SVG_NS, "svg");
1816
+ svg.setAttribute("data-rp-dash", "");
1817
+ svg.setAttribute("width", `${w}`);
1818
+ svg.setAttribute("height", `${h}`);
1819
+ assign(svg, {
1820
+ position: "fixed",
1821
+ top: `${y}px`,
1822
+ left: `${x}px`,
1823
+ overflow: "visible",
1824
+ zIndex: "1",
1825
+ pointerEvents: "none"
1826
+ });
1827
+ const rect = document.createElementNS(SVG_NS, "rect");
1828
+ rect.setAttribute("x", "0.5");
1829
+ rect.setAttribute("y", "0.5");
1830
+ rect.setAttribute("width", `${Math.max(0, w - 1)}`);
1831
+ rect.setAttribute("height", `${Math.max(0, h - 1)}`);
1832
+ rect.setAttribute("rx", `${radius}`);
1833
+ rect.setAttribute("fill", "none");
1834
+ rect.setAttribute("stroke", color);
1835
+ rect.setAttribute("stroke-width", "1");
1836
+ rect.setAttribute("stroke-dasharray", "3 3");
1837
+ svg.appendChild(rect);
1838
+ layer.appendChild(svg);
1839
+ }
1840
+ function renderDecorations(layer, el, rect, { padding, gap, margin }, cs) {
1841
+ clearDecorations(layer);
1842
+ if (margin) {
1843
+ const mt = parseFloat(cs.marginTop) || 0;
1844
+ const mr = parseFloat(cs.marginRight) || 0;
1845
+ const mb = parseFloat(cs.marginBottom) || 0;
1846
+ const ml = parseFloat(cs.marginLeft) || 0;
1847
+ fillRect(layer, rect.left - ml, rect.top - mt, rect.width + ml + mr, mt, MARGIN_FILL);
1848
+ fillRect(layer, rect.left - ml, rect.bottom, rect.width + ml + mr, mb, MARGIN_FILL);
1849
+ fillRect(layer, rect.left - ml, rect.top, ml, rect.height, MARGIN_FILL);
1850
+ fillRect(layer, rect.right, rect.top, mr, rect.height, MARGIN_FILL);
1851
+ }
1852
+ if (padding) {
1853
+ const bt = parseFloat(cs.borderTopWidth) || 0;
1854
+ const br = parseFloat(cs.borderRightWidth) || 0;
1855
+ const bb = parseFloat(cs.borderBottomWidth) || 0;
1856
+ const bl = parseFloat(cs.borderLeftWidth) || 0;
1857
+ const pt = parseFloat(cs.paddingTop) || 0;
1858
+ const pr = parseFloat(cs.paddingRight) || 0;
1859
+ const pb = parseFloat(cs.paddingBottom) || 0;
1860
+ const pl = parseFloat(cs.paddingLeft) || 0;
1861
+ const ring = document.createElement("div");
1862
+ assign(ring, {
1863
+ position: "fixed",
1864
+ top: `${rect.top + bt}px`,
1865
+ left: `${rect.left + bl}px`,
1866
+ width: `${rect.width - bl - br}px`,
1867
+ height: `${rect.height - bt - bb}px`,
1868
+ borderStyle: "solid",
1869
+ borderColor: PADDING_FILL,
1870
+ borderWidth: `${pt}px ${pr}px ${pb}px ${pl}px`,
1871
+ borderRadius: OVERLAY_RADIUS,
1872
+ boxSizing: "border-box",
1873
+ background: "transparent",
1874
+ pointerEvents: "none"
1875
+ });
1876
+ layer.appendChild(ring);
1877
+ }
1878
+ if (gap && /flex|grid/.test(cs.display)) {
1879
+ const kids = [];
1880
+ for (const node of Array.from(el.childNodes)) {
1881
+ let r = null;
1882
+ if (node.nodeType === 1) {
1883
+ r = node.getBoundingClientRect();
1884
+ } else if (node.nodeType === 3 && node.textContent && node.textContent.trim()) {
1885
+ const range = document.createRange();
1886
+ range.selectNodeContents(node);
1887
+ r = range.getBoundingClientRect();
1888
+ }
1889
+ if (r && r.width > 0 && r.height > 0) kids.push(r);
1890
+ }
1891
+ const bt = parseFloat(cs.borderTopWidth) || 0;
1892
+ const br = parseFloat(cs.borderRightWidth) || 0;
1893
+ const bb = parseFloat(cs.borderBottomWidth) || 0;
1894
+ const bl = parseFloat(cs.borderLeftWidth) || 0;
1895
+ const ct = rect.top + bt + (parseFloat(cs.paddingTop) || 0);
1896
+ const cb = rect.bottom - bb - (parseFloat(cs.paddingBottom) || 0);
1897
+ const cl = rect.left + bl + (parseFloat(cs.paddingLeft) || 0);
1898
+ const cr = rect.right - br - (parseFloat(cs.paddingRight) || 0);
1899
+ const rowGap = parseFloat(cs.rowGap) || 0;
1900
+ const colGap = parseFloat(cs.columnGap) || 0;
1901
+ let drew = false;
1902
+ if (colGap > 0) {
1903
+ const byX = [...kids].sort((a, b) => a.left - b.left);
1904
+ for (let i = 0; i < byX.length - 1; i++) {
1905
+ const a = byX[i];
1906
+ const b = byX[i + 1];
1907
+ if (b.left >= a.right && a.bottom > b.top && b.bottom > a.top) {
1908
+ fillRect(layer, a.right, ct, b.left - a.right, cb - ct, GAP_STRIPES);
1909
+ drew = true;
1910
+ }
1911
+ }
1912
+ }
1913
+ if (rowGap > 0) {
1914
+ const byY = [...kids].sort((a, b) => a.top - b.top);
1915
+ for (let i = 0; i < byY.length - 1; i++) {
1916
+ const a = byY[i];
1917
+ const b = byY[i + 1];
1918
+ if (b.top >= a.bottom && a.right > b.left && b.right > a.left) {
1919
+ fillRect(layer, cl, a.bottom, cr - cl, b.top - a.bottom, GAP_STRIPES);
1920
+ drew = true;
1921
+ }
1922
+ }
1923
+ }
1924
+ const inset = cl !== rect.left || ct !== rect.top || cr !== rect.right || cb !== rect.bottom;
1925
+ const dashRadius = inset ? 0 : parseFloat(OVERLAY_RADIUS);
1926
+ if (drew) dashedRect(layer, cl, ct, cr - cl, cb - ct, GAP_DASH, dashRadius);
1927
+ }
1928
+ }
1929
+
1930
+ // src/core/inspector/surfaces/tooltip.ts
1931
+ var TOOLTIP_MAX_W2 = 420;
1932
+ function isDisabled2(el) {
1933
+ try {
1934
+ return el.matches(':disabled,[disabled],[aria-disabled="true"]');
1935
+ } catch {
1936
+ return false;
1937
+ }
1938
+ }
1939
+ var px = (v) => parseFloat(v) || 0;
1940
+ function boxValue(t, r, b, l) {
1941
+ if (!t && !r && !b && !l) return null;
1942
+ if (t === r && r === b && b === l) return `${t}px`;
1943
+ if (t === b && l === r) return `${t}px ${r}px`;
1944
+ return `${t}px ${r}px ${b}px ${l}px`;
1945
+ }
1946
+ function dimsText(rect) {
1947
+ return `${Math.round(rect.width)}\xD7${Math.round(rect.height)}`;
1948
+ }
1949
+ function titleSuffixes(el, selection) {
1950
+ const parts = [];
1951
+ if (isDisabled2(el)) parts.push("disabled");
1952
+ const selIdx = selection.indexOf(el);
1953
+ if (selIdx >= 0) parts.push(`selected #${selIdx + 1}`);
1954
+ return parts;
1955
+ }
1956
+ function tooltipClassSummary(el) {
1957
+ const raw = el.getAttribute("class") || "";
1958
+ const tokens = raw.trim().length > 0 ? raw.trim().split(/\s+/) : [];
1959
+ if (tokens.length === 0) return "";
1960
+ const head = tokens.slice(0, 3).map((cls) => `.${cls}`).join("");
1961
+ return tokens.length > 3 ? `${head} (+${tokens.length - 3})` : head;
1962
+ }
1963
+ function tooltipTitle(el, selection) {
1964
+ const parts = [];
1965
+ const comp = componentChain(el).join(" > ") || componentInfo(el)?.component || tplLabel(el);
1966
+ if (comp) parts.push(comp);
1967
+ parts.push(...titleSuffixes(el, selection));
1968
+ return parts.join(" \xB7 ");
1969
+ }
1970
+ function tooltipMetricsFromStyle(el, cs) {
1971
+ const lines = [];
1972
+ const cls = tooltipClassSummary(el);
1973
+ if (cls) lines.push(cls + (el.id ? ` \xB7 #${el.id}` : ""));
1974
+ else if (el.id) lines.push(`#${el.id}`);
1975
+ const padding = boxValue(
1976
+ px(cs.paddingTop),
1977
+ px(cs.paddingRight),
1978
+ px(cs.paddingBottom),
1979
+ px(cs.paddingLeft)
1980
+ );
1981
+ if (padding) lines.push(`padding: ${padding}`);
1982
+ const rowGap = px(cs.rowGap);
1983
+ const colGap = px(cs.columnGap);
1984
+ if (/flex|grid/.test(cs.display) && (rowGap || colGap)) {
1985
+ lines.push(`gap: ${rowGap === colGap ? `${rowGap}px` : `${rowGap}px ${colGap}px`}`);
1986
+ }
1987
+ const margin = boxValue(
1988
+ px(cs.marginTop),
1989
+ px(cs.marginRight),
1990
+ px(cs.marginBottom),
1991
+ px(cs.marginLeft)
1992
+ );
1993
+ if (margin) lines.push(`margin: ${margin}`);
1994
+ return lines.join("\n");
1995
+ }
1996
+ function updateTooltip(tooltip, label, divider, metrics, dims, el, selection, rect, cs, titleOf = tooltipTitle) {
1997
+ const title = titleOf(el, selection);
1998
+ const metricsText = tooltipMetricsFromStyle(el, cs);
1999
+ label.textContent = title;
2000
+ label.style.display = title ? "block" : "none";
2001
+ metrics.textContent = metricsText;
2002
+ metrics.style.display = metricsText ? "block" : "none";
2003
+ divider.style.display = title && metricsText ? "block" : "none";
2004
+ dims.textContent = dimsText(rect);
2005
+ tooltip.style.display = "flex";
2006
+ const tipH = tooltip.offsetHeight;
2007
+ let top = rect.bottom + 8;
2008
+ if (top + tipH > window.innerHeight) top = rect.top - tipH - 8;
2009
+ let left = rect.left;
2010
+ if (left + TOOLTIP_MAX_W2 > window.innerWidth) {
2011
+ left = window.innerWidth - TOOLTIP_MAX_W2 - 10;
2012
+ }
2013
+ if (left < 4) left = 4;
2014
+ assign(tooltip, { top: `${top}px`, left: `${left}px` });
2015
+ }
2016
+
2017
+ // src/core/inspector/surfaces/markers.ts
2018
+ function renderMarkers(layer, selection) {
2019
+ layer.textContent = "";
2020
+ selection.forEach((el, i) => {
2021
+ if (!el.isConnected) return;
2022
+ const rect = el.getBoundingClientRect();
2023
+ const marker = document.createElement("div");
2024
+ assign(marker, {
2025
+ position: "fixed",
2026
+ top: `${rect.top}px`,
2027
+ left: `${rect.left}px`,
2028
+ width: `${rect.width}px`,
2029
+ height: `${rect.height}px`,
2030
+ background: SELECTED_BG,
2031
+ border: HIGHLIGHT_BORDER,
2032
+ borderRadius: "4px",
2033
+ boxSizing: "border-box",
2034
+ pointerEvents: "none"
2035
+ });
2036
+ const badge = document.createElement("span");
2037
+ badge.textContent = String(i + 1);
2038
+ assign(badge, {
2039
+ position: "absolute",
2040
+ top: "-7px",
2041
+ left: "-7px",
2042
+ minWidth: "14px",
2043
+ height: "14px",
2044
+ padding: "0 3px",
2045
+ borderRadius: "7px",
2046
+ background: HIGHLIGHT_BORDER.split(" ").pop() ?? "#3b82f6",
2047
+ color: "#fff",
2048
+ font: "600 9px/14px ui-monospace, monospace",
2049
+ textAlign: "center",
2050
+ boxSizing: "border-box"
2051
+ });
2052
+ marker.appendChild(badge);
2053
+ const dimsBadge = document.createElement("span");
2054
+ dimsBadge.textContent = dimsText(rect);
2055
+ assign(dimsBadge, {
2056
+ position: "absolute",
2057
+ top: "-20px",
2058
+ right: "0",
2059
+ padding: "1px 5px",
2060
+ borderRadius: "4px",
2061
+ font: "600 10px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace",
2062
+ color: "#fff",
2063
+ background: SOLID_BG,
2064
+ border: PANEL_BORDER,
2065
+ boxShadow: TOOLTIP_SHADOW,
2066
+ whiteSpace: "nowrap",
2067
+ boxSizing: "border-box"
2068
+ });
2069
+ marker.appendChild(dimsBadge);
2070
+ layer.appendChild(marker);
2071
+ });
2072
+ }
2073
+
2074
+ // src/core/inspector/surfaces/overlay.ts
2075
+ function positionOverlay(overlay, rect, animate = true) {
2076
+ if (!animate) overlay.style.transition = "none";
2077
+ assign(overlay, {
2078
+ opacity: "1",
2079
+ top: `${rect.top}px`,
2080
+ left: `${rect.left}px`,
2081
+ width: `${rect.width}px`,
2082
+ height: `${rect.height}px`
2083
+ });
2084
+ if (!animate) {
2085
+ void overlay.offsetWidth;
2086
+ overlay.style.transition = OVERLAY_GLIDE;
2087
+ }
2088
+ }
2089
+ function hideHover(overlay, tooltip) {
2090
+ overlay.style.opacity = "0";
2091
+ tooltip.style.display = "none";
2092
+ }
2093
+
2094
+ // src/core/inspector/inspector.ts
2095
+ var Inspector = class {
2096
+ constructor(callbacks) {
2097
+ this.callbacks = callbacks;
2098
+ this.active = false;
2099
+ this.styleEl = null;
2100
+ this.surfaces = null;
2101
+ this.lastTarget = null;
2102
+ this.selection = [];
2103
+ this.observer = null;
2104
+ this.hovering = false;
2105
+ /**
2106
+ * Dernier rect affiché par l'overlay. `refreshHover` ne repositionne que s'il a
2107
+ * bougé : la notification initiale d'un `ResizeObserver` (à chaque `observe()`
2108
+ * d'une nouvelle cible) couperait sinon la glisse en cours.
2109
+ */
2110
+ this.hoverRect = null;
2111
+ /** rAF en attente du repositionnement du survol (scroll/resize coalescés par frame). */
2112
+ this.frame = 0;
2113
+ /** rAF en attente du traitement mousemove (coalescé par frame, indépendant de `frame`
2114
+ * ci-dessus — déclenchement différent, peuvent être en vol simultanément). */
2115
+ this.moveFrame = 0;
2116
+ /** Dernière position mousemove reçue, traitée une fois par frame. */
2117
+ this.pendingMove = null;
2118
+ /** Mode recherche actif : pas de rect de survol (les rects de recherche prennent le relais). */
2119
+ this.searchMode = false;
2120
+ /** Matcher de la commande clavier « inspect » (modificateur + touche, simple/double-tap). */
2121
+ this.inspectMatcher = createKeyCommandMatcher();
2122
+ /** Coalesce le traitement mousemove à une fois par frame (jusqu'à 60-120 events/s
2123
+ * natifs sinon, chacun forçant un hit-test complet — voir `processMouseMove`). */
2124
+ this.onMouseMove = (e) => {
2125
+ this.pendingMove = { x: e.clientX, y: e.clientY };
2126
+ if (typeof requestAnimationFrame !== "function") {
2127
+ this.processMouseMove();
2128
+ return;
2129
+ }
2130
+ if (this.moveFrame) return;
2131
+ this.moveFrame = requestAnimationFrame(() => {
2132
+ this.moveFrame = 0;
2133
+ this.processMouseMove();
2134
+ });
2135
+ };
2136
+ this.onPress = (e) => {
2137
+ if (this.searchMode) return;
2138
+ if (CONTEXT_MENU_OPEN.value) return;
2139
+ const me = e;
2140
+ if (shouldIgnore(e.target)) return;
2141
+ const target = this.pickTargetAt(me.clientX, me.clientY);
2142
+ if (!target) return;
2143
+ e.preventDefault();
2144
+ e.stopPropagation();
2145
+ e.stopImmediatePropagation();
2146
+ const kind = this.kindOf(e, me);
2147
+ if (!kind) return;
2148
+ const cmds = this.commands();
2149
+ const isMulti = this.multi && gestureMatches(cmds.multi, me, kind);
2150
+ const isCopyHtml = gestureMatches(cmds.copyHtml, me, kind);
2151
+ const isCopy = cmds.copy.modifier === "none" && cmds.copy.trigger === "click" ? kind === "click" && !isMulti && !isCopyHtml : gestureMatches(cmds.copy, me, kind);
2152
+ if (this.multi && (isMulti || this.selection.length > 0 && isCopy)) {
2153
+ this.toggleSelection(target);
2154
+ return;
2155
+ }
2156
+ if (isCopy) {
2157
+ if (isTreeSelectMode()) {
2158
+ this.swallowTrailingPress();
2159
+ requestSelect(target);
2160
+ return;
2161
+ }
2162
+ const result = this.buildResult(target);
2163
+ this.deactivate();
2164
+ this.swallowTrailingPress();
2165
+ this.callbacks.onPick(result);
2166
+ return;
2167
+ }
2168
+ if (isCopyHtml) {
2169
+ if (isTreeSelectMode()) {
2170
+ requestContextMenu(target, me.clientX, me.clientY);
2171
+ return;
2172
+ }
2173
+ if (target !== this.lastTarget) {
2174
+ this.lastTarget = target;
2175
+ this.showHover(target, target.getBoundingClientRect(), false);
2176
+ this.syncObserver();
2177
+ }
2178
+ this.callbacks.onContextMenu?.(target, { x: me.clientX, y: me.clientY });
2179
+ }
2180
+ };
2181
+ this.onKeyDown = (e) => {
2182
+ const cmds = this.commands();
2183
+ const inspectStatus = this.callbacks.onInspect ? this.inspectMatcher.status(e, cmds.inspect) : null;
2184
+ if (inspectStatus === "wait") {
2185
+ e.preventDefault();
2186
+ e.stopPropagation();
2187
+ return;
2188
+ }
2189
+ if (inspectStatus === "fire" && this.callbacks.onInspect && this.lastTarget && this.lastTarget.isConnected) {
2190
+ e.preventDefault();
2191
+ e.stopPropagation();
2192
+ this.callbacks.onInspect(this.lastTarget);
2193
+ return;
2194
+ }
2195
+ if (keyMatches(cmds.confirm, e.key) && this.multi && this.selection.length > 0) {
2196
+ e.preventDefault();
2197
+ e.stopPropagation();
2198
+ this.finishMulti();
2199
+ return;
2200
+ }
2201
+ if (keyMatches(cmds.cancel, e.key)) {
2202
+ e.preventDefault();
2203
+ e.stopPropagation();
2204
+ this.deactivate();
2205
+ this.callbacks.onCancel();
2206
+ }
2207
+ };
2208
+ // Ne touche QUE les markers de sélection : les `transitionend`/`animationend`
2209
+ // d'une page animée réinitialiseraient en boucle la transition de l'overlay
2210
+ // → pas de glisse. Le survol suit scroll/resize via `onViewportChange`.
2211
+ this.refreshAll = () => {
2212
+ if (!this.active) return;
2213
+ this.renderSelection();
2214
+ };
2215
+ /** Scroll (fenêtre ou sous-conteneur, capture) / resize : markers + survol recollé à l'élément. */
2216
+ this.onViewportChange = () => {
2217
+ if (!this.active) return;
2218
+ this.refreshAll();
2219
+ this.scheduleHover();
2220
+ };
2221
+ }
2222
+ get multi() {
2223
+ return this.callbacks.multi !== false && typeof this.callbacks.onPickMany === "function";
2224
+ }
2225
+ activate() {
2226
+ if (this.active || typeof document === "undefined") return;
2227
+ this.active = true;
2228
+ PICKER_ARMED.value = true;
2229
+ this.styleEl = document.createElement("style");
2230
+ this.styleEl.setAttribute(IGNORE_ATTR, "");
2231
+ this.styleEl.textContent = PICKING_CSS;
2232
+ document.head.appendChild(this.styleEl);
2233
+ this.surfaces = createSurfaces();
2234
+ document.body.appendChild(this.surfaces.container);
2235
+ document.body.style.cursor = "crosshair";
2236
+ window.addEventListener("mousemove", this.onMouseMove, true);
2237
+ for (const type of PRESS_EVENTS) {
2238
+ window.addEventListener(type, this.onPress, true);
2239
+ }
2240
+ window.addEventListener("keydown", this.onKeyDown, true);
2241
+ window.addEventListener("scroll", this.onViewportChange, true);
2242
+ window.addEventListener("resize", this.onViewportChange);
2243
+ window.addEventListener("transitionend", this.refreshAll, true);
2244
+ window.addEventListener("animationend", this.refreshAll, true);
2245
+ if (typeof ResizeObserver !== "undefined") {
2246
+ this.observer = new ResizeObserver(() => this.onViewportChange());
2247
+ }
2248
+ }
2249
+ deactivate() {
2250
+ if (!this.active) return;
2251
+ this.active = false;
2252
+ PICKER_ARMED.value = false;
2253
+ this.lastTarget = null;
2254
+ this.hoverRect = null;
2255
+ this.selection = [];
2256
+ this.inspectMatcher.reset();
2257
+ if (typeof document !== "undefined") document.body.style.cursor = "";
2258
+ window.removeEventListener("mousemove", this.onMouseMove, true);
2259
+ for (const type of PRESS_EVENTS) {
2260
+ window.removeEventListener(type, this.onPress, true);
2261
+ }
2262
+ window.removeEventListener("keydown", this.onKeyDown, true);
2263
+ window.removeEventListener("scroll", this.onViewportChange, true);
2264
+ window.removeEventListener("resize", this.onViewportChange);
2265
+ window.removeEventListener("transitionend", this.refreshAll, true);
2266
+ window.removeEventListener("animationend", this.refreshAll, true);
2267
+ if (this.frame && typeof cancelAnimationFrame === "function") {
2268
+ cancelAnimationFrame(this.frame);
2269
+ }
2270
+ this.frame = 0;
2271
+ if (this.moveFrame && typeof cancelAnimationFrame === "function") {
2272
+ cancelAnimationFrame(this.moveFrame);
2273
+ }
2274
+ this.moveFrame = 0;
2275
+ this.pendingMove = null;
2276
+ this.observer?.disconnect();
2277
+ this.observer = null;
2278
+ this.styleEl?.remove();
2279
+ this.surfaces?.container.remove();
2280
+ this.styleEl = null;
2281
+ this.surfaces = null;
2282
+ }
2283
+ // --- Rendu (délègue à surfaces) ------------------------------------------
2284
+ hideHover() {
2285
+ this.hovering = false;
2286
+ this.hoverRect = null;
2287
+ if (!this.surfaces) return;
2288
+ hideHover(this.surfaces.overlay, this.surfaces.tooltip);
2289
+ clearDecorations(this.surfaces.decorLayer);
2290
+ }
2291
+ showHover(el, rect, animate = true) {
2292
+ if (!this.surfaces) return;
2293
+ positionOverlay(this.surfaces.overlay, rect, animate);
2294
+ const cs = getComputedStyle(el);
2295
+ updateTooltip(
2296
+ this.surfaces.tooltip,
2297
+ this.surfaces.tooltipLabel,
2298
+ this.surfaces.tooltipDivider,
2299
+ this.surfaces.tooltipMetrics,
2300
+ this.surfaces.dims,
2301
+ el,
2302
+ this.selection,
2303
+ rect,
2304
+ cs,
2305
+ this.callbacks.getTitle
2306
+ );
2307
+ this.renderDecor(el, rect, cs);
2308
+ this.hovering = true;
2309
+ this.hoverRect = { top: rect.top, left: rect.left, width: rect.width, height: rect.height };
2310
+ }
2311
+ /** Dessine (ou efface) les décorations layout selon `getOverlays`. `cs` : réutilisé s'il
2312
+ * vient d'être calculé par l'appelant (`showHover`), sinon recalculé (`refreshDecorations`,
2313
+ * toggle sans survol). */
2314
+ renderDecor(el, rect, cs) {
2315
+ if (!this.surfaces) return;
2316
+ const overlays = this.callbacks.getOverlays?.();
2317
+ if (overlays && (overlays.padding || overlays.gap || overlays.margin)) {
2318
+ renderDecorations(this.surfaces.decorLayer, el, rect, overlays, cs ?? getComputedStyle(el));
2319
+ } else {
2320
+ clearDecorations(this.surfaces.decorLayer);
2321
+ }
2322
+ }
2323
+ /** Re-render des décorations sur l'élément survolé (toggle sans mousemove). */
2324
+ refreshDecorations() {
2325
+ if (!this.active || !this.surfaces) return;
2326
+ if (this.lastTarget && this.lastTarget.isConnected) {
2327
+ this.renderDecor(this.lastTarget, this.lastTarget.getBoundingClientRect());
2328
+ } else {
2329
+ clearDecorations(this.surfaces.decorLayer);
2330
+ }
2331
+ }
2332
+ renderSelection() {
2333
+ if (this.surfaces) renderMarkers(this.surfaces.markerLayer, this.selection);
2334
+ }
2335
+ pickTargetAt(x, y) {
2336
+ if (this.lastTarget && this.lastTarget.isConnected && containsPoint(this.lastTarget, x, y)) {
2337
+ return this.lastTarget;
2338
+ }
2339
+ return resolveTarget(x, y);
2340
+ }
2341
+ syncObserver() {
2342
+ if (!this.observer) return;
2343
+ this.observer.disconnect();
2344
+ const seen = /* @__PURE__ */ new Set();
2345
+ const watch = (el) => {
2346
+ if (el && el.isConnected && !seen.has(el)) {
2347
+ seen.add(el);
2348
+ this.observer.observe(el);
2349
+ }
2350
+ };
2351
+ watch(this.lastTarget);
2352
+ for (const el of this.selection) watch(el);
2353
+ }
2354
+ // --- Mutations de sélection ----------------------------------------------
2355
+ afterSelectionChange() {
2356
+ this.syncObserver();
2357
+ this.renderSelection();
2358
+ this.callbacks.onSelectionChange?.(this.selection.length);
2359
+ if (this.lastTarget && this.lastTarget.isConnected) {
2360
+ this.showHover(
2361
+ this.lastTarget,
2362
+ this.lastTarget.getBoundingClientRect(),
2363
+ false
2364
+ );
2365
+ }
2366
+ }
2367
+ toggleSelection(el) {
2368
+ const idx = this.selection.indexOf(el);
2369
+ if (idx >= 0) this.selection.splice(idx, 1);
2370
+ else this.selection.push(el);
2371
+ this.afterSelectionChange();
2372
+ }
2373
+ // --- Résultat -------------------------------------------------------------
2374
+ buildResult(el) {
2375
+ const annotated = el.closest("[data-source]");
2376
+ const chain = el instanceof HTMLElement ? componentChain(el) : [];
2377
+ return {
2378
+ route: this.callbacks.getRoute(),
2379
+ xpath: getXPath(el),
2380
+ cssSelector: getCssSelector(el),
2381
+ text: elementText(el),
2382
+ tagName: el.tagName.toLowerCase(),
2383
+ id: el.id || null,
2384
+ reactComponent: chain.length > 0 ? chain.join(" > ") : el.closest("[data-component]")?.getAttribute("data-component") ?? null,
2385
+ reactSource: annotated?.getAttribute("data-source") ?? null
2386
+ };
2387
+ }
2388
+ finishMulti() {
2389
+ const results = this.selection.filter((el) => el.isConnected).map((el) => this.buildResult(el));
2390
+ this.deactivate();
2391
+ this.callbacks.onPickMany?.(results);
2392
+ }
2393
+ /** Avale les events résiduels (pointerup/click) après un pick consommé. */
2394
+ swallowTrailingPress() {
2395
+ const swallow = (e) => {
2396
+ e.preventDefault();
2397
+ e.stopPropagation();
2398
+ e.stopImmediatePropagation();
2399
+ };
2400
+ const cleanup = () => {
2401
+ for (const type of PRESS_EVENTS) {
2402
+ window.removeEventListener(type, swallow, true);
2403
+ }
2404
+ window.removeEventListener("click", cleanup, true);
2405
+ };
2406
+ for (const type of PRESS_EVENTS) {
2407
+ window.addEventListener(type, swallow, true);
2408
+ }
2409
+ window.addEventListener("click", cleanup, true);
2410
+ setTimeout(cleanup, SWALLOW_MS);
2411
+ }
2412
+ // --- Handlers (arrow = identité stable pour add/remove) -------------------
2413
+ /** Active/désactive le mode recherche : fige le rect de survol de l'inspecteur. */
2414
+ setSearchMode(on) {
2415
+ this.searchMode = on;
2416
+ if (on) this.hideHover();
2417
+ }
2418
+ processMouseMove() {
2419
+ const pending = this.pendingMove;
2420
+ if (!pending) return;
2421
+ const { x, y } = pending;
2422
+ if (this.searchMode) {
2423
+ this.lastTarget = null;
2424
+ this.hideHover();
2425
+ return;
2426
+ }
2427
+ if (CONTEXT_MENU_OPEN.value) return;
2428
+ const target = this.lastTarget && this.lastTarget.isConnected && document.elementFromPoint(x, y) === this.lastTarget ? this.lastTarget : resolveTarget(x, y);
2429
+ if (!target || shouldIgnore(target)) {
2430
+ this.lastTarget = null;
2431
+ this.hideHover();
2432
+ return;
2433
+ }
2434
+ if (target === this.lastTarget) return;
2435
+ this.lastTarget = target;
2436
+ this.callbacks.onHover?.(target);
2437
+ const rect = target.getBoundingClientRect();
2438
+ if (rect.width === 0 && rect.height === 0) {
2439
+ this.hideHover();
2440
+ } else {
2441
+ this.showHover(target, rect, this.hovering);
2442
+ }
2443
+ this.syncObserver();
2444
+ }
2445
+ commands() {
2446
+ return this.callbacks.getCommands?.() ?? DEFAULT_SETTINGS.commands;
2447
+ }
2448
+ /** Type de clic de cet event (ou `null` : avalé mais sans action). */
2449
+ kindOf(e, me) {
2450
+ if (e.type === DOWN_TYPE && me.button === 0) return "click";
2451
+ if (e.type === "contextmenu") return "rightclick";
2452
+ if (e.type === "dblclick") return "dblclick";
2453
+ return null;
2454
+ }
2455
+ /** Snapshot de la sélection multiple (Maj+clics). */
2456
+ getSelection() {
2457
+ return [...this.selection];
2458
+ }
2459
+ /** Coalesce les repositionnements du survol à une fois par frame. */
2460
+ scheduleHover() {
2461
+ if (typeof requestAnimationFrame !== "function") {
2462
+ this.refreshHover();
2463
+ return;
2464
+ }
2465
+ if (this.frame) return;
2466
+ this.frame = requestAnimationFrame(() => {
2467
+ this.frame = 0;
2468
+ this.refreshHover();
2469
+ });
2470
+ }
2471
+ /** Repositionne instantanément (sans glisse) le survol sur `lastTarget`. */
2472
+ refreshHover() {
2473
+ if (!this.active || !this.hovering || this.searchMode || !this.lastTarget) return;
2474
+ if (!this.lastTarget.isConnected) {
2475
+ this.lastTarget = null;
2476
+ this.hideHover();
2477
+ return;
2478
+ }
2479
+ const rect = this.lastTarget.getBoundingClientRect();
2480
+ if (rect.width === 0 && rect.height === 0) {
2481
+ this.hideHover();
2482
+ return;
2483
+ }
2484
+ const prev = this.hoverRect;
2485
+ if (prev && prev.top === rect.top && prev.left === rect.left && prev.width === rect.width && prev.height === rect.height) {
2486
+ return;
2487
+ }
2488
+ this.showHover(this.lastTarget, rect, false);
2489
+ }
2490
+ };
2491
+ function createInspector(callbacks) {
2492
+ const inspector = new Inspector(callbacks);
2493
+ return {
2494
+ activate: () => inspector.activate(),
2495
+ deactivate: () => inspector.deactivate(),
2496
+ refreshDecorations: () => inspector.refreshDecorations(),
2497
+ setSearchMode: (on) => inspector.setSearchMode(on),
2498
+ getSelection: () => inspector.getSelection()
2499
+ };
2500
+ }
2501
+
2502
+ export {
2503
+ getState,
2504
+ clearLogs,
2505
+ clearRequests,
2506
+ subscribe,
2507
+ startCapture,
2508
+ IGNORE_ATTR,
2509
+ NPM_MARKER_ATTR,
2510
+ DOUBLE_TAP_WINDOW,
2511
+ CONTEXT_MENU_OPEN,
2512
+ EDITORS,
2513
+ buildEditorUri,
2514
+ DEFAULT_SETTINGS,
2515
+ settingsDelta,
2516
+ loadSettings,
2517
+ saveSettings,
2518
+ refreshSettings,
2519
+ initSettingsRefresh,
2520
+ fetchSettings,
2521
+ buildVscodeUri,
2522
+ vscodeActionFor,
2523
+ vscodeOpenFor,
2524
+ initClickToSource,
2525
+ normalizeSourcePath,
2526
+ resolvePosition,
2527
+ componentInfo,
2528
+ annotateTree,
2529
+ annotate,
2530
+ initComponentAnnotator,
2531
+ parseTplMarker,
2532
+ moduleNameFromSource,
2533
+ annotateFromComments,
2534
+ initTplAnnotator,
2535
+ getCssSelector,
2536
+ getXPath,
2537
+ OUTPUT_PREFIX,
2538
+ formatResult,
2539
+ elementText,
2540
+ formatHtml,
2541
+ formatResults,
2542
+ SEARCH_UI_ATTR,
2543
+ searchElements,
2544
+ toSelector,
2545
+ pickResultFromElement,
2546
+ classPrefixOf,
2547
+ groupResults,
2548
+ findPickedElement,
2549
+ enrichResult,
2550
+ setInspected,
2551
+ getInspected,
2552
+ subscribeInspected,
2553
+ setTreeSelectMode,
2554
+ onSelectRequest,
2555
+ onContextMenuRequest,
2556
+ onDisarmRequest,
2557
+ createKeyCommandMatcher,
2558
+ ACCENT,
2559
+ OVERLAY_Z,
2560
+ UI_Z,
2561
+ HIGHLIGHT_BG,
2562
+ SELECTED_BG,
2563
+ HIGHLIGHT_BORDER,
2564
+ OVERLAY_RADIUS,
2565
+ SOLID_BG,
2566
+ TOOLTIP_SHADOW,
2567
+ PANEL_BORDER,
2568
+ ELEVATED_BG,
2569
+ HOVER_BG,
2570
+ MUTED,
2571
+ PRIMARY,
2572
+ SECONDARY_BG_HOVER,
2573
+ SECONDARY_SURFACE,
2574
+ SECONDARY_BORDER,
2575
+ BTN_SHADOW,
2576
+ CARD_SHADOW,
2577
+ assign,
2578
+ MODULE_OVERLAY_BORDER,
2579
+ MODULE_OVERLAY_BG,
2580
+ MODULE_OVERLAY_LABEL_BG,
2581
+ CMS_OVERLAY_BORDER,
2582
+ CMS_OVERLAY_BG,
2583
+ CMS_OVERLAY_LABEL_BG,
2584
+ updateTooltip,
2585
+ createInspector
2586
+ };
2587
+ //# sourceMappingURL=chunk-2N6FOIM5.js.map