@qaiddev/thumbs-embed 1.6.2 → 1.8.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.
Files changed (37) hide show
  1. package/README.md +32 -21
  2. package/dist/bootstrap.d.ts +6 -0
  3. package/dist/chunks/{annotate-NeITyYNe.js → annotate-D-o8xCV9.js} +24 -17
  4. package/dist/chunks/annotate-D-o8xCV9.js.map +1 -0
  5. package/dist/chunks/dom-DvdtcUS8.js +17 -0
  6. package/dist/chunks/dom-DvdtcUS8.js.map +1 -0
  7. package/dist/chunks/{loader-DnJ3MHkt.js → loader-DHtXHt1z.js} +187 -163
  8. package/dist/chunks/loader-DHtXHt1z.js.map +1 -0
  9. package/dist/chunks/modal-CTbqN-h9.js +213 -0
  10. package/dist/chunks/modal-CTbqN-h9.js.map +1 -0
  11. package/dist/chunks/{recording-DhRZ6-tW.js → recording-Dx8AX-BC.js} +104 -98
  12. package/dist/chunks/recording-Dx8AX-BC.js.map +1 -0
  13. package/dist/chunks/{screenshot-BkOCLuS2.js → screenshot-DYOKg2bS.js} +2 -2
  14. package/dist/chunks/{screenshot-BkOCLuS2.js.map → screenshot-DYOKg2bS.js.map} +1 -1
  15. package/dist/chunks/{targeting-BEQU2Ogo.js → targeting-Dz6z1BYl.js} +3 -2
  16. package/dist/chunks/{targeting-BEQU2Ogo.js.map → targeting-Dz6z1BYl.js.map} +1 -1
  17. package/dist/chunks/{video-BOYqf2Im.js → video-Bd_29-rK.js} +76 -71
  18. package/dist/chunks/video-Bd_29-rK.js.map +1 -0
  19. package/dist/embed.d.ts +11 -0
  20. package/dist/icons.d.ts +2 -0
  21. package/dist/index.js +597 -451
  22. package/dist/index.js.map +1 -1
  23. package/dist/loader.js +1 -1
  24. package/dist/modal.d.ts +19 -1
  25. package/dist/qaid.umd.cjs +14 -31
  26. package/dist/qaid.umd.cjs.map +1 -1
  27. package/dist/recording.d.ts +6 -0
  28. package/dist/screenshot.d.ts +1 -1
  29. package/dist/types.d.ts +33 -2
  30. package/dist/video-capture.d.ts +6 -0
  31. package/package.json +1 -1
  32. package/dist/chunks/annotate-NeITyYNe.js.map +0 -1
  33. package/dist/chunks/loader-DnJ3MHkt.js.map +0 -1
  34. package/dist/chunks/modal-C8Ca7E5j.js +0 -119
  35. package/dist/chunks/modal-C8Ca7E5j.js.map +0 -1
  36. package/dist/chunks/recording-DhRZ6-tW.js.map +0 -1
  37. package/dist/chunks/video-BOYqf2Im.js.map +0 -1
@@ -70,5 +70,11 @@ export declare class RecordingController {
70
70
  private cancelRecordingPreview;
71
71
  private removeVideoPreview;
72
72
  private submitVideoFeedback;
73
+ /**
74
+ * Keep the preview open and say the upload failed. Closing it, as a success
75
+ * does, told the visitor their recording had arrived when it had not. Send
76
+ * is re-enabled for another try; Cancel and Re-record still work.
77
+ */
78
+ private showSendError;
73
79
  private cleanupRecording;
74
80
  }
@@ -2,7 +2,7 @@
2
2
  * Screenshot capture utility using native Screen Capture API
3
3
  */
4
4
  export interface ScreenshotOptions {
5
- /** Quality of WebP compression (0-1). Default: 1.0 */
5
+ /** Quality of WebP compression (0-1). Default: 0.8 */
6
6
  quality?: number;
7
7
  /** Max width of the screenshot. Default: 1280 */
8
8
  maxWidth?: number;
package/dist/types.d.ts CHANGED
@@ -46,7 +46,7 @@ export interface FeedbackConfig {
46
46
  positive?: string;
47
47
  /** Color for negative feedback. Default: rgb(255, 0, 0) */
48
48
  negative?: string;
49
- /** Color for selected element marker. Default: #6366f1 */
49
+ /** Color for selected element marker. Default: #6365f1 */
50
50
  marker?: string;
51
51
  };
52
52
  /** Button size. Default: 'medium' (48px). Small: 36px, Large: 64px */
@@ -75,7 +75,32 @@ export interface FeedbackConfig {
75
75
  dismissLabel?: string;
76
76
  /** Accessible name / tooltip for the single "Feedback" button (singleButton mode) */
77
77
  feedbackLabel?: string;
78
+ /** Heading on the success screen. Default: "Thank you!" */
79
+ confirmationTitle?: string;
80
+ /** Body copy on the success screen. Default: "Your feedback has been received." */
81
+ confirmationMessage?: string;
82
+ /** Dismiss button on the success screen. Default: "Close" */
83
+ confirmationClose?: string;
84
+ /**
85
+ * Heading shown in place of the success screen when the server refuses the
86
+ * message or cannot be reached. Default: "Message not sent"
87
+ */
88
+ errorTitle?: string;
89
+ /**
90
+ * Body copy on that error screen. Default: "Something went wrong, so we
91
+ * did not get your message. Please try again later."
92
+ */
93
+ errorMessage?: string;
78
94
  };
95
+ /**
96
+ * Skip the success screen and dismiss immediately once a message is sent.
97
+ *
98
+ * Default: false. Before 1.7.0 the modal always vanished on submit with no
99
+ * acknowledgement, which reads as a failure — especially inline, where there
100
+ * is no overlay disappearing to signal anything happened. Set true to opt
101
+ * back out.
102
+ */
103
+ hideConfirmation?: boolean;
79
104
  /** Modal width in pixels. Default: 400 */
80
105
  modalWidth?: number;
81
106
  /** Backdrop opacity (0-1). Default: 0.3 */
@@ -135,7 +160,7 @@ export interface FeedbackConfig {
135
160
  screenshotMethod?: "dom" | "permission";
136
161
  /** Screenshot options */
137
162
  screenshotOptions?: {
138
- /** Quality of WebP compression (0-1). Default: 1.0 */
163
+ /** Quality of WebP compression (0-1). Default: 0.8 */
139
164
  quality?: number;
140
165
  /** Max width of the screenshot. Default: 1280 */
141
166
  maxWidth?: number;
@@ -309,7 +334,13 @@ export interface ResolvedFeedbackConfig {
309
334
  recordLabel: string;
310
335
  dismissLabel: string;
311
336
  feedbackLabel: string;
337
+ confirmationTitle: string;
338
+ confirmationMessage: string;
339
+ confirmationClose: string;
340
+ errorTitle: string;
341
+ errorMessage: string;
312
342
  };
343
+ hideConfirmation: boolean;
313
344
  modalWidth: number;
314
345
  backdropOpacity: number;
315
346
  fontFamily: string;
@@ -2,6 +2,12 @@
2
2
  * Video capture utilities
3
3
  * Uses getDisplayMedia + MediaRecorder for screen recording
4
4
  */
5
+ /**
6
+ * Thrown by `start()` when areas were picked for redaction but this browser
7
+ * cannot run the canvas pipeline that blurs them. The recording is refused
8
+ * rather than made without the blur.
9
+ */
10
+ export declare const REDACTION_UNAVAILABLE = "This browser cannot blur the areas you picked, so the recording was not started.";
5
11
  export interface VideoRecorderOptions {
6
12
  /** Max recording duration in seconds. Default: 15 */
7
13
  maxDuration?: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qaiddev/thumbs-embed",
3
- "version": "1.6.2",
3
+ "version": "1.8.0",
4
4
  "description": "Precision User Feedback",
5
5
  "type": "module",
6
6
  "main": "./dist/qaid.umd.cjs",
@@ -1 +0,0 @@
1
- {"version":3,"file":"annotate-NeITyYNe.js","sources":["../../src/icons.ts","../../src/dom-utils.ts","../../src/annotate.ts"],"sourcesContent":["/**\n * SVG icon strings for thumbs up/down buttons\n */\n\nexport const THUMBS_UP_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M14 10h4.764a2 2 0 011.789 2.894l-3.5 7A2 2 0 0115.263 21h-4.017c-.163 0-.326-.02-.485-.06L7 20m7-10V5a2 2 0 00-2-2h-.095c-.5 0-.905.405-.905.905 0 .714-.211 1.412-.608 2.006L7 11v9m7-10h-2M7 20H5a2 2 0 01-2-2v-6a2 2 0 012-2h2.5\"/>\n</svg>`;\n\nexport const THUMBS_DOWN_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M10 14H5.236a2 2 0 01-1.789-2.894l3.5-7A2 2 0 018.737 3h4.018a2 2 0 01.485.06l3.76.94m-7 10v5a2 2 0 002 2h.095c.5 0 .905-.405.905-.905 0-.714.211-1.412.608-2.006L17 13V4m-7 10h2m5-10h2a2 2 0 012 2v6a2 2 0 01-2 2h-2.5\"/>\n</svg>`;\n\nexport const RECORD_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M15.75 10.5l4.72-4.72a.75.75 0 011.28.53v11.38a.75.75 0 01-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 002.25-2.25v-9a2.25 2.25 0 00-2.25-2.25h-9A2.25 2.25 0 002.25 7.5v9a2.25 2.25 0 002.25 2.25z\"/>\n</svg>`;\n\n/** Chat-bubble icon for the single, sentiment-free \"Feedback\" button. */\nexport const FEEDBACK_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M8 10h8M8 14h5m-9 6l3.5-3.5H18a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v14z\"/>\n</svg>`;\n\n/* ---------------------------------------------------------------------------\n * Screenshot annotation toolbar icons. Same 24×24 stroked style as the thumbs\n * icons above so they inherit `.qaid-icon` sizing and `currentColor`.\n * ------------------------------------------------------------------------- */\n\nexport const RECTANGLE_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <rect x=\"4\" y=\"6\" width=\"16\" height=\"12\" rx=\"1\" stroke-linejoin=\"round\"/>\n</svg>`;\n\nexport const ARROW_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M5 19L19 5m0 0h-8m8 0v8\"/>\n</svg>`;\n\nexport const PENCIL_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M12 20h9M16.5 3.5a2.121 2.121 0 013 3L7 19l-4 1 1-4L16.5 3.5z\"/>\n</svg>`;\n\nexport const BLUR_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M12 3s6 6.4 6 10a6 6 0 01-12 0c0-3.6 6-10 6-10z\"/>\n</svg>`;\n\nexport const UNDO_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M9 14L4 9l5-5M4 9h11a5 5 0 010 10h-4\"/>\n</svg>`;\n\nexport const DONE_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M20 6L9 17l-5-5\"/>\n</svg>`;\n\nexport const SKIP_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" class=\"qaid-icon\" fill=\"none\" viewBox=\"0 0 24 24\" stroke=\"currentColor\" stroke-width=\"2\">\n <path stroke-linecap=\"round\" stroke-linejoin=\"round\" d=\"M6 6l12 12M18 6L6 18\"/>\n</svg>`;\n","/**\n * DOM utility functions\n */\n\n/**\n * Create an element with attributes and optional children\n */\nexport function createElement<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n attrs?: Record<string, string>,\n children?: (Node | string)[]\n): HTMLElementTagNameMap[K] {\n const el = document.createElement(tag);\n\n if (attrs) {\n for (const [key, value] of Object.entries(attrs)) {\n if (key === \"className\") {\n el.className = value;\n } else {\n el.setAttribute(key, value);\n }\n }\n }\n\n if (children) {\n for (const child of children) {\n if (typeof child === \"string\") {\n el.appendChild(document.createTextNode(child));\n } else {\n el.appendChild(child);\n }\n }\n }\n\n return el;\n}\n\n/**\n * Check if viewport width indicates mobile device\n */\nexport function isMobileViewport(breakpoint = 640): boolean {\n return typeof window !== \"undefined\" && window.innerWidth < breakpoint;\n}\n\n/**\n * Get element at point, temporarily hiding shadow hosts so elementFromPoint\n * sees through to the page elements underneath.\n * Uses visibility:hidden which skips the element in elementFromPoint without\n * triggering reflow.\n */\nexport function getElementAtPointUnderOverlay(\n x: number,\n y: number,\n hosts: HTMLElement[]\n): Element | null {\n const saved = hosts.map((h) => h.style.visibility);\n hosts.forEach((h) => (h.style.visibility = \"hidden\"));\n const element = document.elementFromPoint(x, y);\n hosts.forEach((h, i) => (h.style.visibility = saved[i]));\n return element;\n}\n\n/**\n * Check if an element is part of the feedback embed\n * With shadow DOM, embed elements are inside shadow hosts marked with\n * data-qaid-embed or data-qaid-embed-overlay\n */\nexport function isEmbedElement(element: Element | null): boolean {\n if (!element) return false;\n // Check if the element itself is a shadow host\n if (element.hasAttribute(\"data-qaid-embed\") || element.hasAttribute(\"data-qaid-embed-overlay\")) return true;\n // Check ancestors for shadow host\n return !!element.closest(\"[data-qaid-embed], [data-qaid-embed-overlay]\");\n}\n\n/**\n * Get element bounds with optional padding\n */\nexport function getElementBounds(\n element: Element,\n padding = 0\n): { x: number; y: number; width: number; height: number } {\n const rect = element.getBoundingClientRect();\n return {\n x: rect.left - padding,\n y: rect.top - padding,\n width: rect.width + padding * 2,\n height: rect.height + padding * 2,\n };\n}\n\n/**\n * Remove all elements with a specific class\n */\nexport function removeAllByClass(className: string): void {\n document.querySelectorAll(`.${className}`).forEach((el) => {\n el.classList.remove(className);\n });\n}\n","/**\n * Screenshot annotation / markup editor for the thumbs embed.\n *\n * After a screenshot is captured the user can draw on it — rectangles, arrows,\n * a freehand pen, and a blur/redact box — in a full-screen, focus-trapped,\n * WCAG 2.2 AA dialog rendered inside the embed's overlay shadow root. On \"Done\"\n * the base image and the vector shapes are composited into a fresh WebP data\n * URL (so downstream code is unchanged); on \"Skip\"/Escape the original is kept.\n *\n * The geometry and compositing are kept as pure-ish exported functions\n * (`drawShape`, `rectFromPoints`, `compositeAnnotations`) so they can be tested\n * without a real rendering engine — happy-dom has no raster, so tests assert on\n * spied canvas-context calls rather than pixels. The {@link AnnotationEditor}\n * controller keeps the DOM wiring thin and its interactive methods are public\n * so they can be driven directly in tests.\n */\n\nimport { createElement } from \"./dom-utils\";\nimport {\n RECTANGLE_ICON,\n ARROW_ICON,\n PENCIL_ICON,\n BLUR_ICON,\n UNDO_ICON,\n DONE_ICON,\n SKIP_ICON,\n} from \"./icons\";\n\n/** The four drawing tools. */\nexport type ShapeType = \"rect\" | \"arrow\" | \"pen\" | \"blur\";\n\n/** A point in the screenshot's natural-pixel coordinate space. */\nexport interface Point {\n x: number;\n y: number;\n}\n\n/**\n * A single vector annotation. `rect`, `arrow` and `blur` use `points[0]` as the\n * drag start and `points[1]` as the drag end; `pen` uses every point in order.\n */\nexport interface Shape {\n type: ShapeType;\n color: string;\n strokeWidth: number;\n points: Point[];\n}\n\n/** Tile size (natural px) for the mosaic drawn by the blur/redact tool. */\nconst BLUR_TILE = 12;\n\n/** Default stroke colour: a high-visibility red that reads on most screenshots. */\nconst DEFAULT_STROKE = \"#ef4444\";\n/** Default swatch palette when the embed doesn't supply one. */\nconst DEFAULT_PALETTE = [\"#ef4444\", \"#f59e0b\", \"#22c55e\", \"#3b82f6\", \"#111827\", \"#ffffff\"];\n/** Friendly names for common swatches (for accessible labels). */\nconst COLOR_NAMES: Record<string, string> = {\n \"#ef4444\": \"red\",\n \"#f59e0b\": \"amber\",\n \"#22c55e\": \"green\",\n \"#3b82f6\": \"blue\",\n \"#111827\": \"black\",\n \"#ffffff\": \"white\",\n \"#6366f1\": \"indigo\",\n};\n/** Accessible name for a swatch colour — a friendly name, else the hex. */\nfunction colorName(hex: string): string {\n return COLOR_NAMES[hex.toLowerCase()] ?? hex;\n}\n/** Default stroke width in natural pixels. */\nconst DEFAULT_STROKE_WIDTH = 4;\n/** Default WebP quality for the re-encoded composite. */\nconst DEFAULT_QUALITY = 0.8;\n\n/** Human-readable labels for the toolbar / announcements (all overridable). */\nexport interface AnnotationLabels {\n title: string;\n instructions: string;\n rectangle: string;\n arrow: string;\n pen: string;\n blur: string;\n undo: string;\n skip: string;\n done: string;\n colors: string;\n}\n\nconst DEFAULT_LABELS: AnnotationLabels = {\n title: \"Annotate screenshot\",\n instructions:\n \"Draw on the screenshot to highlight or hide details, then choose Done to attach it or Skip to send the original.\",\n rectangle: \"Rectangle\",\n arrow: \"Arrow\",\n pen: \"Pen\",\n blur: \"Blur or redact\",\n undo: \"Undo last\",\n skip: \"Skip annotation\",\n done: \"Done\",\n colors: \"Drawing colour\",\n};\n\n/**\n * Normalise two drag corners into a top-left origin plus positive width/height,\n * regardless of the direction the user dragged.\n */\nexport function rectFromPoints(\n a: Point,\n b: Point\n): { x: number; y: number; w: number; h: number } {\n return {\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n w: Math.abs(a.x - b.x),\n h: Math.abs(a.y - b.y),\n };\n}\n\n/** A drag/shape too small to be a deliberate mark (a click, not a drag). */\nfunction isDegenerate(shape: Shape): boolean {\n if (shape.type === \"pen\") return shape.points.length < 2;\n const r = rectFromPoints(shape.points[0], shape.points[1]);\n return r.w < 3 && r.h < 3;\n}\n\nfunction drawArrow(\n ctx: CanvasRenderingContext2D,\n from: Point,\n to: Point,\n width: number\n): void {\n ctx.beginPath();\n ctx.moveTo(from.x, from.y);\n ctx.lineTo(to.x, to.y);\n ctx.stroke();\n\n const angle = Math.atan2(to.y - from.y, to.x - from.x);\n const head = Math.max(10, width * 3);\n ctx.beginPath();\n ctx.moveTo(to.x, to.y);\n ctx.lineTo(\n to.x - head * Math.cos(angle - Math.PI / 6),\n to.y - head * Math.sin(angle - Math.PI / 6)\n );\n ctx.moveTo(to.x, to.y);\n ctx.lineTo(\n to.x - head * Math.cos(angle + Math.PI / 6),\n to.y - head * Math.sin(angle + Math.PI / 6)\n );\n ctx.stroke();\n}\n\nfunction drawPen(ctx: CanvasRenderingContext2D, points: Point[]): void {\n if (points.length === 0) return;\n ctx.beginPath();\n ctx.moveTo(points[0].x, points[0].y);\n for (let i = 1; i < points.length; i++) {\n ctx.lineTo(points[i].x, points[i].y);\n }\n ctx.stroke();\n}\n\n/**\n * Redact a region so the underlying content is GONE from the composite — not\n * merely dimmed. Both fills are fully opaque (no alpha), so nothing bleeds\n * through; the two-tone mosaic just gives it a recognisable \"redacted\" texture.\n * There is no real Gaussian blur (it can't be verified without a raster), and a\n * translucent wash would leave sensitive text faintly legible — so this paints\n * solid.\n */\nfunction drawBlur(\n ctx: CanvasRenderingContext2D,\n x: number,\n y: number,\n w: number,\n h: number\n): void {\n ctx.fillStyle = \"rgb(15, 23, 42)\";\n ctx.fillRect(x, y, w, h);\n ctx.fillStyle = \"rgb(37, 47, 63)\";\n for (let ty = y; ty < y + h; ty += BLUR_TILE) {\n for (let tx = x; tx < x + w; tx += BLUR_TILE) {\n const checker =\n (Math.floor((tx - x) / BLUR_TILE) + Math.floor((ty - y) / BLUR_TILE)) %\n 2 ===\n 0;\n if (checker) {\n ctx.fillRect(\n tx,\n ty,\n Math.min(BLUR_TILE, x + w - tx),\n Math.min(BLUR_TILE, y + h - ty)\n );\n }\n }\n }\n}\n\n/**\n * Draw a single shape onto a 2D context in the shape's own (natural-pixel)\n * coordinates. Used both for the live editing preview and for the final\n * composite, so what the user sees is exactly what is submitted.\n */\nexport function drawShape(ctx: CanvasRenderingContext2D, shape: Shape): void {\n ctx.save();\n ctx.strokeStyle = shape.color;\n ctx.fillStyle = shape.color;\n ctx.lineWidth = shape.strokeWidth;\n ctx.lineJoin = \"round\";\n ctx.lineCap = \"round\";\n\n switch (shape.type) {\n case \"rect\": {\n const r = rectFromPoints(shape.points[0], shape.points[1]);\n ctx.strokeRect(r.x, r.y, r.w, r.h);\n break;\n }\n case \"arrow\":\n drawArrow(ctx, shape.points[0], shape.points[1], shape.strokeWidth);\n break;\n case \"pen\":\n drawPen(ctx, shape.points);\n break;\n case \"blur\": {\n const r = rectFromPoints(shape.points[0], shape.points[1]);\n drawBlur(ctx, r.x, r.y, r.w, r.h);\n break;\n }\n }\n\n ctx.restore();\n}\n\n/** Load an image from a data URL. Resolves with the element once decoded. */\nfunction loadImage(src: string): Promise<HTMLImageElement> {\n return new Promise((resolve, reject) => {\n const img = new Image();\n img.onload = (): void => resolve(img);\n img.onerror = (): void => reject(new Error(\"Failed to load screenshot\"));\n img.src = src;\n });\n}\n\n/**\n * Composite the base screenshot and the drawn shapes into a new WebP data URL\n * at the image's natural size. Falls back to the original data URL if the image\n * can't be loaded or a 2D context isn't available (so a submission is never\n * lost). This is intentionally standalone so it can be unit-tested in isolation.\n */\nexport async function compositeAnnotations(\n dataUrl: string,\n shapes: Shape[],\n opts: { quality?: number } = {}\n): Promise<string> {\n const quality = opts.quality ?? DEFAULT_QUALITY;\n\n let img: HTMLImageElement;\n try {\n img = await loadImage(dataUrl);\n } catch {\n return dataUrl;\n }\n\n const canvas = document.createElement(\"canvas\");\n canvas.width = img.naturalWidth || img.width || 1;\n canvas.height = img.naturalHeight || img.height || 1;\n\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return dataUrl;\n\n ctx.drawImage(img, 0, 0, canvas.width, canvas.height);\n for (const shape of shapes) {\n drawShape(ctx, shape);\n }\n\n return canvas.toDataURL(\"image/webp\", quality);\n}\n\n/** Options for {@link AnnotationEditor} / {@link openAnnotationEditor}. */\nexport interface AnnotationEditorOptions {\n /** The captured screenshot as a WebP data URL. */\n dataUrl: string;\n /** Shadow root (or element) the editor is mounted into. */\n root: ShadowRoot | HTMLElement;\n /** WebP quality for the re-encoded composite. */\n quality?: number;\n /** Default stroke colour for rectangle/arrow/pen. */\n color?: string;\n /** Colour swatches offered in the toolbar. The active `color` is ensured present. */\n palette?: string[];\n /** Default stroke width. */\n strokeWidth?: number;\n /** Label overrides. */\n labels?: Partial<AnnotationLabels>;\n /** Apply the embed's per-instance `--qaid-*` CSS variables to the container. */\n applyVars?: (el: HTMLElement) => void;\n /** Announce a message via the embed's live regions. */\n announce?: (message: string, assertive?: boolean) => void;\n /** Turn the container into an accessible modal dialog (focus trap + inert). */\n openDialog?: (\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string }\n ) => void;\n /** Tear down the dialog semantics and restore focus. */\n closeDialog?: () => void;\n}\n\nlet editorSeq = 0;\n\n/**\n * Full-screen screenshot annotation editor. Construct it, call {@link open}\n * (which returns a promise resolving to the composited WebP, or `null` when the\n * user skips), and the controller manages its own DOM and teardown.\n */\nexport class AnnotationEditor {\n readonly shapes: Shape[] = [];\n tool: ShapeType = \"rect\";\n\n private readonly opts: AnnotationEditorOptions;\n private readonly labels: AnnotationLabels;\n private color: string;\n private readonly palette: string[];\n private readonly strokeWidth: number;\n private readonly uid = `qaid-annotate-${++editorSeq}`;\n\n private container!: HTMLDivElement;\n private canvas!: HTMLCanvasElement;\n private ctx: CanvasRenderingContext2D | null = null;\n private toolbar!: HTMLDivElement;\n private undoBtn!: HTMLButtonElement;\n private img: HTMLImageElement | null = null;\n\n private drawing = false;\n private current: Shape | null = null;\n private settled = false;\n // Assigned in open() before any settle() is reachable (done/skip only fire\n // after the editor is mounted).\n private resolveResult!: (value: string | null) => void;\n\n constructor(opts: AnnotationEditorOptions) {\n this.opts = opts;\n this.labels = { ...DEFAULT_LABELS, ...(opts.labels ?? {}) };\n this.color = opts.color ?? DEFAULT_STROKE;\n this.palette = (opts.palette && opts.palette.length ? opts.palette : DEFAULT_PALETTE).slice();\n // Ensure the active colour is offered as a swatch so it stays selectable.\n if (!this.palette.some((c) => c.toLowerCase() === this.color.toLowerCase())) {\n this.palette.unshift(this.color);\n }\n this.strokeWidth = opts.strokeWidth ?? DEFAULT_STROKE_WIDTH;\n }\n\n /** Mount the editor and resolve when the user commits (Done) or skips. */\n open(): Promise<string | null> {\n const promise = new Promise<string | null>((resolve) => {\n this.resolveResult = resolve;\n });\n this.mount();\n return promise;\n }\n\n private toolButton(tool: ShapeType, icon: string, label: string): HTMLButtonElement {\n const btn = createElement(\"button\", {\n type: \"button\",\n class: \"qaid-annotate-tool\",\n \"data-qaid-tool\": tool,\n \"aria-pressed\": tool === this.tool ? \"true\" : \"false\",\n \"aria-label\": `${label} tool`,\n title: label,\n });\n btn.innerHTML = `${icon}<span class=\"qaid-annotate-btn-text\">${label}</span>`;\n return btn;\n }\n\n /** A round colour swatch button for the toolbar's colour group. */\n private swatchButton(color: string): HTMLButtonElement {\n const name = colorName(color);\n const btn = createElement(\"button\", {\n type: \"button\",\n class: \"qaid-annotate-swatch\",\n \"data-qaid-color\": color,\n \"aria-pressed\": color.toLowerCase() === this.color.toLowerCase() ? \"true\" : \"false\",\n \"aria-label\": `Draw in ${name}`,\n title: name,\n });\n btn.style.setProperty(\"--qaid-swatch\", color);\n return btn;\n }\n\n private actionButton(\n action: string,\n icon: string,\n label: string,\n extraClass: string\n ): HTMLButtonElement {\n const btn = createElement(\"button\", {\n type: \"button\",\n class: `qaid-annotate-action ${extraClass}`,\n \"data-qaid-action\": action,\n \"aria-label\": label,\n title: label,\n });\n btn.innerHTML = `${icon}<span class=\"qaid-annotate-btn-text\">${label}</span>`;\n return btn;\n }\n\n private mount(): void {\n const titleId = `${this.uid}-title`;\n const descId = `${this.uid}-desc`;\n\n this.container = createElement(\"div\", { class: \"qaid-annotate\" });\n this.opts.applyVars?.(this.container);\n\n const title = createElement(\"h2\", {\n id: titleId,\n class: \"qaid-annotate-title\",\n });\n title.textContent = this.labels.title;\n\n const desc = createElement(\"p\", {\n id: descId,\n class: \"qaid-annotate-desc\",\n });\n desc.textContent = this.labels.instructions;\n\n const stage = createElement(\"div\", { class: \"qaid-annotate-stage\" });\n this.canvas = document.createElement(\"canvas\");\n this.canvas.className = \"qaid-annotate-canvas\";\n this.canvas.width = 1;\n this.canvas.height = 1;\n this.canvas.setAttribute(\"role\", \"img\");\n this.canvas.setAttribute(\"aria-label\", this.labels.title);\n this.ctx = this.canvas.getContext(\"2d\");\n stage.appendChild(this.canvas);\n\n this.toolbar = createElement(\"div\", {\n class: \"qaid-annotate-toolbar\",\n role: \"toolbar\",\n \"aria-label\": this.labels.title,\n });\n\n const tools = createElement(\"div\", { class: \"qaid-annotate-tools\" });\n tools.appendChild(this.toolButton(\"rect\", RECTANGLE_ICON, this.labels.rectangle));\n tools.appendChild(this.toolButton(\"arrow\", ARROW_ICON, this.labels.arrow));\n tools.appendChild(this.toolButton(\"pen\", PENCIL_ICON, this.labels.pen));\n tools.appendChild(this.toolButton(\"blur\", BLUR_ICON, this.labels.blur));\n\n const colors = createElement(\"div\", {\n class: \"qaid-annotate-colors\",\n role: \"group\",\n \"aria-label\": this.labels.colors,\n });\n for (const c of this.palette) colors.appendChild(this.swatchButton(c));\n\n this.undoBtn = this.actionButton(\"undo\", UNDO_ICON, this.labels.undo, \"qaid-annotate-undo\");\n this.undoBtn.disabled = true;\n\n const skipBtn = this.actionButton(\"skip\", SKIP_ICON, this.labels.skip, \"qaid-annotate-skip\");\n const doneBtn = this.actionButton(\"done\", DONE_ICON, this.labels.done, \"qaid-annotate-done\");\n\n const actions = createElement(\"div\", { class: \"qaid-annotate-actions\" });\n actions.appendChild(this.undoBtn);\n actions.appendChild(skipBtn);\n actions.appendChild(doneBtn);\n\n this.toolbar.appendChild(tools);\n this.toolbar.appendChild(colors);\n this.toolbar.appendChild(actions);\n\n this.container.appendChild(title);\n this.container.appendChild(desc);\n this.container.appendChild(stage);\n this.container.appendChild(this.toolbar);\n this.opts.root.appendChild(this.container);\n\n this.toolbar.addEventListener(\"click\", this.onToolbarClick);\n this.canvas.addEventListener(\"pointerdown\", this.onPointerDown);\n this.container.addEventListener(\"pointermove\", this.onPointerMove);\n this.container.addEventListener(\"pointerup\", this.onPointerUp);\n this.container.addEventListener(\"keydown\", this.onKeyDown);\n\n this.opts.openDialog?.(this.container, {\n labelledbyId: titleId,\n describedbyId: descId,\n });\n this.opts.announce?.(this.labels.instructions);\n\n loadImage(this.opts.dataUrl)\n .then((img) => {\n this.img = img;\n this.canvas.width = img.naturalWidth || img.width || 1;\n this.canvas.height = img.naturalHeight || img.height || 1;\n this.redraw();\n })\n .catch(() => {\n this.img = null;\n this.redraw();\n });\n }\n\n /** Convert a pointer event's client coordinates into natural image pixels. */\n private toImageCoords(e: { clientX: number; clientY: number }): Point {\n const rect = this.canvas.getBoundingClientRect();\n const scaleX = this.canvas.width / (rect.width || this.canvas.width);\n const scaleY = this.canvas.height / (rect.height || this.canvas.height);\n return {\n x: (e.clientX - rect.left) * scaleX,\n y: (e.clientY - rect.top) * scaleY,\n };\n }\n\n /** Repaint the display canvas: base image (if loaded) then every shape. */\n redraw(): void {\n const ctx = this.ctx;\n if (!ctx) return;\n ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);\n if (this.img) {\n ctx.drawImage(this.img, 0, 0, this.canvas.width, this.canvas.height);\n }\n for (const shape of this.shapes) {\n drawShape(ctx, shape);\n }\n if (this.current) {\n drawShape(ctx, this.current);\n }\n }\n\n /** Select the active drawing tool and reflect it on the toolbar. */\n selectTool(tool: ShapeType): void {\n this.tool = tool;\n const buttons = this.toolbar.querySelectorAll<HTMLButtonElement>(\"[data-qaid-tool]\");\n buttons.forEach((btn) => {\n btn.setAttribute(\n \"aria-pressed\",\n btn.getAttribute(\"data-qaid-tool\") === tool ? \"true\" : \"false\"\n );\n });\n const label = this.labels[LABEL_KEY[tool]];\n this.opts.announce?.(`${label} tool selected`);\n }\n\n /** Set the active drawing colour; subsequent shapes use it. */\n selectColor(color: string): void {\n this.color = color;\n const swatches = this.toolbar.querySelectorAll<HTMLButtonElement>(\"[data-qaid-color]\");\n swatches.forEach((s) => {\n s.setAttribute(\n \"aria-pressed\",\n (s.getAttribute(\"data-qaid-color\") ?? \"\").toLowerCase() === color.toLowerCase()\n ? \"true\"\n : \"false\"\n );\n });\n this.opts.announce?.(`${colorName(color)} colour selected`);\n }\n\n private onToolbarClick = (e: Event): void => {\n const target = e.target as HTMLElement | null;\n const btn = target?.closest<HTMLElement>(\n \"[data-qaid-tool],[data-qaid-action],[data-qaid-color]\"\n );\n if (!btn) return;\n const color = btn.getAttribute(\"data-qaid-color\");\n if (color) {\n this.selectColor(color);\n return;\n }\n const tool = btn.getAttribute(\"data-qaid-tool\");\n if (tool) {\n this.selectTool(tool as ShapeType);\n return;\n }\n const action = btn.getAttribute(\"data-qaid-action\");\n if (action === \"undo\") this.undo();\n else if (action === \"skip\") this.skip();\n else if (action === \"done\") void this.done();\n };\n\n onPointerDown = (e: PointerEvent): void => {\n e.preventDefault?.();\n this.drawing = true;\n const p = this.toImageCoords(e);\n this.current = {\n type: this.tool,\n color: this.color,\n strokeWidth: this.strokeWidth,\n points: this.tool === \"pen\" ? [p] : [p, { ...p }],\n };\n this.redraw();\n };\n\n onPointerMove = (e: PointerEvent): void => {\n if (!this.drawing || !this.current) return;\n const p = this.toImageCoords(e);\n if (this.current.type === \"pen\") {\n this.current.points.push(p);\n } else {\n this.current.points[1] = p;\n }\n this.redraw();\n };\n\n onPointerUp = (): void => {\n if (!this.drawing || !this.current) return;\n this.drawing = false;\n const shape = this.current;\n this.current = null;\n if (isDegenerate(shape)) {\n this.redraw();\n return;\n }\n this.shapes.push(shape);\n this.undoBtn.disabled = false;\n this.opts.announce?.(\"Annotation added\");\n this.redraw();\n };\n\n onKeyDown = (e: KeyboardEvent): void => {\n if (e.key === \"Escape\") {\n e.preventDefault();\n this.skip();\n return;\n }\n if (e.key === \"Enter\") {\n const target = e.target as HTMLElement | null;\n // Let Enter activate a focused tool/action button natively.\n if (target?.getAttribute(\"data-qaid-tool\") || target?.getAttribute(\"data-qaid-action\")) {\n return;\n }\n e.preventDefault();\n void this.done();\n }\n };\n\n /** Remove the most recently added shape. */\n undo(): void {\n if (this.shapes.length === 0) {\n this.opts.announce?.(\"Nothing to undo\");\n return;\n }\n this.shapes.pop();\n this.undoBtn.disabled = this.shapes.length === 0;\n this.opts.announce?.(\"Removed last annotation\");\n this.redraw();\n }\n\n /** Composite the annotations and resolve with the new WebP data URL. */\n async done(): Promise<void> {\n if (this.settled) return;\n const out = await compositeAnnotations(this.opts.dataUrl, this.shapes, {\n quality: this.opts.quality,\n });\n this.opts.announce?.(\"Annotated screenshot attached\");\n this.settle(out);\n }\n\n /** Discard annotations and resolve with `null` (caller keeps the original). */\n skip(): void {\n if (this.settled) return;\n this.opts.announce?.(\"Annotation skipped\");\n this.settle(null);\n }\n\n private settle(value: string | null): void {\n this.settled = true;\n this.teardown();\n this.resolveResult(value);\n }\n\n private teardown(): void {\n this.toolbar.removeEventListener(\"click\", this.onToolbarClick);\n this.canvas.removeEventListener(\"pointerdown\", this.onPointerDown);\n this.container.removeEventListener(\"pointermove\", this.onPointerMove);\n this.container.removeEventListener(\"pointerup\", this.onPointerUp);\n this.container.removeEventListener(\"keydown\", this.onKeyDown);\n this.opts.closeDialog?.();\n this.container.remove();\n }\n}\n\n/** Maps a tool id to its label key, for announcements. */\nconst LABEL_KEY: Record<ShapeType, keyof AnnotationLabels> = {\n rect: \"rectangle\",\n arrow: \"arrow\",\n pen: \"pen\",\n blur: \"blur\",\n};\n\n/**\n * Open the annotation editor and resolve with the composited WebP data URL, or\n * `null` if the user skipped. Thin entry point used by the embed.\n */\nexport function openAnnotationEditor(\n opts: AnnotationEditorOptions\n): Promise<string | null> {\n return new AnnotationEditor(opts).open();\n}\n"],"names":["THUMBS_UP_ICON","THUMBS_DOWN_ICON","RECORD_ICON","FEEDBACK_ICON","RECTANGLE_ICON","ARROW_ICON","PENCIL_ICON","BLUR_ICON","UNDO_ICON","DONE_ICON","SKIP_ICON","createElement","tag","attrs","children","el","key","value","isMobileViewport","breakpoint","getElementAtPointUnderOverlay","x","y","hosts","saved","h","element","i","isEmbedElement","getElementBounds","padding","rect","BLUR_TILE","DEFAULT_STROKE","DEFAULT_PALETTE","COLOR_NAMES","colorName","hex","DEFAULT_STROKE_WIDTH","DEFAULT_QUALITY","DEFAULT_LABELS","rectFromPoints","a","b","isDegenerate","shape","r","drawArrow","ctx","from","to","width","angle","head","drawPen","points","drawBlur","w","ty","tx","drawShape","loadImage","src","resolve","reject","img","compositeAnnotations","dataUrl","shapes","opts","quality","canvas","editorSeq","AnnotationEditor","c","promise","tool","icon","label","btn","color","name","action","extraClass","titleId","descId","title","desc","stage","tools","colors","skipBtn","doneBtn","actions","e","scaleX","scaleY","LABEL_KEY","s","p","target","out","openAnnotationEditor"],"mappings":"AAIO,MAAMA,IAAiB;AAAA;AAAA,SAIjBC,IAAmB;AAAA;AAAA,SAInBC,IAAc;AAAA;AAAA,SAKdC,IAAgB;AAAA;AAAA,SAShBC,IAAiB;AAAA;AAAA,SAIjBC,IAAa;AAAA;AAAA,SAIbC,IAAc;AAAA;AAAA,SAIdC,IAAY;AAAA;AAAA,SAIZC,IAAY;AAAA;AAAA,SAIZC,IAAY;AAAA;AAAA,SAIZC,IAAY;AAAA;AAAA;AC3ClB,SAASC,EACdC,GACAC,GACAC,GAC0B;AAC1B,QAAMC,IAAK,SAAS,cAAcH,CAAG;AAErC,MAAIC;AACF,eAAW,CAACG,GAAKC,CAAK,KAAK,OAAO,QAAQJ,CAAK;AAC7C,MAAIG,MAAQ,cACVD,EAAG,YAAYE,IAEfF,EAAG,aAAaC,GAAKC,CAAK;AAehC,SAAOF;AACT;AAKO,SAASG,EAAiBC,IAAa,KAAc;AAC1D,SAAO,OAAO,SAAW,OAAe,OAAO,aAAaA;AAC9D;AAQO,SAASC,EACdC,GACAC,GACAC,GACgB;AAChB,QAAMC,IAAQD,EAAM,IAAI,CAACE,MAAMA,EAAE,MAAM,UAAU;AACjD,EAAAF,EAAM,QAAQ,CAACE,MAAOA,EAAE,MAAM,aAAa,QAAS;AACpD,QAAMC,IAAU,SAAS,iBAAiBL,GAAGC,CAAC;AAC9C,SAAAC,EA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AAMO,SAASK,EACdjC,GACwB;AACxB,SAAO,IAAII,EAAiBJ,CAAI,EAAE,KAAA;AACpC;;;;;;;;;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"loader-DnJ3MHkt.js","sources":["../../src/styles.ts","../../src/a11y.ts","../../src/modal-positioning.ts","../../src/console-capture.ts","../../src/quest-launcher.ts","../../src/embed.ts","../../src/bootstrap.ts","../../src/loader.ts"],"sourcesContent":["/**\n * CSS styles for the feedback embed\n * Uses .qaid- prefix to avoid conflicts\n */\n\n// Import CSS as strings (vite handles minification in production)\nimport shadowStyles from \"./styles-shadow.css?inline\";\nimport lightStyles from \"./styles-light.css?inline\";\n\nlet instanceCount = 0;\n\n/** Default button styles included in shadow root */\nconst DEFAULT_BUTTON_STYLES = `button.qaid-btn{width:var(--qaid-btn-size);height:var(--qaid-btn-size);border-radius:50%;border:none;background:#f3f4f6;color:#374151;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -1px rgba(0,0,0,.06);transition:background-color .2s,color .2s,transform .2s;-webkit-appearance:none;appearance:none;--qaid-hover-up-bg:var(--qaid-positive);--qaid-hover-up-color:#fff;--qaid-hover-down-bg:var(--qaid-negative);--qaid-hover-down-color:#fff}button.qaid-btn:hover{transform:scale(1.05)}button.qaid-btn-up:hover{background:var(--qaid-hover-up-bg);color:var(--qaid-hover-up-color)}button.qaid-btn-down:hover{background:var(--qaid-hover-down-bg);color:var(--qaid-hover-down-color)}button.qaid-btn-feedback:hover{background:var(--qaid-marker,#6366f1);color:var(--qaid-marker-text,#fff)}button.qaid-btn svg{width:var(--qaid-icon-size);height:var(--qaid-icon-size)}`;\n\nexport interface BuildCssVarsOptions {\n positiveColor?: string;\n negativeColor?: string;\n /** Color for selected element marker */\n markerColor?: string;\n /** Button size: small (36px), medium (48px), large (64px) */\n buttonSize?: \"small\" | \"medium\" | \"large\";\n /** Modal width in pixels */\n modalWidth?: number;\n /** Backdrop opacity (0-1) */\n backdropOpacity?: number;\n /** Font family */\n fontFamily?: string;\n /** Base font size in pixels */\n fontSize?: number;\n}\n\nconst BUTTON_SIZES = {\n small: 36,\n medium: 48,\n large: 64,\n} as const;\n\nconst ICON_SIZES = {\n small: 18,\n medium: 24,\n large: 32,\n} as const;\n\n/**\n * Calculate relative luminance of a color\n * Returns value between 0 (black) and 1 (white)\n */\nfunction getLuminance(r: number, g: number, b: number): number {\n const [rs, gs, bs] = [r, g, b].map((c) => {\n c = c / 255;\n return c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);\n });\n return 0.2126 * rs + 0.7152 * gs + 0.0722 * bs;\n}\n\n/**\n * Parse a color string (hex or rgb) and return RGB values\n */\nfunction parseColor(color: string): { r: number; g: number; b: number } | null {\n // Hex format\n if (color.startsWith(\"#\")) {\n const hex = color.slice(1);\n const fullHex = hex.length === 3\n ? hex.split(\"\").map((c) => c + c).join(\"\")\n : hex;\n const num = parseInt(fullHex, 16);\n return {\n r: (num >> 16) & 255,\n g: (num >> 8) & 255,\n b: num & 255,\n };\n }\n // RGB format\n const match = color.match(/rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)/);\n if (match) {\n return {\n r: parseInt(match[1]),\n g: parseInt(match[2]),\n b: parseInt(match[3]),\n };\n }\n return null;\n}\n\n/**\n * Get the best contrasting text color (black or white) for a background\n */\nfunction getContrastTextColor(bgColor: string): string {\n const rgb = parseColor(bgColor);\n if (!rgb) return \"white\";\n const luminance = getLuminance(rgb.r, rgb.g, rgb.b);\n // Use white text on dark backgrounds, black on light\n return luminance > 0.4 ? \"black\" : \"white\";\n}\n\n/**\n * Build a map of CSS variable names to values for per-instance scoping\n */\nexport function buildCssVars(options: BuildCssVarsOptions = {}): Record<string, string> {\n const {\n positiveColor = \"rgb(0, 200, 83)\",\n negativeColor = \"rgb(255, 0, 0)\",\n markerColor = \"#6366f1\",\n buttonSize = \"medium\",\n modalWidth = 400,\n backdropOpacity = 0.3,\n fontFamily = \"system-ui, -apple-system, sans-serif\",\n fontSize = 16,\n } = options;\n\n const btnSize = BUTTON_SIZES[buttonSize];\n const iconSize = ICON_SIZES[buttonSize];\n const markerTextColor = getContrastTextColor(markerColor);\n\n return {\n \"--qaid-positive\": positiveColor,\n \"--qaid-negative\": negativeColor,\n \"--qaid-marker\": markerColor,\n \"--qaid-marker-text\": markerTextColor,\n \"--qaid-btn-size\": `${btnSize}px`,\n \"--qaid-icon-size\": `${iconSize}px`,\n \"--qaid-modal-width\": `${modalWidth}px`,\n \"--qaid-backdrop-opacity\": String(backdropOpacity),\n \"--qaid-font-family\": fontFamily,\n \"--qaid-font-size\": `${fontSize}px`,\n };\n}\n\n/**\n * Apply CSS variables to an element via inline style properties\n */\nexport function applyCssVars(el: HTMLElement, vars: Record<string, string>): void {\n for (const [name, value] of Object.entries(vars)) {\n el.style.setProperty(name, value);\n }\n}\n\n/**\n * Get the CSS string to inject into a shadow root\n * Includes base shadow styles + default button styles\n */\nexport function getEmbedStyles(): string {\n return shadowStyles + DEFAULT_BUTTON_STYLES;\n}\n\n/**\n * Inject light DOM styles (cursor override + highlight)\n * Reference-counted across instances\n */\nexport function injectStyles(): void {\n instanceCount++;\n if (instanceCount > 1) return;\n\n const style = document.createElement(\"style\");\n style.id = \"qaid-styles\";\n style.textContent = lightStyles;\n document.head.appendChild(style);\n}\n\n/**\n * Remove light DOM styles when last instance is destroyed\n */\nexport function removeStyles(): void {\n if (instanceCount <= 0) return;\n instanceCount--;\n if (instanceCount === 0) {\n document.getElementById(\"qaid-styles\")!.remove();\n }\n}\n\n/** Reset internal state — for tests only */\nexport function _resetStylesState(): void {\n instanceCount = 0;\n const style = document.getElementById(\"qaid-styles\");\n if (style) {\n style.remove();\n }\n}\n","/**\n * Shared accessibility primitives for the qaid embeds.\n *\n * These helpers are intentionally framework-free and self-contained (no CSS\n * dependency) so they can be dropped into any open shadow root. They cover the\n * cross-cutting WCAG 2.2 AA infrastructure called for in the embed\n * accessibility plan: live-region announcements, focus management (trap,\n * save/restore), dialog semantics, and background isolation.\n */\n\n/** Host for the live regions: either a shadow root or a plain element. */\nexport type AnnounceRoot = ShadowRoot | HTMLElement;\n\n/** Options accepted by {@link announce}. */\nexport interface AnnounceOptions {\n /** Route the message through the assertive (role=\"alert\") region. */\n assertive?: boolean;\n}\n\n/** Options accepted by {@link applyDialog}. */\nexport interface ApplyDialogOptions {\n /** id of the element that labels the dialog (wired via aria-labelledby). */\n labelledbyId?: string;\n /** id of the element that describes the dialog (wired via aria-describedby). */\n describedbyId?: string;\n /** Fallback accessible name when no labelling element exists. */\n label?: string;\n}\n\n/** Handle returned by {@link createFocusTrap}. */\nexport interface FocusTrap {\n /** Remove the trap's key handler and clean up any tabindex it added. */\n release(): void;\n}\n\nconst POLITE_ATTR = \"data-qaid-a11y-live\";\n\nconst VISUALLY_HIDDEN_CSS =\n \"position:absolute;width:1px;height:1px;margin:-1px;padding:0;\" +\n \"border:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);\" +\n \"white-space:nowrap;\";\n\n/**\n * Selector for natively focusable / author-focusable elements. Elements that\n * opt out with tabindex=\"-1\" are excluded below in {@link getFocusable}.\n */\nconst FOCUSABLE_SELECTOR = [\n \"a[href]\",\n \"button\",\n \"input\",\n \"textarea\",\n \"select\",\n \"[tabindex]\",\n].join(\",\");\n\nfunction ownerDoc(root: AnnounceRoot): Document {\n return root.ownerDocument || document;\n}\n\nfunction getLiveRegion(root: AnnounceRoot, assertive: boolean): HTMLElement {\n const kind = assertive ? \"assertive\" : \"polite\";\n const existing = root.querySelector<HTMLElement>(\n `[${POLITE_ATTR}=\"${kind}\"]`\n );\n if (existing) return existing;\n\n const doc = ownerDoc(root);\n const region = doc.createElement(\"div\");\n region.setAttribute(POLITE_ATTR, kind);\n region.setAttribute(\"role\", assertive ? \"alert\" : \"status\");\n region.setAttribute(\"aria-live\", assertive ? \"assertive\" : \"polite\");\n region.setAttribute(\"aria-atomic\", \"true\");\n region.style.cssText = VISUALLY_HIDDEN_CSS;\n root.appendChild(region);\n return region;\n}\n\n/**\n * Announce a message to assistive technology via a visually-hidden live region\n * mounted inside `root`. The two regions (polite role=\"status\" and assertive\n * role=\"alert\") are created lazily on first use and reused thereafter.\n *\n * The target region is cleared before the new text is written so that repeated\n * identical messages are re-announced rather than coalesced.\n */\nexport function announce(\n root: AnnounceRoot,\n message: string,\n opts: AnnounceOptions = {}\n): void {\n const region = getLiveRegion(root, !!opts.assertive);\n // Clear-then-set so an identical repeat is still perceived as a change.\n region.textContent = \"\";\n region.textContent = message;\n}\n\nfunction isDisabled(el: HTMLElement): boolean {\n if (el.hasAttribute(\"disabled\")) return true;\n const asInput = el as HTMLElement & { disabled?: boolean };\n return asInput.disabled === true;\n}\n\nfunction isHidden(el: HTMLElement): boolean {\n let node: HTMLElement | null = el;\n while (node) {\n if (node.hasAttribute(\"hidden\")) return true;\n const style = node.style;\n if (\n style &&\n (style.display === \"none\" ||\n style.visibility === \"hidden\" ||\n style.visibility === \"collapse\")\n ) {\n return true;\n }\n node = node.parentElement;\n }\n return false;\n}\n\n/**\n * Collect the focusable descendants of `container` in DOM order, excluding\n * disabled controls, elements opted out with tabindex=\"-1\", and elements that\n * are hidden (via the hidden attribute or an inline display/visibility rule on\n * themselves or an ancestor up to the document root).\n */\nexport function getFocusable(container: HTMLElement): HTMLElement[] {\n const nodes = Array.from(\n container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)\n );\n return nodes.filter((el) => {\n if (el.getAttribute(\"tabindex\") === \"-1\") return false;\n if (el instanceof HTMLInputElement && el.type === \"hidden\") return false;\n if (el instanceof HTMLAnchorElement && !el.getAttribute(\"href\")) return false;\n if (isDisabled(el)) return false;\n if (isHidden(el)) return false;\n return true;\n });\n}\n\n/** Resolve the deepest active element, drilling through open shadow roots. */\nfunction getDeepActiveElement(doc: Document): HTMLElement | null {\n let active: Element | null = doc.activeElement;\n while (active && active.shadowRoot && active.shadowRoot.activeElement) {\n active = active.shadowRoot.activeElement;\n }\n return active instanceof HTMLElement ? active : null;\n}\n\n/**\n * Trap keyboard focus inside `container`: Tab / Shift+Tab cycle between the\n * first and last focusable descendants and can never leave the container. On\n * creation focus moves to the first focusable element, or to the container\n * itself (made programmatically focusable) when it has no focusable children.\n *\n * Call {@link FocusTrap.release} to remove the handler; pair it with\n * {@link restoreFocus} to return focus to the invoking control.\n */\nexport function createFocusTrap(container: HTMLElement): FocusTrap {\n const doc = container.ownerDocument || document;\n let addedTabindex = false;\n\n const onKeydown = (event: KeyboardEvent): void => {\n if (event.key !== \"Tab\") return;\n\n const focusable = getFocusable(container);\n if (focusable.length === 0) {\n // Nothing to move to — keep focus pinned on the container.\n event.preventDefault();\n container.focus();\n return;\n }\n\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n const active = getDeepActiveElement(doc);\n const withinTrap = active ? focusable.indexOf(active) !== -1 : false;\n\n if (event.shiftKey) {\n if (!withinTrap || active === first) {\n event.preventDefault();\n last.focus();\n }\n } else {\n if (!withinTrap || active === last) {\n event.preventDefault();\n first.focus();\n }\n }\n };\n\n container.addEventListener(\"keydown\", onKeydown);\n\n const initial = getFocusable(container);\n if (initial.length > 0) {\n initial[0].focus();\n } else {\n if (!container.hasAttribute(\"tabindex\")) {\n container.setAttribute(\"tabindex\", \"-1\");\n addedTabindex = true;\n }\n container.focus();\n }\n\n return {\n release(): void {\n container.removeEventListener(\"keydown\", onKeydown);\n if (addedTabindex) {\n container.removeAttribute(\"tabindex\");\n addedTabindex = false;\n }\n },\n };\n}\n\n/**\n * Capture the currently focused element (drilling through shadow roots) so it\n * can be restored later with {@link restoreFocus}. Returns null when focus is\n * on nothing focusable.\n */\nexport function saveFocus(): HTMLElement | null {\n return getDeepActiveElement(document);\n}\n\n/**\n * Restore focus to a previously saved element. Safe to call with null or an\n * element that has since been detached (a missing/throwing focus is ignored).\n */\nexport function restoreFocus(el: HTMLElement | null): void {\n if (!el || typeof el.focus !== \"function\") return;\n try {\n el.focus();\n } catch {\n // The element may have been removed; nothing more to do.\n }\n}\n\n/**\n * Apply dialog semantics to `el`: role=\"dialog\", aria-modal=\"true\", and the\n * naming/description wiring described by `opts`. Prefer aria-labelledby /\n * aria-describedby pointing at visible title/subtitle elements; fall back to\n * aria-label when no visible label element exists.\n */\nexport function applyDialog(el: HTMLElement, opts: ApplyDialogOptions = {}): void {\n el.setAttribute(\"role\", \"dialog\");\n el.setAttribute(\"aria-modal\", \"true\");\n if (opts.labelledbyId) {\n el.setAttribute(\"aria-labelledby\", opts.labelledbyId);\n }\n if (opts.describedbyId) {\n el.setAttribute(\"aria-describedby\", opts.describedbyId);\n }\n if (opts.label) {\n el.setAttribute(\"aria-label\", opts.label);\n }\n}\n\n/** Walk up to the body-level ancestor of `el`, crossing shadow boundaries. */\nfunction topLevelAncestor(el: HTMLElement, body: HTMLElement): HTMLElement | null {\n let node: Node | null = el;\n while (node && node !== body) {\n const parent: Node | null = node.parentNode;\n if (parent === body) return node as HTMLElement;\n if (parent && (parent as ShadowRoot).host) {\n node = (parent as ShadowRoot).host;\n continue;\n }\n if (!parent) return null;\n node = parent;\n }\n return null;\n}\n\n/**\n * Isolate the background from assistive technology while a dialog is open by\n * marking every top-level sibling of the dialog inert (with an aria-hidden\n * fallback). `except` is the open dialog (or any element inside it); the\n * top-level element that contains it is left interactive.\n *\n * Returns a restore function that reverts every attribute this call changed,\n * leaving elements that were already inert/hidden untouched.\n */\nexport function setBackgroundInert(except: HTMLElement): () => void {\n const doc = except.ownerDocument || document;\n const body = doc.body;\n if (!body) return () => {};\n\n const keep = topLevelAncestor(except, body);\n const changed: Array<{\n el: HTMLElement;\n prevInert: boolean;\n prevAriaHidden: string | null;\n }> = [];\n\n Array.from(body.children).forEach((child) => {\n if (!(child instanceof HTMLElement)) return;\n if (keep && child === keep) return;\n\n const prevInert = child.inert === true;\n const prevAriaHidden = child.getAttribute(\"aria-hidden\");\n // Only record (and later revert) elements we actually change.\n if (prevInert && prevAriaHidden === \"true\") return;\n\n child.inert = true;\n child.setAttribute(\"aria-hidden\", \"true\");\n changed.push({ el: child, prevInert, prevAriaHidden });\n });\n\n return function restore(): void {\n while (changed.length) {\n // The loop guard guarantees pop() returns an entry.\n const entry = changed.pop()!;\n entry.el.inert = entry.prevInert;\n if (entry.prevAriaHidden === null) {\n entry.el.removeAttribute(\"aria-hidden\");\n } else {\n entry.el.setAttribute(\"aria-hidden\", entry.prevAriaHidden);\n }\n }\n };\n}\n","/**\n * Modal positioning utilities\n */\n\nimport type { SelectedBounds } from \"./types\";\n\nexport interface ModalPosition {\n top: number;\n left: number;\n position: \"above\" | \"below\";\n}\n\nexport interface ArrowPosition {\n left: number;\n}\n\nexport interface ModalDimensions {\n width: number;\n height: number;\n arrowHeight: number;\n gap: number;\n viewportPadding: number;\n}\n\nconst DEFAULT_DIMENSIONS: ModalDimensions = {\n width: 400,\n height: 280,\n arrowHeight: 12,\n gap: 8,\n viewportPadding: 16,\n};\n\n/**\n * Calculate whether modal should go above or below the target element\n */\nexport function calculateVerticalPosition(\n bounds: SelectedBounds,\n viewportHeight: number,\n totalHeight: number,\n gap: number,\n viewportPadding: number\n): { top: number; position: \"above\" | \"below\" } {\n const spaceAbove = bounds.y;\n const spaceBelow = viewportHeight - (bounds.y + bounds.height);\n\n // Prefer below if there's enough space\n if (spaceBelow >= totalHeight + gap) {\n return {\n top: bounds.y + bounds.height + gap,\n position: \"below\",\n };\n }\n\n // Try above if there's enough space\n if (spaceAbove >= totalHeight + gap) {\n return {\n top: bounds.y - totalHeight - gap,\n position: \"above\",\n };\n }\n\n // Neither fits perfectly - clamp to viewport\n const position = spaceBelow > spaceAbove ? \"below\" : \"above\";\n let top: number;\n\n if (position === \"below\") {\n top = Math.min(\n bounds.y + bounds.height + gap,\n viewportHeight - totalHeight - viewportPadding\n );\n } else {\n top = Math.max(viewportPadding, bounds.y - totalHeight - gap);\n }\n\n return { top, position };\n}\n\n/**\n * Calculate horizontal position of modal, clamped to viewport\n */\nexport function calculateHorizontalPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n modalWidth: number,\n viewportPadding: number\n): number {\n const centerX = bounds.x + bounds.width / 2;\n let left = centerX - modalWidth / 2;\n\n // Clamp to viewport\n left = Math.max(viewportPadding, Math.min(left, viewportWidth - modalWidth - viewportPadding));\n\n return left;\n}\n\n/**\n * Calculate arrow position relative to modal\n * Points at the click position, not the element center\n */\nexport function calculateArrowPosition(\n bounds: SelectedBounds,\n modalLeft: number,\n modalWidth: number,\n minOffset = 24,\n arrowWidth = 24\n): number {\n // Use click position for arrow, not element center\n const targetX = bounds.clickX;\n // Subtract half the arrow width to center it on the target\n const arrowLeft = targetX - modalLeft - arrowWidth / 2;\n\n // Clamp arrow to stay within modal bounds\n return Math.max(minOffset, Math.min(arrowLeft, modalWidth - minOffset - arrowWidth / 2));\n}\n\n/**\n * Calculate complete modal position based on selected element bounds\n */\nexport function calculateModalPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n viewportHeight: number,\n dimensions: ModalDimensions = DEFAULT_DIMENSIONS\n): ModalPosition {\n const totalHeight = dimensions.height + dimensions.arrowHeight;\n\n const vertical = calculateVerticalPosition(\n bounds,\n viewportHeight,\n totalHeight,\n dimensions.gap,\n dimensions.viewportPadding\n );\n\n const left = calculateHorizontalPosition(\n bounds,\n viewportWidth,\n dimensions.width,\n dimensions.viewportPadding\n );\n\n return {\n top: vertical.top,\n left,\n position: vertical.position,\n };\n}\n\nexport interface TooltipPositionOptions {\n /** Gap in pixels between anchor and tooltip, and from viewport edges */\n gap?: number;\n}\n\n/**\n * Calculate tooltip position relative to an anchor, clamped to the viewport.\n * Pure function: no DOM access — caller passes measured rects and viewport size.\n *\n * Strategy:\n * - Place below the anchor by default\n * - Flip above if below would overflow vertically\n * - Clamp horizontally to viewport, then vertically to viewport\n */\nexport function calculateTooltipPosition(\n anchor: { top: number; bottom: number; left: number },\n tooltip: { width: number; height: number },\n viewport: { width: number; height: number },\n options: TooltipPositionOptions = {}\n): { top: number; left: number } {\n const gap = options.gap ?? 8;\n\n let top = anchor.bottom + gap;\n\n // Flip above if below overflows\n if (top + tooltip.height > viewport.height - gap) {\n top = anchor.top - tooltip.height - gap;\n }\n\n // Clamp horizontally\n let left = anchor.left;\n if (left < gap) {\n left = gap;\n } else if (left + tooltip.width > viewport.width - gap) {\n left = viewport.width - tooltip.width - gap;\n }\n\n // Clamp vertically\n if (top < gap) {\n top = gap;\n } else if (top + tooltip.height > viewport.height - gap) {\n top = viewport.height - tooltip.height - gap;\n }\n\n return { top, left };\n}\n\n/**\n * Calculate both modal and arrow positions\n */\nexport function calculateModalAndArrowPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n viewportHeight: number,\n dimensions: ModalDimensions = DEFAULT_DIMENSIONS\n): { modal: ModalPosition; arrow: ArrowPosition } {\n const modal = calculateModalPosition(bounds, viewportWidth, viewportHeight, dimensions);\n\n const arrowLeft = calculateArrowPosition(\n bounds,\n modal.left,\n dimensions.width\n );\n\n return {\n modal,\n arrow: { left: arrowLeft },\n };\n}\n","/**\n * Console capture utilities\n */\n\nimport type { ConsoleError } from \"./types\";\n\nconst MAX_MESSAGES = 20;\n\nexport interface ConsoleCapture {\n errors: ConsoleError[];\n restore: () => void;\n}\n\ntype ConsoleLevel = \"error\" | \"warn\" | \"log\";\n\n/**\n * Wrap console methods to capture messages\n */\nexport function captureConsoleErrors(\n onError?: (error: ConsoleError) => void\n): ConsoleCapture {\n const errors: ConsoleError[] = [];\n const originalError = console.error;\n const originalWarn = console.warn;\n const originalLog = console.log;\n\n const capture = (level: ConsoleLevel, args: unknown[]) => {\n const error: ConsoleError = {\n message: args.map((arg) => String(arg)).join(\" \"),\n timestamp: Date.now(),\n level,\n };\n\n // Keep max messages\n if (errors.length >= MAX_MESSAGES) {\n errors.shift();\n }\n errors.push(error);\n\n // Call callback if provided\n if (onError) {\n onError(error);\n }\n };\n\n console.error = function (...args: unknown[]) {\n capture(\"error\", args);\n originalError.apply(console, args);\n };\n\n console.warn = function (...args: unknown[]) {\n capture(\"warn\", args);\n originalWarn.apply(console, args);\n };\n\n console.log = function (...args: unknown[]) {\n capture(\"log\", args);\n originalLog.apply(console, args);\n };\n\n return {\n errors,\n restore: () => {\n console.error = originalError;\n console.warn = originalWarn;\n console.log = originalLog;\n },\n };\n}\n\n/**\n * Add an error to the captured errors array\n */\nexport function addError(errors: ConsoleError[], error: ConsoleError): void {\n if (errors.length >= MAX_MESSAGES) {\n errors.shift();\n }\n errors.push(error);\n}\n\n/**\n * Format console error for display\n */\nexport function formatError(error: ConsoleError): string {\n const date = new Date(error.timestamp);\n const time = date.toLocaleTimeString();\n const levelPrefix = error.level === \"error\" ? \"ERR\" : error.level === \"warn\" ? \"WRN\" : \"LOG\";\n return `[${time}] [${levelPrefix}] ${error.message}`;\n}\n","/**\n * Lazy loader + launcher for `@qaiddev/quests-embed`.\n *\n * `thumbs-embed` links a button to a quest but owns no questionnaire code\n * and takes no build-time dependency on the quests package. Instead the\n * quests widget is imported from a CDN the first time a quest is triggered,\n * so the shipped bundle stays zero-dependency and small.\n *\n * Only the tiny slice of the quests public API that we actually use is\n * modelled here structurally, so a version bump of the quests package that\n * keeps this surface stable needs no change in thumbs-embed.\n */\n\n/** Default ES-module URL, pinned to a compatible major on unpkg. */\nexport const DEFAULT_QUESTS_MODULE_URL =\n \"https://unpkg.com/@qaiddev/quests-embed@1/dist/qaid-quests.js\";\n\n/** The bit of a QaidQuests instance we hold onto. */\nexport interface QuestInstance {\n destroy(): void;\n}\n\n/** The bit of QaidQuests config we pass. Mirrors QuestsConfig loosely. */\nexport interface LaunchedQuestConfig {\n endpoint: string;\n configUrl: string;\n apiKey?: string;\n metadata?: Record<string, unknown>;\n onComplete?: (answers: Record<string, unknown>) => void;\n onClose?: () => void;\n}\n\ntype QuestsConstructor = new (config: LaunchedQuestConfig) => QuestInstance;\n\n/** Shape of the quests module's default/entry exports. */\nexport interface QuestsModule {\n QaidQuests: QuestsConstructor;\n}\n\ntype Importer = (url: string) => Promise<unknown>;\n\nconst defaultImporter: Importer = (url) =>\n // The URL is a runtime value, not a static specifier — keep Vite from\n // trying to analyze/bundle it.\n import(/* @vite-ignore */ url);\n\nlet importer: Importer = defaultImporter;\nlet modulePromise: Promise<QuestsModule> | null = null;\nlet cachedUrl: string | null = null;\n\n/**\n * @internal Test seam: swap the dynamic importer and clear the cache.\n * Pass `null` to restore the real dynamic `import()`. Not re-exported\n * from the package entry, so it isn't public API.\n */\nexport function _setQuestsImporter(fn: Importer | null): void {\n importer = fn ?? defaultImporter;\n modulePromise = null;\n cachedUrl = null;\n}\n\n/**\n * Import the quests module, caching the promise per URL. A failed load\n * clears the cache so a later trigger can retry (e.g. after a transient\n * network error) rather than being stuck with a rejected promise.\n */\nexport function loadQuestsModule(moduleUrl: string): Promise<QuestsModule> {\n if (modulePromise && cachedUrl === moduleUrl) return modulePromise;\n cachedUrl = moduleUrl;\n modulePromise = Promise.resolve(importer(moduleUrl))\n .then((mod) => {\n const m = mod as Partial<QuestsModule>;\n if (!m || typeof m.QaidQuests !== \"function\") {\n throw new Error(\"quests module has no QaidQuests export\");\n }\n return m as QuestsModule;\n })\n .catch((err) => {\n modulePromise = null;\n cachedUrl = null;\n throw err;\n });\n return modulePromise;\n}\n\nexport interface LaunchQuestOptions {\n /** Quest id to launch (the `[id]` in `{base}/{id}/definition`). */\n questId: string;\n /** Quest-service base URL, e.g. \"https://qaid.dev/api/quests\". */\n base: string;\n /** API key for the quest service (optional). */\n apiKey?: string;\n /** ES-module URL to load the quests widget from. */\n moduleUrl: string;\n /** Feedback record id to correlate the response with (optional). */\n feedbackId?: string | number | null;\n /** Called when the quest embed is torn down. */\n onClose?: () => void;\n}\n\n/**\n * Load the quests widget (if not already loaded) and open the given quest\n * as its own centered modal. Rejects if the module can't be loaded — the\n * caller should fall back to its normal UI.\n */\nexport async function launchQuest(opts: LaunchQuestOptions): Promise<QuestInstance> {\n const mod = await loadQuestsModule(opts.moduleUrl);\n const base = opts.base.replace(/\\/+$/, \"\");\n const metadata =\n opts.feedbackId != null ? { feedbackId: opts.feedbackId } : undefined;\n return new mod.QaidQuests({\n endpoint: `${base}/responses`,\n configUrl: `${base}/${encodeURIComponent(opts.questId)}/definition`,\n apiKey: opts.apiKey || undefined,\n metadata,\n onClose: opts.onClose,\n });\n}\n","import type {\n FeedbackConfig,\n ResolvedFeedbackConfig,\n FeedbackData,\n FeedbackType,\n SelectedBounds,\n EmbedState,\n FeedbackPayload,\n FeedbackResponse,\n} from \"./types\";\nimport { THUMBS_UP_ICON, THUMBS_DOWN_ICON, RECORD_ICON, FEEDBACK_ICON } from \"./icons\";\nimport { injectStyles, removeStyles, buildCssVars, applyCssVars, getEmbedStyles } from \"./styles\";\n// The element-targeting subsystem (with element-selector, ~14 KB) lives in a\n// lazily-loaded chunk (targeting.ts), pulled in the first time the user targets.\nimport type { TargetingController, TargetingHost } from \"./targeting\";\nimport {\n announce,\n createFocusTrap,\n saveFocus,\n restoreFocus,\n applyDialog,\n setBackgroundInert,\n type FocusTrap,\n} from \"./a11y\";\nimport { calculateTooltipPosition } from \"./modal-positioning\";\nimport type { ModalController, ModalHost } from \"./modal\";\nimport { captureConsoleErrors, type ConsoleCapture } from \"./console-capture\";\n// The whole video-recording subsystem lives in a lazily-loaded chunk\n// (recording.ts), pulled in the first time the record button is used. Only the\n// types are imported eagerly (erased at build time).\nimport type { RecordingController, RecordingHost } from \"./recording\";\nimport { isMobileViewport } from \"./dom-utils\";\n// Screenshot capture and the annotation editor are loaded on demand the first\n// time a screenshot is taken — see submitFeedback() / openAnnotationEditor().\nimport {\n launchQuest,\n DEFAULT_QUESTS_MODULE_URL,\n type QuestInstance,\n} from \"./quest-launcher\";\n\nconst VISITOR_ID_KEY = \"qaid_visitor_id\";\nconst HIDE_FEEDBACK_KEY = \"qaid_hide_feedback\";\n/** Default annotation swatches: red, amber, green, blue, near-black, white. */\nconst DEFAULT_ANNOTATION_PALETTE = [\n \"#ef4444\",\n \"#f59e0b\",\n \"#22c55e\",\n \"#3b82f6\",\n \"#111827\",\n \"#ffffff\",\n];\n\n// True when the primary pointer is touch (phone/tablet). On these devices the\n// Screen Capture API (getDisplayMedia) shows an intrusive \"start capturing\"\n// system prompt, dims the screen, and on iOS returns a rotated frame — so the\n// permission-free DOM/canvas screenshot is the right default there.\nfunction isTouchPrimaryDevice(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(pointer: coarse)\").matches\n );\n}\n\nfunction getHideKey(apiKey?: string): string {\n return apiKey ? `${HIDE_FEEDBACK_KEY}_${apiKey}` : HIDE_FEEDBACK_KEY;\n}\n\nexport function isHiddenByUser(apiKey?: string): boolean {\n try {\n return localStorage.getItem(getHideKey(apiKey)) === \"1\";\n } catch {\n return false;\n }\n}\n\nexport function setHiddenByUser(apiKey?: string, hidden = true): void {\n try {\n if (hidden) {\n localStorage.setItem(getHideKey(apiKey), \"1\");\n } else {\n localStorage.removeItem(getHideKey(apiKey));\n }\n } catch {\n // localStorage not available\n }\n}\n\n/**\n * Get or create a visitor ID stored in localStorage\n */\nexport function getOrCreateVisitorId(): string {\n try {\n let visitorId = localStorage.getItem(VISITOR_ID_KEY);\n if (!visitorId) {\n visitorId = crypto.randomUUID();\n localStorage.setItem(VISITOR_ID_KEY, visitorId);\n }\n return visitorId;\n } catch {\n // localStorage not available, generate a session-only ID\n return crypto.randomUUID();\n }\n}\n\n/**\n * QaidFeedback - Standalone feedback collection embed\n */\nexport class QaidFeedback {\n private config: ResolvedFeedbackConfig;\n private state: EmbedState = \"IDLE\";\n private feedbackData: FeedbackData = {\n feedbackType: null,\n elementSelector: null,\n elementText: null,\n consoleErrors: [],\n };\n private selectedBounds: SelectedBounds = {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n clickX: 0,\n clickY: 0,\n visible: false,\n };\n private feedbackId: number | null = null;\n // A quest launched from a button (in place of the message box), if any.\n private activeQuest: QuestInstance | null = null;\n private isMobile = false;\n private visitorId: string;\n\n // Console capture\n private consoleCapture: ConsoleCapture | null = null;\n\n // Video recording — the whole subsystem lives in a lazily-loaded chunk\n // (recording.ts); a thumbs-only visitor never downloads it.\n private recording: RecordingController | null = null;\n // Element targeting — also a lazily-loaded chunk (targeting.ts).\n private targeting: TargetingController | null = null;\n private targetingPrewarmed = false;\n // Preload-on-intent: warm the lazily-split feature chunks before first use.\n private prewarmHandle: number | null = null;\n private prewarmIsTimeout = false;\n private videoPrewarmed = false;\n private screenshotPrewarmed = false;\n\n // Shadow DOM\n private shadowHost: HTMLDivElement | null = null;\n private shadowRoot: ShadowRoot | null = null;\n\n // Overlay shadow DOM (always on document.body for full-page coverage)\n private overlayShadowHost: HTMLDivElement | null = null;\n private overlayShadowRoot: ShadowRoot | null = null;\n\n // DOM elements (inside shadow root)\n private buttonsContainer: HTMLDivElement | null = null;\n private isUserProvidedContainer = false;\n // The message modal lives in a lazily-loaded chunk (modal.ts).\n private modal: ModalController | null = null;\n private modalPrewarmed = false;\n private dismissBtn: HTMLButtonElement | null = null;\n\n // Per-instance CSS variables\n private cssVars: Record<string, string> = {};\n\n private activeThumbBtn: HTMLElement | null = null;\n // Tracks whether the pending activation came from the keyboard (Enter/Space)\n // rather than a pointer, so targeting can avoid elementFromPoint(0,0).\n private keyboardActivation = false;\n\n // Accessibility: dialog focus management\n private dialogTrigger: HTMLElement | null = null;\n private dialogTrap: FocusTrap | null = null;\n private dialogRestoreInert: (() => void) | null = null;\n\n // Unique id suffix for aria-labelledby/describedby references\n private readonly uid = Math.random().toString(36).slice(2, 9);\n\n // Bound event handlers\n private boundKeyDown: (e: KeyboardEvent) => void;\n private boundResize: () => void;\n\n // Start with buttons slid off-screen (localStorage dismiss, no animation)\n private _startDismissed = false;\n\n // DOM persistence (survives framework client-side navigation)\n private destroyed = false;\n private domObserver: MutationObserver | null = null;\n private boundBeforeSwap: ((e: Event) => void) | null = null;\n\n constructor(config: FeedbackConfig) {\n this.config = {\n endpoint: config.endpoint,\n apiKey: config.apiKey ?? \"\",\n container: config.container ?? \"\",\n buttonClass: config.buttonClass ?? \"\",\n direction: config.direction ?? \"horizontal\",\n position: config.position ?? \"bottom-right\",\n offset: {\n x: config.offset?.x ?? 16,\n y: config.offset?.y ?? 16,\n },\n zIndex: config.zIndex ?? 50,\n skipTargeting: config.skipTargeting ?? false,\n singleButton: config.singleButton ?? false,\n feedbackMode: config.feedbackMode ?? \"target\",\n colors: {\n positive: config.colors?.positive ?? \"rgb(0, 200, 83)\",\n negative: config.colors?.negative ?? \"rgb(255, 0, 0)\",\n marker: config.colors?.marker ?? \"#6366f1\",\n },\n buttonSize: config.buttonSize ?? \"medium\",\n text: {\n tooltip: config.text?.tooltip ?? \"\",\n modalTitle: config.text?.modalTitle ?? \"Thank you for your feedback!\",\n modalSubtitle: config.text?.modalSubtitle ?? \"Would you like to add a message to help us understand your feedback better?\",\n placeholder: config.text?.placeholder ?? \"Optional: Tell us more about your experience...\",\n submitButton: config.text?.submitButton ?? \"Submit\",\n skipButton: config.text?.skipButton ?? \"Skip\",\n positiveLabel: config.text?.positiveLabel ?? \"Send positive feedback\",\n negativeLabel: config.text?.negativeLabel ?? \"Send negative feedback\",\n recordLabel: config.text?.recordLabel ?? \"Record a screen recording\",\n dismissLabel: config.text?.dismissLabel ?? \"Hide Feedback\",\n feedbackLabel: config.text?.feedbackLabel ?? \"Send feedback\",\n },\n modalWidth: config.modalWidth ?? 400,\n backdropOpacity: config.backdropOpacity ?? 0.3,\n fontFamily: config.fontFamily ?? \"system-ui, -apple-system, sans-serif\",\n fontSize: config.fontSize ?? 16,\n captureScreenshot: config.captureScreenshot ?? false,\n annotate: config.annotate ?? true,\n annotationColor: config.annotationColor ?? config.colors?.marker ?? \"#6366f1\",\n annotationPalette: config.annotationPalette ?? DEFAULT_ANNOTATION_PALETTE,\n screenshotMethod: config.screenshotMethod ?? \"permission\",\n screenshotOptions: {\n quality: config.screenshotOptions?.quality ?? 0.8,\n maxWidth: config.screenshotOptions?.maxWidth ?? 1280,\n maxHeight: config.screenshotOptions?.maxHeight ?? 800,\n },\n incognito: config.incognito ?? false,\n hideDismiss: config.hideDismiss ?? false,\n positiveIcon: config.positiveIcon ?? \"\",\n negativeIcon: config.negativeIcon ?? \"\",\n feedbackIcon: config.feedbackIcon ?? \"\",\n hideThumbs: config.hideThumbs ?? false,\n css: config.css ?? \"\",\n captureVideo: config.captureVideo ?? false,\n videoOptions: {\n maxDuration: config.videoOptions?.maxDuration ?? 15,\n redaction: config.videoOptions?.redaction ?? false,\n },\n recordIcon: config.recordIcon ?? \"\",\n quests: {\n base: config.quests?.base ?? \"\",\n up: config.quests?.up ?? \"\",\n down: config.quests?.down ?? \"\",\n video: config.quests?.video ?? \"\",\n // Quest service reuses the feedback API key unless overridden.\n apiKey: config.quests?.apiKey ?? config.apiKey ?? \"\",\n moduleUrl: config.quests?.moduleUrl ?? DEFAULT_QUESTS_MODULE_URL,\n },\n };\n\n // Bind event handlers\n this.boundKeyDown = this.handleKeyDown.bind(this);\n this.boundResize = this.handleResize.bind(this);\n\n // Get or create visitor ID for anonymous feedback tracking\n this.visitorId = getOrCreateVisitorId();\n\n this.init();\n }\n\n private applyVars(el: HTMLElement): void {\n applyCssVars(el, this.cssVars);\n }\n\n /**\n * Announce a message via the shared visually-hidden live regions.\n * Prefer the overlay shadow root (which hosts every transient surface and\n * is never inerted by its own dialogs) so announcements are not suppressed\n * while a dialog aria-hides the main button host.\n */\n private announceMsg(message: string, assertive = false): void {\n const root = this.overlayShadowRoot ?? this.shadowRoot;\n if (root) announce(root, message, { assertive });\n }\n\n /**\n * Turn a transient surface into an accessible modal dialog: save the\n * invoking control, apply dialog semantics, trap focus, and inert the\n * background. Paired with closeDialogA11y() on every close path.\n */\n private openDialogA11y(\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string; label?: string }\n ): void {\n this.dialogTrigger = saveFocus();\n applyDialog(container, opts);\n this.dialogTrap = createFocusTrap(container);\n this.dialogRestoreInert = setBackgroundInert(container);\n }\n\n private closeDialogA11y(): void {\n this.dialogTrap?.release();\n this.dialogTrap = null;\n if (this.dialogRestoreInert) {\n this.dialogRestoreInert();\n this.dialogRestoreInert = null;\n }\n restoreFocus(this.dialogTrigger);\n this.dialogTrigger = null;\n }\n\n private clearActiveThumb(): void {\n if (this.activeThumbBtn) {\n this.activeThumbBtn.setAttribute(\"aria-pressed\", \"false\");\n this.activeThumbBtn = null;\n }\n }\n\n private init(): void {\n // Inject shared light DOM styles (cursor + highlight, reference counted)\n injectStyles();\n\n // Build per-instance CSS variables\n this.cssVars = buildCssVars({\n positiveColor: this.config.colors.positive,\n negativeColor: this.config.colors.negative,\n markerColor: this.config.colors.marker,\n buttonSize: this.config.buttonSize,\n modalWidth: this.config.modalWidth,\n backdropOpacity: this.config.backdropOpacity,\n fontFamily: this.config.fontFamily,\n fontSize: this.config.fontSize,\n });\n\n // Restore dismiss preference from localStorage (skip if hideDismiss)\n if (!this.config.hideDismiss && isHiddenByUser(this.config.apiKey)) {\n this._startDismissed = true;\n }\n\n // Check mobile\n this.checkMobile();\n window.addEventListener(\"resize\", this.boundResize);\n\n // Create shadow host and embed\n this.createEmbed();\n\n // Capture console errors\n this.consoleCapture = captureConsoleErrors((_error) => {\n this.feedbackData.consoleErrors = this.consoleCapture?.errors ?? [];\n });\n this.feedbackData.consoleErrors = this.consoleCapture.errors;\n\n // Persist across client-side navigations (Astro View Transitions, etc.)\n this.observeDom();\n\n // Preload split feature chunks on idle when their config flags are set, so\n // the first screenshot / recording doesn't wait on a chunk fetch. Hovering\n // the record button also warms the video chunk (see createEmbed).\n if (\n (this.config.captureVideo && this.videoSupported()) ||\n this.config.captureScreenshot\n ) {\n this.schedulePrewarm(() => {\n if (this.config.captureVideo && this.videoSupported()) this.prewarmVideo();\n if (this.config.captureScreenshot) this.prewarmScreenshot();\n });\n }\n }\n\n /**\n * Best-effort preload of a lazily-split feature chunk so its first use is\n * instant. Warming fetches + compiles (and defines) the module; the feature\n * modules have no load-time side effects, so this is safe. Errors are\n * swallowed — a failed preload just falls back to an on-demand load.\n */\n private prewarmVideo(): void {\n if (this.videoPrewarmed) return;\n this.videoPrewarmed = true;\n // Warm both the recording controller chunk and the capture chunk it pulls\n // in on start, so the first recording begins without waiting on either.\n import(\"./recording\").catch(() => {});\n import(\"./video-capture\").catch(() => {});\n }\n\n private prewarmScreenshot(): void {\n if (this.screenshotPrewarmed) return;\n this.screenshotPrewarmed = true;\n (this.shouldCaptureViaDom()\n ? import(\"./screenshot-dom\")\n : import(\"./screenshot\")\n ).catch(() => {});\n if (this.config.annotate) import(\"./annotate\").catch(() => {});\n }\n\n /** Run fn when the main thread is idle; cancelled by destroy(). */\n private schedulePrewarm(fn: () => void): void {\n const w = window as unknown as {\n requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;\n };\n const guarded = (): void => {\n if (!this.destroyed) fn();\n };\n if (typeof w.requestIdleCallback === \"function\") {\n this.prewarmIsTimeout = false;\n this.prewarmHandle = w.requestIdleCallback(guarded, { timeout: 2000 });\n } else {\n this.prewarmIsTimeout = true;\n this.prewarmHandle = window.setTimeout(guarded, 1200);\n }\n }\n\n /**\n * Watch for the shadow hosts being removed from the DOM by framework\n * client-side navigation (e.g. Astro View Transitions swapping <body>\n * contents, or any SPA router that replaces DOM subtrees). If the host\n * is disconnected and destroy() wasn't called, re-append it.\n *\n * Also hooks into Astro's `astro:before-swap` when available, which\n * lets us carry elements into the new document before the swap happens\n * (avoids a flash of the widget disappearing and reappearing).\n */\n private observeDom(): void {\n // Astro View Transitions: carry hosts into the new document pre-swap\n this.boundBeforeSwap = (e: Event) => {\n const newDoc = (e as any).newDocument as Document | undefined;\n if (!newDoc || this.destroyed) return;\n if (this.shadowHost) newDoc.body.appendChild(this.shadowHost);\n if (this.overlayShadowHost) newDoc.body.appendChild(this.overlayShadowHost);\n };\n document.addEventListener(\"astro:before-swap\", this.boundBeforeSwap);\n\n // Generic fallback: MutationObserver to catch any framework removing our hosts\n this.domObserver = new MutationObserver(() => {\n if (this.destroyed) return;\n if (this.shadowHost && !this.shadowHost.isConnected) {\n document.body.appendChild(this.shadowHost);\n }\n if (this.overlayShadowHost && !this.overlayShadowHost.isConnected) {\n document.body.appendChild(this.overlayShadowHost);\n }\n });\n this.domObserver.observe(document.body, { childList: true });\n }\n\n private checkMobile(): void {\n this.isMobile = isMobileViewport();\n }\n\n private handleResize(): void {\n this.checkMobile();\n }\n\n private createEmbed(): void {\n // Create the shadow host element\n this.shadowHost = document.createElement(\"div\");\n this.shadowHost.setAttribute(\"data-qaid-embed\", \"\");\n this.shadowHost.style.position = \"static\";\n this.shadowHost.style.display = \"contents\";\n\n // Check if user provided a container selector\n let userContainer: HTMLElement | null = null;\n if (this.config.container) {\n userContainer = document.querySelector(this.config.container);\n }\n\n if (userContainer) {\n userContainer.appendChild(this.shadowHost);\n this.isUserProvidedContainer = true;\n // Container mode never needs a dismiss button\n this.config.hideDismiss = true;\n } else {\n // Set shadow host to fixed positioning for auto-created containers\n this.shadowHost.style.position = \"fixed\";\n this.shadowHost.style.display = \"block\";\n this.shadowHost.style.inset = \"0\";\n this.shadowHost.style.pointerEvents = \"none\";\n this.shadowHost.style.zIndex = String(this.config.zIndex);\n document.body.appendChild(this.shadowHost);\n }\n\n // Attach shadow root\n this.shadowRoot = this.shadowHost.attachShadow({ mode: \"open\" });\n\n // Inject base styles into shadow root\n const baseStyle = document.createElement(\"style\");\n baseStyle.textContent = getEmbedStyles();\n this.shadowRoot.appendChild(baseStyle);\n\n // Inject theme CSS if provided\n if (this.config.css) {\n const themeStyle = document.createElement(\"style\");\n themeStyle.textContent = this.config.css;\n this.shadowRoot.appendChild(themeStyle);\n }\n\n // Create buttons container inside shadow root\n const dirClass = this.config.direction === \"vertical\" ? \"qaid-vertical\" : \"\";\n if (this.isUserProvidedContainer) {\n this.buttonsContainer = document.createElement(\"div\");\n this.buttonsContainer.className = `qaid-buttons qaid-${this.config.position} ${dirClass}`.trim();\n if (this.config.incognito) {\n this.buttonsContainer.classList.add(\"qaid-incognito\");\n }\n } else {\n this.buttonsContainer = document.createElement(\"div\");\n this.buttonsContainer.className = `qaid-buttons qaid-auto-container qaid-${this.config.position} ${dirClass}${this.config.incognito ? \" qaid-incognito\" : \"\"}`.trim();\n this.buttonsContainer.style.pointerEvents = \"auto\";\n // Apply custom offset\n const { x: offsetX, y: offsetY } = this.config.offset;\n if (this.config.position.includes(\"right\")) {\n this.buttonsContainer.style.right = `${offsetX}px`;\n } else {\n this.buttonsContainer.style.left = `${offsetX}px`;\n }\n if (this.config.position.includes(\"bottom\")) {\n this.buttonsContainer.style.bottom = `${offsetY}px`;\n } else {\n this.buttonsContainer.style.top = `${offsetY}px`;\n }\n }\n\n // Apply per-instance CSS variables to buttons container\n this.applyVars(this.buttonsContainer);\n this.shadowRoot.appendChild(this.buttonsContainer);\n\n // Track input modality so a keyboard-activated control (Enter/Space) can be\n // distinguished from a pointer click. A keyboard-fired synthetic click has\n // clientX/clientY===0, which would break elementFromPoint targeting.\n this.buttonsContainer.addEventListener(\"keydown\", (ev) => {\n if (ev.key === \"Enter\" || ev.key === \" \" || ev.key === \"Spacebar\") {\n this.keyboardActivation = true;\n }\n });\n this.buttonsContainer.addEventListener(\"mousedown\", () => {\n this.keyboardActivation = false;\n });\n this.buttonsContainer.addEventListener(\"pointerdown\", () => {\n this.keyboardActivation = false;\n });\n\n // Determine button classes\n const useCustomClass = !!this.config.buttonClass;\n const btnBaseClass = useCustomClass\n ? `qaid-btn-structural ${this.config.buttonClass}`\n : \"qaid-btn\";\n\n // Determine tooltip text\n const defaultTooltip = \"Feedback for us?\";\n const tooltipText = this.config.text.tooltip || defaultTooltip;\n\n // Create shared tooltip element (inside shadow root)\n const tooltip = document.createElement(\"div\");\n tooltip.className = \"qaid-tooltip-text\";\n tooltip.textContent = tooltipText;\n this.applyVars(tooltip);\n this.shadowRoot.appendChild(tooltip);\n this.tooltipElement = tooltip;\n\n // Single sentiment-free \"Feedback\" button, or the thumbs up/down pair.\n if (this.config.singleButton) {\n const fbWrapper = document.createElement(\"div\");\n fbWrapper.className = \"qaid-tooltip-wrapper\";\n\n const fbBtn = document.createElement(\"button\");\n fbBtn.type = \"button\";\n fbBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-feedback` : \"qaid-btn qaid-btn-feedback\";\n fbBtn.setAttribute(\"aria-label\", this.config.text.feedbackLabel);\n fbBtn.innerHTML = this.config.feedbackIcon || FEEDBACK_ICON;\n fbBtn.addEventListener(\"click\", (e) => this.handleThumbClick(\"neutral\", e.currentTarget as HTMLElement, e));\n fbBtn.addEventListener(\"mouseenter\", () => {\n this.prewarmTargeting();\n this.showTooltip(fbBtn);\n });\n fbBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n fbWrapper.appendChild(fbBtn);\n\n this.buttonsContainer.appendChild(fbWrapper);\n } else if (!this.config.hideThumbs) {\n // Thumbs up button\n const upWrapper = document.createElement(\"div\");\n upWrapper.className = \"qaid-tooltip-wrapper\";\n\n const upBtn = document.createElement(\"button\");\n upBtn.type = \"button\";\n upBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-up` : \"qaid-btn qaid-btn-up\";\n upBtn.setAttribute(\"aria-label\", this.config.text.positiveLabel);\n upBtn.innerHTML = this.config.positiveIcon || THUMBS_UP_ICON;\n upBtn.addEventListener(\"click\", (e) => this.handleThumbClick(\"up\", e.currentTarget as HTMLElement, e));\n upBtn.addEventListener(\"mouseenter\", () => {\n this.prewarmTargeting();\n this.showTooltip(upBtn);\n });\n upBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n upWrapper.appendChild(upBtn);\n\n // Thumbs down button\n const downWrapper = document.createElement(\"div\");\n downWrapper.className = \"qaid-tooltip-wrapper\";\n\n const downBtn = document.createElement(\"button\");\n downBtn.type = \"button\";\n downBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-down` : \"qaid-btn qaid-btn-down\";\n downBtn.setAttribute(\"aria-label\", this.config.text.negativeLabel);\n downBtn.innerHTML = this.config.negativeIcon || THUMBS_DOWN_ICON;\n downBtn.addEventListener(\"click\", (e) => this.handleThumbClick(\"down\", e.currentTarget as HTMLElement, e));\n downBtn.addEventListener(\"mouseenter\", () => {\n this.prewarmTargeting();\n this.showTooltip(downBtn);\n });\n downBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n downWrapper.appendChild(downBtn);\n\n this.buttonsContainer.appendChild(upWrapper);\n this.buttonsContainer.appendChild(downWrapper);\n }\n\n // Record button (only when captureVideo is true and browser supports it)\n if (this.config.captureVideo && this.videoSupported()) {\n const recordWrapper = document.createElement(\"div\");\n recordWrapper.className = \"qaid-tooltip-wrapper\";\n\n const recordBtn = document.createElement(\"button\");\n recordBtn.type = \"button\";\n recordBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-record` : \"qaid-btn qaid-btn-record\";\n recordBtn.setAttribute(\"aria-label\", this.config.text.recordLabel);\n recordBtn.innerHTML = this.config.recordIcon || RECORD_ICON;\n recordBtn.addEventListener(\"click\", () => {\n void this.ensureRecording().then((rec) =>\n this.config.videoOptions.redaction ? rec.startPicking() : rec.startRecording()\n );\n });\n // Warm the video chunk on hover/focus/touch — the ~200ms before a click —\n // so recording starts without waiting on the chunk fetch.\n const warmVideo = (): void => this.prewarmVideo();\n recordBtn.addEventListener(\"mouseenter\", () => {\n warmVideo();\n this.showTooltip(recordBtn);\n });\n recordBtn.addEventListener(\"focus\", warmVideo);\n recordBtn.addEventListener(\"touchstart\", warmVideo, { passive: true });\n recordBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n recordWrapper.appendChild(recordBtn);\n\n this.buttonsContainer.appendChild(recordWrapper);\n }\n\n // Dismiss (X) button — only in body/fixed mode (hidden for container embeds)\n if (!this.config.hideDismiss) {\n this.dismissBtn = document.createElement(\"button\");\n this.dismissBtn.type = \"button\";\n this.dismissBtn.className = \"qaid-dismiss-btn\";\n this.dismissBtn.setAttribute(\"aria-label\", this.config.text.dismissLabel);\n this.dismissBtn.title = this.config.text.dismissLabel;\n this.dismissBtn.innerHTML = `<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M2 2l8 8M10 2l-8 8\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"/></svg>`;\n this.dismissBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.handleDismiss();\n });\n // Insert as first child so it sits to the left of thumb buttons\n this.buttonsContainer.insertBefore(this.dismissBtn, this.buttonsContainer.firstChild);\n\n // If previously dismissed via localStorage, start fully hidden so it\n // doesn't flash back on hover — matching the dismiss behavior.\n if (this._startDismissed) {\n this.buttonsContainer.classList.add(\"qaid-dismissed\");\n }\n }\n }\n\n /**\n * Lazily create a separate overlay shadow host on document.body.\n * This host contains all full-page elements (targeting overlay, marker,\n * backdrop, modal, recording indicator, video preview) so they escape\n * clip-path / transform containing blocks in user containers.\n */\n private ensureOverlayHost(): ShadowRoot {\n if (this.overlayShadowRoot) return this.overlayShadowRoot;\n\n this.overlayShadowHost = document.createElement(\"div\");\n this.overlayShadowHost.setAttribute(\"data-qaid-embed-overlay\", \"\");\n this.overlayShadowHost.style.position = \"fixed\";\n this.overlayShadowHost.style.inset = \"0\";\n this.overlayShadowHost.style.pointerEvents = \"none\";\n this.overlayShadowHost.style.zIndex = String(this.config.zIndex);\n document.body.appendChild(this.overlayShadowHost);\n\n this.overlayShadowRoot = this.overlayShadowHost.attachShadow({ mode: \"open\" });\n\n // Inject base styles into overlay shadow root\n const baseStyle = document.createElement(\"style\");\n baseStyle.textContent = getEmbedStyles();\n this.overlayShadowRoot.appendChild(baseStyle);\n\n // Inject theme CSS if provided\n if (this.config.css) {\n const themeStyle = document.createElement(\"style\");\n themeStyle.textContent = this.config.css;\n this.overlayShadowRoot.appendChild(themeStyle);\n }\n\n return this.overlayShadowRoot;\n }\n\n private tooltipElement: HTMLElement | null = null;\n\n private showTooltip(anchor: HTMLElement): void {\n const tooltip = this.tooltipElement!;\n\n // Make visible to measure\n tooltip.style.visibility = \"hidden\";\n tooltip.classList.add(\"qaid-tooltip-visible\");\n\n const anchorRect = anchor.getBoundingClientRect();\n const tooltipRect = tooltip.getBoundingClientRect();\n const { top, left } = calculateTooltipPosition(\n anchorRect,\n tooltipRect,\n { width: window.innerWidth, height: window.innerHeight }\n );\n\n tooltip.style.top = `${top}px`;\n tooltip.style.left = `${left}px`;\n tooltip.style.visibility = \"visible\";\n }\n\n private hideTooltip(): void {\n this.tooltipElement!.classList.remove(\"qaid-tooltip-visible\");\n }\n\n private handleDismiss(): void {\n // Fully remove the widget. It does not linger as a hover-reveal ghost\n // (that's `qaid-incognito`); once dismissed it stays gone until the\n // visitor clears the stored preference.\n this.buttonsContainer!.classList.add(\"qaid-dismissed\");\n setHiddenByUser(this.config.apiKey, true);\n }\n\n private handleThumbClick(type: FeedbackType, buttonEl: HTMLElement, e: MouseEvent): void {\n // If user clicks a thumb while in incognito mode, they want it back.\n // (Dismissed widgets are `display:none`, so this can't fire for them.)\n if (this.buttonsContainer?.classList.contains(\"qaid-incognito\")) {\n this.buttonsContainer.classList.remove(\"qaid-incognito\");\n setHiddenByUser(this.config.apiKey, false);\n }\n // A message modal follows this feedback flow — warm its chunk now.\n this.prewarmModal();\n // \"annotate\" mode and skipTargeting both bypass element targeting and go\n // straight to the (screenshot →) modal flow.\n if (this.config.skipTargeting || this.config.feedbackMode === \"annotate\") {\n this.submitDirectFeedback(type, buttonEl);\n } else {\n // Expose targeting on/off state on the trigger\n this.activeThumbBtn = buttonEl;\n buttonEl.setAttribute(\"aria-pressed\", \"true\");\n // A keyboard-activated <button> fires a synthetic click whose clientX/\n // clientY are (0,0). Route those through the keyboard path instead of\n // elementFromPoint(0,0). `keyboardActivation` is set by a preceding\n // Enter/Space keydown and cleared by any pointerdown/mousedown.\n const keyboard = this.keyboardActivation;\n this.keyboardActivation = false;\n // Load the targeting chunk (pre-warmed on hover) then start it.\n void this.ensureTargeting().then((t) => {\n if (this.destroyed) return;\n if (keyboard) t.startKeyboard(type);\n else t.startPointer(type, e);\n });\n }\n }\n\n private submitDirectFeedback(type: FeedbackType, buttonEl: HTMLElement): void {\n this.feedbackData.feedbackType = type;\n this.feedbackData.elementSelector = null;\n this.feedbackData.elementText = null;\n\n // Use the button's position for modal placement\n const rect = buttonEl.getBoundingClientRect();\n this.selectedBounds = {\n x: rect.left,\n y: rect.top,\n width: rect.width,\n height: rect.height,\n clickX: rect.left + rect.width / 2,\n clickY: rect.top + rect.height / 2,\n visible: false,\n };\n this.submitFeedback();\n }\n\n\n private handleKeyDown(e: KeyboardEvent): void {\n if (e.key === \"Escape\") {\n // The recording controller owns Escape while recording / in preview /\n // picking; let it consume the key first.\n if (this.recording?.handleEscape()) return;\n if (this.state === \"TARGETING\") {\n this.targeting?.cancel();\n } else if (this.state === \"MODAL_OPEN\") {\n this.modal?.close();\n }\n }\n }\n\n\n /** Whether to capture the screenshot with the DOM/canvas method (html2canvas)\n * instead of the permission-based Screen Capture API. Explicit \"dom\" wins;\n * otherwise DOM is used on touch devices to avoid the getDisplayMedia prompt. */\n private shouldCaptureViaDom(): boolean {\n return this.config.screenshotMethod === \"dom\" || isTouchPrimaryDevice();\n }\n\n /**\n * Open the full-screen annotation editor over the captured screenshot,\n * reusing the overlay shadow host and the shared dialog a11y helpers.\n * Resolves with the composited WebP data URL, or null when the user skips\n * (caller keeps the original). Pointer events on the overlay host are\n * enabled while the editor is open and restored on close.\n */\n private async openAnnotationEditor(screenshot: string): Promise<string | null> {\n const root = this.ensureOverlayHost();\n const host = this.overlayShadowHost!;\n const prevPointerEvents = host.style.pointerEvents;\n host.style.pointerEvents = \"auto\";\n try {\n const { openAnnotationEditor } = await import(\"./annotate\");\n return await openAnnotationEditor({\n dataUrl: screenshot,\n root,\n quality: this.config.screenshotOptions.quality,\n color: this.config.annotationColor,\n palette: this.config.annotationPalette,\n applyVars: (el) => this.applyVars(el),\n announce: (msg, assertive) => this.announceMsg(msg, assertive),\n openDialog: (container, opts) => this.openDialogA11y(container, opts),\n closeDialog: () => this.closeDialogA11y(),\n });\n } catch (err) {\n // The annotate chunk failed to load / the editor threw — keep the\n // original screenshot rather than aborting the whole submission.\n console.error(\"Annotation editor failed to open:\", err);\n return null;\n } finally {\n host.style.pointerEvents = prevPointerEvents;\n }\n }\n\n private async submitFeedback(): Promise<void> {\n // Capture screenshot if enabled (server will gate by plan). \"annotate\" mode\n // always captures one to mark up, even without captureScreenshot set.\n let screenshot: string | null = null;\n const wantScreenshot =\n this.config.captureScreenshot || this.config.feedbackMode === \"annotate\";\n if (wantScreenshot) {\n // Loaded on demand so visitors who never submit a screenshot never\n // download the capture + annotation code. A capture failure (denied\n // permission, chunk load error) must never abort the feedback — we just\n // submit without a screenshot so the user still reaches the modal.\n try {\n if (this.shouldCaptureViaDom()) {\n const { captureDomScreenshot } = await import(\"./screenshot-dom\");\n screenshot = await captureDomScreenshot(this.config.screenshotOptions);\n } else {\n const { captureScreenshot } = await import(\"./screenshot\");\n screenshot = await captureScreenshot(this.config.screenshotOptions);\n }\n if (screenshot) this.announceMsg(\"Screenshot captured\");\n } catch (err) {\n console.error(\"Screenshot capture failed:\", err);\n screenshot = null;\n }\n }\n\n // Let the user mark up / redact the screenshot before it is submitted.\n // The message modal only opens after the POST below, so the composited\n // result lands in the same request — no backend change needed. On skip\n // the editor resolves null and the original screenshot is kept.\n if (screenshot && this.config.annotate) {\n screenshot = (await this.openAnnotationEditor(screenshot)) ?? screenshot;\n }\n\n // Include element bounds for server-side screenshot fallback\n // Only include if we have an element selector (element was targeted)\n const elementBounds = this.feedbackData.elementSelector\n ? {\n x: this.selectedBounds.x,\n y: this.selectedBounds.y,\n width: this.selectedBounds.width,\n height: this.selectedBounds.height,\n }\n : null;\n\n const payload: FeedbackPayload = {\n feedbackType: this.feedbackData.feedbackType!,\n pageUrl: window.location.href,\n apiKey: this.config.apiKey || undefined,\n elementSelector: this.feedbackData.elementSelector,\n elementText: this.feedbackData.elementText,\n consoleErrors: [...this.feedbackData.consoleErrors],\n screenWidth: window.innerWidth,\n screenHeight: window.innerHeight,\n clickX: this.selectedBounds.clickX,\n clickY: this.selectedBounds.clickY,\n scrollX: window.scrollX,\n scrollY: window.scrollY,\n screenshot,\n visitorId: this.visitorId,\n // Include element bounds and user agent for server-side screenshot fallback\n elementBounds,\n userAgent: navigator.userAgent,\n };\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n\n if (response.ok) {\n const data: FeedbackResponse = await response.json();\n this.feedbackId = data.id;\n this.announceMsg(\"Feedback sent\");\n }\n } catch (error) {\n console.error(\"Failed to submit feedback:\", error);\n this.announceMsg(\"Failed to send feedback\", true);\n }\n\n // If this button is linked to a quest, launch it in place of the\n // message box. The feedback record already exists, so on success we\n // just tear down the targeting UI and hand off. On any load failure we\n // fall through to the classic message box so the user can still leave\n // an optional message.\n const type = this.feedbackData.feedbackType;\n // Quest links are keyed by up/down/video; neutral single-button feedback\n // has no quest mapping, so it always falls through to the message box.\n if (type && type !== \"neutral\" && (await this.tryLaunchQuest(type, this.feedbackId))) {\n this.resetFeedbackUi();\n return;\n }\n\n // Always show the message modal as the terminal state (even if the API\n // failed — useful for demos).\n this.state = \"MODAL_OPEN\";\n try {\n // The modal chunk loads async; bail if the embed was destroyed meanwhile,\n // so a raced modal never opens (and never leaks a listener) post-destroy.\n const modal = await this.ensureModal();\n if (this.destroyed) return;\n modal.open();\n\n // Enable pointer events on overlay host for modal\n if (this.overlayShadowHost) {\n this.overlayShadowHost.style.pointerEvents = \"auto\";\n }\n } catch (err) {\n // The modal chunk failed to load/open. Never leave the user stuck in a\n // re-targetable limbo: thank them and reset to IDLE so a fresh click\n // starts a clean flow (the feedback itself was already POSTed above).\n console.error(\"Failed to open the feedback modal:\", err);\n this.announceMsg(\"Thank you for your feedback!\", true);\n this.resetFeedbackUi();\n }\n }\n\n /**\n * Quest id linked to `type`, or \"\" when quest launching is disabled\n * (no `base`) or this button has no quest configured.\n */\n private questIdFor(type: \"up\" | \"down\" | \"video\"): string {\n const q = this.config.quests;\n return q.base ? q[type] || \"\" : \"\";\n }\n\n /**\n * Launch the quest linked to `type`, if any. Resolves `true` when a quest\n * was configured and the widget launched; `false` when no quest is\n * configured or the widget failed to load (caller falls back to its\n * normal UI). The created feedback record id is passed through so the\n * quest response can be joined back to it server-side.\n */\n private async tryLaunchQuest(\n type: \"up\" | \"down\" | \"video\",\n feedbackId: number | string | null,\n ): Promise<boolean> {\n const questId = this.questIdFor(type);\n if (!questId) return false;\n try {\n this.activeQuest?.destroy();\n this.activeQuest = await launchQuest({\n questId,\n base: this.config.quests.base,\n apiKey: this.config.quests.apiKey || undefined,\n moduleUrl: this.config.quests.moduleUrl,\n feedbackId,\n onClose: () => {\n this.activeQuest = null;\n },\n });\n return true;\n } catch (error) {\n console.error(\"Failed to launch quest:\", error);\n this.activeQuest = null;\n return false;\n }\n }\n\n /**\n * Reset the thumbs targeting/marker UI back to idle without opening or\n * closing the message modal. Shared by closeModal() and the quest-launch\n * path (which bypasses the modal entirely).\n */\n private resetFeedbackUi(): void {\n this.targeting?.hideMarker();\n if (this.overlayShadowHost) {\n this.overlayShadowHost.style.pointerEvents = \"none\";\n }\n this.state = \"IDLE\";\n this.feedbackId = null;\n this.feedbackData.feedbackType = null;\n this.feedbackData.elementSelector = null;\n this.feedbackData.elementText = null;\n this.selectedBounds.visible = false;\n }\n\n\n /**\n * Lazily load and instantiate the modal controller. The message modal lives\n * in a separate chunk, fetched the first time it opens (and pre-warmed while\n * the user targets an element — see prewarmModal).\n */\n private async ensureModal(): Promise<ModalController> {\n if (!this.modal) {\n const { ModalController } = await import(\"./modal\");\n this.modal = new ModalController(this.makeModalHost());\n }\n return this.modal;\n }\n\n /** Narrow view of the embed the modal controller talks back through. */\n private makeModalHost(): ModalHost {\n const self = this;\n return {\n get config() {\n return self.config;\n },\n get uid() {\n return self.uid;\n },\n get isMobile() {\n return self.isMobile;\n },\n get state() {\n return self.state;\n },\n get boundKeyDown() {\n return self.boundKeyDown;\n },\n get feedbackData() {\n return self.feedbackData;\n },\n get selectedBounds() {\n return self.selectedBounds;\n },\n get feedbackId() {\n return self.feedbackId;\n },\n setFeedbackId: (id) => {\n self.feedbackId = id;\n },\n ensureOverlayHost: () => self.ensureOverlayHost(),\n applyVars: (el) => self.applyVars(el),\n announceMsg: (message, assertive) => self.announceMsg(message, assertive),\n openDialogA11y: (container, opts) => self.openDialogA11y(container, opts),\n closeDialogA11y: () => self.closeDialogA11y(),\n resetFeedbackUi: () => self.resetFeedbackUi(),\n };\n }\n\n /** Warm the modal chunk while the user is targeting, so it opens instantly. */\n private prewarmModal(): void {\n if (this.modalPrewarmed) return;\n this.modalPrewarmed = true;\n import(\"./modal\").catch(() => {});\n }\n\n /**\n * Lazily load and instantiate the targeting controller. The subsystem (with\n * element-selector) lives in a separate chunk, fetched the first time the\n * user targets — pre-warmed on thumb-button hover (see prewarmTargeting).\n */\n private async ensureTargeting(): Promise<TargetingController> {\n if (!this.targeting) {\n const { TargetingController } = await import(\"./targeting\");\n this.targeting = new TargetingController(this.makeTargetingHost());\n }\n return this.targeting;\n }\n\n /** Narrow view of the embed the targeting controller talks back through. */\n private makeTargetingHost(): TargetingHost {\n const self = this;\n return {\n get config() {\n return self.config;\n },\n get cssVars() {\n return self.cssVars;\n },\n get state() {\n return self.state;\n },\n get shadowHost() {\n return self.shadowHost;\n },\n get overlayShadowHost() {\n return self.overlayShadowHost;\n },\n get boundKeyDown() {\n return self.boundKeyDown;\n },\n get feedbackData() {\n return self.feedbackData;\n },\n get selectedBounds() {\n return self.selectedBounds;\n },\n setState: (state) => {\n self.state = state;\n },\n ensureOverlayHost: () => self.ensureOverlayHost(),\n applyVars: (el) => self.applyVars(el),\n announceMsg: (message, assertive) => self.announceMsg(message, assertive),\n clearActiveThumb: () => self.clearActiveThumb(),\n submitFeedback: () => self.submitFeedback(),\n };\n }\n\n /** Warm the targeting chunk on thumb-button hover, before the click. */\n private prewarmTargeting(): void {\n if (this.targetingPrewarmed || this.config.skipTargeting) return;\n this.targetingPrewarmed = true;\n import(\"./targeting\").catch(() => {});\n }\n\n // ==================== Video Recording ====================\n\n /**\n * Cheap synchronous capability check so the record button can render without\n * pulling in the (lazily-loaded) video subsystem. Mirrors\n * isVideoRecordingSupported() in video-capture.ts.\n */\n private videoSupported(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n !!navigator.mediaDevices &&\n typeof navigator.mediaDevices.getDisplayMedia === \"function\" &&\n typeof MediaRecorder !== \"undefined\"\n );\n }\n\n\n /**\n * Lazily load and instantiate the recording controller. The whole recording\n * subsystem lives in a separate chunk, fetched only the first time the record\n * button is used (and pre-warmed on hover — see prewarmVideo).\n */\n private async ensureRecording(): Promise<RecordingController> {\n if (!this.recording) {\n const { RecordingController } = await import(\"./recording\");\n this.recording = new RecordingController(this.makeRecordingHost());\n }\n return this.recording;\n }\n\n /** Narrow view of the embed the recording controller talks back through. */\n private makeRecordingHost(): RecordingHost {\n const self = this;\n return {\n get config() {\n return self.config;\n },\n get visitorId() {\n return self.visitorId;\n },\n get uid() {\n return self.uid;\n },\n get overlayShadowHost() {\n return self.overlayShadowHost;\n },\n get consoleCapture() {\n return self.consoleCapture;\n },\n get boundKeyDown() {\n return self.boundKeyDown;\n },\n get state() {\n return self.state;\n },\n setState: (state) => {\n self.state = state;\n },\n ensureOverlayHost: () => self.ensureOverlayHost(),\n applyVars: (el) => self.applyVars(el),\n announceMsg: (message, assertive) => self.announceMsg(message, assertive),\n openDialogA11y: (container, opts) => self.openDialogA11y(container, opts),\n closeDialogA11y: () => self.closeDialogA11y(),\n setButtonsDisabled: (disabled) => self.setButtonsDisabled(disabled),\n tryLaunchQuest: (type, feedbackId) => self.tryLaunchQuest(type, feedbackId),\n };\n }\n\n private setButtonsDisabled(disabled: boolean): void {\n if (!this.buttonsContainer) return;\n const buttons = this.buttonsContainer.querySelectorAll<HTMLButtonElement>(\"button.qaid-btn, button.qaid-btn-structural\");\n buttons.forEach((btn) => {\n if (disabled) {\n // Don't disable the record button itself (it has its own state)\n if (!btn.classList.contains(\"qaid-btn-record\")) {\n btn.disabled = true;\n btn.style.opacity = \"0.5\";\n }\n } else {\n btn.disabled = false;\n btn.style.opacity = \"\";\n }\n });\n }\n\n /**\n * Destroy the embed and clean up all resources\n */\n public destroy(): void {\n // Flag as destroyed so the DOM observer doesn't re-attach hosts\n this.destroyed = true;\n\n // Disconnect DOM persistence observers\n if (this.domObserver) {\n this.domObserver.disconnect();\n this.domObserver = null;\n }\n if (this.boundBeforeSwap) {\n document.removeEventListener(\"astro:before-swap\", this.boundBeforeSwap);\n this.boundBeforeSwap = null;\n }\n\n // Tear down the targeting subsystem + release any open dialog focus state\n this.targeting?.destroy();\n this.targeting = null;\n this.clearActiveThumb();\n this.closeDialogA11y();\n\n // Cancel any pending idle preload\n if (this.prewarmHandle !== null) {\n const w = window as unknown as { cancelIdleCallback?: (h: number) => void };\n if (this.prewarmIsTimeout) clearTimeout(this.prewarmHandle);\n else w.cancelIdleCallback?.(this.prewarmHandle);\n this.prewarmHandle = null;\n }\n\n // Tear down the recording subsystem (recorder, picker, preview) if loaded.\n this.recording?.destroy();\n this.recording = null;\n // Tear down the message modal if it was loaded/open.\n this.modal?.destroy();\n this.modal = null;\n\n // Tear down any quest launched from a button\n this.activeQuest?.destroy();\n this.activeQuest = null;\n\n // Restore console.error\n if (this.consoleCapture) {\n this.consoleCapture.restore();\n this.consoleCapture = null;\n }\n\n // Remove event listeners\n window.removeEventListener(\"resize\", this.boundResize);\n document.removeEventListener(\"keydown\", this.boundKeyDown);\n\n document.body.classList.remove(\"qaid-targeting\", \"qaid-type-up\");\n document.body.style.removeProperty(\"--qaid-positive\");\n document.body.style.removeProperty(\"--qaid-negative\");\n\n // Remove shadow hosts from DOM (this removes shadow roots and all their contents)\n if (this.shadowHost) {\n this.shadowHost.remove();\n this.shadowHost = null;\n this.shadowRoot = null;\n }\n if (this.overlayShadowHost) {\n this.overlayShadowHost.remove();\n this.overlayShadowHost = null;\n this.overlayShadowRoot = null;\n }\n this.buttonsContainer = null;\n this.dismissBtn = null;\n this.tooltipElement = null;\n\n // Remove light DOM styles (reference counted)\n removeStyles();\n }\n}\n","/**\n * Auto-initialization from a `<script>` tag.\n *\n * Shared by both delivery entries: the legacy UMD/API entry (`index.ts`) and\n * the minimal ESM loader (`loader.ts`). Kept out of `index.ts` so the loader\n * can auto-init without pulling in `index.ts`'s feature re-exports — that\n * re-export graph is what anchors screenshot/video/annotate into the main\n * chunk and defeats code-splitting.\n */\n\nimport { QaidFeedback } from \"./embed\";\nimport type { FeedbackConfig } from \"./types\";\n\n/**\n * Find theme CSS from an element matched by a CSS selector.\n * Used by data-css-selector attribute and JSON cssSelector property.\n */\nfunction findCssFromSelector(selector: string): string {\n const el = document.querySelector(selector);\n return el?.textContent?.trim() ?? \"\";\n}\n\n/**\n * Parse JSON config from a separate script tag with type=\"application/json\"\n * Looks for: <script type=\"application/json\" data-feedback-config>{ ... }</script>\n */\nfunction parseJsonConfig(): Partial<FeedbackConfig> | null {\n const configScript = document.querySelector(\n 'script[type=\"application/json\"][data-feedback-config]'\n );\n if (!configScript) return null;\n\n const textContent = configScript.textContent?.trim();\n if (!textContent) return null;\n\n try {\n const parsed = JSON.parse(textContent);\n // Resolve cssSelector → css\n if (parsed.cssSelector && !parsed.css) {\n parsed.css = findCssFromSelector(parsed.cssSelector);\n delete parsed.cssSelector;\n }\n return parsed;\n } catch {\n return null;\n }\n}\n\n/**\n * Parse config from data-* attributes (backward compatibility)\n */\nfunction parseDataAttributes(script: HTMLScriptElement): Partial<FeedbackConfig> | null {\n const endpoint = script.getAttribute(\"data-endpoint\");\n if (!endpoint) return null;\n\n const position = script.getAttribute(\"data-position\") as\n | \"bottom-right\"\n | \"bottom-left\"\n | \"top-right\"\n | \"top-left\"\n | null;\n const zIndex = script.getAttribute(\"data-zindex\");\n const positiveColor = script.getAttribute(\"data-positive-color\");\n const negativeColor = script.getAttribute(\"data-negative-color\");\n const markerColor = script.getAttribute(\"data-marker-color\");\n const container = script.getAttribute(\"data-container\");\n const buttonClass = script.getAttribute(\"data-button-class\");\n const skipTargeting = script.getAttribute(\"data-skip-targeting\");\n const singleButton = script.getAttribute(\"data-single-button\");\n const feedbackMode = script.getAttribute(\"data-feedback-mode\") as\n | \"target\"\n | \"annotate\"\n | null;\n const incognito = script.getAttribute(\"data-incognito\");\n const buttonSize = script.getAttribute(\"data-button-size\") as\n | \"small\"\n | \"medium\"\n | \"large\"\n | null;\n const offsetX = script.getAttribute(\"data-offset-x\");\n const offsetY = script.getAttribute(\"data-offset-y\");\n const modalWidth = script.getAttribute(\"data-modal-width\");\n const backdropOpacity = script.getAttribute(\"data-backdrop-opacity\");\n const fontFamily = script.getAttribute(\"data-font-family\");\n const fontSize = script.getAttribute(\"data-font-size\");\n const tooltip = script.getAttribute(\"data-tooltip\");\n const modalTitle = script.getAttribute(\"data-modal-title\");\n const modalSubtitle = script.getAttribute(\"data-modal-subtitle\");\n const placeholder = script.getAttribute(\"data-placeholder\");\n const submitButton = script.getAttribute(\"data-submit-button\");\n const skipButton = script.getAttribute(\"data-skip-button\");\n const positiveIcon = script.getAttribute(\"data-positive-icon\");\n const negativeIcon = script.getAttribute(\"data-negative-icon\");\n const feedbackIcon = script.getAttribute(\"data-feedback-icon\");\n const feedbackLabel = script.getAttribute(\"data-feedback-label\");\n const apiKey = script.getAttribute(\"data-api-key\");\n const captureScreenshot = script.getAttribute(\"data-capture-screenshot\");\n const annotate = script.getAttribute(\"data-annotate\");\n const annotationColor = script.getAttribute(\"data-annotation-color\");\n const screenshotQuality = script.getAttribute(\"data-screenshot-quality\");\n const screenshotMaxWidth = script.getAttribute(\"data-screenshot-max-width\");\n const screenshotMaxHeight = script.getAttribute(\"data-screenshot-max-height\");\n const captureVideo = script.getAttribute(\"data-capture-video\");\n const redaction = script.getAttribute(\"data-video-redaction\");\n const hideThumbs = script.getAttribute(\"data-hide-thumbs\");\n const hideDismiss = script.getAttribute(\"data-hide-dismiss\");\n const videoMaxDuration = script.getAttribute(\"data-video-max-duration\");\n const screenshotMethod = script.getAttribute(\"data-screenshot-method\") as \"dom\" | \"permission\" | null;\n const direction = script.getAttribute(\"data-direction\") as \"horizontal\" | \"vertical\" | null;\n const cssSelector = script.getAttribute(\"data-css-selector\");\n const questBase = script.getAttribute(\"data-quest-base\");\n const questUp = script.getAttribute(\"data-quest-up\");\n const questDown = script.getAttribute(\"data-quest-down\");\n const questVideo = script.getAttribute(\"data-quest-video\");\n const questApiKey = script.getAttribute(\"data-quest-api-key\");\n const questModuleUrl = script.getAttribute(\"data-quest-module-url\");\n\n return {\n endpoint,\n css: cssSelector ? findCssFromSelector(cssSelector) : undefined,\n apiKey: apiKey ?? undefined,\n captureScreenshot: captureScreenshot === \"true\" ? true : undefined,\n // Annotation is on by default; only an explicit \"false\" disables it.\n annotate: annotate === \"false\" ? false : undefined,\n annotationColor: annotationColor ?? undefined,\n screenshotOptions: (screenshotQuality || screenshotMaxWidth || screenshotMaxHeight) ? {\n quality: screenshotQuality ? parseFloat(screenshotQuality) : undefined,\n maxWidth: screenshotMaxWidth ? parseInt(screenshotMaxWidth, 10) : undefined,\n maxHeight: screenshotMaxHeight ? parseInt(screenshotMaxHeight, 10) : undefined,\n } : undefined,\n container: container ?? undefined,\n buttonClass: buttonClass ?? undefined,\n direction: direction ?? undefined,\n position: position ?? undefined,\n zIndex: zIndex ? parseInt(zIndex, 10) : undefined,\n skipTargeting: skipTargeting === \"true\" ? true : undefined,\n singleButton: singleButton === \"true\" ? true : undefined,\n feedbackMode: feedbackMode ?? undefined,\n incognito: incognito === \"true\" ? true : undefined,\n buttonSize: buttonSize ?? undefined,\n offset: (offsetX || offsetY) ? {\n x: offsetX ? parseInt(offsetX, 10) : undefined,\n y: offsetY ? parseInt(offsetY, 10) : undefined,\n } : undefined,\n modalWidth: modalWidth ? parseInt(modalWidth, 10) : undefined,\n backdropOpacity: backdropOpacity ? parseFloat(backdropOpacity) : undefined,\n fontFamily: fontFamily ?? undefined,\n fontSize: fontSize ? parseInt(fontSize, 10) : undefined,\n colors: {\n positive: positiveColor ?? undefined,\n negative: negativeColor ?? undefined,\n marker: markerColor ?? undefined,\n },\n text: (tooltip || modalTitle || modalSubtitle || placeholder || submitButton || skipButton || feedbackLabel) ? {\n tooltip: tooltip ?? undefined,\n modalTitle: modalTitle ?? undefined,\n modalSubtitle: modalSubtitle ?? undefined,\n placeholder: placeholder ?? undefined,\n submitButton: submitButton ?? undefined,\n skipButton: skipButton ?? undefined,\n feedbackLabel: feedbackLabel ?? undefined,\n } : undefined,\n positiveIcon: positiveIcon ?? undefined,\n negativeIcon: negativeIcon ?? undefined,\n feedbackIcon: feedbackIcon ?? undefined,\n screenshotMethod: screenshotMethod ?? undefined,\n captureVideo: captureVideo === \"true\" ? true : undefined,\n hideThumbs: hideThumbs === \"true\" ? true : undefined,\n hideDismiss: hideDismiss === \"true\" ? true : undefined,\n videoOptions: (videoMaxDuration || redaction) ? {\n maxDuration: videoMaxDuration ? parseInt(videoMaxDuration, 10) : undefined,\n redaction: redaction === \"true\" ? true : undefined,\n } : undefined,\n quests: questBase ? {\n base: questBase,\n up: questUp ?? undefined,\n down: questDown ?? undefined,\n video: questVideo ?? undefined,\n apiKey: questApiKey ?? undefined,\n moduleUrl: questModuleUrl ?? undefined,\n } : undefined,\n };\n}\n\n/**\n * Initialize a QaidFeedback instance from the current `<script>` tag's JSON\n * config block or data-* attributes. Safe to call in any environment — it\n * no-ops when there is no document or no endpoint config.\n */\nexport function autoInit(): void {\n if (typeof document === \"undefined\") return;\n\n const run = (): void => {\n // `document.currentScript` is null inside an ES module (the loader entry),\n // so fall back to locating the embed's own script tag by its data-endpoint.\n const script =\n (document.currentScript as HTMLScriptElement | null) ??\n document.querySelector<HTMLScriptElement>(\"script[data-endpoint]\");\n // Try JSON config from a separate script tag first, fall back to data-* attrs.\n const jsonConfig = parseJsonConfig();\n const dataConfig = script ? parseDataAttributes(script) : null;\n const config = jsonConfig ?? dataConfig;\n\n if (config?.endpoint) {\n new QaidFeedback(config as FeedbackConfig);\n }\n };\n\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", run);\n } else {\n run();\n }\n}\n","/**\n * Minimal ESM loader entry for progressive delivery.\n *\n * ```html\n * <script type=\"module\" src=\"…/loader.js\" data-endpoint=\"/api/feedback\"></script>\n * ```\n *\n * Ships only the core (thumbs buttons, modal, element targeting, submit).\n * Screenshot capture, the annotation editor, and the video subsystem\n * (including redaction) load on demand as separate chunks the first time each\n * is used — so a visitor who only gives a thumbs-up never downloads them.\n *\n * The full programmatic API (createVideoRecorder, openAnnotationEditor, …)\n * lives on the package's main entry (`@qaiddev/thumbs-embed`).\n */\n\nimport { QaidFeedback } from \"./embed\";\nimport { autoInit } from \"./bootstrap\";\n\nexport { QaidFeedback };\nexport type { FeedbackConfig } from \"./types\";\n\nautoInit();\n"],"names":["instanceCount","DEFAULT_BUTTON_STYLES","BUTTON_SIZES","ICON_SIZES","getLuminance","r","g","b","rs","gs","bs","c","parseColor","color","hex","fullHex","num","match","getContrastTextColor","bgColor","rgb","buildCssVars","options","positiveColor","negativeColor","markerColor","buttonSize","modalWidth","backdropOpacity","fontFamily","fontSize","btnSize","iconSize","markerTextColor","applyCssVars","el","vars","name","value","getEmbedStyles","shadowStyles","injectStyles","style","lightStyles","removeStyles","POLITE_ATTR","VISUALLY_HIDDEN_CSS","FOCUSABLE_SELECTOR","ownerDoc","root","getLiveRegion","assertive","kind","existing","region","announce","message","opts","isDisabled","isHidden","node","getFocusable","container","getDeepActiveElement","doc","active","createFocusTrap","addedTabindex","onKeydown","event","focusable","first","last","withinTrap","initial","saveFocus","restoreFocus","applyDialog","topLevelAncestor","body","parent","setBackgroundInert","except","keep","changed","child","prevInert","prevAriaHidden","entry","DEFAULT_DIMENSIONS","calculateVerticalPosition","bounds","viewportHeight","totalHeight","gap","viewportPadding","spaceAbove","spaceBelow","position","top","calculateHorizontalPosition","viewportWidth","left","calculateArrowPosition","modalLeft","minOffset","arrowWidth","arrowLeft","calculateModalPosition","dimensions","vertical","calculateTooltipPosition","anchor","tooltip","viewport","calculateModalAndArrowPosition","modal","MAX_MESSAGES","captureConsoleErrors","onError","errors","originalError","originalWarn","originalLog","capture","level","args","error","arg","DEFAULT_QUESTS_MODULE_URL","defaultImporter","url","importer","modulePromise","cachedUrl","loadQuestsModule","moduleUrl","mod","m","err","launchQuest","base","metadata","VISITOR_ID_KEY","HIDE_FEEDBACK_KEY","DEFAULT_ANNOTATION_PALETTE","isTouchPrimaryDevice","getHideKey","apiKey","isHiddenByUser","setHiddenByUser","hidden","getOrCreateVisitorId","visitorId","QaidFeedback","config","_error","n","fn","w","guarded","e","newDoc","isMobileViewport","userContainer","baseStyle","themeStyle","dirClass","offsetX","offsetY","ev","useCustomClass","btnBaseClass","tooltipText","fbWrapper","fbBtn","FEEDBACK_ICON","upWrapper","upBtn","THUMBS_UP_ICON","downWrapper","downBtn","THUMBS_DOWN_ICON","recordWrapper","recordBtn","RECORD_ICON","rec","warmVideo","anchorRect","tooltipRect","type","buttonEl","keyboard","t","rect","screenshot","host","prevPointerEvents","openAnnotationEditor","msg","captureDomScreenshot","captureScreenshot","elementBounds","payload","response","data","q","feedbackId","questId","ModalController","self","id","TargetingController","state","RecordingController","disabled","btn","findCssFromSelector","selector","parseJsonConfig","configScript","textContent","parsed","parseDataAttributes","script","endpoint","zIndex","buttonClass","skipTargeting","singleButton","feedbackMode","incognito","modalTitle","modalSubtitle","placeholder","submitButton","skipButton","positiveIcon","negativeIcon","feedbackIcon","feedbackLabel","annotate","annotationColor","screenshotQuality","screenshotMaxWidth","screenshotMaxHeight","captureVideo","redaction","hideThumbs","hideDismiss","videoMaxDuration","screenshotMethod","direction","cssSelector","questBase","questUp","questDown","questVideo","questApiKey","questModuleUrl","autoInit","run","jsonConfig","dataConfig"],"mappings":";;AASA,IAAIA,IAAgB;AAGpB,MAAMC,KAAwB,m6BAmBxBC,KAAe;AAAA,EACnB,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AACT,GAEMC,KAAa;AAAA,EACjB,OAAO;AAAA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