reflet-sdk 0.1.5 → 0.2.0

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,2276 @@
1
+ "use client";
2
+ import { t as Reflet } from "./client-BYuSKJw5.js";
3
+ import { t as RefletContext } from "./react-context-DZw_HHjj.js";
4
+ import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
5
+ import { jsx, jsxs } from "react/jsx-runtime";
6
+ import { createPortal } from "react-dom";
7
+ //#region src/feedback/core/capture.ts
8
+ /** Marks every node the widget owns, so captures never include the panel. */
9
+ const WIDGET_MARKER = "data-reflet-widget";
10
+ const MAX_PIXEL_RATIO = 2;
11
+ const DEFAULT_MAX_WIDTH = 2400;
12
+ function buildSnapdomOptions(options) {
13
+ const ratio = options.devicePixelRatio ?? 1;
14
+ return {
15
+ cache: "disabled",
16
+ clip: options.element ? void 0 : "viewport",
17
+ dpr: Math.min(Math.max(ratio || 1, 1), MAX_PIXEL_RATIO),
18
+ embedFonts: true,
19
+ exclude: [`[${WIDGET_MARKER}]`, ...options.excludeSelectors ?? []],
20
+ fast: true
21
+ };
22
+ }
23
+ function fitWithin(size, maxWidth) {
24
+ if (size.width <= maxWidth) return {
25
+ height: size.height,
26
+ scale: 1,
27
+ width: size.width
28
+ };
29
+ const scale = maxWidth / size.width;
30
+ return {
31
+ height: Math.max(1, Math.round(size.height * scale)),
32
+ scale,
33
+ width: maxWidth
34
+ };
35
+ }
36
+ function toBlob$1(canvas) {
37
+ return new Promise((resolve) => {
38
+ canvas.toBlob(resolve, "image/png");
39
+ });
40
+ }
41
+ function downscale(canvas, target) {
42
+ const resized = document.createElement("canvas");
43
+ resized.width = target.width;
44
+ resized.height = target.height;
45
+ const context = resized.getContext("2d");
46
+ if (!context) return canvas;
47
+ context.imageSmoothingQuality = "high";
48
+ context.drawImage(canvas, 0, 0, target.width, target.height);
49
+ return resized;
50
+ }
51
+ /**
52
+ * Renders what the user is looking at right now.
53
+ *
54
+ * Runs off the DOM rather than `getDisplayMedia` on purpose: a screen-share
55
+ * permission prompt on every report would cost more reports than it captures.
56
+ * Returns null instead of throwing — a screenshot is never worth losing the
57
+ * written feedback.
58
+ */
59
+ async function captureViewport(options = {}) {
60
+ try {
61
+ const { snapdom } = await import("@zumer/snapdom");
62
+ const target = options.element ?? document.documentElement;
63
+ const canvas = await snapdom.toCanvas(target, buildSnapdomOptions({
64
+ devicePixelRatio: window.devicePixelRatio,
65
+ element: options.element,
66
+ excludeSelectors: options.excludeSelectors
67
+ }));
68
+ const fitted = fitWithin({
69
+ height: canvas.height,
70
+ width: canvas.width
71
+ }, options.maxWidth ?? DEFAULT_MAX_WIDTH);
72
+ const output = fitted.scale === 1 ? canvas : downscale(canvas, fitted);
73
+ const blob = await toBlob$1(output);
74
+ if (!blob) return null;
75
+ return {
76
+ blob,
77
+ height: output.height,
78
+ mimeType: "image/png",
79
+ objectUrl: URL.createObjectURL(blob),
80
+ width: output.width
81
+ };
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+ function releaseCapture(image) {
87
+ if (image) URL.revokeObjectURL(image.objectUrl);
88
+ }
89
+ //#endregion
90
+ //#region src/feedback/core/react-source.ts
91
+ const FIBER_KEY_PREFIXES = ["__reactFiber$", "__reactInternalInstance$"];
92
+ const MEMO_TYPE = Symbol.for("react.memo");
93
+ const FORWARD_REF_TYPE = Symbol.for("react.forward_ref");
94
+ const MAX_STACK_DEPTH = 6;
95
+ const MAX_FIBER_WALK = 60;
96
+ const MAX_OWNER_WALK = 8;
97
+ const ORIGIN_PREFIX = /^[a-z][\w+.-]*:\/\/[^/]*/i;
98
+ const WEBPACK_PREFIX = /^webpack-internal:\/{2,}(\.\/)?/;
99
+ const STACK_LOCATION = /([^\s()]+):(\d+):(\d+)\)?\s*$/;
100
+ const NON_SOURCE_FRAME = /node_modules|\/_next\/|\/chunks?\/|\/\.vite\/|\/dist\/|\/build\/|hot-update/;
101
+ const SOURCE_EXTENSION = /\.(?:[cm]?[jt]sx?)$/;
102
+ const SOURCE_ROOT_MARKERS = [
103
+ "src",
104
+ "app",
105
+ "pages",
106
+ "components",
107
+ "features",
108
+ "lib"
109
+ ];
110
+ function isRecord(value) {
111
+ return typeof value === "object" && value !== null;
112
+ }
113
+ /** React attaches the fiber under a randomly suffixed key on the host node. */
114
+ function getFiberFromNode(node) {
115
+ for (const key of Object.getOwnPropertyNames(node)) for (const prefix of FIBER_KEY_PREFIXES) if (key.startsWith(prefix)) return Reflect.get(node, key) ?? null;
116
+ return null;
117
+ }
118
+ function readName(value) {
119
+ if (typeof value !== "function" && !isRecord(value)) return null;
120
+ const displayName = Reflect.get(value, "displayName");
121
+ if (typeof displayName === "string" && displayName) return displayName;
122
+ const name = Reflect.get(value, "name");
123
+ return typeof name === "string" && name ? name : null;
124
+ }
125
+ function componentName(type, depth = 0) {
126
+ if (typeof type === "string" || type === null || depth > 3) return null;
127
+ if (isRecord(type)) {
128
+ const marker = Reflect.get(type, "$$typeof");
129
+ if (marker === MEMO_TYPE) return componentName(Reflect.get(type, "type"), depth + 1);
130
+ if (marker === FORWARD_REF_TYPE) return componentName(Reflect.get(type, "render"), depth + 1);
131
+ }
132
+ const name = readName(type);
133
+ if (!name || name.length < 2) return null;
134
+ return name[0] === name[0]?.toUpperCase() || name.includes("/") ? name : null;
135
+ }
136
+ /** Component names owning the fiber, innermost first. */
137
+ function resolveComponentStack(fiber) {
138
+ const stack = [];
139
+ let current = fiber;
140
+ let steps = 0;
141
+ while (isRecord(current) && steps < MAX_FIBER_WALK) {
142
+ const name = componentName(Reflect.get(current, "type")) ?? componentName(Reflect.get(current, "elementType"));
143
+ if (name && stack.at(-1) !== name) {
144
+ stack.push(name);
145
+ if (stack.length >= MAX_STACK_DEPTH) break;
146
+ }
147
+ current = Reflect.get(current, "return");
148
+ steps++;
149
+ }
150
+ return stack;
151
+ }
152
+ function shortenSourcePath(raw) {
153
+ const path = raw.replace(WEBPACK_PREFIX, "").replace(ORIGIN_PREFIX, "").split("?")[0];
154
+ if (!path) return raw;
155
+ for (const marker of SOURCE_ROOT_MARKERS) {
156
+ if (path.startsWith(`${marker}/`)) return path;
157
+ const index = path.lastIndexOf(`/${marker}/`);
158
+ if (index !== -1) return path.slice(index + 1);
159
+ }
160
+ return path.split("/").filter(Boolean).slice(-3).join("/");
161
+ }
162
+ function formatLocation(fileName, line, column) {
163
+ const base = `${shortenSourcePath(fileName)}:${line}`;
164
+ return column === void 0 ? base : `${base}:${column}`;
165
+ }
166
+ function fromDebugSource(source) {
167
+ if (!isRecord(source)) return;
168
+ const fileName = Reflect.get(source, "fileName");
169
+ const lineNumber = Reflect.get(source, "lineNumber");
170
+ if (typeof fileName !== "string" || typeof lineNumber !== "number") return;
171
+ const columnNumber = Reflect.get(source, "columnNumber");
172
+ return formatLocation(fileName, lineNumber, typeof columnNumber === "number" ? columnNumber : void 0);
173
+ }
174
+ function fromDebugStack(stack) {
175
+ const raw = isRecord(stack) ? Reflect.get(stack, "stack") : stack;
176
+ if (typeof raw !== "string") return;
177
+ for (const line of raw.split("\n")) {
178
+ const match = STACK_LOCATION.exec(line);
179
+ const file = match?.[1];
180
+ if (!(match && file) || NON_SOURCE_FRAME.test(file)) continue;
181
+ const path = file.replace(ORIGIN_PREFIX, "").split("?")[0] ?? "";
182
+ if (!SOURCE_EXTENSION.test(path)) continue;
183
+ return formatLocation(path, Number(match[2]), Number(match[3]));
184
+ }
185
+ }
186
+ /**
187
+ * `src/components/login-form.tsx:46:19` when the React build exposes it.
188
+ * Production bundles strip debug info — callers must treat this as optional.
189
+ */
190
+ function resolveSourceLocation(fiber) {
191
+ let current = fiber;
192
+ let steps = 0;
193
+ while (isRecord(current) && steps < MAX_OWNER_WALK) {
194
+ const located = fromDebugSource(Reflect.get(current, "_debugSource")) ?? fromDebugStack(Reflect.get(current, "_debugStack"));
195
+ if (located) return located;
196
+ current = Reflect.get(current, "_debugOwner");
197
+ steps++;
198
+ }
199
+ }
200
+ function inspectReactElement(element) {
201
+ const fiber = getFiberFromNode(element);
202
+ return {
203
+ componentStack: resolveComponentStack(fiber),
204
+ sourceLocation: resolveSourceLocation(fiber)
205
+ };
206
+ }
207
+ //#endregion
208
+ //#region src/feedback/core/element-selector.ts
209
+ const SAFE_ID = /^[A-Za-z][\w-]*$/;
210
+ const WHITESPACE = /\s+/g;
211
+ const MAX_LABEL_LENGTH = 80;
212
+ const MAX_HTML_LENGTH = 600;
213
+ const MAX_DEPTH = 12;
214
+ const MAX_SELECTOR_LENGTH = 600;
215
+ const MAX_SOURCE_LOCATION_LENGTH = 400;
216
+ function isUnique(selector) {
217
+ try {
218
+ return document.querySelectorAll(selector).length === 1;
219
+ } catch {
220
+ return false;
221
+ }
222
+ }
223
+ function escapeAttributeValue(value) {
224
+ return value.replace(/["\\]/g, "\\$&");
225
+ }
226
+ function uniqueHandle(element) {
227
+ const id = element.getAttribute("id");
228
+ if (id && SAFE_ID.test(id) && isUnique(`#${id}`)) return `#${id}`;
229
+ const testId = element.getAttribute("data-testid");
230
+ if (testId) {
231
+ const selector = `[data-testid="${escapeAttributeValue(testId)}"]`;
232
+ if (isUnique(selector)) return selector;
233
+ }
234
+ return null;
235
+ }
236
+ function positionalSegment(element) {
237
+ const tag = element.localName;
238
+ const parent = element.parentElement;
239
+ if (!parent) return tag;
240
+ const sameTag = Array.from(parent.children).filter((child) => child.localName === tag);
241
+ if (sameTag.length <= 1) return tag;
242
+ return `${tag}:nth-of-type(${sameTag.indexOf(element) + 1})`;
243
+ }
244
+ /**
245
+ * Shortest selector that still resolves back to `element` from the document.
246
+ */
247
+ function buildSelector(element) {
248
+ if (element === document.documentElement) return "html";
249
+ if (element === document.body) return "body";
250
+ const handle = uniqueHandle(element);
251
+ if (handle) return handle;
252
+ const segments = [];
253
+ let current = element;
254
+ let depth = 0;
255
+ while (current && depth < MAX_DEPTH) {
256
+ if (current === document.body) {
257
+ segments.unshift("body");
258
+ break;
259
+ }
260
+ if (current === document.documentElement) {
261
+ segments.unshift("html");
262
+ break;
263
+ }
264
+ const ancestorHandle = current === element ? null : uniqueHandle(current);
265
+ if (ancestorHandle) {
266
+ segments.unshift(ancestorHandle);
267
+ break;
268
+ }
269
+ segments.unshift(positionalSegment(current));
270
+ current = current.parentElement;
271
+ depth++;
272
+ }
273
+ return segments.join(" > ");
274
+ }
275
+ function truncate(value, max) {
276
+ return value.length <= max ? value : `${value.slice(0, max - 1)}…`;
277
+ }
278
+ function accessibleLabel(element) {
279
+ const explicit = element.getAttribute("aria-label") ?? element.getAttribute("title") ?? element.getAttribute("alt") ?? element.getAttribute("placeholder");
280
+ if (explicit?.trim()) return explicit.trim();
281
+ return (element.textContent ?? "").replace(WHITESPACE, " ").trim();
282
+ }
283
+ /** Short human label such as `button "Sign in"` or `div.card`. */
284
+ function describeElement(element) {
285
+ const tag = element.localName;
286
+ const label = accessibleLabel(element);
287
+ if (label) return truncate(`${tag} "${label}"`, MAX_LABEL_LENGTH);
288
+ const firstClass = element.classList.item(0);
289
+ return truncate(firstClass ? `${tag}.${firstClass}` : tag, MAX_LABEL_LENGTH);
290
+ }
291
+ function getElementRect(element) {
292
+ const rect = element.getBoundingClientRect();
293
+ return {
294
+ height: Math.round(rect.height),
295
+ width: Math.round(rect.width),
296
+ x: Math.round(rect.x),
297
+ y: Math.round(rect.y)
298
+ };
299
+ }
300
+ /** Everything an agent needs to find the picked element back in the codebase. */
301
+ function buildElementSelection(element) {
302
+ const { componentStack, sourceLocation } = inspectReactElement(element);
303
+ return {
304
+ componentStack,
305
+ html: truncate(element.outerHTML, MAX_HTML_LENGTH),
306
+ label: describeElement(element),
307
+ rect: getElementRect(element),
308
+ selector: truncate(buildSelector(element), MAX_SELECTOR_LENGTH),
309
+ sourceLocation: sourceLocation ? truncate(sourceLocation, MAX_SOURCE_LOCATION_LENGTH) : sourceLocation
310
+ };
311
+ }
312
+ //#endregion
313
+ //#region src/feedback/core/page-context.ts
314
+ const BROWSER_PATTERNS = [
315
+ ["Edge", /Edg(?:e|A|iOS)?\/([\d.]+)/],
316
+ ["Opera", /OPR\/([\d.]+)/],
317
+ ["Samsung Internet", /SamsungBrowser\/([\d.]+)/],
318
+ ["Firefox", /(?:Firefox|FxiOS)\/([\d.]+)/],
319
+ ["Chrome", /(?:Chrome|CriOS)\/([\d.]+)/],
320
+ ["Safari", /Version\/([\d.]+).*Safari/]
321
+ ];
322
+ const OS_PATTERNS = [
323
+ ["iOS", /iPhone|iPad|iPod/],
324
+ ["Android", /Android/],
325
+ ["Windows", /Windows NT/],
326
+ ["macOS", /Mac OS X|Macintosh/],
327
+ ["ChromeOS", /CrOS/],
328
+ ["Linux", /Linux|X11/]
329
+ ];
330
+ const MOBILE_HINT = /Mobile|iPhone|iPod/;
331
+ const TABLET_HINT = /iPad|Tablet/;
332
+ const TRAILING_ZERO = /\.0$/;
333
+ const ANDROID = /Android/;
334
+ function shortenVersion(version) {
335
+ return version.split(".").slice(0, 2).join(".").replace(TRAILING_ZERO, "");
336
+ }
337
+ function detectDevice(userAgent) {
338
+ if (TABLET_HINT.test(userAgent)) return "tablet";
339
+ if (MOBILE_HINT.test(userAgent)) return "mobile";
340
+ return ANDROID.test(userAgent) ? "tablet" : "desktop";
341
+ }
342
+ function parseUserAgent(userAgent) {
343
+ const info = { device: detectDevice(userAgent) };
344
+ for (const [name, pattern] of BROWSER_PATTERNS) {
345
+ const version = pattern.exec(userAgent)?.[1];
346
+ if (version) {
347
+ info.browser = `${name} ${shortenVersion(version)}`;
348
+ break;
349
+ }
350
+ }
351
+ for (const [name, pattern] of OS_PATTERNS) if (pattern.test(userAgent)) {
352
+ info.os = name;
353
+ break;
354
+ }
355
+ return info;
356
+ }
357
+ const MAX_PAGE_TITLE_LENGTH = 300;
358
+ const MAX_URL_LENGTH = 2e3;
359
+ const MAX_USER_AGENT_LENGTH = 600;
360
+ function clip(value, max) {
361
+ return value.length <= max ? value : value.slice(0, max);
362
+ }
363
+ function optionalText(value, max) {
364
+ return value?.trim() ? clip(value, max) : void 0;
365
+ }
366
+ function resolveTimezone() {
367
+ try {
368
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
369
+ } catch {}
370
+ }
371
+ /** Everything about the page that a bug report needs and the DOM already knows. */
372
+ function collectPageContext(options) {
373
+ const userAgent = navigator.userAgent;
374
+ const agent = parseUserAgent(userAgent);
375
+ return {
376
+ browser: agent.browser,
377
+ device: agent.device,
378
+ language: navigator.language,
379
+ os: agent.os,
380
+ pageTitle: optionalText(document.title, MAX_PAGE_TITLE_LENGTH),
381
+ referrer: optionalText(document.referrer, MAX_URL_LENGTH),
382
+ screen: {
383
+ height: window.screen.height,
384
+ width: window.screen.width
385
+ },
386
+ sdkVersion: options?.sdkVersion,
387
+ timezone: resolveTimezone(),
388
+ url: clip(window.location.href, MAX_URL_LENGTH),
389
+ userAgent: clip(userAgent, MAX_USER_AGENT_LENGTH),
390
+ viewport: {
391
+ devicePixelRatio: window.devicePixelRatio,
392
+ height: window.innerHeight,
393
+ width: window.innerWidth
394
+ }
395
+ };
396
+ }
397
+ //#endregion
398
+ //#region src/feedback/types.ts
399
+ /** Reported with every submission. Keep in sync with package.json on release. */
400
+ const SDK_VERSION = "0.2.0";
401
+ const DEFAULT_WIDGET_LABELS = {
402
+ annotateHint: "Draw on the screenshot to point at the problem.",
403
+ attachScreenshot: "Attach a screenshot",
404
+ back: "Back",
405
+ cancel: "Cancel",
406
+ categoryBug: "Bug",
407
+ categoryIdea: "Idea",
408
+ categoryQuestion: "Question",
409
+ clearAnnotations: "Clear drawing",
410
+ descriptionPlaceholder: "What happened? What did you expect?",
411
+ dismissForDays: "Hide for {days} days",
412
+ done: "Done",
413
+ emailLabel: "Email",
414
+ emailPlaceholder: "you@company.com",
415
+ errorGeneric: "Something went wrong. Please try again.",
416
+ errorTitleRequired: "Tell us a bit about it first.",
417
+ pickElement: "Point at an element",
418
+ pickElementHint: "Click the element you are talking about — cancel with",
419
+ recapture: "Retake",
420
+ removeScreenshot: "Remove",
421
+ retakeHint: "Screenshot of this page",
422
+ submit: "Send feedback",
423
+ successMessage: "We read every report. Thanks for taking the time.",
424
+ successTitle: "Feedback sent",
425
+ title: "Send feedback",
426
+ titlePlaceholder: "Short summary",
427
+ trigger: "Feedback",
428
+ undo: "Undo"
429
+ };
430
+ //#endregion
431
+ //#region src/feedback/core/annotations.ts
432
+ const ANNOTATION_COLORS = [
433
+ "#ef4444",
434
+ "#f59e0b",
435
+ "#22c55e",
436
+ "#3b82f6",
437
+ "#111827"
438
+ ];
439
+ const BOX_TOOLS = [
440
+ "rectangle",
441
+ "highlight",
442
+ "blur"
443
+ ];
444
+ const MIN_GESTURE_LENGTH = 8;
445
+ const ARROW_HEAD_ANGLE = Math.PI / 7;
446
+ const DEFAULT_PATH_TOLERANCE = 2.5;
447
+ function normalizeRect(start, end) {
448
+ return {
449
+ height: Math.abs(end.y - start.y),
450
+ width: Math.abs(end.x - start.x),
451
+ x: Math.min(start.x, end.x),
452
+ y: Math.min(start.y, end.y)
453
+ };
454
+ }
455
+ /** The two barbs closing the arrow tip, both `size` px away from `end`. */
456
+ function arrowHead(start, end, size) {
457
+ const angle = Math.atan2(end.y - start.y, end.x - start.x);
458
+ if (Math.hypot(end.x - start.x, end.y - start.y) === 0) return [end, end];
459
+ const barb = (offset) => ({
460
+ x: end.x - size * Math.cos(angle + offset),
461
+ y: end.y - size * Math.sin(angle + offset)
462
+ });
463
+ return [barb(-ARROW_HEAD_ANGLE), barb(ARROW_HEAD_ANGLE)];
464
+ }
465
+ /** Drops points a user cannot perceive, keeping the payload small. */
466
+ function simplifyPath(points, tolerance = DEFAULT_PATH_TOLERANCE) {
467
+ if (points.length < 3) return points;
468
+ const [first, ...rest] = points;
469
+ if (!first) return points;
470
+ const kept = [first];
471
+ let anchor = first;
472
+ for (const point of rest.slice(0, -1)) if (Math.hypot(point.x - anchor.x, point.y - anchor.y) >= tolerance) {
473
+ kept.push(point);
474
+ anchor = point;
475
+ }
476
+ const last = points.at(-1);
477
+ if (last) kept.push(last);
478
+ return kept;
479
+ }
480
+ function isDegenerate(annotation) {
481
+ if (annotation.tool === "pen") return (annotation.points?.length ?? 0) < 2;
482
+ const { start, end } = annotation;
483
+ return Math.hypot(end.x - start.x, end.y - start.y) < MIN_GESTURE_LENGTH;
484
+ }
485
+ function toWire(annotation) {
486
+ const { color, start, end, tool } = annotation;
487
+ if (tool === "pen") return {
488
+ color,
489
+ points: simplifyPath(annotation.points ?? []),
490
+ type: tool,
491
+ x: start.x,
492
+ y: start.y
493
+ };
494
+ if (BOX_TOOLS.includes(tool)) {
495
+ const rect = normalizeRect(start, end);
496
+ return {
497
+ color,
498
+ height: rect.height,
499
+ type: tool,
500
+ width: rect.width,
501
+ x: rect.x,
502
+ y: rect.y
503
+ };
504
+ }
505
+ return {
506
+ color,
507
+ endX: end.x,
508
+ endY: end.y,
509
+ type: tool,
510
+ x: start.x,
511
+ y: start.y
512
+ };
513
+ }
514
+ /** Serializes to the shape the Reflet API stores next to the screenshot. */
515
+ function toWireAnnotations(annotations) {
516
+ return annotations.filter((item) => !isDegenerate(item)).map(toWire);
517
+ }
518
+ //#endregion
519
+ //#region src/feedback/core/annotation-renderer.ts
520
+ const STROKE_WIDTH = 3;
521
+ const ARROW_HEAD_SIZE = 16;
522
+ const HIGHLIGHT_ALPHA = .3;
523
+ const REDACTION_FILL = "#111827";
524
+ const PIXEL_BLOCK = 10;
525
+ function scalePoint(point, scale) {
526
+ return {
527
+ x: point.x * scale,
528
+ y: point.y * scale
529
+ };
530
+ }
531
+ function scaleRect(rect, scale) {
532
+ return {
533
+ height: rect.height * scale,
534
+ width: rect.width * scale,
535
+ x: rect.x * scale,
536
+ y: rect.y * scale
537
+ };
538
+ }
539
+ function isCanvasElement(value) {
540
+ return typeof HTMLCanvasElement !== "undefined" && value instanceof HTMLCanvasElement;
541
+ }
542
+ /**
543
+ * Downsamples the region and paints it back enlarged, so redacted pixels are
544
+ * unrecoverable. Falls back to an opaque block wherever 2d canvases are absent.
545
+ */
546
+ function redact(context, rect) {
547
+ const source = context.canvas;
548
+ const width = Math.max(1, Math.round(rect.width / PIXEL_BLOCK));
549
+ const height = Math.max(1, Math.round(rect.height / PIXEL_BLOCK));
550
+ if (isCanvasElement(source)) {
551
+ const offscreen = document.createElement("canvas");
552
+ offscreen.width = width;
553
+ offscreen.height = height;
554
+ const offscreenContext = offscreen.getContext("2d");
555
+ if (offscreenContext) {
556
+ offscreenContext.imageSmoothingEnabled = true;
557
+ offscreenContext.drawImage(source, rect.x, rect.y, rect.width, rect.height, 0, 0, width, height);
558
+ context.drawImage(offscreen, rect.x, rect.y, rect.width, rect.height);
559
+ return;
560
+ }
561
+ }
562
+ context.fillStyle = REDACTION_FILL;
563
+ context.fillRect(rect.x, rect.y, rect.width, rect.height);
564
+ }
565
+ function drawArrow(context, start, end, scale) {
566
+ context.beginPath();
567
+ context.moveTo(start.x, start.y);
568
+ context.lineTo(end.x, end.y);
569
+ context.stroke();
570
+ const [left, right] = arrowHead(start, end, ARROW_HEAD_SIZE * scale);
571
+ context.beginPath();
572
+ context.moveTo(end.x, end.y);
573
+ context.lineTo(left.x, left.y);
574
+ context.lineTo(right.x, right.y);
575
+ context.closePath();
576
+ context.fill();
577
+ }
578
+ function drawPen(context, points, scale) {
579
+ const [first, ...rest] = points;
580
+ if (!first) return;
581
+ const head = scalePoint(first, scale);
582
+ context.beginPath();
583
+ context.moveTo(head.x, head.y);
584
+ for (const point of rest) {
585
+ const scaled = scalePoint(point, scale);
586
+ context.lineTo(scaled.x, scaled.y);
587
+ }
588
+ context.stroke();
589
+ }
590
+ function drawAnnotation(context, annotation, scale) {
591
+ const { color, tool } = annotation;
592
+ const rect = scaleRect(normalizeRect(annotation.start, annotation.end), scale);
593
+ context.save();
594
+ context.lineWidth = STROKE_WIDTH * scale;
595
+ context.lineCap = "round";
596
+ context.lineJoin = "round";
597
+ context.strokeStyle = color;
598
+ context.fillStyle = color;
599
+ switch (tool) {
600
+ case "pen":
601
+ drawPen(context, annotation.points ?? [], scale);
602
+ break;
603
+ case "arrow":
604
+ drawArrow(context, scalePoint(annotation.start, scale), scalePoint(annotation.end, scale), scale);
605
+ break;
606
+ case "rectangle":
607
+ context.strokeRect(rect.x, rect.y, rect.width, rect.height);
608
+ break;
609
+ case "highlight":
610
+ context.globalAlpha = HIGHLIGHT_ALPHA;
611
+ context.fillRect(rect.x, rect.y, rect.width, rect.height);
612
+ break;
613
+ default: redact(context, rect);
614
+ }
615
+ context.restore();
616
+ }
617
+ function drawAnnotations(context, annotations, options) {
618
+ const scale = options?.scale ?? 1;
619
+ for (const annotation of annotations) if (!isDegenerate(annotation)) drawAnnotation(context, annotation, scale);
620
+ }
621
+ function loadImage(url) {
622
+ return new Promise((resolve, reject) => {
623
+ const image = new Image();
624
+ image.onload = () => resolve(image);
625
+ image.onerror = () => reject(/* @__PURE__ */ new Error("Screenshot could not be decoded"));
626
+ image.src = url;
627
+ });
628
+ }
629
+ function toBlob(canvas) {
630
+ return new Promise((resolve) => {
631
+ canvas.toBlob(resolve, "image/png");
632
+ });
633
+ }
634
+ /**
635
+ * Burns the annotations into a copy of the capture so reviewers and agents see
636
+ * the drawing without needing to replay the vector data.
637
+ */
638
+ async function renderAnnotatedImage(source, annotations) {
639
+ if (annotations.length === 0) return null;
640
+ const canvas = document.createElement("canvas");
641
+ canvas.width = source.width;
642
+ canvas.height = source.height;
643
+ const context = canvas.getContext("2d");
644
+ if (!context) return null;
645
+ const image = await loadImage(source.objectUrl);
646
+ context.drawImage(image, 0, 0, source.width, source.height);
647
+ drawAnnotations(context, annotations);
648
+ const blob = await toBlob(canvas);
649
+ if (!blob) return null;
650
+ return {
651
+ blob,
652
+ height: source.height,
653
+ mimeType: "image/png",
654
+ objectUrl: URL.createObjectURL(blob),
655
+ width: source.width
656
+ };
657
+ }
658
+ //#endregion
659
+ //#region src/feedback/ui/icons.tsx
660
+ function Svg({ children, size = 16 }) {
661
+ return /* @__PURE__ */ jsx("svg", {
662
+ "aria-hidden": "true",
663
+ fill: "none",
664
+ height: size,
665
+ stroke: "currentColor",
666
+ strokeLinecap: "round",
667
+ strokeLinejoin: "round",
668
+ strokeWidth: "1.8",
669
+ viewBox: "0 0 24 24",
670
+ width: size,
671
+ children
672
+ });
673
+ }
674
+ function ChatIcon() {
675
+ return /* @__PURE__ */ jsx(Svg, {
676
+ size: 18,
677
+ children: /* @__PURE__ */ jsx("path", { d: "M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" })
678
+ });
679
+ }
680
+ function CloseIcon() {
681
+ return /* @__PURE__ */ jsx(Svg, { children: /* @__PURE__ */ jsx("path", { d: "M18 6 6 18M6 6l12 12" }) });
682
+ }
683
+ function BugIcon() {
684
+ return /* @__PURE__ */ jsx(Svg, {
685
+ size: 14,
686
+ children: /* @__PURE__ */ jsx("path", { d: "M8 6a4 4 0 0 1 8 0M6 10h12v4a6 6 0 0 1-12 0zM3 12h3M18 12h3M4.5 6.5 7 8M19.5 6.5 17 8M4.5 17.5 7 16M19.5 17.5 17 16" })
687
+ });
688
+ }
689
+ function IdeaIcon() {
690
+ return /* @__PURE__ */ jsx(Svg, {
691
+ size: 14,
692
+ children: /* @__PURE__ */ jsx("path", { d: "M9 18h6M10 21h4M12 3a6 6 0 0 0-3.6 10.8c.5.4.8.9.9 1.5l.1.7h5.2l.1-.7c.1-.6.4-1.1.9-1.5A6 6 0 0 0 12 3" })
693
+ });
694
+ }
695
+ function QuestionIcon() {
696
+ return /* @__PURE__ */ jsxs(Svg, {
697
+ size: 14,
698
+ children: [/* @__PURE__ */ jsx("circle", {
699
+ cx: "12",
700
+ cy: "12",
701
+ r: "9"
702
+ }), /* @__PURE__ */ jsx("path", { d: "M9.6 9.4a2.5 2.5 0 1 1 3.3 2.4c-.6.2-.9.8-.9 1.4v.3M12 17h.01" })]
703
+ });
704
+ }
705
+ function CameraIcon() {
706
+ return /* @__PURE__ */ jsxs(Svg, { children: [/* @__PURE__ */ jsx("path", { d: "M3 8.5A1.5 1.5 0 0 1 4.5 7h2.2l1.2-2h8.2l1.2 2h2.2A1.5 1.5 0 0 1 21 8.5v9A1.5 1.5 0 0 1 19.5 19h-15A1.5 1.5 0 0 1 3 17.5z" }), /* @__PURE__ */ jsx("circle", {
707
+ cx: "12",
708
+ cy: "13",
709
+ r: "3.2"
710
+ })] });
711
+ }
712
+ function PencilIcon() {
713
+ return /* @__PURE__ */ jsx(Svg, { children: /* @__PURE__ */ jsx("path", { d: "M16.5 4.5a2.1 2.1 0 0 1 3 3L8 19l-4 1 1-4z" }) });
714
+ }
715
+ function TargetIcon() {
716
+ return /* @__PURE__ */ jsxs(Svg, { children: [/* @__PURE__ */ jsx("path", { d: "M12 3v3M12 18v3M3 12h3M18 12h3" }), /* @__PURE__ */ jsx("circle", {
717
+ cx: "12",
718
+ cy: "12",
719
+ r: "5"
720
+ })] });
721
+ }
722
+ function TrashIcon() {
723
+ return /* @__PURE__ */ jsx(Svg, { children: /* @__PURE__ */ jsx("path", { d: "M4 7h16M9 7V5h6v2M6 7l1 13h10l1-13M10 11v5M14 11v5" }) });
724
+ }
725
+ function ArrowIcon() {
726
+ return /* @__PURE__ */ jsx(Svg, { children: /* @__PURE__ */ jsx("path", { d: "M5 19 19 5M11 5h8v8" }) });
727
+ }
728
+ function SquareIcon() {
729
+ return /* @__PURE__ */ jsx(Svg, { children: /* @__PURE__ */ jsx("rect", {
730
+ height: "13",
731
+ rx: "1.5",
732
+ width: "16",
733
+ x: "4",
734
+ y: "5.5"
735
+ }) });
736
+ }
737
+ function HighlightIcon() {
738
+ return /* @__PURE__ */ jsx(Svg, { children: /* @__PURE__ */ jsx("path", { d: "M4 15h16M6 5h12v7H6z" }) });
739
+ }
740
+ function BlurIcon() {
741
+ return /* @__PURE__ */ jsxs(Svg, { children: [/* @__PURE__ */ jsx("path", { d: "M12 3c3.5 4 5.5 6.6 5.5 9.2A5.5 5.5 0 0 1 6.5 12.2C6.5 9.6 8.5 7 12 3" }), /* @__PURE__ */ jsx("path", { d: "M9 13h.01M12 15h.01M15 12h.01" })] });
742
+ }
743
+ function UndoIcon() {
744
+ return /* @__PURE__ */ jsx(Svg, { children: /* @__PURE__ */ jsx("path", { d: "M4 9h11a5 5 0 0 1 0 10h-5M4 9l4-4M4 9l4 4" }) });
745
+ }
746
+ function CheckIcon({ size = 28 }) {
747
+ return /* @__PURE__ */ jsx("svg", {
748
+ "aria-hidden": "true",
749
+ fill: "none",
750
+ height: size,
751
+ stroke: "currentColor",
752
+ strokeLinecap: "round",
753
+ strokeLinejoin: "round",
754
+ strokeWidth: "2.4",
755
+ viewBox: "0 0 24 24",
756
+ width: size,
757
+ children: /* @__PURE__ */ jsx("path", { d: "m5 13 4 4L19 7" })
758
+ });
759
+ }
760
+ //#endregion
761
+ //#region src/feedback/ui/annotator.tsx
762
+ const TOOLS = [
763
+ {
764
+ icon: PencilIcon,
765
+ id: "pen",
766
+ label: "Draw"
767
+ },
768
+ {
769
+ icon: ArrowIcon,
770
+ id: "arrow",
771
+ label: "Arrow"
772
+ },
773
+ {
774
+ icon: SquareIcon,
775
+ id: "rectangle",
776
+ label: "Box"
777
+ },
778
+ {
779
+ icon: HighlightIcon,
780
+ id: "highlight",
781
+ label: "Highlight"
782
+ },
783
+ {
784
+ icon: BlurIcon,
785
+ id: "blur",
786
+ label: "Hide"
787
+ }
788
+ ];
789
+ function toImagePoint(canvas, clientX, clientY) {
790
+ const bounds = canvas.getBoundingClientRect();
791
+ return {
792
+ x: (clientX - bounds.left) / bounds.width * canvas.width,
793
+ y: (clientY - bounds.top) / bounds.height * canvas.height
794
+ };
795
+ }
796
+ function Annotator({ annotations, capture, labels, onChange, onDone }) {
797
+ const canvasRef = useRef(null);
798
+ const nextId = useRef(0);
799
+ const [tool, setTool] = useState("pen");
800
+ const [color, setColor] = useState(ANNOTATION_COLORS[0]);
801
+ const [draft, setDraft] = useState(null);
802
+ const [base, setBase] = useState(null);
803
+ useEffect(() => {
804
+ let active = true;
805
+ const image = new Image();
806
+ image.onload = () => {
807
+ if (active) setBase(image);
808
+ };
809
+ image.src = capture.objectUrl;
810
+ return () => {
811
+ active = false;
812
+ setBase(null);
813
+ };
814
+ }, [capture.objectUrl]);
815
+ useEffect(() => {
816
+ const canvas = canvasRef.current;
817
+ const context = canvas?.getContext("2d");
818
+ if (!(canvas && context)) return;
819
+ context.clearRect(0, 0, canvas.width, canvas.height);
820
+ if (base) context.drawImage(base, 0, 0, canvas.width, canvas.height);
821
+ drawAnnotations(context, draft ? [...annotations, draft] : annotations);
822
+ }, [
823
+ annotations,
824
+ base,
825
+ draft
826
+ ]);
827
+ const onPointerDown = (event) => {
828
+ const canvas = canvasRef.current;
829
+ if (!canvas) return;
830
+ canvas.setPointerCapture(event.pointerId);
831
+ const point = toImagePoint(canvas, event.clientX, event.clientY);
832
+ nextId.current += 1;
833
+ setDraft({
834
+ color,
835
+ end: point,
836
+ id: `a${nextId.current}`,
837
+ points: tool === "pen" ? [point] : void 0,
838
+ start: point,
839
+ tool
840
+ });
841
+ };
842
+ const onPointerMove = (event) => {
843
+ const canvas = canvasRef.current;
844
+ if (!(canvas && draft)) return;
845
+ const point = toImagePoint(canvas, event.clientX, event.clientY);
846
+ setDraft(draft.tool === "pen" ? {
847
+ ...draft,
848
+ end: point,
849
+ points: [...draft.points ?? [], point]
850
+ } : {
851
+ ...draft,
852
+ end: point
853
+ });
854
+ };
855
+ const onPointerUp = () => {
856
+ if (!draft) return;
857
+ if (!isDegenerate(draft)) onChange([...annotations, draft]);
858
+ setDraft(null);
859
+ };
860
+ useEffect(() => {
861
+ const onKeyDown = (event) => {
862
+ if (event.key === "Escape") {
863
+ event.preventDefault();
864
+ onDone();
865
+ }
866
+ };
867
+ document.addEventListener("keydown", onKeyDown);
868
+ return () => document.removeEventListener("keydown", onKeyDown);
869
+ }, [onDone]);
870
+ return /* @__PURE__ */ jsxs("div", {
871
+ className: "overlay",
872
+ children: [/* @__PURE__ */ jsx("div", {
873
+ className: "editor",
874
+ children: /* @__PURE__ */ jsx("canvas", {
875
+ height: capture.height,
876
+ onPointerCancel: onPointerUp,
877
+ onPointerDown,
878
+ onPointerMove,
879
+ onPointerUp,
880
+ ref: canvasRef,
881
+ width: capture.width
882
+ })
883
+ }), /* @__PURE__ */ jsxs("div", {
884
+ className: "toolbar",
885
+ children: [
886
+ /* @__PURE__ */ jsx("div", {
887
+ className: "group",
888
+ children: TOOLS.map(({ icon: Icon, id, label }) => /* @__PURE__ */ jsx("button", {
889
+ "aria-label": label,
890
+ "aria-pressed": tool === id,
891
+ className: "tool",
892
+ onClick: () => setTool(id),
893
+ title: label,
894
+ type: "button",
895
+ children: /* @__PURE__ */ jsx(Icon, {})
896
+ }, id))
897
+ }),
898
+ /* @__PURE__ */ jsx("div", {
899
+ className: "group",
900
+ children: ANNOTATION_COLORS.map((value) => /* @__PURE__ */ jsx("button", {
901
+ "aria-label": `Color ${value}`,
902
+ "aria-pressed": color === value,
903
+ className: "swatch",
904
+ onClick: () => setColor(value),
905
+ style: { background: value },
906
+ type: "button"
907
+ }, value))
908
+ }),
909
+ /* @__PURE__ */ jsxs("div", {
910
+ className: "group",
911
+ children: [
912
+ /* @__PURE__ */ jsx("button", {
913
+ "aria-label": labels.undo,
914
+ className: "tool",
915
+ disabled: annotations.length === 0,
916
+ onClick: () => onChange(annotations.slice(0, -1)),
917
+ title: labels.undo,
918
+ type: "button",
919
+ children: /* @__PURE__ */ jsx(UndoIcon, {})
920
+ }),
921
+ /* @__PURE__ */ jsx("button", {
922
+ "aria-label": labels.clearAnnotations,
923
+ className: "tool",
924
+ disabled: annotations.length === 0,
925
+ onClick: () => onChange([]),
926
+ title: labels.clearAnnotations,
927
+ type: "button",
928
+ children: /* @__PURE__ */ jsx(TrashIcon, {})
929
+ }),
930
+ /* @__PURE__ */ jsx("button", {
931
+ className: "done-btn",
932
+ onClick: onDone,
933
+ type: "button",
934
+ children: labels.done
935
+ })
936
+ ]
937
+ })
938
+ ]
939
+ })]
940
+ });
941
+ }
942
+ //#endregion
943
+ //#region src/feedback/ui/launcher.tsx
944
+ function Launcher({ compact, isOpen, label, onClick }) {
945
+ return /* @__PURE__ */ jsxs("button", {
946
+ "aria-expanded": isOpen,
947
+ "aria-label": label,
948
+ className: "launcher",
949
+ "data-compact": compact || isOpen ? "true" : "false",
950
+ onClick,
951
+ type: "button",
952
+ children: [isOpen ? /* @__PURE__ */ jsx(CloseIcon, {}) : /* @__PURE__ */ jsx(ChatIcon, {}), !(compact || isOpen) && label]
953
+ });
954
+ }
955
+ //#endregion
956
+ //#region src/feedback/ui/panel.tsx
957
+ const CATEGORY_META = {
958
+ bug: {
959
+ icon: BugIcon,
960
+ labelKey: "categoryBug"
961
+ },
962
+ idea: {
963
+ icon: IdeaIcon,
964
+ labelKey: "categoryIdea"
965
+ },
966
+ question: {
967
+ icon: QuestionIcon,
968
+ labelKey: "categoryQuestion"
969
+ }
970
+ };
971
+ function Attachment({ labels, state }) {
972
+ if (state.isCapturing) return /* @__PURE__ */ jsxs("div", {
973
+ className: "attachment",
974
+ children: [/* @__PURE__ */ jsx("div", { className: "thumb" }), /* @__PURE__ */ jsxs("div", {
975
+ className: "meta",
976
+ children: [/* @__PURE__ */ jsx("strong", { children: labels.retakeHint }), /* @__PURE__ */ jsx("span", { children: "…" })]
977
+ })]
978
+ });
979
+ if (!state.capture) return /* @__PURE__ */ jsxs("button", {
980
+ className: "ghost-btn",
981
+ onClick: () => state.takeCapture(),
982
+ type: "button",
983
+ children: [/* @__PURE__ */ jsx(CameraIcon, {}), labels.attachScreenshot]
984
+ });
985
+ const annotationCount = state.annotations.length;
986
+ return /* @__PURE__ */ jsxs("div", {
987
+ className: "attachment",
988
+ children: [
989
+ /* @__PURE__ */ jsx("div", {
990
+ className: "thumb",
991
+ children: /* @__PURE__ */ jsx("img", {
992
+ alt: "",
993
+ height: state.capture.height,
994
+ src: state.capture.objectUrl,
995
+ width: state.capture.width
996
+ })
997
+ }),
998
+ /* @__PURE__ */ jsxs("div", {
999
+ className: "meta",
1000
+ children: [/* @__PURE__ */ jsx("strong", { children: labels.retakeHint }), /* @__PURE__ */ jsxs("span", { children: [
1001
+ state.capture.width,
1002
+ "×",
1003
+ state.capture.height,
1004
+ annotationCount > 0 ? ` · ${annotationCount} marks` : ""
1005
+ ] })]
1006
+ }),
1007
+ /* @__PURE__ */ jsxs("div", {
1008
+ className: "actions",
1009
+ children: [
1010
+ /* @__PURE__ */ jsx("button", {
1011
+ "aria-label": labels.annotateHint,
1012
+ className: "icon-btn",
1013
+ onClick: () => state.setStep("annotate"),
1014
+ title: labels.annotateHint,
1015
+ type: "button",
1016
+ children: /* @__PURE__ */ jsx(PencilIcon, {})
1017
+ }),
1018
+ /* @__PURE__ */ jsx("button", {
1019
+ "aria-label": labels.recapture,
1020
+ className: "icon-btn",
1021
+ onClick: () => state.takeCapture(),
1022
+ title: labels.recapture,
1023
+ type: "button",
1024
+ children: /* @__PURE__ */ jsx(CameraIcon, {})
1025
+ }),
1026
+ /* @__PURE__ */ jsx("button", {
1027
+ "aria-label": labels.removeScreenshot,
1028
+ className: "icon-btn",
1029
+ onClick: state.removeCapture,
1030
+ title: labels.removeScreenshot,
1031
+ type: "button",
1032
+ children: /* @__PURE__ */ jsx(TrashIcon, {})
1033
+ })
1034
+ ]
1035
+ })
1036
+ ]
1037
+ });
1038
+ }
1039
+ function SelectionChip({ labels, state }) {
1040
+ const { selection } = state;
1041
+ if (!selection) return /* @__PURE__ */ jsxs("button", {
1042
+ className: "ghost-btn",
1043
+ onClick: () => state.setStep("picking"),
1044
+ type: "button",
1045
+ children: [/* @__PURE__ */ jsx(TargetIcon, {}), labels.pickElement]
1046
+ });
1047
+ const component = selection.componentStack[0];
1048
+ return /* @__PURE__ */ jsxs("span", {
1049
+ className: "chip",
1050
+ children: [
1051
+ /* @__PURE__ */ jsx(TargetIcon, {}),
1052
+ /* @__PURE__ */ jsxs("span", {
1053
+ className: "truncate",
1054
+ children: [
1055
+ component ? /* @__PURE__ */ jsx("strong", { children: `<${component}>` }) : selection.label,
1056
+ " ",
1057
+ /* @__PURE__ */ jsx("code", { children: selection.sourceLocation ?? selection.selector })
1058
+ ]
1059
+ }),
1060
+ /* @__PURE__ */ jsx("button", {
1061
+ "aria-label": labels.cancel,
1062
+ className: "icon-btn",
1063
+ onClick: state.clearSelection,
1064
+ type: "button",
1065
+ children: /* @__PURE__ */ jsx(CloseIcon, {})
1066
+ })
1067
+ ]
1068
+ });
1069
+ }
1070
+ function FeedbackPanel({ categories, labels, state }) {
1071
+ const messageRef = useRef(null);
1072
+ useEffect(() => {
1073
+ messageRef.current?.focus();
1074
+ }, []);
1075
+ if (state.step === "success") return /* @__PURE__ */ jsx("section", {
1076
+ "aria-live": "polite",
1077
+ className: "panel",
1078
+ children: /* @__PURE__ */ jsxs("div", {
1079
+ className: "done",
1080
+ children: [
1081
+ /* @__PURE__ */ jsx(CheckIcon, {}),
1082
+ /* @__PURE__ */ jsx("h2", { children: labels.successTitle }),
1083
+ /* @__PURE__ */ jsx("p", { children: labels.successMessage })
1084
+ ]
1085
+ })
1086
+ });
1087
+ return /* @__PURE__ */ jsxs("section", {
1088
+ "aria-label": labels.title,
1089
+ className: "panel",
1090
+ children: [
1091
+ /* @__PURE__ */ jsxs("header", {
1092
+ className: "head",
1093
+ children: [
1094
+ /* @__PURE__ */ jsx("h2", { children: labels.title }),
1095
+ /* @__PURE__ */ jsx("span", { className: "spacer" }),
1096
+ /* @__PURE__ */ jsx("button", {
1097
+ "aria-label": labels.cancel,
1098
+ className: "icon-btn",
1099
+ onClick: state.close,
1100
+ type: "button",
1101
+ children: /* @__PURE__ */ jsx(CloseIcon, {})
1102
+ })
1103
+ ]
1104
+ }),
1105
+ /* @__PURE__ */ jsxs("form", {
1106
+ className: "body",
1107
+ onSubmit: (event) => {
1108
+ event.preventDefault();
1109
+ state.submit();
1110
+ },
1111
+ children: [
1112
+ categories.length > 1 && /* @__PURE__ */ jsx("fieldset", {
1113
+ className: "segmented",
1114
+ children: categories.map((value) => {
1115
+ const { icon: Icon, labelKey } = CATEGORY_META[value];
1116
+ return /* @__PURE__ */ jsxs("button", {
1117
+ "aria-pressed": state.category === value,
1118
+ onClick: () => state.setCategory(value),
1119
+ type: "button",
1120
+ children: [/* @__PURE__ */ jsx(Icon, {}), labels[labelKey]]
1121
+ }, value);
1122
+ })
1123
+ }),
1124
+ /* @__PURE__ */ jsx("textarea", {
1125
+ "aria-label": labels.descriptionPlaceholder,
1126
+ maxLength: 4e3,
1127
+ onChange: (event) => state.setMessage(event.target.value),
1128
+ placeholder: labels.descriptionPlaceholder,
1129
+ ref: messageRef,
1130
+ value: state.message
1131
+ }),
1132
+ /* @__PURE__ */ jsx(Attachment, {
1133
+ labels,
1134
+ state
1135
+ }),
1136
+ /* @__PURE__ */ jsx(SelectionChip, {
1137
+ labels,
1138
+ state
1139
+ }),
1140
+ state.isAnonymous && /* @__PURE__ */ jsx("input", {
1141
+ "aria-label": labels.emailLabel,
1142
+ autoComplete: "email",
1143
+ onChange: (event) => state.setEmail(event.target.value),
1144
+ placeholder: labels.emailPlaceholder,
1145
+ type: "email",
1146
+ value: state.email
1147
+ }),
1148
+ /* @__PURE__ */ jsx("div", {
1149
+ "aria-hidden": "true",
1150
+ className: "hp",
1151
+ children: /* @__PURE__ */ jsx("input", {
1152
+ autoComplete: "off",
1153
+ name: "company-website",
1154
+ onChange: (event) => state.setHoneypot(event.target.value),
1155
+ tabIndex: -1,
1156
+ value: state.honeypot
1157
+ })
1158
+ }),
1159
+ state.error && /* @__PURE__ */ jsx("p", {
1160
+ className: "error",
1161
+ children: state.error
1162
+ }),
1163
+ /* @__PURE__ */ jsx("button", {
1164
+ className: "submit",
1165
+ disabled: state.isSubmitting || !state.message.trim(),
1166
+ type: "submit",
1167
+ children: state.isSubmitting ? /* @__PURE__ */ jsx("span", { className: "spinner" }) : labels.submit
1168
+ })
1169
+ ]
1170
+ }),
1171
+ /* @__PURE__ */ jsxs("footer", {
1172
+ className: "footer",
1173
+ "data-dismissible": state.canDismiss,
1174
+ children: [state.canDismiss && /* @__PURE__ */ jsx("button", {
1175
+ className: "dismiss-btn",
1176
+ onClick: state.dismiss,
1177
+ type: "button",
1178
+ children: labels.dismissForDays.replace("{days}", String(state.dismissForDays))
1179
+ }), /* @__PURE__ */ jsxs("span", { children: [
1180
+ "Powered by",
1181
+ " ",
1182
+ /* @__PURE__ */ jsx("a", {
1183
+ href: "https://reflet.app",
1184
+ rel: "noopener noreferrer",
1185
+ target: "_blank",
1186
+ children: "Reflet"
1187
+ })
1188
+ ] })]
1189
+ })
1190
+ ]
1191
+ });
1192
+ }
1193
+ //#endregion
1194
+ //#region src/feedback/ui/picker.tsx
1195
+ const LABEL_HEIGHT = 28;
1196
+ const LABEL_GAP = 6;
1197
+ function isWidgetOwned(element) {
1198
+ return element.closest(`[${WIDGET_MARKER}]`) !== null;
1199
+ }
1200
+ function elementUnder(x, y) {
1201
+ const element = document.elementFromPoint(x, y);
1202
+ if (!element || isWidgetOwned(element)) return null;
1203
+ return element;
1204
+ }
1205
+ function describeTarget(element) {
1206
+ return {
1207
+ componentName: resolveComponentStack(getFiberFromNode(element))[0],
1208
+ label: describeElement(element),
1209
+ rect: element.getBoundingClientRect(),
1210
+ selector: buildSelector(element)
1211
+ };
1212
+ }
1213
+ /**
1214
+ * Points at any element in the page the way a coding agent needs it: the React
1215
+ * component that owns it plus a selector that resolves back to it.
1216
+ */
1217
+ function ElementPicker({ hint, onCancel, onPick }) {
1218
+ const [target, setTarget] = useState(null);
1219
+ useEffect(() => {
1220
+ const swallow = (event) => {
1221
+ event.preventDefault();
1222
+ event.stopPropagation();
1223
+ };
1224
+ const onMove = (event) => {
1225
+ const element = elementUnder(event.clientX, event.clientY);
1226
+ setTarget(element ? describeTarget(element) : null);
1227
+ };
1228
+ const onClick = (event) => {
1229
+ swallow(event);
1230
+ const element = elementUnder(event.clientX, event.clientY);
1231
+ if (element) onPick(element);
1232
+ };
1233
+ const onKeyDown = (event) => {
1234
+ if (event.key === "Escape") {
1235
+ swallow(event);
1236
+ onCancel();
1237
+ }
1238
+ };
1239
+ document.addEventListener("pointermove", onMove, true);
1240
+ document.addEventListener("pointerdown", swallow, true);
1241
+ document.addEventListener("mousedown", swallow, true);
1242
+ document.addEventListener("mouseup", swallow, true);
1243
+ document.addEventListener("click", onClick, true);
1244
+ document.addEventListener("keydown", onKeyDown, true);
1245
+ const previousCursor = document.body.style.cursor;
1246
+ document.body.style.cursor = "crosshair";
1247
+ return () => {
1248
+ document.removeEventListener("pointermove", onMove, true);
1249
+ document.removeEventListener("pointerdown", swallow, true);
1250
+ document.removeEventListener("mousedown", swallow, true);
1251
+ document.removeEventListener("mouseup", swallow, true);
1252
+ document.removeEventListener("click", onClick, true);
1253
+ document.removeEventListener("keydown", onKeyDown, true);
1254
+ document.body.style.cursor = previousCursor;
1255
+ };
1256
+ }, [onCancel, onPick]);
1257
+ const rect = target?.rect;
1258
+ const labelAbove = rect ? rect.top > 34 : true;
1259
+ return /* @__PURE__ */ jsxs("div", { children: [
1260
+ rect && /* @__PURE__ */ jsx("div", {
1261
+ className: "picker-box",
1262
+ style: {
1263
+ height: rect.height,
1264
+ left: rect.left,
1265
+ top: rect.top,
1266
+ width: rect.width
1267
+ }
1268
+ }),
1269
+ rect && target && /* @__PURE__ */ jsxs("div", {
1270
+ className: "picker-label",
1271
+ style: {
1272
+ left: Math.max(4, rect.left),
1273
+ top: labelAbove ? rect.top - LABEL_HEIGHT - LABEL_GAP : rect.bottom + LABEL_GAP
1274
+ },
1275
+ children: [target.componentName ? /* @__PURE__ */ jsx("strong", { children: `<${target.componentName}>` }) : /* @__PURE__ */ jsx("strong", { children: target.label }), /* @__PURE__ */ jsx("code", { children: target.selector })]
1276
+ }),
1277
+ /* @__PURE__ */ jsxs("div", {
1278
+ className: "picker-hint",
1279
+ children: [
1280
+ hint,
1281
+ " ",
1282
+ /* @__PURE__ */ jsx("kbd", { children: "Esc" })
1283
+ ]
1284
+ })
1285
+ ] });
1286
+ }
1287
+ //#endregion
1288
+ //#region src/feedback/ui/styles.ts
1289
+ /**
1290
+ * Styles for the feedback widget. Injected into a shadow root, so nothing here
1291
+ * leaks into the host app and nothing from the host app leaks in.
1292
+ */
1293
+ const WIDGET_STYLES = `
1294
+ :host {
1295
+ --rf-bg: #ffffff;
1296
+ --rf-bg-subtle: #f6f7f9;
1297
+ --rf-border: #e4e6eb;
1298
+ --rf-text: #16181d;
1299
+ --rf-text-muted: #6b7280;
1300
+ --rf-primary: #4f46e5;
1301
+ --rf-primary-text: #ffffff;
1302
+ --rf-danger: #dc2626;
1303
+ --rf-success: #16a34a;
1304
+ --rf-radius: 14px;
1305
+ --rf-shadow: 0 1px 2px rgb(16 24 40 / 6%), 0 12px 32px -8px rgb(16 24 40 / 18%);
1306
+ --rf-ring: 0 0 0 3px color-mix(in srgb, var(--rf-primary) 28%, transparent);
1307
+ --rf-ease: cubic-bezier(0.32, 0.72, 0, 1);
1308
+ color-scheme: light;
1309
+ all: initial;
1310
+ font-family: var(--rf-font, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif);
1311
+ }
1312
+
1313
+ :host([data-theme="dark"]) {
1314
+ --rf-bg: #17181c;
1315
+ --rf-bg-subtle: #212228;
1316
+ --rf-border: #2e3038;
1317
+ --rf-text: #f3f4f6;
1318
+ --rf-text-muted: #9aa1ad;
1319
+ --rf-shadow: 0 1px 2px rgb(0 0 0 / 40%), 0 16px 40px -12px rgb(0 0 0 / 60%);
1320
+ color-scheme: dark;
1321
+ }
1322
+
1323
+ *, *::before, *::after { box-sizing: border-box; }
1324
+
1325
+ .root {
1326
+ position: fixed;
1327
+ z-index: 2147483000;
1328
+ font-family: inherit;
1329
+ font-size: 14px;
1330
+ line-height: 1.45;
1331
+ color: var(--rf-text);
1332
+ }
1333
+
1334
+ .root[data-position="bottom-right"] { bottom: var(--rf-offset); right: var(--rf-offset); align-items: flex-end; }
1335
+ .root[data-position="bottom-left"] { bottom: var(--rf-offset); left: var(--rf-offset); align-items: flex-start; }
1336
+ .root[data-position="top-right"] { top: var(--rf-offset); right: var(--rf-offset); align-items: flex-end; }
1337
+ .root[data-position="top-left"] { top: var(--rf-offset); left: var(--rf-offset); align-items: flex-start; }
1338
+
1339
+ .stack { display: flex; flex-direction: column; gap: 12px; }
1340
+ .root[data-position^="top"] .stack { flex-direction: column-reverse; }
1341
+
1342
+ button {
1343
+ font: inherit;
1344
+ color: inherit;
1345
+ margin: 0;
1346
+ cursor: pointer;
1347
+ border: 0;
1348
+ background: none;
1349
+ }
1350
+
1351
+ :focus-visible { outline: none; box-shadow: var(--rf-ring); }
1352
+
1353
+ .launcher {
1354
+ display: inline-flex;
1355
+ align-items: center;
1356
+ gap: 8px;
1357
+ height: 44px;
1358
+ padding: 0 16px;
1359
+ border-radius: 999px;
1360
+ background: var(--rf-primary);
1361
+ color: var(--rf-primary-text);
1362
+ font-weight: 550;
1363
+ box-shadow: var(--rf-shadow);
1364
+ transition: transform 160ms var(--rf-ease), filter 160ms var(--rf-ease);
1365
+ }
1366
+ .launcher:hover { transform: translateY(-1px); filter: brightness(1.06); }
1367
+ .launcher:active { transform: translateY(0) scale(0.97); }
1368
+ .launcher[data-compact="true"] { width: 44px; padding: 0; justify-content: center; }
1369
+
1370
+ .panel {
1371
+ width: min(384px, calc(100vw - 32px));
1372
+ max-height: min(620px, calc(100vh - 96px));
1373
+ display: flex;
1374
+ flex-direction: column;
1375
+ overflow: hidden;
1376
+ background: var(--rf-bg);
1377
+ border: 1px solid var(--rf-border);
1378
+ border-radius: var(--rf-radius);
1379
+ box-shadow: var(--rf-shadow);
1380
+ animation: rf-in 220ms var(--rf-ease);
1381
+ }
1382
+
1383
+ @keyframes rf-in {
1384
+ from { opacity: 0; transform: translateY(8px) scale(0.98); }
1385
+ to { opacity: 1; transform: none; }
1386
+ }
1387
+
1388
+ @media (prefers-reduced-motion: reduce) {
1389
+ .panel, .launcher { animation: none; transition: none; }
1390
+ }
1391
+
1392
+ .head {
1393
+ display: flex;
1394
+ align-items: center;
1395
+ gap: 8px;
1396
+ padding: 14px 14px 10px;
1397
+ }
1398
+ .head h2 { margin: 0; font-size: 15px; font-weight: 600; }
1399
+ .head .spacer { flex: 1; }
1400
+
1401
+ .icon-btn {
1402
+ display: inline-flex;
1403
+ align-items: center;
1404
+ justify-content: center;
1405
+ width: 30px;
1406
+ height: 30px;
1407
+ border-radius: 8px;
1408
+ color: var(--rf-text-muted);
1409
+ transition: background 120ms var(--rf-ease), color 120ms var(--rf-ease);
1410
+ }
1411
+ .icon-btn:hover { background: var(--rf-bg-subtle); color: var(--rf-text); }
1412
+
1413
+ .body { display: flex; flex-direction: column; gap: 12px; padding: 0 14px 14px; overflow-y: auto; }
1414
+
1415
+ .segmented {
1416
+ border: 0;
1417
+ margin: 0;
1418
+ min-inline-size: 0;
1419
+ display: grid;
1420
+ grid-auto-flow: column;
1421
+ grid-auto-columns: 1fr;
1422
+ gap: 4px;
1423
+ padding: 4px;
1424
+ background: var(--rf-bg-subtle);
1425
+ border-radius: 10px;
1426
+ }
1427
+ .segmented button {
1428
+ display: flex;
1429
+ align-items: center;
1430
+ justify-content: center;
1431
+ gap: 6px;
1432
+ height: 32px;
1433
+ border-radius: 7px;
1434
+ font-size: 13px;
1435
+ font-weight: 500;
1436
+ color: var(--rf-text-muted);
1437
+ transition: background 140ms var(--rf-ease), color 140ms var(--rf-ease);
1438
+ }
1439
+ .segmented button[aria-pressed="true"] {
1440
+ background: var(--rf-bg);
1441
+ color: var(--rf-text);
1442
+ box-shadow: 0 1px 2px rgb(16 24 40 / 8%);
1443
+ }
1444
+
1445
+ textarea, input[type="email"] {
1446
+ width: 100%;
1447
+ padding: 10px 12px;
1448
+ font: inherit;
1449
+ color: var(--rf-text);
1450
+ background: var(--rf-bg);
1451
+ border: 1px solid var(--rf-border);
1452
+ border-radius: 10px;
1453
+ transition: border-color 140ms var(--rf-ease), box-shadow 140ms var(--rf-ease);
1454
+ }
1455
+ textarea { min-height: 92px; max-height: 220px; resize: none; }
1456
+ textarea::placeholder, input::placeholder { color: var(--rf-text-muted); }
1457
+ textarea:focus, input:focus { outline: none; border-color: var(--rf-primary); box-shadow: var(--rf-ring); }
1458
+
1459
+ .attachment {
1460
+ display: flex;
1461
+ gap: 10px;
1462
+ padding: 8px;
1463
+ border: 1px solid var(--rf-border);
1464
+ border-radius: 10px;
1465
+ background: var(--rf-bg-subtle);
1466
+ }
1467
+ .thumb {
1468
+ position: relative;
1469
+ flex: 0 0 84px;
1470
+ height: 56px;
1471
+ overflow: hidden;
1472
+ border-radius: 6px;
1473
+ border: 1px solid var(--rf-border);
1474
+ background: var(--rf-bg);
1475
+ }
1476
+ .thumb img { width: 100%; height: 100%; object-fit: cover; object-position: top center; display: block; }
1477
+ .attachment .meta { display: flex; flex-direction: column; justify-content: center; gap: 4px; min-width: 0; }
1478
+ .attachment .meta strong { font-size: 12.5px; font-weight: 550; }
1479
+ .attachment .meta span { font-size: 12px; color: var(--rf-text-muted); }
1480
+ .attachment .actions { display: flex; gap: 4px; margin-left: auto; align-items: center; }
1481
+
1482
+ .chip {
1483
+ display: inline-flex;
1484
+ align-items: center;
1485
+ gap: 6px;
1486
+ max-width: 100%;
1487
+ padding: 5px 8px;
1488
+ font-size: 12px;
1489
+ border: 1px solid var(--rf-border);
1490
+ border-radius: 8px;
1491
+ background: var(--rf-bg-subtle);
1492
+ color: var(--rf-text-muted);
1493
+ }
1494
+ .chip code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11.5px; color: var(--rf-text); }
1495
+ .chip .truncate { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1496
+
1497
+ .row { display: flex; gap: 8px; align-items: center; }
1498
+ .ghost-btn {
1499
+ display: inline-flex;
1500
+ align-items: center;
1501
+ gap: 6px;
1502
+ height: 32px;
1503
+ padding: 0 10px;
1504
+ font-size: 13px;
1505
+ font-weight: 500;
1506
+ color: var(--rf-text-muted);
1507
+ border: 1px solid var(--rf-border);
1508
+ border-radius: 9px;
1509
+ transition: background 140ms var(--rf-ease), color 140ms var(--rf-ease);
1510
+ }
1511
+ .ghost-btn:hover { background: var(--rf-bg-subtle); color: var(--rf-text); }
1512
+
1513
+ .submit {
1514
+ display: inline-flex;
1515
+ align-items: center;
1516
+ justify-content: center;
1517
+ gap: 8px;
1518
+ width: 100%;
1519
+ height: 38px;
1520
+ font-weight: 550;
1521
+ color: var(--rf-primary-text);
1522
+ background: var(--rf-primary);
1523
+ border-radius: 10px;
1524
+ transition: filter 140ms var(--rf-ease);
1525
+ }
1526
+ .submit:hover:not(:disabled) { filter: brightness(1.06); }
1527
+ .submit:disabled { opacity: 0.55; cursor: not-allowed; }
1528
+
1529
+ .error { margin: 0; font-size: 12.5px; color: var(--rf-danger); }
1530
+ .hint { margin: 0; font-size: 12px; color: var(--rf-text-muted); }
1531
+
1532
+ .footer {
1533
+ min-height: 44px;
1534
+ padding: 0 14px;
1535
+ border-top: 1px solid var(--rf-border);
1536
+ display: flex;
1537
+ align-items: center;
1538
+ justify-content: center;
1539
+ gap: 12px;
1540
+ font-size: 11.5px;
1541
+ color: var(--rf-text-muted);
1542
+ }
1543
+ .footer[data-dismissible="true"] { justify-content: space-between; }
1544
+ .footer a { color: inherit; text-decoration: none; font-weight: 550; }
1545
+ .footer a:hover { color: var(--rf-text); }
1546
+ .dismiss-btn {
1547
+ align-self: stretch;
1548
+ color: inherit;
1549
+ font-size: 11.5px;
1550
+ text-decoration: underline;
1551
+ text-underline-offset: 3px;
1552
+ }
1553
+ .dismiss-btn:hover { color: var(--rf-text); }
1554
+
1555
+ .done { display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 32px 20px 36px; text-align: center; }
1556
+ .done svg { color: var(--rf-success); }
1557
+ .done h2 { margin: 0; font-size: 15px; }
1558
+ .done p { margin: 0; font-size: 13px; color: var(--rf-text-muted); }
1559
+
1560
+ .spinner {
1561
+ width: 15px;
1562
+ height: 15px;
1563
+ border: 2px solid currentColor;
1564
+ border-right-color: transparent;
1565
+ border-radius: 50%;
1566
+ animation: rf-spin 700ms linear infinite;
1567
+ }
1568
+ @keyframes rf-spin { to { transform: rotate(360deg); } }
1569
+
1570
+ .hp { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
1571
+
1572
+ .overlay {
1573
+ position: fixed;
1574
+ inset: 0;
1575
+ z-index: 2147483001;
1576
+ display: flex;
1577
+ flex-direction: column;
1578
+ background: rgb(9 10 13 / 78%);
1579
+ backdrop-filter: blur(2px);
1580
+ }
1581
+
1582
+ .editor { flex: 1; display: flex; align-items: center; justify-content: center; padding: 24px 24px 0; min-height: 0; }
1583
+ .editor canvas {
1584
+ max-width: 100%;
1585
+ max-height: 100%;
1586
+ border-radius: 8px;
1587
+ box-shadow: 0 24px 60px -12px rgb(0 0 0 / 60%);
1588
+ cursor: crosshair;
1589
+ touch-action: none;
1590
+ }
1591
+
1592
+ .toolbar {
1593
+ display: flex;
1594
+ align-items: center;
1595
+ justify-content: center;
1596
+ gap: 6px;
1597
+ flex-wrap: wrap;
1598
+ padding: 14px 16px calc(14px + env(safe-area-inset-bottom));
1599
+ }
1600
+ .toolbar .group {
1601
+ display: flex;
1602
+ align-items: center;
1603
+ gap: 4px;
1604
+ padding: 5px;
1605
+ background: var(--rf-bg);
1606
+ border: 1px solid var(--rf-border);
1607
+ border-radius: 12px;
1608
+ box-shadow: var(--rf-shadow);
1609
+ }
1610
+ .tool {
1611
+ display: inline-flex;
1612
+ align-items: center;
1613
+ justify-content: center;
1614
+ width: 34px;
1615
+ height: 34px;
1616
+ border-radius: 8px;
1617
+ color: var(--rf-text-muted);
1618
+ transition: background 140ms var(--rf-ease), color 140ms var(--rf-ease);
1619
+ }
1620
+ .tool:hover { background: var(--rf-bg-subtle); color: var(--rf-text); }
1621
+ .tool[aria-pressed="true"] { background: var(--rf-primary); color: var(--rf-primary-text); }
1622
+ .swatch {
1623
+ width: 22px;
1624
+ height: 22px;
1625
+ border-radius: 50%;
1626
+ border: 2px solid transparent;
1627
+ transition: transform 140ms var(--rf-ease);
1628
+ }
1629
+ .swatch[aria-pressed="true"] { border-color: var(--rf-text); transform: scale(1.12); }
1630
+ .toolbar .done-btn {
1631
+ height: 34px;
1632
+ padding: 0 14px;
1633
+ font-weight: 550;
1634
+ border-radius: 8px;
1635
+ color: var(--rf-primary-text);
1636
+ background: var(--rf-primary);
1637
+ }
1638
+
1639
+ .picker { position: fixed; inset: 0; z-index: 2147483002; cursor: crosshair; }
1640
+ .picker-box {
1641
+ position: fixed;
1642
+ pointer-events: none;
1643
+ border: 2px solid var(--rf-primary);
1644
+ border-radius: 3px;
1645
+ background: color-mix(in srgb, var(--rf-primary) 12%, transparent);
1646
+ transition: all 90ms var(--rf-ease);
1647
+ }
1648
+ .picker-label {
1649
+ position: fixed;
1650
+ pointer-events: none;
1651
+ display: flex;
1652
+ align-items: center;
1653
+ gap: 6px;
1654
+ max-width: min(420px, 90vw);
1655
+ padding: 5px 9px;
1656
+ font-size: 12px;
1657
+ font-weight: 500;
1658
+ color: var(--rf-primary-text);
1659
+ background: var(--rf-primary);
1660
+ border-radius: 7px;
1661
+ white-space: nowrap;
1662
+ overflow: hidden;
1663
+ text-overflow: ellipsis;
1664
+ }
1665
+ .picker-label code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; opacity: 0.82; }
1666
+ .picker-hint {
1667
+ position: fixed;
1668
+ left: 50%;
1669
+ bottom: 24px;
1670
+ transform: translateX(-50%);
1671
+ padding: 9px 14px;
1672
+ font-size: 13px;
1673
+ color: var(--rf-text);
1674
+ background: var(--rf-bg);
1675
+ border: 1px solid var(--rf-border);
1676
+ border-radius: 10px;
1677
+ box-shadow: var(--rf-shadow);
1678
+ }
1679
+ .picker-hint kbd {
1680
+ padding: 1px 5px;
1681
+ font: inherit;
1682
+ font-size: 11.5px;
1683
+ border: 1px solid var(--rf-border);
1684
+ border-radius: 4px;
1685
+ background: var(--rf-bg-subtle);
1686
+ }
1687
+ @media (pointer: coarse) {
1688
+ .icon-btn, .tool, .swatch {
1689
+ width: 44px;
1690
+ height: 44px;
1691
+ }
1692
+
1693
+ .segmented button, .ghost-btn, .submit, .toolbar .done-btn {
1694
+ min-height: 44px;
1695
+ }
1696
+
1697
+ .dismiss-btn, .footer a {
1698
+ display: inline-flex;
1699
+ min-height: 44px;
1700
+ align-items: center;
1701
+ }
1702
+
1703
+ .footer a {
1704
+ min-width: 44px;
1705
+ justify-content: center;
1706
+ }
1707
+ }
1708
+
1709
+ `;
1710
+ //#endregion
1711
+ //#region src/feedback/ui/shadow-portal.tsx
1712
+ const DARK_QUERY = "(prefers-color-scheme: dark)";
1713
+ function useResolvedTheme(theme) {
1714
+ const [systemDark, setSystemDark] = useState(false);
1715
+ useEffect(() => {
1716
+ if (theme !== "auto" || typeof window.matchMedia !== "function") return;
1717
+ const query = window.matchMedia(DARK_QUERY);
1718
+ setSystemDark(query.matches);
1719
+ const onChange = (event) => setSystemDark(event.matches);
1720
+ query.addEventListener("change", onChange);
1721
+ return () => query.removeEventListener("change", onChange);
1722
+ }, [theme]);
1723
+ if (theme === "auto") return systemDark ? "dark" : "light";
1724
+ return theme;
1725
+ }
1726
+ /**
1727
+ * Hosts the widget in a shadow root: the app's CSS cannot reach the panel and
1728
+ * the panel's CSS cannot reach the app. Direct DOM work is unavoidable here —
1729
+ * React has no declarative way to create a shadow root.
1730
+ */
1731
+ function ShadowPortal({ children, offset, primaryColor, theme }) {
1732
+ const [shadowRoot, setShadowRoot] = useState(null);
1733
+ const resolvedTheme = useResolvedTheme(theme);
1734
+ useEffect(() => {
1735
+ const host = document.createElement("div");
1736
+ host.setAttribute(WIDGET_MARKER, "");
1737
+ const root = host.attachShadow({ mode: "open" });
1738
+ const style = document.createElement("style");
1739
+ style.textContent = WIDGET_STYLES;
1740
+ root.append(style);
1741
+ document.body.append(host);
1742
+ setShadowRoot(root);
1743
+ return () => host.remove();
1744
+ }, []);
1745
+ useEffect(() => {
1746
+ const host = shadowRoot?.host;
1747
+ if (!(host instanceof HTMLElement)) return;
1748
+ host.setAttribute("data-theme", resolvedTheme);
1749
+ host.style.setProperty("--rf-offset", `${offset}px`);
1750
+ if (primaryColor) host.style.setProperty("--rf-primary", primaryColor);
1751
+ }, [
1752
+ shadowRoot,
1753
+ resolvedTheme,
1754
+ primaryColor,
1755
+ offset
1756
+ ]);
1757
+ if (!shadowRoot) return null;
1758
+ return createPortal(children, shadowRoot);
1759
+ }
1760
+ //#endregion
1761
+ //#region src/feedback/core/console-recorder.ts
1762
+ const DEFAULT_LIMIT = 30;
1763
+ const MAX_MESSAGE_LENGTH = 1e3;
1764
+ const RECORDED_METHODS = ["error", "warn"];
1765
+ function serializeArgument(value) {
1766
+ if (typeof value === "string") return value;
1767
+ if (value instanceof Error) return `${value.name}: ${value.message}`;
1768
+ if (value === null || value === void 0) return String(value);
1769
+ if (typeof value === "object") try {
1770
+ return JSON.stringify(value) ?? "[unserializable]";
1771
+ } catch {
1772
+ return "[unserializable]";
1773
+ }
1774
+ if (typeof value === "function") return "[function]";
1775
+ return String(value);
1776
+ }
1777
+ function formatMessage(args) {
1778
+ const message = args.map(serializeArgument).join(" ");
1779
+ return message.length > MAX_MESSAGE_LENGTH ? `${message.slice(0, 999)}…` : message;
1780
+ }
1781
+ /**
1782
+ * Buffers the console noise a user saw right before reporting a bug.
1783
+ * Wrappers delegate to the previous implementation, so nothing is swallowed.
1784
+ */
1785
+ function startConsoleRecorder(options) {
1786
+ const limit = options?.limit ?? DEFAULT_LIMIT;
1787
+ const buffer = [];
1788
+ let active = true;
1789
+ const push = (level, message) => {
1790
+ if (!(active && message)) return;
1791
+ buffer.push({
1792
+ level,
1793
+ message,
1794
+ timestamp: Date.now()
1795
+ });
1796
+ if (buffer.length > limit) buffer.splice(0, buffer.length - limit);
1797
+ };
1798
+ const originals = /* @__PURE__ */ new Map();
1799
+ const wrappers = /* @__PURE__ */ new Map();
1800
+ for (const method of RECORDED_METHODS) {
1801
+ const original = console[method];
1802
+ const wrapper = (...args) => {
1803
+ push(method, formatMessage(args));
1804
+ Reflect.apply(original, console, args);
1805
+ };
1806
+ originals.set(method, original);
1807
+ wrappers.set(method, wrapper);
1808
+ console[method] = wrapper;
1809
+ }
1810
+ const onError = (event) => {
1811
+ const where = event.filename ? ` (${event.filename}:${event.lineno}:${event.colno})` : "";
1812
+ push("error", `${event.message}${where}`);
1813
+ };
1814
+ const onRejection = (event) => {
1815
+ push("error", `Unhandled rejection: ${serializeArgument(event.reason)}`);
1816
+ };
1817
+ window.addEventListener("error", onError);
1818
+ window.addEventListener("unhandledrejection", onRejection);
1819
+ return {
1820
+ events: () => buffer.slice(),
1821
+ stop: () => {
1822
+ if (!active) return;
1823
+ active = false;
1824
+ buffer.length = 0;
1825
+ for (const method of RECORDED_METHODS) {
1826
+ const original = originals.get(method);
1827
+ if (original && console[method] === wrappers.get(method)) console[method] = original;
1828
+ }
1829
+ window.removeEventListener("error", onError);
1830
+ window.removeEventListener("unhandledrejection", onRejection);
1831
+ }
1832
+ };
1833
+ }
1834
+ //#endregion
1835
+ //#region src/feedback/core/submit.ts
1836
+ const MAX_TITLE_LENGTH = 100;
1837
+ const NEWLINE = /\r?\n/;
1838
+ /** First line of the message, cut on a word boundary so titles stay readable. */
1839
+ function deriveTitle(message) {
1840
+ const firstLine = message.split(NEWLINE).map((line) => line.trim()).find(Boolean) ?? "";
1841
+ if (firstLine.length <= MAX_TITLE_LENGTH) return firstLine;
1842
+ const clipped = firstLine.slice(0, 99);
1843
+ const lastSpace = clipped.lastIndexOf(" ");
1844
+ return `${(lastSpace > 0 ? clipped.slice(0, lastSpace) : clipped).trimEnd()}…`;
1845
+ }
1846
+ function buildDescription(params) {
1847
+ const { category, email, isAnonymous, message } = params;
1848
+ const label = category.charAt(0).toUpperCase() + category.slice(1);
1849
+ const contact = isAnonymous && email ? `\n\n---\nContact: ${email}` : "";
1850
+ return `[${label}] ${message.trim()}${contact}`;
1851
+ }
1852
+ async function attachScreenshot(transport, feedbackId, submission) {
1853
+ const { annotated, annotations, context, screenshot } = submission;
1854
+ if (!screenshot) return false;
1855
+ const original = await transport.getScreenshotUploadUrl();
1856
+ const storageId = await transport.uploadImage(original.uploadUrl, screenshot);
1857
+ let annotatedStorageId;
1858
+ if (annotated) {
1859
+ const target = await transport.getScreenshotUploadUrl();
1860
+ annotatedStorageId = await transport.uploadImage(target.uploadUrl, annotated);
1861
+ }
1862
+ const wireAnnotations = toWireAnnotations(annotations);
1863
+ await transport.saveScreenshot({
1864
+ annotatedStorageId,
1865
+ annotations: wireAnnotations.length > 0 ? wireAnnotations : void 0,
1866
+ feedbackId,
1867
+ filename: "screenshot.png",
1868
+ height: screenshot.height,
1869
+ mimeType: screenshot.mimeType,
1870
+ pageUrl: context.url,
1871
+ size: screenshot.blob.size,
1872
+ storageId,
1873
+ width: screenshot.width
1874
+ });
1875
+ return true;
1876
+ }
1877
+ /**
1878
+ * Creates the feedback first, then attaches the capture. A failed upload is
1879
+ * reported back but never discards what the user wrote.
1880
+ */
1881
+ async function submitWidgetFeedback(transport, submission) {
1882
+ const title = deriveTitle(submission.message);
1883
+ if (!title) throw new Error("Please describe your feedback before sending it.");
1884
+ const { feedbackId } = await transport.create({
1885
+ context: submission.context,
1886
+ description: buildDescription(submission),
1887
+ title
1888
+ });
1889
+ let screenshotSaved = false;
1890
+ try {
1891
+ screenshotSaved = await attachScreenshot(transport, feedbackId, submission);
1892
+ } catch {
1893
+ screenshotSaved = false;
1894
+ }
1895
+ return {
1896
+ feedbackId,
1897
+ screenshotSaved
1898
+ };
1899
+ }
1900
+ function isStorageResponse(value) {
1901
+ return typeof value === "object" && value !== null && typeof Reflect.get(value, "storageId") === "string";
1902
+ }
1903
+ function createFeedbackTransport(client) {
1904
+ return {
1905
+ create: (params) => client.create(params),
1906
+ getScreenshotUploadUrl: () => client.getScreenshotUploadUrl(),
1907
+ saveScreenshot: (params) => client.saveScreenshot(params),
1908
+ uploadImage: async (uploadUrl, image) => {
1909
+ const response = await fetch(uploadUrl, {
1910
+ body: image.blob,
1911
+ headers: { "Content-Type": image.mimeType },
1912
+ method: "POST"
1913
+ });
1914
+ if (!response.ok) throw new Error(`Screenshot upload failed (${response.status})`);
1915
+ const payload = await response.json();
1916
+ if (!isStorageResponse(payload)) throw new Error("Screenshot upload returned no storage id");
1917
+ return payload.storageId;
1918
+ }
1919
+ };
1920
+ }
1921
+ //#endregion
1922
+ //#region src/feedback/ui/use-widget-state.ts
1923
+ const SUCCESS_CLOSE_DELAY = 2400;
1924
+ const IS_APPLE = /Mac|iPhone|iPad/;
1925
+ const MILLISECONDS_PER_DAY = 864e5;
1926
+ const DISMISSAL_STORAGE_PREFIX = "reflet-feedback-dismissed";
1927
+ function readDismissedUntil(key) {
1928
+ if (typeof window === "undefined") return 0;
1929
+ try {
1930
+ const value = Number.parseInt(window.localStorage.getItem(key) ?? "", 10);
1931
+ if (Number.isFinite(value) && value > Date.now()) return value;
1932
+ window.localStorage.removeItem(key);
1933
+ } catch {
1934
+ return 0;
1935
+ }
1936
+ return 0;
1937
+ }
1938
+ function writeDismissedUntil(key, until) {
1939
+ try {
1940
+ window.localStorage.setItem(key, String(until));
1941
+ } catch {}
1942
+ }
1943
+ /**
1944
+ * Matches shortcuts written as `alt+f` or `mod+shift+k`, where `mod` is the
1945
+ * platform's command key.
1946
+ */
1947
+ function matchesHotkey(event, hotkey, platform = typeof navigator === "undefined" ? "" : navigator.platform) {
1948
+ const parts = hotkey.toLowerCase().split("+").map((part) => part.trim());
1949
+ const key = parts.at(-1);
1950
+ if (!key || event.key.toLowerCase() !== key) return false;
1951
+ const isApple = IS_APPLE.test(platform);
1952
+ const wantsMod = parts.includes("mod");
1953
+ const expected = {
1954
+ alt: parts.includes("alt") || parts.includes("option"),
1955
+ ctrl: parts.includes("ctrl") || wantsMod && !isApple,
1956
+ meta: parts.includes("meta") || parts.includes("cmd") || wantsMod && isApple,
1957
+ shift: parts.includes("shift")
1958
+ };
1959
+ return event.altKey === expected.alt && event.ctrlKey === expected.ctrl && event.metaKey === expected.meta && event.shiftKey === expected.shift;
1960
+ }
1961
+ function highlightFor(selection, capture) {
1962
+ const scale = capture.width / window.innerWidth;
1963
+ const { rect } = selection;
1964
+ return {
1965
+ color: "#4f46e5",
1966
+ end: {
1967
+ x: (rect.x + rect.width) * scale,
1968
+ y: (rect.y + rect.height) * scale
1969
+ },
1970
+ id: `selection-${rect.x}-${rect.y}`,
1971
+ start: {
1972
+ x: rect.x * scale,
1973
+ y: rect.y * scale
1974
+ },
1975
+ tool: "rectangle"
1976
+ };
1977
+ }
1978
+ function useWidgetState(props) {
1979
+ const context = useContext(RefletContext);
1980
+ const publicKey = props.publicKey ?? context?.publicKey;
1981
+ const baseUrl = props.baseUrl ?? context?.baseUrl;
1982
+ const user = props.user ?? context?.user;
1983
+ const userToken = props.userToken ?? context?.userToken;
1984
+ const isAnonymous = !(user || userToken);
1985
+ const dismissForDays = props.dismissForDays !== void 0 && Number.isFinite(props.dismissForDays) && props.dismissForDays > 0 ? props.dismissForDays : null;
1986
+ const dismissalKey = `${DISMISSAL_STORAGE_PREFIX}:${publicKey ?? "default"}:${user?.id ?? "anonymous"}`;
1987
+ const [isOpen, setIsOpen] = useState(false);
1988
+ const [step, setStep] = useState("compose");
1989
+ const [category, setCategory] = useState(props.defaultCategory ?? "bug");
1990
+ const [message, setMessage] = useState("");
1991
+ const [email, setEmail] = useState("");
1992
+ const [honeypot, setHoneypot] = useState("");
1993
+ const [capture, setCapture] = useState(null);
1994
+ const [annotations, setAnnotations] = useState([]);
1995
+ const [selection, setSelection] = useState(null);
1996
+ const [isCapturing, setIsCapturing] = useState(false);
1997
+ const [isSubmitting, setIsSubmitting] = useState(false);
1998
+ const [error, setError] = useState(null);
1999
+ const [dismissedUntil, setDismissedUntil] = useState(() => readDismissedUntil(dismissalKey));
2000
+ const captureRef = useRef(null);
2001
+ const consoleRef = useRef(null);
2002
+ useEffect(() => {
2003
+ captureRef.current = capture;
2004
+ }, [capture]);
2005
+ useEffect(() => {
2006
+ setDismissedUntil(readDismissedUntil(dismissalKey));
2007
+ }, [dismissalKey]);
2008
+ useEffect(() => {
2009
+ if (props.captureConsole === false) return;
2010
+ const recorder = startConsoleRecorder();
2011
+ consoleRef.current = recorder;
2012
+ return () => {
2013
+ consoleRef.current = null;
2014
+ recorder.stop();
2015
+ };
2016
+ }, [props.captureConsole]);
2017
+ useEffect(() => () => {
2018
+ releaseCapture(captureRef.current);
2019
+ }, []);
2020
+ const replaceCapture = useCallback((next) => {
2021
+ releaseCapture(captureRef.current);
2022
+ setCapture(next);
2023
+ }, []);
2024
+ const takeCapture = useCallback((element) => {
2025
+ setIsCapturing(true);
2026
+ captureViewport({ element }).catch(() => null).then((image) => {
2027
+ setIsCapturing(false);
2028
+ replaceCapture(image);
2029
+ });
2030
+ }, [replaceCapture]);
2031
+ const reset = useCallback(() => {
2032
+ releaseCapture(captureRef.current);
2033
+ setCapture(null);
2034
+ setAnnotations([]);
2035
+ setSelection(null);
2036
+ setMessage("");
2037
+ setEmail("");
2038
+ setHoneypot("");
2039
+ setError(null);
2040
+ setStep("compose");
2041
+ setCategory(props.defaultCategory ?? "bug");
2042
+ }, [props.defaultCategory]);
2043
+ const close = useCallback(() => {
2044
+ setIsOpen(false);
2045
+ reset();
2046
+ props.onClose?.();
2047
+ }, [reset, props.onClose]);
2048
+ const dismiss = useCallback(() => {
2049
+ if (dismissForDays === null) return;
2050
+ const until = Date.now() + dismissForDays * MILLISECONDS_PER_DAY;
2051
+ writeDismissedUntil(dismissalKey, until);
2052
+ setIsOpen(false);
2053
+ reset();
2054
+ setDismissedUntil(until);
2055
+ props.onDismiss?.({ until });
2056
+ }, [
2057
+ dismissForDays,
2058
+ dismissalKey,
2059
+ props.onDismiss,
2060
+ reset
2061
+ ]);
2062
+ const open = useCallback(() => {
2063
+ setIsOpen(true);
2064
+ setStep("compose");
2065
+ props.onOpen?.();
2066
+ if (props.captureOnOpen !== false) takeCapture();
2067
+ }, [
2068
+ props.captureOnOpen,
2069
+ props.onOpen,
2070
+ takeCapture
2071
+ ]);
2072
+ const selectElement = useCallback((element) => {
2073
+ const picked = buildElementSelection(element);
2074
+ setSelection(picked);
2075
+ setStep("compose");
2076
+ const current = captureRef.current;
2077
+ if (current) setAnnotations((previous) => [...previous.filter((item) => !item.id.startsWith("selection-")), highlightFor(picked, current)]);
2078
+ }, []);
2079
+ const clearSelection = useCallback(() => {
2080
+ setSelection(null);
2081
+ setAnnotations((previous) => previous.filter((item) => !item.id.startsWith("selection-")));
2082
+ }, []);
2083
+ const removeCapture = useCallback(() => {
2084
+ replaceCapture(null);
2085
+ setAnnotations([]);
2086
+ }, [replaceCapture]);
2087
+ const client = useMemo(() => publicKey ? new Reflet({
2088
+ baseUrl,
2089
+ publicKey,
2090
+ user,
2091
+ userToken
2092
+ }) : null, [
2093
+ baseUrl,
2094
+ publicKey,
2095
+ user,
2096
+ userToken
2097
+ ]);
2098
+ const submit = useCallback(async () => {
2099
+ if (honeypot) {
2100
+ setStep("success");
2101
+ return;
2102
+ }
2103
+ if (!client) {
2104
+ setError("Reflet is missing a publicKey. Pass one to RefletFeedback or RefletProvider.");
2105
+ return;
2106
+ }
2107
+ setIsSubmitting(true);
2108
+ setError(null);
2109
+ let annotated = null;
2110
+ try {
2111
+ annotated = capture ? await renderAnnotatedImage(capture, annotations) : null;
2112
+ const result = await submitWidgetFeedback(createFeedbackTransport(client), {
2113
+ annotated,
2114
+ annotations,
2115
+ category,
2116
+ context: {
2117
+ ...collectPageContext({ sdkVersion: SDK_VERSION }),
2118
+ consoleEvents: consoleRef.current?.events(),
2119
+ metadata: props.metadata,
2120
+ selection: selection ?? void 0
2121
+ },
2122
+ email,
2123
+ isAnonymous,
2124
+ message,
2125
+ screenshot: capture
2126
+ });
2127
+ setStep("success");
2128
+ props.onSubmit?.({ feedbackId: result.feedbackId });
2129
+ setTimeout(close, SUCCESS_CLOSE_DELAY);
2130
+ } catch (submitError) {
2131
+ setError(submitError instanceof Error ? submitError.message : "Something went wrong. Please try again.");
2132
+ } finally {
2133
+ releaseCapture(annotated);
2134
+ setIsSubmitting(false);
2135
+ }
2136
+ }, [
2137
+ annotations,
2138
+ capture,
2139
+ category,
2140
+ client,
2141
+ close,
2142
+ email,
2143
+ honeypot,
2144
+ isAnonymous,
2145
+ message,
2146
+ props.metadata,
2147
+ props.onSubmit,
2148
+ selection
2149
+ ]);
2150
+ return {
2151
+ annotations,
2152
+ canDismiss: dismissForDays !== null,
2153
+ capture,
2154
+ category,
2155
+ clearSelection,
2156
+ close,
2157
+ dismiss,
2158
+ dismissForDays,
2159
+ email,
2160
+ error,
2161
+ honeypot,
2162
+ isAnonymous,
2163
+ isCapturing,
2164
+ isDismissed: dismissedUntil > Date.now(),
2165
+ isOpen,
2166
+ isSubmitting,
2167
+ message,
2168
+ open,
2169
+ removeCapture,
2170
+ selectElement,
2171
+ selection,
2172
+ setAnnotations,
2173
+ setCategory,
2174
+ setEmail,
2175
+ setHoneypot,
2176
+ setMessage,
2177
+ setStep,
2178
+ step,
2179
+ submit,
2180
+ takeCapture
2181
+ };
2182
+ }
2183
+ //#endregion
2184
+ //#region src/feedback/widget.tsx
2185
+ const DEFAULT_CATEGORIES = [
2186
+ "bug",
2187
+ "idea",
2188
+ "question"
2189
+ ];
2190
+ const DEFAULT_OFFSET = 20;
2191
+ /**
2192
+ * Floating feedback button with a screenshot, annotation and element picker
2193
+ * flow. Mount it once, anywhere below `RefletProvider` or with its own
2194
+ * `publicKey`.
2195
+ */
2196
+ function RefletFeedback(props) {
2197
+ const { categories = DEFAULT_CATEGORIES, enabled = true, hotkey = null, offset = DEFAULT_OFFSET, position = "bottom-right", theme = "auto" } = props;
2198
+ const labels = {
2199
+ ...DEFAULT_WIDGET_LABELS,
2200
+ ...props.labels
2201
+ };
2202
+ const state = useWidgetState(props);
2203
+ const { close, isOpen, open } = state;
2204
+ useEffect(() => {
2205
+ if (!(hotkey && enabled)) return;
2206
+ const onKeyDown = (event) => {
2207
+ if (matchesHotkey(event, hotkey)) {
2208
+ event.preventDefault();
2209
+ if (isOpen) close();
2210
+ else open();
2211
+ }
2212
+ };
2213
+ document.addEventListener("keydown", onKeyDown);
2214
+ return () => document.removeEventListener("keydown", onKeyDown);
2215
+ }, [
2216
+ close,
2217
+ enabled,
2218
+ hotkey,
2219
+ isOpen,
2220
+ open
2221
+ ]);
2222
+ useEffect(() => {
2223
+ if (!isOpen || state.step !== "compose") return;
2224
+ const onKeyDown = (event) => {
2225
+ if (event.key === "Escape") close();
2226
+ };
2227
+ document.addEventListener("keydown", onKeyDown);
2228
+ return () => document.removeEventListener("keydown", onKeyDown);
2229
+ }, [
2230
+ close,
2231
+ isOpen,
2232
+ state.step
2233
+ ]);
2234
+ if (!enabled || state.isDismissed) return null;
2235
+ const showPanel = isOpen && state.step !== "picking" && state.step !== "annotate";
2236
+ return /* @__PURE__ */ jsxs(ShadowPortal, {
2237
+ offset,
2238
+ primaryColor: props.primaryColor,
2239
+ theme,
2240
+ children: [
2241
+ /* @__PURE__ */ jsx("div", {
2242
+ className: "root",
2243
+ "data-position": position,
2244
+ children: /* @__PURE__ */ jsxs("div", {
2245
+ className: "stack",
2246
+ children: [showPanel && /* @__PURE__ */ jsx(FeedbackPanel, {
2247
+ categories,
2248
+ labels,
2249
+ state
2250
+ }), /* @__PURE__ */ jsx(Launcher, {
2251
+ compact: isOpen,
2252
+ isOpen,
2253
+ label: labels.trigger,
2254
+ onClick: isOpen ? close : open
2255
+ })]
2256
+ })
2257
+ }),
2258
+ isOpen && state.step === "annotate" && state.capture && /* @__PURE__ */ jsx(Annotator, {
2259
+ annotations: state.annotations,
2260
+ capture: state.capture,
2261
+ labels,
2262
+ onChange: state.setAnnotations,
2263
+ onDone: () => state.setStep("compose")
2264
+ }),
2265
+ isOpen && state.step === "picking" && /* @__PURE__ */ jsx(ElementPicker, {
2266
+ hint: labels.pickElementHint,
2267
+ onCancel: () => state.setStep("compose"),
2268
+ onPick: state.selectElement
2269
+ })
2270
+ ]
2271
+ });
2272
+ }
2273
+ //#endregion
2274
+ export { RefletFeedback, buildElementSelection, captureViewport, collectPageContext, releaseCapture };
2275
+
2276
+ //# sourceMappingURL=feedback.js.map