@qaiddev/thumbs-embed 1.11.0 → 1.12.1

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 (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +39 -13
  3. package/dist/a11y-dialog.d.ts +77 -0
  4. package/dist/a11y.d.ts +6 -65
  5. package/dist/chunks/annotate-DGyRcgPt.js +2 -0
  6. package/dist/chunks/{annotate-5zJWs-aB.js.map → annotate-DGyRcgPt.js.map} +1 -1
  7. package/dist/chunks/core-BsR7oV99.js +26 -0
  8. package/dist/chunks/core-BsR7oV99.js.map +1 -0
  9. package/dist/chunks/dom-scpOS8nl.js +2 -0
  10. package/dist/chunks/{dom-DvdtcUS8.js.map → dom-scpOS8nl.js.map} +1 -1
  11. package/dist/chunks/modal-DYxcs1Gm.js +2 -0
  12. package/dist/chunks/modal-DYxcs1Gm.js.map +1 -0
  13. package/dist/chunks/recording-BUw5-5Rf.js +2 -0
  14. package/dist/chunks/{recording-CPzxRL7f.js.map → recording-BUw5-5Rf.js.map} +1 -1
  15. package/dist/chunks/screenshot-CNe1irEz.js +2 -0
  16. package/dist/chunks/{screenshot-DYOKg2bS.js.map → screenshot-CNe1irEz.js.map} +1 -1
  17. package/dist/chunks/screenshot-dom-ZYP2w2h0.js +2 -0
  18. package/dist/chunks/{screenshot-dom-CME7tYRE.js.map → screenshot-dom-ZYP2w2h0.js.map} +1 -1
  19. package/dist/chunks/send-C26DRoYc.js +2 -0
  20. package/dist/chunks/send-C26DRoYc.js.map +1 -0
  21. package/dist/chunks/targeting-CMUEe-7C.js +6 -0
  22. package/dist/chunks/{targeting-mahtuPpo.js.map → targeting-CMUEe-7C.js.map} +1 -1
  23. package/dist/chunks/video-BSP4s2te.js +2 -0
  24. package/dist/chunks/{video-Bd_29-rK.js.map → video-BSP4s2te.js.map} +1 -1
  25. package/dist/embed.d.ts +26 -31
  26. package/dist/index.js +1495 -1390
  27. package/dist/index.js.map +1 -1
  28. package/dist/loader.d.ts +6 -4
  29. package/dist/loader.js +1 -6
  30. package/dist/loader.js.map +1 -1
  31. package/dist/modal-positioning.d.ts +0 -27
  32. package/dist/qaid.umd.cjs +14 -14
  33. package/dist/qaid.umd.cjs.map +1 -1
  34. package/dist/quest-config.d.ts +2 -0
  35. package/dist/quest-launcher.d.ts +1 -3
  36. package/dist/send.d.ts +60 -0
  37. package/dist/tooltip-positioning.d.ts +31 -0
  38. package/package.json +2 -2
  39. package/dist/chunks/annotate-5zJWs-aB.js +0 -357
  40. package/dist/chunks/core-CL1dwdaN.js +0 -1342
  41. package/dist/chunks/core-CL1dwdaN.js.map +0 -1
  42. package/dist/chunks/dom-DvdtcUS8.js +0 -17
  43. package/dist/chunks/modal-DccueVYZ.js +0 -222
  44. package/dist/chunks/modal-DccueVYZ.js.map +0 -1
  45. package/dist/chunks/recording-CPzxRL7f.js +0 -323
  46. package/dist/chunks/screenshot-DYOKg2bS.js +0 -33
  47. package/dist/chunks/screenshot-dom-CME7tYRE.js +0 -63
  48. package/dist/chunks/targeting-mahtuPpo.js +0 -298
  49. package/dist/chunks/video-Bd_29-rK.js +0 -214
@@ -0,0 +1 @@
1
+ {"version":3,"file":"core-BsR7oV99.js","sources":["../../src/icons.ts","../../src/styles.ts","../../src/a11y.ts","../../src/tooltip-positioning.ts","../../src/console-capture.ts","../../src/dom-utils.ts","../../src/quest-config.ts","../../src/embed.ts","../../src/bootstrap.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\n/** Exclamation mark for the \"message not sent\" screen. */\nexport const ERROR_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 6v8m0 4h.01\"/>\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 * 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,#6365f1);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 = \"#6365f1\",\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 // Optional: a client-side router (Astro's view transitions, any SPA that\n // swaps <head>) can remove this element out from under us, so by the time\n // a later destroy() runs there may be nothing to remove. Asserting it here\n // threw and took the rest of destroy() — and any re-mount after it — down.\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: live-region\n * announcements. This is all the startup chunk needs. The dialog helpers\n * (focus trap, save/restore, dialog semantics, background isolation) live in\n * a11y-dialog.ts, which only the lazily-loaded click path pulls in.\n *\n * Framework-free and self-contained (no CSS dependency), so it can be dropped\n * into any open shadow root.\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\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\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","/**\n * Tooltip positioning. Kept apart from modal-positioning so the startup chunk\n * carries only this, and the modal maths travels with the modal chunk.\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 * 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 * 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","/** Default ES-module URL for the quests widget, 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","import type {\n FeedbackConfig,\n ResolvedFeedbackConfig,\n FeedbackData,\n FeedbackType,\n SelectedBounds,\n EmbedState,\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\";\n// Only live-region announcements are needed at startup. The dialog helpers\n// (focus trap, inert background) load with the click path (a11y-dialog.ts).\nimport { announce } from \"./a11y\";\nimport type { DialogOptions } from \"./a11y-dialog\";\nimport { calculateTooltipPosition } from \"./tooltip-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// The send flow (screenshot, markup, POST, quest or message box) is its own\n// lazily-loaded chunk (send.ts), as is the quests loader it uses; both are\n// pre-warmed before the click (see prewarmClickPath / prewarmQuests).\nimport type { SendHost } from \"./send\";\nimport type { QuestInstance } from \"./quest-launcher\";\nimport { DEFAULT_QUESTS_MODULE_URL } from \"./quest-config\";\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 * A random v4 UUID.\n *\n * `crypto.randomUUID` exists only in secure contexts (HTTPS and localhost). On\n * a plain http:// page it is undefined, and calling it threw inside the\n * constructor, so the widget never appeared. `crypto.getRandomValues` has no\n * such restriction; `Math.random` covers a runtime with no `crypto` at all.\n * The id only groups one browser's feedback, so it needs to be unique, not\n * secret.\n */\nexport function randomId(): string {\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (c && typeof c.randomUUID === \"function\") return c.randomUUID();\n\n const bytes = new Uint8Array(16);\n if (c && typeof c.getRandomValues === \"function\") {\n c.getRandomValues(bytes);\n } else {\n for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256);\n }\n // RFC 4122 version 4 / variant 1 bits, so the result reads as a real UUID.\n bytes[6] = (bytes[6] & 0x0f) | 0x40;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\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 = randomId();\n localStorage.setItem(VISITOR_ID_KEY, visitorId);\n }\n return visitorId;\n } catch {\n // localStorage not available, generate a session-only ID\n return randomId();\n }\n}\n\n/**\n * QaidFeedback - Standalone feedback collection embed\n */\n\n/**\n * Put a feature's <style> after the base styles and any earlier feature's,\n * but before the theme's, so a theme still overrides the feature defaults.\n */\nfunction insertFeatureStyle(root: ShadowRoot, css: string): void {\n const style = document.createElement(\"style\");\n style.setAttribute(\"data-qaid-feature\", \"\");\n style.textContent = css;\n const marks = root.querySelectorAll(\"style[data-qaid-base], style[data-qaid-feature]\");\n const after = marks[marks.length - 1];\n root.insertBefore(style, after ? after.nextSibling : root.firstChild);\n}\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 /**\n * This feedback's record id, once its POST answers (null if it failed).\n * The message box and a linked quest open without waiting for it; the\n * PATCHes that need the id wait on this instead.\n */\n private feedbackIdPromise: Promise<number | null> = Promise.resolve(null);\n private questsPrewarmed = false;\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 // Preload-on-intent: warm the lazily-split feature chunks before first use.\n // The click path (send, message box, targeting) warms when the pointer or\n // focus reaches the buttons, or on idle, whichever comes first.\n private clickPathPrewarmed = false;\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 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. The helpers load with the click\n // path; `dialogClose` undoes the open dialog (trap, inert, focus).\n private dialogModule: typeof import(\"./a11y-dialog\") | null = null;\n private dialogClose: (() => 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 ?? \"#6365f1\",\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 confirmationTitle: config.text?.confirmationTitle ?? \"Thank you!\",\n confirmationMessage:\n config.text?.confirmationMessage ?? \"Your feedback has been received.\",\n confirmationClose: config.text?.confirmationClose ?? \"Close\",\n errorTitle: config.text?.errorTitle ?? \"Message not sent\",\n errorMessage:\n config.text?.errorMessage ??\n \"Something went wrong, so we did not get your message. Please try again later.\",\n },\n hideConfirmation: config.hideConfirmation ?? false,\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 ?? \"#6365f1\",\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 /** Load the dialog a11y helpers; every surface that opens a dialog awaits this first. */\n private async loadDialogA11y(): Promise<void> {\n this.dialogModule ??= await import(\"./a11y-dialog\");\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. Callers\n * reach it only after loadDialogA11y() has resolved.\n */\n private openDialogA11y(container: HTMLElement, opts: DialogOptions): void {\n this.dialogClose = this.dialogModule!.openDialog(container, opts);\n }\n\n private closeDialogA11y(): void {\n const close = this.dialogClose;\n this.dialogClose = null;\n close?.();\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 // Linked quests are warmed the same way — the quests module and each\n // quest's definition — so a click opens the quest from memory.\n // The click path (send flow, message box, targeting) warms here too, if\n // the pointer or focus has not reached the buttons first.\n this.schedulePrewarm(() => {\n this.prewarmClickPath();\n if (this.config.captureVideo && this.videoSupported()) this.prewarmVideo();\n if (this.config.captureScreenshot) this.prewarmScreenshot();\n this.prewarmQuests();\n });\n }\n\n /**\n * Warm everything a thumb click needs: the send flow, the dialog helpers,\n * the message box, and targeting (unless it is skipped). Runs once, on the\n * first of: pointer or focus entering the buttons, or the idle callback.\n */\n private prewarmClickPath(): void {\n if (this.clickPathPrewarmed) return;\n this.clickPathPrewarmed = true;\n import(\"./send\").catch(() => {});\n import(\"./a11y-dialog\").catch(() => {});\n import(\"./modal\").catch(() => {});\n if (!this.skipsTargeting()) import(\"./targeting\").catch(() => {});\n }\n\n /** \"annotate\" mode and skipTargeting both go straight to the send flow. */\n private skipsTargeting(): boolean {\n return this.config.skipTargeting || this.config.feedbackMode === \"annotate\";\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 /** Quest ids linked to any button, when quest launching is on. */\n private linkedQuestIds(): string[] {\n const q = this.config.quests;\n return q.base ? [q.up, q.down, q.video].filter((id) => id) : [];\n }\n\n /**\n * Load the quests module and fetch every linked quest's definition, so a\n * click opens the quest with no network wait. Both are best-effort: a miss\n * just means the quest loads on click, as it always did.\n */\n private prewarmQuests(): void {\n if (this.questsPrewarmed) return;\n const ids = this.linkedQuestIds();\n if (ids.length === 0) return;\n this.questsPrewarmed = true;\n const { base, moduleUrl } = this.config.quests;\n import(\"./quest-launcher\")\n .then((q) => {\n q.loadQuestsModule(moduleUrl).catch(() => {});\n for (const id of ids) void q.prefetchQuestDefinition(q.questDefinitionUrl(base, id));\n })\n .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.setAttribute(\"data-qaid-base\", \"\");\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 // The pointer or keyboard focus reaching the buttons is the moment before\n // a click: warm the click path now, unless idle got there first.\n const warmClickPath = (): void => this.prewarmClickPath();\n this.buttonsContainer.addEventListener(\"pointerenter\", warmClickPath);\n this.buttonsContainer.addEventListener(\"focusin\", warmClickPath);\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\", () => this.showTooltip(fbBtn));\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.prewarmQuests();\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.prewarmQuests();\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, plus the styles of any\n // feature that loaded before this root existed.\n const baseStyle = document.createElement(\"style\");\n baseStyle.setAttribute(\"data-qaid-base\", \"\");\n baseStyle.textContent = getEmbedStyles();\n this.overlayShadowRoot.appendChild(baseStyle);\n for (const css of this.featureStyles) insertFeatureStyle(this.overlayShadowRoot, css);\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 /** The styles of every feature chunk loaded so far, in load order. */\n private featureStyles: string[] = [];\n\n /**\n * Add a feature chunk's styles to both shadow roots. The core stylesheet\n * styles only the buttons; the message box, targeting, video and markup\n * editor bring their own CSS with their chunk, so a page that never opens\n * them never downloads it.\n */\n private addFeatureStyles(css: string): void {\n if (this.featureStyles.includes(css)) return;\n this.featureStyles.push(css);\n for (const root of [this.shadowRoot, this.overlayShadowRoot]) {\n if (root) insertFeatureStyle(root, css);\n }\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 // Usually warm already (pointer/focus on the buttons, or idle); a\n // programmatic click is the exception.\n this.prewarmClickPath();\n // \"annotate\" mode and skipTargeting both bypass element targeting and go\n // straight to the (screenshot →) modal flow.\n if (this.skipsTargeting()) {\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 before the click) 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 void 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 * Run the send flow (send.ts, loaded on demand and pre-warmed before the\n * click): screenshot, markup, POST, then a linked quest or the message box.\n * If its chunk will not load, say so and reset rather than leave the\n * visitor stuck mid-flow.\n */\n private async submitFeedback(): Promise<void> {\n try {\n const [send] = await Promise.all([import(\"./send\"), this.loadDialogA11y()]);\n await send.submitFeedback(this.makeSendHost());\n } catch (err) {\n console.error(\"Failed to send feedback:\", err);\n this.announceMsg(\"Failed to send feedback\", true);\n this.resetFeedbackUi();\n }\n }\n\n /**\n * Launch the quest linked to `type` through the send chunk. Resolves false\n * when none is linked, or when the chunk or the quest will not load.\n */\n private async tryLaunchQuest(\n type: \"up\" | \"down\" | \"video\",\n feedbackId: number | string | null,\n ): Promise<boolean> {\n try {\n const send = await import(\"./send\");\n return await send.tryLaunchQuest(this.makeSendHost(), type, feedbackId);\n } catch (err) {\n console.error(\"Failed to launch quest:\", err);\n return false;\n }\n }\n\n /** Narrow view of the embed the send flow talks back through. */\n private makeSendHost(): SendHost {\n const self = this;\n return {\n get config() {\n return self.config;\n },\n get visitorId() {\n return self.visitorId;\n },\n get feedbackData() {\n return self.feedbackData;\n },\n get selectedBounds() {\n return self.selectedBounds;\n },\n get destroyed() {\n return self.destroyed;\n },\n get overlayShadowHost() {\n return self.overlayShadowHost;\n },\n get activeQuest() {\n return self.activeQuest;\n },\n set activeQuest(quest) {\n self.activeQuest = quest;\n },\n setState: (state) => {\n self.state = state;\n },\n setFeedbackId: (id) => {\n self.feedbackIdPromise = id;\n },\n shouldCaptureViaDom: () => self.shouldCaptureViaDom(),\n ensureOverlayHost: () => self.ensureOverlayHost(),\n ensureModal: () => self.ensureModal(),\n addFeatureStyles: (css) => self.addFeatureStyles(css),\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 /**\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.feedbackIdPromise = Promise.resolve(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\n * before the click — see prewarmClickPath).\n */\n private async ensureModal(): Promise<ModalController> {\n if (!this.modal) {\n const [{ ModalController, styles }] = await Promise.all([\n import(\"./modal\"),\n this.loadDialogA11y(),\n ]);\n this.addFeatureStyles(styles);\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 whenFeedbackId: () => self.feedbackIdPromise,\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 /**\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 before the click (see prewarmClickPath).\n */\n private async ensureTargeting(): Promise<TargetingController> {\n if (!this.targeting) {\n const { TargetingController, styles } = await import(\"./targeting\");\n this.addFeatureStyles(styles);\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 // ==================== 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, styles }] = await Promise.all([\n import(\"./recording\"),\n this.loadDialogA11y(),\n ]);\n this.addFeatureStyles(styles);\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 * Say, once per attribute, that a value was ignored. The embed never throws\n * over a bad attribute: it keeps its default and tells the developer why.\n */\nfunction warnIgnored(attr: string, value: string, expected: string): void {\n console.warn(`[thumbs-embed] Ignoring ${attr}=\"${value}\": expected ${expected}.`);\n}\n\n/**\n * Split a comma-separated list, but not on commas inside parentheses, so\n * `rgb(0, 128, 0)` stays one colour.\n */\nfunction splitTopLevel(value: string): string[] {\n const parts: string[] = [];\n let depth = 0;\n let current = \"\";\n for (const ch of value) {\n if (ch === \"(\") depth++;\n if (ch === \")\") depth = Math.max(0, depth - 1);\n if (ch === \",\" && depth === 0) {\n parts.push(current.trim());\n current = \"\";\n } else {\n current += ch;\n }\n }\n parts.push(current.trim());\n return parts;\n}\n\n/**\n * A list of colours, written as a JSON array (`[\"#f00\",\"#0f0\"]`) or as a\n * comma-separated list (`#f00, rgb(0, 128, 0)`). Any empty entry, a\n * non-string entry, an empty list or malformed JSON rejects the whole value.\n */\nfunction parseColorList(attr: string, raw: string | null): string[] | undefined {\n if (raw === null) return undefined;\n const value = raw.trim();\n let list: unknown = null;\n // Anything that looks like JSON is read as JSON, so an object is rejected\n // rather than taken as a one-colour list.\n if (value.startsWith(\"[\") || value.startsWith(\"{\")) {\n try {\n list = JSON.parse(value);\n } catch {\n list = null;\n }\n } else {\n list = splitTopLevel(value);\n }\n if (\n Array.isArray(list) &&\n list.length > 0 &&\n list.every((c) => typeof c === \"string\" && c.trim() !== \"\")\n ) {\n return (list as string[]).map((c) => c.trim());\n }\n warnIgnored(attr, raw, \"a JSON array of colours or a comma-separated list\");\n return undefined;\n}\n\n/**\n * A screen-reader label. An empty one would leave an icon-only button with\n * no accessible name, so it is ignored in favour of the default.\n */\nfunction parseLabel(attr: string, raw: string | null): string | undefined {\n if (raw === null) return undefined;\n if (raw.trim() === \"\") {\n warnIgnored(attr, raw, \"a non-empty label\");\n return undefined;\n }\n return raw;\n}\n\n/**\n * Parse config from data-* attributes. Every option that can be written as\n * text has one, so the JSON config block is a choice, not a requirement.\n *\n * Exported for tests: index.ts does not re-export it, so this is not public API.\n */\nexport function 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 hideConfirmation = script.getAttribute(\"data-hide-confirmation\");\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 confirmationTitle = script.getAttribute(\"data-confirmation-title\");\n const confirmationMessage = script.getAttribute(\"data-confirmation-message\");\n const confirmationClose = script.getAttribute(\"data-confirmation-close\");\n const errorTitle = script.getAttribute(\"data-error-title\");\n const errorMessage = script.getAttribute(\"data-error-message\");\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 css = script.getAttribute(\"data-css\");\n const positiveLabel = parseLabel(\"data-positive-label\", script.getAttribute(\"data-positive-label\"));\n const negativeLabel = parseLabel(\"data-negative-label\", script.getAttribute(\"data-negative-label\"));\n const recordLabel = parseLabel(\"data-record-label\", script.getAttribute(\"data-record-label\"));\n const dismissLabel = parseLabel(\"data-dismiss-label\", script.getAttribute(\"data-dismiss-label\"));\n const annotationPalette = parseColorList(\n \"data-annotation-palette\",\n script.getAttribute(\"data-annotation-palette\")\n );\n const recordIcon = script.getAttribute(\"data-record-icon\");\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 // Inline CSS wins over a selector, as `css` wins over `cssSelector` in\n // the JSON block.\n css: 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 annotationPalette,\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 hideConfirmation: hideConfirmation === \"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 || confirmationTitle || confirmationMessage || confirmationClose || errorTitle || errorMessage || positiveLabel || negativeLabel || recordLabel || dismissLabel) ? {\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 confirmationTitle: confirmationTitle ?? undefined,\n confirmationMessage: confirmationMessage ?? undefined,\n confirmationClose: confirmationClose ?? undefined,\n errorTitle: errorTitle ?? undefined,\n errorMessage: errorMessage ?? undefined,\n positiveLabel,\n negativeLabel,\n recordLabel,\n dismissLabel,\n } : undefined,\n positiveIcon: positiveIcon ?? undefined,\n recordIcon: recordIcon ?? 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 // The JSON block wins. The attributes are only read without one, so a\n // bad attribute beside a block doesn't warn about a value never used.\n const config = parseJsonConfig() ?? (script ? parseDataAttributes(script) : null);\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"],"names":["THUMBS_UP_ICON","THUMBS_DOWN_ICON","RECORD_ICON","FEEDBACK_ICON","RECTANGLE_ICON","ARROW_ICON","PENCIL_ICON","BLUR_ICON","UNDO_ICON","DONE_ICON","ERROR_ICON","SKIP_ICON","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","ownerDoc","root","getLiveRegion","assertive","kind","existing","region","announce","message","opts","calculateTooltipPosition","anchor","tooltip","viewport","gap","top","left","MAX_MESSAGES","captureConsoleErrors","onError","errors","originalError","originalWarn","originalLog","capture","level","args","error","arg","createElement","tag","attrs","children","key","isMobileViewport","breakpoint","getElementAtPointUnderOverlay","x","y","hosts","saved","h","element","i","isEmbedElement","getElementBounds","padding","rect","DEFAULT_QUESTS_MODULE_URL","VISITOR_ID_KEY","HIDE_FEEDBACK_KEY","DEFAULT_ANNOTATION_PALETTE","isTouchPrimaryDevice","getHideKey","apiKey","isHiddenByUser","setHiddenByUser","hidden","randomId","bytes","getOrCreateVisitorId","visitorId","insertFeatureStyle","css","marks","after","QaidFeedback","config","n","container","close","_error","q","id","ids","base","moduleUrl","fn","w","guarded","e","newDoc","userContainer","baseStyle","themeStyle","dirClass","offsetX","offsetY","ev","warmClickPath","useCustomClass","btnBaseClass","tooltipText","fbWrapper","fbBtn","upWrapper","upBtn","downWrapper","downBtn","recordWrapper","recordBtn","rec","warmVideo","anchorRect","tooltipRect","type","buttonEl","keyboard","t","send","err","feedbackId","self","quest","state","ModalController","styles","TargetingController","RecordingController","disabled","btn","findCssFromSelector","selector","parseJsonConfig","configScript","textContent","parsed","warnIgnored","attr","expected","splitTopLevel","parts","depth","current","ch","parseColorList","raw","list","parseLabel","parseDataAttributes","script","endpoint","position","zIndex","buttonClass","skipTargeting","hideConfirmation","singleButton","feedbackMode","incognito","modalTitle","confirmationTitle","confirmationMessage","confirmationClose","errorTitle","errorMessage","modalSubtitle","placeholder","submitButton","skipButton","positiveIcon","negativeIcon","feedbackIcon","feedbackLabel","captureScreenshot","annotate","annotationColor","screenshotQuality","screenshotMaxWidth","screenshotMaxHeight","captureVideo","redaction","hideThumbs","hideDismiss","videoMaxDuration","screenshotMethod","direction","cssSelector","positiveLabel","negativeLabel","recordLabel","dismissLabel","annotationPalette","recordIcon","questBase","questUp","questDown","questVideo","questApiKey","questModuleUrl","autoInit","run"],"mappings":"AAIO,MAAMA,EAAiB;AAAA;AAAA,QAIjBC,EAAmB;AAAA;AAAA,QAInBC,GAAc;AAAA;AAAA,QAKdC,EAAgB;AAAA;AAAA,QAShBC,GAAiB;AAAA;AAAA,QAIjBC,GAAa;AAAA;AAAA,QAIbC,GAAc;AAAA;AAAA,QAIdC,GAAY;AAAA;AAAA,QAIZC,GAAY;AAAA;AAAA,QAIZC,GAAY;AAAA;AAAA,QAKZC,GAAa;AAAA;AAAA,QAIbC,GAAW;AAAA;AAAA,kvFC9CxB,IAAIC,EAAgB,EAGpB,MAAMC,GAAwB,k6BAmBxBC,GAAe,CACnB,MAAO,GACP,OAAQ,GACR,MAAO,EACT,EAEMC,GAAa,CACjB,MAAO,GACP,OAAQ,GACR,MAAO,EACT,EAMA,SAASC,GAAaC,EAAWC,EAAWC,EAAmB,CAC7D,KAAM,CAACC,EAAIC,EAAIC,CAAE,EAAI,CAACL,EAAGC,EAAGC,CAAC,EAAE,IAAKI,IAClCA,EAAIA,EAAI,IACDA,GAAK,OAAUA,EAAI,MAAQ,KAAK,KAAKA,EAAI,MAAS,MAAO,GAAG,EACpE,EACD,MAAO,OAASH,EAAK,MAASC,EAAK,MAASC,CAC9C,CAKA,SAASE,GAAWC,EAA2D,CAE7E,GAAIA,EAAM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,t,...i){const n=f.createElement(l);if(t){if(t.class&&(n.className=t.class),t.style&&(n.style.cssText=t.style),t.html!=null&&(n.innerHTML=t.html),t.text!=null&&(n.textContent=t.text),t.attrs)for(const e in t.attrs)n.setAttribute(e,t.attrs[e]);if(t.on)for(const e in t.on)n.addEventListener(e,t.on[e])}for(const e of i)e!=null&&e!==!1&&n.append(e);return n}export{c as h};
2
+ //# sourceMappingURL=dom-scpOS8nl.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"dom-DvdtcUS8.js","sources":["../../src/dom.ts"],"sourcesContent":["/**\n * Nano DOM factory — a purpose-built, construction-only helper for this embed.\n *\n * The embed builds all of its UI imperatively inside a Shadow DOM. That means\n * the same create → set class/style/attrs → wire events → append dance repeats\n * across every button, overlay, modal, and recording control. `h()` collapses\n * that dance into a single declarative expression.\n *\n * It is deliberately NOT a framework: no reactivity, no virtual DOM, no runtime\n * state. It only constructs. That fits what the embed actually needs (one-shot\n * DOM construction plus a few imperative updates), adds no dependency, and\n * keeps the package zero-dependency. Aliasing `document` here also lets the\n * minifier mangle the call site, which the global `document.createElement`\n * can't be.\n */\n\nconst d = document;\n\nexport interface ElProps {\n /** className */\n class?: string;\n /** Inline styles as a cssText string. */\n style?: string;\n /** innerHTML — for icons / trusted SVG markup. */\n html?: string;\n /** textContent. */\n text?: string;\n /** Attributes set via setAttribute (aria-*, data-*, type, role, …). */\n attrs?: Record<string, string>;\n /** Event listeners keyed by type. */\n on?: Record<string, (e: Event) => void>;\n}\n\ntype Child = Node | string | null | undefined | false;\n\n/**\n * Create an element, apply props, and append children. Falsy children are\n * skipped so conditional content reads cleanly (`cond && h(...)`).\n */\nexport function h<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n props?: ElProps | null,\n ...children: Child[]\n): HTMLElementTagNameMap[K] {\n const el = d.createElement(tag);\n if (props) {\n if (props.class) el.className = props.class;\n if (props.style) el.style.cssText = props.style;\n if (props.html != null) el.innerHTML = props.html;\n if (props.text != null) el.textContent = props.text;\n if (props.attrs) {\n for (const k in props.attrs) el.setAttribute(k, props.attrs[k]);\n }\n if (props.on) {\n for (const k in props.on) el.addEventListener(k, props.on[k]);\n }\n }\n for (const child of children) {\n if (child != null && child !== false) el.append(child);\n }\n return el;\n}\n"],"names":["d","h","tag","props","children","el","k","child"],"mappings":"AAgBA,MAAMA,IAAI;AAuBH,SAASC,EACdC,GACAC,MACGC,GACuB;AAC1B,QAAMC,IAAKL,EAAE,cAAcE,CAAG;AAC9B,MAAIC,GAAO;AAKT,QAJIA,EAAM,UAAOE,EAAG,YAAYF,EAAM,QAClCA,EAAM,UAAOE,EAAG,MAAM,UAAUF,EAAM,QACtCA,EAAM,QAAQ,SAAME,EAAG,YAAYF,EAAM,OACzCA,EAAM,QAAQ,SAAME,EAAG,cAAcF,EAAM,OAC3CA,EAAM;AACR,iBAAWG,KAAKH,EAAM,MAAO,CAAAE,EAAG,aAAaC,GAAGH,EAAM,MAAMG,CAAC,CAAC;AAEhE,QAAIH,EAAM;AACR,iBAAWG,KAAKH,EAAM,GAAI,CAAAE,EAAG,iBAAiBC,GAAGH,EAAM,GAAGG,CAAC,CAAC;AAAA,EAEhE;AACA,aAAWC,KAASH;AAClB,IAAIG,KAAS,QAAQA,MAAU,MAAOF,EAAG,OAAOE,CAAK;AAEvD,SAAOF;AACT;"}
1
+ {"version":3,"file":"dom-scpOS8nl.js","sources":["../../src/dom.ts"],"sourcesContent":["/**\n * Nano DOM factory — a purpose-built, construction-only helper for this embed.\n *\n * The embed builds all of its UI imperatively inside a Shadow DOM. That means\n * the same create → set class/style/attrs → wire events → append dance repeats\n * across every button, overlay, modal, and recording control. `h()` collapses\n * that dance into a single declarative expression.\n *\n * It is deliberately NOT a framework: no reactivity, no virtual DOM, no runtime\n * state. It only constructs. That fits what the embed actually needs (one-shot\n * DOM construction plus a few imperative updates), adds no dependency, and\n * keeps the package zero-dependency. Aliasing `document` here also lets the\n * minifier mangle the call site, which the global `document.createElement`\n * can't be.\n */\n\nconst d = document;\n\nexport interface ElProps {\n /** className */\n class?: string;\n /** Inline styles as a cssText string. */\n style?: string;\n /** innerHTML — for icons / trusted SVG markup. */\n html?: string;\n /** textContent. */\n text?: string;\n /** Attributes set via setAttribute (aria-*, data-*, type, role, …). */\n attrs?: Record<string, string>;\n /** Event listeners keyed by type. */\n on?: Record<string, (e: Event) => void>;\n}\n\ntype Child = Node | string | null | undefined | false;\n\n/**\n * Create an element, apply props, and append children. Falsy children are\n * skipped so conditional content reads cleanly (`cond && h(...)`).\n */\nexport function h<K extends keyof HTMLElementTagNameMap>(\n tag: K,\n props?: ElProps | null,\n ...children: Child[]\n): HTMLElementTagNameMap[K] {\n const el = d.createElement(tag);\n if (props) {\n if (props.class) el.className = props.class;\n if (props.style) el.style.cssText = props.style;\n if (props.html != null) el.innerHTML = props.html;\n if (props.text != null) el.textContent = props.text;\n if (props.attrs) {\n for (const k in props.attrs) el.setAttribute(k, props.attrs[k]);\n }\n if (props.on) {\n for (const k in props.on) el.addEventListener(k, props.on[k]);\n }\n }\n for (const child of children) {\n if (child != null && child !== false) el.append(child);\n }\n return el;\n}\n"],"names":["d","h","tag","props","children","el","k","child"],"mappings":"AAgBA,MAAMA,EAAI,SAuBH,SAASC,EACdC,EACAC,KACGC,EACuB,CAC1B,MAAMC,EAAKL,EAAE,cAAcE,CAAG,EAC9B,GAAIC,EAAO,CAKT,GAJIA,EAAM,QAAOE,EAAG,UAAYF,EAAM,OAClCA,EAAM,QAAOE,EAAG,MAAM,QAAUF,EAAM,OACtCA,EAAM,MAAQ,OAAME,EAAG,UAAYF,EAAM,MACzCA,EAAM,MAAQ,OAAME,EAAG,YAAcF,EAAM,MAC3CA,EAAM,MACR,UAAWG,KAAKH,EAAM,MAAOE,EAAG,aAAaC,EAAGH,EAAM,MAAMG,CAAC,CAAC,EAEhE,GAAIH,EAAM,GACR,UAAWG,KAAKH,EAAM,GAAIE,EAAG,iBAAiBC,EAAGH,EAAM,GAAGG,CAAC,CAAC,CAEhE,CACA,UAAWC,KAASH,EACdG,GAAS,MAAQA,IAAU,IAAOF,EAAG,OAAOE,CAAK,EAEvD,OAAOF,CACT"}
@@ -0,0 +1,2 @@
1
+ import{h as s}from"./dom-scpOS8nl.js";import{T as f,d as m,F as b,a as g,E as q}from"./core-BsR7oV99.js";const p={width:400,height:280,arrowHeight:12,gap:8,viewportPadding:16};function x(n,i,e,t,o){const a=n.y,r=i-(n.y+n.height);if(r>=e+t)return{top:n.y+n.height+t,position:"below"};if(a>=e+t)return{top:n.y-e-t,position:"above"};const l=r>a?"below":"above";let d;return l==="below"?d=Math.min(n.y+n.height+t,i-e-o):d=Math.max(o,n.y-e-t),{top:d,position:l}}function y(n,i,e,t){let a=n.x+n.width/2-e/2;return a=Math.max(t,Math.min(a,i-e-t)),a}function v(n,i,e,t=24,o=24){const r=n.clickX-i-o/2;return Math.max(t,Math.min(r,e-t-o/2))}function k(n,i,e,t=p){const o=t.height+t.arrowHeight,a=x(n,e,o,t.gap,t.viewportPadding),r=y(n,i,t.width,t.viewportPadding);return{top:a.top,left:r,position:a.position}}function w(n,i,e,t=p){const o=k(n,i,e,t),a=v(n,o.left,t.width);return{modal:o,arrow:{left:a}}}const C=".qaid-backdrop{position:fixed;inset:0;z-index:45;background:#0000004d}.qaid-modal-container{position:fixed;z-index:50;display:flex;flex-direction:column;align-items:flex-start;max-height:calc(100vh - 32px);font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:var(--qaid-font-size, 16px)}.qaid-modal-container.qaid-above{flex-direction:column-reverse}.qaid-modal-arrow{width:0;height:0;border-left:12px solid transparent;border-right:12px solid transparent;position:relative;align-self:flex-start}.qaid-modal-container.qaid-below .qaid-modal-arrow{border-bottom:12px solid light-dark(#ffffff,#1f2937)}.qaid-modal-container.qaid-above .qaid-modal-arrow{border-top:12px solid light-dark(#ffffff,#1f2937)}.qaid-modal-box{color-scheme:inherit;background:light-dark(#ffffff,#1f2937);border-radius:1rem;padding:1.5rem;box-shadow:0 25px 50px -12px light-dark(rgba(0,0,0,.25),rgba(0,0,0,.5));width:var(--qaid-modal-width, 400px);max-width:calc(100vw - 32px);max-height:calc(100vh - 60px);overflow-y:auto}.qaid-modal-header{display:flex;align-items:flex-start;gap:.75rem;margin-bottom:1rem}button.qaid-type-toggle{border:none;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s;flex-shrink:0;-webkit-appearance:none;appearance:none}button.qaid-type-toggle:hover{transform:scale(1.1)}button.qaid-type-toggle:not(.qaid-type-toggle-custom){width:2.5rem;height:2.5rem;border-radius:50%}button.qaid-type-toggle:not(.qaid-type-toggle-custom) svg{width:1.25rem;height:1.25rem}button.qaid-type-toggle.qaid-type-up{background:var(--qaid-positive);color:#fff}button.qaid-type-toggle.qaid-type-down{background:var(--qaid-negative);color:#fff}.qaid-type-static{width:2.5rem;height:2.5rem;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;background:var(--qaid-marker, #6365f1);color:var(--qaid-marker-text, white)}.qaid-type-static svg{width:1.25rem;height:1.25rem}.qaid-modal-header-text{flex:1;min-width:0}.qaid-modal-title{font-size:calc(var(--qaid-font-size, 16px) * 1.125);font-weight:700;margin:0 0 .25rem;color:light-dark(#1f2937,#f9fafb)}.qaid-modal-subtitle{color:light-dark(#6b7280,#9ca3af);margin:0;font-size:calc(var(--qaid-font-size, 16px) * .875)}.qaid-textarea{width:100%;height:6rem;padding:.75rem;border:1px solid light-dark(#d1d5db,#374151);border-radius:.5rem;font-family:inherit;font-size:var(--qaid-font-size, 16px);resize:vertical;margin-bottom:1rem;box-sizing:border-box;background:light-dark(#ffffff,#111827);color:light-dark(#1f2937,#f9fafb)}.qaid-textarea:focus{outline:none;border-color:var(--qaid-marker);box-shadow:0 0 0 3px color-mix(in srgb,var(--qaid-marker) 20%,transparent)}.qaid-btn-row{display:flex;gap:.5rem;justify-content:flex-end}button.qaid-btn-submit{padding:.5rem 1rem;background:var(--qaid-marker);color:var(--qaid-marker-text, white);border:none;border-radius:.5rem;font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;cursor:pointer;transition:background-color .2s,filter .2s;-webkit-appearance:none;appearance:none}button.qaid-btn-submit:hover{filter:brightness(.85)}button.qaid-btn-submit:focus{outline:none;box-shadow:0 0 0 3px color-mix(in srgb,var(--qaid-marker) 30%,transparent)}.qaid-bottom-sheet{position:fixed;bottom:0;left:0;right:0;z-index:50;animation:qaid-slideUpSheet .3s ease-out;font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:var(--qaid-font-size, 16px)}.qaid-bottom-sheet-content{background:light-dark(#ffffff,#1f2937);border-radius:1rem 1rem 0 0;padding:1.5rem;padding-bottom:max(1.5rem,env(safe-area-inset-bottom))}.qaid-bottom-sheet-handle{width:36px;height:4px;background:light-dark(rgba(0,0,0,.2),rgba(255,255,255,.2));border-radius:2px;margin:0 auto 1rem}@keyframes qaid-slideUpSheet{0%{transform:translateY(100%)}to{transform:translateY(0)}}.qaid-confirm{display:flex;flex-direction:column;align-items:center;text-align:center;gap:.5rem;padding:.5rem 0}.qaid-confirm-icon{display:flex;align-items:center;justify-content:center;width:44px;height:44px;border-radius:9999px;color:#fff;background:var(--qaid-success, #22c55e);margin-bottom:.25rem;animation:qaid-confirm-pop .28s cubic-bezier(.34,1.56,.64,1)}.qaid-confirm-icon .qaid-icon{width:24px;height:24px}.qaid-confirm-error .qaid-confirm-icon{background:var(--qaid-error, #dc2626)}.qaid-confirm-title{margin:0;font-size:var(--qaid-font-size, 16px);font-weight:600;color:var(--qaid-text, light-dark(#111827, #f9fafb))}.qaid-confirm-title:focus-visible{outline:2px solid var(--qaid-primary, #6365f1);outline-offset:3px;border-radius:4px}.qaid-confirm-message{margin:0;font-size:calc(var(--qaid-font-size, 16px) * .875);color:var(--qaid-text-muted, light-dark(#6b7280, #9ca3af))}.qaid-confirm .qaid-confirm-close{margin-top:.5rem;min-width:96px}@keyframes qaid-confirm-pop{0%{transform:scale(.6);opacity:0}to{transform:scale(1);opacity:1}}@media(prefers-reduced-motion:reduce){.qaid-confirm-icon{animation:none}}.qaid-textarea:focus-visible,button.qaid-btn-submit:focus-visible{outline:2px solid var(--qaid-marker, #6365f1);outline-offset:2px}@media(forced-colors:active){.qaid-textarea:focus,button.qaid-btn-submit:focus{outline:2px solid CanvasText;outline-offset:2px}}";class z{constructor(i){this.host=i}host;modalContainer=null;backdrop=null;finalized=!1;open(){this.finalized=!1;const i=this.host.ensureOverlayHost();this.backdrop=document.createElement("div"),this.backdrop.className="qaid-backdrop",this.backdrop.style.zIndex=String(this.host.config.zIndex+2),this.backdrop.style.background=`rgba(0, 0, 0, ${this.host.config.backdropOpacity})`,this.backdrop.addEventListener("click",()=>this.close()),this.host.applyVars(this.backdrop),this.host.isMobile?this.showBottomSheet():this.showPositionedModal(),i.appendChild(this.backdrop),document.addEventListener("keydown",this.host.boundKeyDown)}close(){this.host.state==="MODAL_OPEN"&&!this.finalized&&(this.finalized=!0,this.host.whenFeedbackId().then(i=>{i&&fetch(`${this.host.config.endpoint}/${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:null})}).catch(e=>console.error("Failed to finalize feedback:",e))})),this.teardown(),this.host.resetFeedbackUi()}destroy(){this.teardown()}teardown(){this.host.closeDialogA11y(),this.modalContainer&&(this.modalContainer.remove(),this.modalContainer=null),this.backdrop&&(this.backdrop.remove(),this.backdrop=null),document.removeEventListener("keydown",this.host.boundKeyDown)}showBottomSheet(){const i=this.host.ensureOverlayHost(),e=document.createElement("div");e.className="qaid-bottom-sheet",e.style.zIndex=String(this.host.config.zIndex+3),e.appendChild(s("div",{class:"qaid-bottom-sheet-content"},s("div",{class:"qaid-bottom-sheet-handle"}),this.buildModalContent())),this.host.applyVars(e),i.appendChild(e),this.modalContainer=e,this.setupModalInteractions()}showPositionedModal(){const i=this.host.ensureOverlayHost(),{modal:e,arrow:t}=w(this.host.selectedBounds,window.innerWidth,window.innerHeight,{width:this.host.config.modalWidth,height:280,arrowHeight:12,gap:8,viewportPadding:16});this.modalContainer=document.createElement("div"),this.modalContainer.className=`qaid-modal-container qaid-${e.position}`,this.modalContainer.style.top=`${e.top}px`,this.modalContainer.style.left=`${e.left}px`,this.modalContainer.style.zIndex=String(this.host.config.zIndex+3);const o=document.createElement("div");o.className="qaid-modal-arrow",o.style.left=`${t.left}px`;const a=document.createElement("div");a.className="qaid-modal-box",a.appendChild(this.buildModalContent()),this.modalContainer.appendChild(o),this.modalContainer.appendChild(a),this.host.applyVars(this.modalContainer),i.appendChild(this.modalContainer),this.setupModalInteractions()}buildModalContent(){const{config:i,uid:e}=this.host,t=i.text,o=this.host.feedbackData.feedbackType,a=o==="up",r=i.positiveIcon||f,l=i.negativeIcon||m,d=i.buttonClass?`qaid-type-toggle qaid-type-toggle-custom ${i.buttonClass} ${a?"qaid-btn-up":"qaid-btn-down"}`:`qaid-type-toggle ${a?"qaid-type-up":"qaid-type-down"}`,c=a?"Feedback type: positive":"Feedback type: negative",u=o==="neutral"?s("span",{class:"qaid-type-static",html:i.feedbackIcon||b,attrs:{"aria-hidden":"true"}}):s("button",{class:d,html:a?r:l,attrs:{type:"button",title:"Click to switch","aria-pressed":String(a),"aria-label":c}}),h=document.createDocumentFragment();return h.append(s("div",{class:"qaid-modal-header"},u,s("div",{class:"qaid-modal-header-text"},s("h3",{class:"qaid-modal-title",text:t.modalTitle,attrs:{id:`qaid-modal-title-${e}`}}),s("p",{class:"qaid-modal-subtitle",text:t.modalSubtitle,attrs:{id:`qaid-modal-subtitle-${e}`}}))),s("textarea",{class:"qaid-textarea",attrs:{"aria-label":t.modalSubtitle,placeholder:t.placeholder}}),s("div",{class:"qaid-btn-row"},s("button",{class:"qaid-btn-submit",text:t.skipButton,attrs:{type:"button"}}))),h}setupModalInteractions(){this.host.openDialogA11y(this.modalContainer,{labelledbyId:`qaid-modal-title-${this.host.uid}`,describedbyId:`qaid-modal-subtitle-${this.host.uid}`});const i=this.modalContainer.querySelector(".qaid-textarea"),e=this.modalContainer.querySelector(".qaid-btn-submit");i&&(setTimeout(()=>i.focus(),100),i.addEventListener("input",()=>{e&&(e.textContent=i.value.trim()?this.host.config.text.submitButton:this.host.config.text.skipButton)})),e&&e.addEventListener("click",()=>{const o=i?.value.trim()||null;this.submitMessage(o)});const t=this.modalContainer.querySelector(".qaid-type-toggle");t&&t.addEventListener("click",()=>{const o=this.host.feedbackData.feedbackType==="up"?"down":"up";this.host.feedbackData.feedbackType=o,this.host.config.buttonClass?(t.classList.toggle("qaid-btn-up",o==="up"),t.classList.toggle("qaid-btn-down",o==="down")):(t.classList.toggle("qaid-type-up",o==="up"),t.classList.toggle("qaid-type-down",o==="down"));const a=this.host.config.positiveIcon||f,r=this.host.config.negativeIcon||m;t.innerHTML=o==="up"?a:r;const l=o==="up"?"Feedback type: positive":"Feedback type: negative";t.setAttribute("aria-pressed",String(o==="up")),t.setAttribute("aria-label",l),this.host.announceMsg(l),this.host.whenFeedbackId().then(d=>{d&&fetch(`${this.host.config.endpoint}/${d}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedbackType:o})}).catch(c=>console.error("Failed to update feedback type:",c))})})}async submitMessage(i){let e=null;this.finalized=!0;const t=await this.host.whenFeedbackId();if(t)try{const o=await fetch(`${this.host.config.endpoint}/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:i})});e=o.ok,o.ok||console.error("Failed to submit feedback message: HTTP",o.status)}catch(o){console.error("Failed to submit feedback message:",o),e=!1}if(e===!1){this.showResult(!1);return}if(e&&!this.host.config.hideConfirmation){this.showResult(!0);return}this.close()}showResult(i){const e=this.modalContainer?.querySelector(".qaid-modal-box")??this.modalContainer?.querySelector(".qaid-bottom-sheet-content")??this.modalContainer;if(!e){this.close();return}const t=this.host.config.text,o=i?t.confirmationTitle:t.errorTitle,a=i?t.confirmationMessage:t.errorMessage,r=s("h3",{class:"qaid-confirm-title",text:o,attrs:{id:`qaid-confirm-title-${this.host.uid}`,tabindex:"-1"}});e.textContent="",e.appendChild(s("div",{class:i?"qaid-confirm":"qaid-confirm qaid-confirm-error"},s("span",{class:"qaid-confirm-icon",html:i?g:q,attrs:{"aria-hidden":"true"}}),r,s("p",{class:"qaid-confirm-message",text:a}),s("button",{class:"qaid-btn-submit qaid-confirm-close",text:t.confirmationClose,attrs:{type:"button"},on:{click:()=>this.close()}}))),requestAnimationFrame(()=>r.focus()),this.host.announceMsg(`${o} ${a}`,!0)}}const I=C;export{z as ModalController,I as styles};
2
+ //# sourceMappingURL=modal-DYxcs1Gm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modal-DYxcs1Gm.js","sources":["../../src/modal-positioning.ts","../../src/modal.ts"],"sourcesContent":["/**\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\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 * Feedback message modal — extracted from embed.ts into its own lazily-loaded\n * chunk. It's fetched the first time a message modal opens (after feedback is\n * submitted), and pre-warmed while the user is targeting an element.\n *\n * The controller owns the modal/backdrop DOM and the message PATCH flow, and\n * talks back to the embed through the narrow `ModalHost` interface.\n */\n\nimport { calculateModalAndArrowPosition } from \"./modal-positioning\";\nimport { h } from \"./dom\";\nimport featureStyles from \"./styles-modal.css?inline\";\nimport {\n THUMBS_UP_ICON,\n THUMBS_DOWN_ICON,\n FEEDBACK_ICON,\n DONE_ICON,\n ERROR_ICON,\n} from \"./icons\";\nimport type {\n ResolvedFeedbackConfig,\n EmbedState,\n FeedbackData,\n SelectedBounds,\n} from \"./types\";\n\n/** The slice of the embed the modal needs. */\nexport interface ModalHost {\n readonly config: ResolvedFeedbackConfig;\n readonly uid: string;\n readonly isMobile: boolean;\n readonly state: EmbedState;\n readonly boundKeyDown: (e: KeyboardEvent) => void;\n /** Live references — the toggle mutates feedbackType; positioning reads bounds. */\n readonly feedbackData: FeedbackData;\n readonly selectedBounds: SelectedBounds;\n /**\n * The id of this feedback's record. The modal opens while the POST that\n * creates it is still in flight, so every PATCH waits on this; null when\n * the POST failed.\n */\n whenFeedbackId(): Promise<number | null>;\n ensureOverlayHost(): ShadowRoot;\n applyVars(el: HTMLElement): void;\n announceMsg(message: string, assertive?: boolean): void;\n openDialogA11y(\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string; label?: string }\n ): void;\n closeDialogA11y(): void;\n resetFeedbackUi(): void;\n}\n\nexport class ModalController {\n private modalContainer: HTMLDivElement | null = null;\n private backdrop: HTMLDivElement | null = null;\n /** Set once the message is sent, so closing does not PATCH over it. */\n private finalized = false;\n\n constructor(private host: ModalHost) {}\n\n open(): void {\n this.finalized = false;\n const root = this.host.ensureOverlayHost();\n\n // Create backdrop\n this.backdrop = document.createElement(\"div\");\n this.backdrop.className = \"qaid-backdrop\";\n this.backdrop.style.zIndex = String(this.host.config.zIndex + 2);\n this.backdrop.style.background = `rgba(0, 0, 0, ${this.host.config.backdropOpacity})`;\n this.backdrop.addEventListener(\"click\", () => this.close());\n this.host.applyVars(this.backdrop);\n\n if (this.host.isMobile) {\n this.showBottomSheet();\n } else {\n this.showPositionedModal();\n }\n\n root.appendChild(this.backdrop);\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n /** Escape / external close. Runs the finalize-PATCH + teardown. */\n close(): void {\n // If the modal is open and we're closing without submitting, still finalize.\n // Taken before the reset below, which starts the next feedback afresh.\n if (this.host.state === \"MODAL_OPEN\" && !this.finalized) {\n this.finalized = true;\n void this.host.whenFeedbackId().then((id) => {\n if (!id) return;\n fetch(`${this.host.config.endpoint}/${id}`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ message: null }),\n }).catch((err) => console.error(\"Failed to finalize feedback:\", err));\n });\n }\n\n this.teardown();\n this.host.resetFeedbackUi();\n }\n\n /** DOM/listener teardown only — no PATCH, no state reset (for embed destroy). */\n destroy(): void {\n this.teardown();\n }\n\n private teardown(): void {\n this.host.closeDialogA11y();\n if (this.modalContainer) {\n this.modalContainer.remove();\n this.modalContainer = null;\n }\n if (this.backdrop) {\n this.backdrop.remove();\n this.backdrop = null;\n }\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n private showBottomSheet(): void {\n const root = this.host.ensureOverlayHost();\n\n const sheet = document.createElement(\"div\");\n sheet.className = \"qaid-bottom-sheet\";\n sheet.style.zIndex = String(this.host.config.zIndex + 3);\n\n sheet.appendChild(\n h(\n \"div\",\n { class: \"qaid-bottom-sheet-content\" },\n h(\"div\", { class: \"qaid-bottom-sheet-handle\" }),\n this.buildModalContent()\n )\n );\n\n this.host.applyVars(sheet);\n root.appendChild(sheet);\n this.modalContainer = sheet;\n\n this.setupModalInteractions();\n }\n\n private showPositionedModal(): void {\n const root = this.host.ensureOverlayHost();\n\n const { modal, arrow } = calculateModalAndArrowPosition(\n this.host.selectedBounds,\n window.innerWidth,\n window.innerHeight,\n {\n width: this.host.config.modalWidth,\n height: 280,\n arrowHeight: 12,\n gap: 8,\n viewportPadding: 16,\n }\n );\n\n this.modalContainer = document.createElement(\"div\");\n this.modalContainer.className = `qaid-modal-container qaid-${modal.position}`;\n this.modalContainer.style.top = `${modal.top}px`;\n this.modalContainer.style.left = `${modal.left}px`;\n this.modalContainer.style.zIndex = String(this.host.config.zIndex + 3);\n\n const arrowEl = document.createElement(\"div\");\n arrowEl.className = \"qaid-modal-arrow\";\n arrowEl.style.left = `${arrow.left}px`;\n\n const box = document.createElement(\"div\");\n box.className = \"qaid-modal-box\";\n box.appendChild(this.buildModalContent());\n\n this.modalContainer.appendChild(arrowEl);\n this.modalContainer.appendChild(box);\n this.host.applyVars(this.modalContainer);\n root.appendChild(this.modalContainer);\n\n this.setupModalInteractions();\n }\n\n /**\n * The modal's contents, built as nodes rather than an HTML string.\n *\n * Every piece of copy (title, subtitle, placeholder, button) goes in as\n * text, so a `<`, `&` or `\"` in a translation shows as written instead of\n * being parsed as markup or cutting an attribute short. Only the icons are\n * markup, because they are documented as SVG/HTML strings.\n */\n private buildModalContent(): DocumentFragment {\n const { config, uid } = this.host;\n const text = config.text;\n const type = this.host.feedbackData.feedbackType;\n const isUp = type === \"up\";\n const positiveIcon = config.positiveIcon || THUMBS_UP_ICON;\n const negativeIcon = config.negativeIcon || THUMBS_DOWN_ICON;\n const toggleClass = config.buttonClass\n ? `qaid-type-toggle qaid-type-toggle-custom ${config.buttonClass} ${isUp ? \"qaid-btn-up\" : \"qaid-btn-down\"}`\n : `qaid-type-toggle ${isUp ? \"qaid-type-up\" : \"qaid-type-down\"}`;\n const toggleLabel = isUp ? \"Feedback type: positive\" : \"Feedback type: negative\";\n // Neutral (single-button) feedback has no sentiment to toggle — show a\n // static feedback icon in place of the up/down toggle.\n const header =\n type === \"neutral\"\n ? h(\"span\", {\n class: \"qaid-type-static\",\n html: config.feedbackIcon || FEEDBACK_ICON,\n attrs: { \"aria-hidden\": \"true\" },\n })\n : h(\"button\", {\n class: toggleClass,\n html: isUp ? positiveIcon : negativeIcon,\n attrs: {\n type: \"button\",\n title: \"Click to switch\",\n \"aria-pressed\": String(isUp),\n \"aria-label\": toggleLabel,\n },\n });\n\n const fragment = document.createDocumentFragment();\n fragment.append(\n h(\n \"div\",\n { class: \"qaid-modal-header\" },\n header,\n h(\n \"div\",\n { class: \"qaid-modal-header-text\" },\n h(\"h3\", {\n class: \"qaid-modal-title\",\n text: text.modalTitle,\n attrs: { id: `qaid-modal-title-${uid}` },\n }),\n h(\"p\", {\n class: \"qaid-modal-subtitle\",\n text: text.modalSubtitle,\n attrs: { id: `qaid-modal-subtitle-${uid}` },\n })\n )\n ),\n h(\"textarea\", {\n class: \"qaid-textarea\",\n attrs: { \"aria-label\": text.modalSubtitle, placeholder: text.placeholder },\n }),\n h(\n \"div\",\n { class: \"qaid-btn-row\" },\n h(\"button\", {\n class: \"qaid-btn-submit\",\n text: text.skipButton,\n attrs: { type: \"button\" },\n })\n )\n );\n return fragment;\n }\n\n private setupModalInteractions(): void {\n // Dialog semantics + focus trap + background inert\n this.host.openDialogA11y(this.modalContainer!, {\n labelledbyId: `qaid-modal-title-${this.host.uid}`,\n describedbyId: `qaid-modal-subtitle-${this.host.uid}`,\n });\n\n const textarea =\n this.modalContainer!.querySelector<HTMLTextAreaElement>(\".qaid-textarea\");\n const submitBtn =\n this.modalContainer!.querySelector<HTMLButtonElement>(\".qaid-btn-submit\");\n if (textarea) {\n // Auto-focus\n setTimeout(() => textarea.focus(), 100);\n\n // Update button text based on content\n textarea.addEventListener(\"input\", () => {\n if (submitBtn) {\n submitBtn.textContent = textarea.value.trim()\n ? this.host.config.text.submitButton\n : this.host.config.text.skipButton;\n }\n });\n }\n\n if (submitBtn) {\n submitBtn.addEventListener(\"click\", () => {\n const message = textarea?.value.trim() || null;\n this.submitMessage(message);\n });\n }\n\n // Handle feedback type toggle\n const typeToggle = this.modalContainer!.querySelector<HTMLButtonElement>(\".qaid-type-toggle\");\n if (typeToggle) {\n typeToggle.addEventListener(\"click\", () => {\n const newType = this.host.feedbackData.feedbackType === \"up\" ? \"down\" : \"up\";\n this.host.feedbackData.feedbackType = newType;\n\n // Update UI — use different classes depending on custom buttonClass\n if (this.host.config.buttonClass) {\n typeToggle.classList.toggle(\"qaid-btn-up\", newType === \"up\");\n typeToggle.classList.toggle(\"qaid-btn-down\", newType === \"down\");\n } else {\n typeToggle.classList.toggle(\"qaid-type-up\", newType === \"up\");\n typeToggle.classList.toggle(\"qaid-type-down\", newType === \"down\");\n }\n const positiveIcon = this.host.config.positiveIcon || THUMBS_UP_ICON;\n const negativeIcon = this.host.config.negativeIcon || THUMBS_DOWN_ICON;\n typeToggle.innerHTML = newType === \"up\" ? positiveIcon : negativeIcon;\n\n // Update accessible state and announce the change\n const toggleLabel = newType === \"up\" ? \"Feedback type: positive\" : \"Feedback type: negative\";\n typeToggle.setAttribute(\"aria-pressed\", String(newType === \"up\"));\n typeToggle.setAttribute(\"aria-label\", toggleLabel);\n this.host.announceMsg(toggleLabel);\n\n // Update feedback on server, once the record exists\n void this.host.whenFeedbackId().then((id) => {\n if (!id) return;\n fetch(`${this.host.config.endpoint}/${id}`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ feedbackType: newType }),\n }).catch((err) => console.error(\"Failed to update feedback type:\", err));\n });\n });\n }\n }\n\n private async submitMessage(message: string | null): Promise<void> {\n // null = nothing was attempted (the initial POST never produced an id);\n // otherwise whether the server accepted the PATCH.\n let delivered: boolean | null = null;\n\n // Before the await: an Escape while the POST is still out must not send\n // a second, empty PATCH over this message.\n this.finalized = true;\n const id = await this.host.whenFeedbackId();\n if (id) {\n try {\n const response = await fetch(`${this.host.config.endpoint}/${id}`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ message }),\n });\n // fetch resolves on any HTTP reply. A 4xx/5xx means the server\n // refused or lost the message, so it is not a success.\n delivered = response.ok;\n if (!response.ok) {\n console.error(\"Failed to submit feedback message: HTTP\", response.status);\n }\n } catch (error) {\n console.error(\"Failed to submit feedback message:\", error);\n delivered = false;\n }\n }\n\n // The message was lost. Closing quietly reads as success, so say so —\n // even with hideConfirmation, which only opts out of the success screen.\n if (delivered === false) {\n this.showResult(false);\n return;\n }\n\n // A submit that simply removes the modal reads as a failure — nothing\n // acknowledges that the message was sent. Show a success screen unless the\n // host opted out.\n //\n // With no feedbackId the initial POST never landed and there was nothing\n // to send the message to; that path closes exactly as it did before.\n if (delivered && !this.host.config.hideConfirmation) {\n this.showResult(true);\n return;\n }\n this.close();\n }\n\n /**\n * Replace the modal's contents with the outcome: a checkmark and a short\n * acknowledgement, or an error mark and a \"not sent\" notice.\n *\n * The submit button that had focus is gone by this point, so focus moves to\n * the heading (WCAG 2.4.3) and the message is announced. Mirrors the quests\n * embed's thank-you screen so the two products confirm the same way. Copy\n * goes in as text, never markup.\n */\n private showResult(delivered: boolean): void {\n const box = this.modalContainer?.querySelector(\".qaid-modal-box\")\n ?? this.modalContainer?.querySelector(\".qaid-bottom-sheet-content\")\n ?? this.modalContainer;\n\n if (!box) {\n // Nothing to draw into — never strand the user with an open modal.\n this.close();\n return;\n }\n\n const text = this.host.config.text;\n const heading = delivered ? text.confirmationTitle : text.errorTitle;\n const body = delivered ? text.confirmationMessage : text.errorMessage;\n\n const title = h(\"h3\", {\n class: \"qaid-confirm-title\",\n text: heading,\n attrs: { id: `qaid-confirm-title-${this.host.uid}`, tabindex: \"-1\" },\n });\n\n box.textContent = \"\";\n box.appendChild(\n h(\n \"div\",\n { class: delivered ? \"qaid-confirm\" : \"qaid-confirm qaid-confirm-error\" },\n h(\"span\", {\n class: \"qaid-confirm-icon\",\n html: delivered ? DONE_ICON : ERROR_ICON,\n attrs: { \"aria-hidden\": \"true\" },\n }),\n title,\n h(\"p\", { class: \"qaid-confirm-message\", text: body }),\n h(\"button\", {\n class: \"qaid-btn-submit qaid-confirm-close\",\n text: text.confirmationClose,\n attrs: { type: \"button\" },\n on: { click: () => this.close() },\n })\n )\n );\n\n // Focus after paint, matching the quests embed.\n requestAnimationFrame(() => title.focus());\n this.host.announceMsg(`${heading} ${body}`, true);\n }\n}\n\n/** This feature's shadow-DOM styles; the embed adds them when it loads the chunk. */\nexport const styles = featureStyles;\n"],"names":["DEFAULT_DIMENSIONS","calculateVerticalPosition","bounds","viewportHeight","totalHeight","gap","viewportPadding","spaceAbove","spaceBelow","position","top","calculateHorizontalPosition","viewportWidth","modalWidth","left","calculateArrowPosition","modalLeft","minOffset","arrowWidth","arrowLeft","calculateModalPosition","dimensions","vertical","calculateModalAndArrowPosition","modal","ModalController","host","root","id","err","sheet","h","arrow","arrowEl","box","config","uid","text","type","isUp","positiveIcon","THUMBS_UP_ICON","negativeIcon","THUMBS_DOWN_ICON","toggleClass","toggleLabel","header","FEEDBACK_ICON","fragment","textarea","submitBtn","message","typeToggle","newType","delivered","response","error","heading","body","title","DONE_ICON","ERROR_ICON","styles","featureStyles"],"mappings":"yGAwBA,MAAMA,EAAsC,CAC1C,MAAO,IACP,OAAQ,IACR,YAAa,GACb,IAAK,EACL,gBAAiB,EACnB,EAKO,SAASC,EACdC,EACAC,EACAC,EACAC,EACAC,EAC8C,CAC9C,MAAMC,EAAaL,EAAO,EACpBM,EAAaL,GAAkBD,EAAO,EAAIA,EAAO,QAGvD,GAAIM,GAAcJ,EAAcC,EAC9B,MAAO,CACL,IAAKH,EAAO,EAAIA,EAAO,OAASG,EAChC,SAAU,OAAA,EAKd,GAAIE,GAAcH,EAAcC,EAC9B,MAAO,CACL,IAAKH,EAAO,EAAIE,EAAcC,EAC9B,SAAU,OAAA,EAKd,MAAMI,EAAWD,EAAaD,EAAa,QAAU,QACrD,IAAIG,EAEJ,OAAID,IAAa,QACfC,EAAM,KAAK,IACTR,EAAO,EAAIA,EAAO,OA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AEDvB,EAAI,YAAc,GAClBA,EAAI,YACFH,EACE,MACA,CAAE,MAAOuB,EAAY,eAAiB,iCAAA,EACtCvB,EAAE,OAAQ,CACR,MAAO,oBACP,KAAMuB,EAAYM,EAAYC,EAC9B,MAAO,CAAE,cAAe,MAAA,CAAO,CAChC,EACDF,EACA5B,EAAE,IAAK,CAAE,MAAO,uBAAwB,KAAM2B,EAAM,EACpD3B,EAAE,SAAU,CACV,MAAO,qCACP,KAAMM,EAAK,kBACX,MAAO,CAAE,KAAM,QAAA,EACf,GAAI,CAAE,MAAO,IAAM,KAAK,OAAM,CAAE,CACjC,CAAA,CACH,EAIF,sBAAsB,IAAMsB,EAAM,OAAO,EACzC,KAAK,KAAK,YAAY,GAAGF,CAAO,IAAIC,CAAI,GAAI,EAAI,CAClD,CACF,CAGO,MAAMI,EAASC"}
@@ -0,0 +1,2 @@
1
+ import{h as n}from"./dom-scpOS8nl.js";import{i as g}from"./core-BsR7oV99.js";const v=".qaid-recording-indicator{position:fixed;pointer-events:auto;top:12px;left:50%;transform:translate(-50%);display:flex;align-items:center;gap:.5rem;padding:.5rem 1rem;background:light-dark(#1f2937,#374151);color:#fff;border-radius:9999px;font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;box-shadow:0 4px 12px #0000004d;z-index:99999;animation:qaid-slideDown .2s ease-out}.qaid-recording-dot{width:10px;height:10px;background:#dc2626;border-radius:50%;animation:qaid-dotPulse 1.5s ease-in-out infinite}@keyframes qaid-dotPulse{0%,to{opacity:1}50%{opacity:.3}}.qaid-recording-time{font-variant-numeric:tabular-nums;min-width:2.5rem;text-align:center}button.qaid-recording-stop{padding:.25rem .75rem;background:#dc2626;color:#fff;border:none;border-radius:9999px;font-size:calc(var(--qaid-font-size, 16px) * .75);font-weight:600;cursor:pointer;transition:background-color .2s;-webkit-appearance:none;appearance:none}button.qaid-recording-stop:hover{background:#b91c1c}.qaid-video-preview{position:fixed;inset:0 0 auto;height:100vh;height:100dvh;display:flex;align-items:center;justify-content:center;padding:16px;padding-top:max(16px,env(safe-area-inset-top));padding-bottom:max(16px,env(safe-area-inset-bottom));box-sizing:border-box;background:#0009;z-index:99998;animation:qaid-fadeIn .2s ease-out}@keyframes qaid-fadeIn{0%{opacity:0}to{opacity:1}}.qaid-video-preview-box{color-scheme:inherit;background:light-dark(#ffffff,#1f2937);border-radius:1rem;padding:1.5rem;box-shadow:0 25px 50px -12px #00000080;width:560px;max-width:100%;max-height:100%;overflow-y:auto;font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:var(--qaid-font-size, 16px)}.qaid-video-preview-box h3{font-size:calc(var(--qaid-font-size, 16px) * 1.125);font-weight:700;margin:0 0 1rem;color:light-dark(#1f2937,#f9fafb)}.qaid-video-preview-box video{width:100%;max-height:50vh;max-height:50dvh;object-fit:contain;border-radius:.5rem;background:#000;margin-bottom:1rem}.qaid-video-preview-box textarea{width:100%;height:4rem;padding:.75rem;border:1px solid light-dark(#d1d5db,#374151);border-radius:.5rem;font-family:inherit;font-size:calc(var(--qaid-font-size, 16px) * .875);resize:vertical;margin-bottom:1rem;box-sizing:border-box;background:light-dark(#ffffff,#111827);color:light-dark(#1f2937,#f9fafb)}.qaid-video-preview-box textarea:focus{outline:none;border-color:var(--qaid-marker);box-shadow:0 0 0 3px color-mix(in srgb,var(--qaid-marker) 20%,transparent)}.qaid-video-error{margin:0 0 .75rem;font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;color:light-dark(#b91c1c,#fca5a5)}.qaid-video-preview-actions{display:flex;gap:.5rem;justify-content:flex-end}button.qaid-video-btn{padding:.5rem 1rem;border:none;border-radius:.5rem;font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;cursor:pointer;transition:background-color .2s,filter .2s;-webkit-appearance:none;appearance:none}button.qaid-video-btn-cancel{background:light-dark(#f3f4f6,#374151);color:light-dark(#374151,#d1d5db)}button.qaid-video-btn-cancel:hover{background:light-dark(#e5e7eb,#4b5563)}button.qaid-video-btn-rerecord{background:light-dark(#fef3c7,#78350f);color:light-dark(#92400e,#fde68a)}button.qaid-video-btn-rerecord:hover{filter:brightness(.9)}button.qaid-video-btn-send{background:var(--qaid-marker);color:var(--qaid-marker-text, white)}button.qaid-video-btn-send:hover{filter:brightness(.85)}button.qaid-video-btn-send:disabled{opacity:.5;cursor:not-allowed}.qaid-video-sending{display:flex;align-items:center;gap:.5rem;font-size:calc(var(--qaid-font-size, 16px) * .875);color:light-dark(#6b7280,#9ca3af)}@keyframes qaid-slideDown{0%{transform:translateY(-100%)}to{transform:translateY(0)}}button.qaid-recording-stop{min-height:24px}.qaid-video-preview-box textarea:focus-visible{outline:2px solid var(--qaid-marker, #6365f1);outline-offset:2px}@media(forced-colors:active){.qaid-video-preview-box textarea:focus{outline:2px solid CanvasText;outline-offset:2px}}",b=20,u=4096;function l(d){const e=typeof d=="string"?d:JSON.stringify(d);return e.length>u?e.slice(0,u)+"\u2026[truncated]":e}function p(d,e){d.length>=b&&d.shift(),d.push(e)}async function m(d){try{const e=await d.clone().text();return l(e)}catch{return}}function x(){const d=[],e=window.fetch;window.fetch=async function(o,r){const s=typeof o=="string"?o:o instanceof URL?o.toString():o.url,a=r?.method??(typeof o=="object"&&"method"in o?o.method:"GET");let c;r?.body&&(c=l(r.body));const h=await e.apply(window,[o,r]);if(h.status>=400){const f=await m(h);p(d,{url:s,method:a.toUpperCase(),status:h.status,statusText:h.statusText,requestBody:c,responseBody:f,timestamp:Date.now()})}return h};const i=XMLHttpRequest.prototype.open,t=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(o,r,...s){return this._qaid_method=o,this._qaid_url=typeof r=="string"?r:r.toString(),i.apply(this,[o,r,...s])},XMLHttpRequest.prototype.send=function(o){const r=this,s=o?l(o):void 0;return r.addEventListener("load",function(){r.status>=400&&p(d,{url:r._qaid_url,method:r._qaid_method.toUpperCase(),status:r.status,statusText:r.statusText,requestBody:s,responseBody:l(r.responseText),timestamp:Date.now()})}),t.apply(this,[o])},{errors:d,restore:()=>{window.fetch=e,XMLHttpRequest.prototype.open=i,XMLHttpRequest.prototype.send=t}}}class w{constructor(e){this.host=e}host;videoRecorder=null;networkCapture=null;recordedBlob=null;recordingIndicator=null;videoPreview=null;isRecording=!1;isSendingVideo=!1;redactPicks=[];redactPickerRoot=null;redactRafId=0;boundRedactClick=e=>this.handleRedactPickClick(e);handleEscape(){return this.isRecording?(this.stopRecording(),!0):this.videoPreview?(this.cancelRecordingPreview(),!0):this.redactPickerRoot?(this.finishRedactionPicking(!1),!0):!1}destroy(){this.redactRafId&&cancelAnimationFrame(this.redactRafId),this.redactRafId=0,document.removeEventListener("click",this.boundRedactClick,!0),this.redactPickerRoot&&(this.redactPickerRoot.remove(),this.redactPickerRoot=null),this.redactPicks=[],this.cleanupRecording(),this.removeVideoPreview()}async startRecording(e=[]){if(!(this.isRecording||this.host.state!=="IDLE"))try{this.networkCapture=x();const{createVideoRecorder:i}=await import("./video-BSP4s2te.js");this.videoRecorder=i({maxDuration:this.host.config.videoOptions.maxDuration,redactionElements:e}),this.videoRecorder.onTick(t=>{this.updateRecordingTimer(t)}),this.videoRecorder.onStop(t=>{this.isRecording&&(this.recordedBlob=t,this.isRecording=!1,this.host.announceMsg("Recording stopped"),this.removeRecordingIndicator(),document.removeEventListener("keydown",this.host.boundKeyDown),this.host.setButtonsDisabled(!1),t&&t.size>0?this.showRecordingPreview():this.cleanupRecording())}),await this.videoRecorder.start(),this.isRecording=!0,this.host.announceMsg("Recording started"),this.host.setButtonsDisabled(!0),this.showRecordingIndicator(),document.addEventListener("keydown",this.host.boundKeyDown)}catch(i){i instanceof Error&&/current tab|cannot blur/i.test(i.message)&&this.host.announceMsg(i.message),this.cleanupRecording()}}async stopRecording(){try{this.recordedBlob=await this.videoRecorder.stop()}catch{this.recordedBlob=null}this.isRecording=!1,this.host.announceMsg("Recording stopped"),this.removeRecordingIndicator(),document.removeEventListener("keydown",this.host.boundKeyDown),this.recordedBlob&&this.recordedBlob.size>0?this.showRecordingPreview():this.cleanupRecording()}startPicking(){if(this.isRecording||this.host.state!=="IDLE")return;this.host.setState("REDACT_PICKING"),this.redactPicks=[];const e=this.host.ensureOverlayHost(),i=n("div",{style:"position:absolute;inset:0;"}),t=n("div",{class:"qaid-redact-picker",style:"position:fixed;inset:0;pointer-events:none;"},i,n("div",{style:"position:fixed;left:50%;bottom:24px;transform:translateX(-50%);display:flex;gap:12px;align-items:center;pointer-events:auto;background:#0b1220;color:#fff;border:1px solid #ff6b6b;border-radius:9999px;padding:10px 16px;font:600 13px system-ui,sans-serif;box-shadow:0 8px 30px rgba(0,0,0,.5);"},n("span",{text:"Click sensitive areas to blur",attrs:{"data-qaid-redact-label":""}}),n("button",{text:"Start recording",attrs:{type:"button"},style:"cursor:pointer;border:0;border-radius:9999px;padding:8px 14px;background:#ff6b6b;color:#0b1220;font:inherit;",on:{click:()=>this.finishRedactionPicking(!0)}}),n("button",{text:"Cancel",attrs:{type:"button"},style:"cursor:pointer;border:0;background:transparent;color:#9fb3c8;font:inherit;",on:{click:()=>this.finishRedactionPicking(!1)}})));e.appendChild(t),this.redactPickerRoot=t;const o=()=>{this.renderRedactPicks(i),this.redactRafId=requestAnimationFrame(o)};o(),document.addEventListener("click",this.boundRedactClick,!0),document.addEventListener("keydown",this.host.boundKeyDown),this.host.announceMsg("Click sensitive areas to blur, then start recording")}handleRedactPickClick(e){const i=e.target instanceof Element?e.target:null;if(!i||g(i)||this.redactPickerRoot?.contains(i))return;e.preventDefault(),e.stopPropagation();const t=this.redactPicks.indexOf(i);t>=0?this.redactPicks.splice(t,1):this.redactPicks.push(i);const o=this.redactPickerRoot?.querySelector("[data-qaid-redact-label]");if(o){const r=this.redactPicks.length;o.textContent=r===0?"Click sensitive areas to blur":`${r} area${r===1?"":"s"} will be blurred`}}renderRedactPicks(e){e.textContent="";for(const i of this.redactPicks){const t=i.getBoundingClientRect();t.width<=0||t.height<=0||e.appendChild(n("div",{style:`position:fixed;left:${t.left}px;top:${t.top}px;width:${t.width}px;height:${t.height}px;border:2px solid #ff6b6b;border-radius:4px;background:rgba(255,107,107,.18);pointer-events:none;`}))}}finishRedactionPicking(e){this.redactRafId&&cancelAnimationFrame(this.redactRafId),this.redactRafId=0,document.removeEventListener("click",this.boundRedactClick,!0),document.removeEventListener("keydown",this.host.boundKeyDown),this.redactPickerRoot&&(this.redactPickerRoot.remove(),this.redactPickerRoot=null);const i=this.redactPicks;this.redactPicks=[],this.host.setState("IDLE"),e&&this.startRecording(i)}showRecordingIndicator(){const e=this.host.ensureOverlayHost();this.recordingIndicator=n("div",{class:"qaid-recording-indicator",style:`z-index:${this.host.config.zIndex+100}`},n("div",{class:"qaid-recording-dot"}),n("span",{class:"qaid-recording-time",text:this.formatTime(this.host.config.videoOptions.maxDuration)}),n("button",{class:"qaid-recording-stop",text:"Stop",attrs:{type:"button"},on:{click:()=>this.stopRecording()}})),this.host.applyVars(this.recordingIndicator),e.appendChild(this.recordingIndicator)}updateRecordingTimer(e){if(!this.recordingIndicator)return;const i=this.recordingIndicator.querySelector(".qaid-recording-time");if(i){const t=Math.max(0,this.host.config.videoOptions.maxDuration-e);i.textContent=this.formatTime(t),t>0&&t<=5&&this.host.announceMsg(`${t} second${t===1?"":"s"} remaining`)}}formatTime(e){const i=Math.floor(e/60),t=e%60;return`${i}:${t.toString().padStart(2,"0")}`}removeRecordingIndicator(){this.recordingIndicator&&(this.recordingIndicator.remove(),this.recordingIndicator=null)}showRecordingPreview(){const e=this.host.ensureOverlayHost(),i=URL.createObjectURL(this.recordedBlob),t=`qaid-video-title-${this.host.uid}`,o=n("h3",{text:"Review your recording",attrs:{id:t}}),r=n("video");r.src=i,r.controls=!0,r.autoplay=!0,r.muted=!0;const s=n("textarea",{attrs:{placeholder:"Optional: Describe the issue you recorded...","aria-label":"Describe the issue you recorded"}}),a=n("button",{class:"qaid-video-btn qaid-video-btn-send",text:"Send",attrs:{type:"button"},on:{click:()=>this.submitVideoFeedback(s.value.trim()||null,a)}}),c=n("div",{class:"qaid-video-preview-box"},o,r,s,n("div",{class:"qaid-video-preview-actions"},n("button",{class:"qaid-video-btn qaid-video-btn-cancel",text:"Cancel",attrs:{type:"button"},on:{click:()=>this.cancelRecordingPreview()}}),n("button",{class:"qaid-video-btn qaid-video-btn-rerecord",text:"Re-record",attrs:{type:"button"},on:{click:()=>{this.cancelRecordingPreview(),this.startRecording()}}}),a));this.videoPreview=n("div",{class:"qaid-video-preview",style:`z-index:${this.host.config.zIndex+100}`},c),this.host.applyVars(this.videoPreview),this.host.overlayShadowHost&&(this.host.overlayShadowHost.style.pointerEvents="auto"),e.appendChild(this.videoPreview),this.host.openDialogA11y(c,{labelledbyId:o.id}),document.addEventListener("keydown",this.host.boundKeyDown)}cancelRecordingPreview(){this.removeVideoPreview(),this.cleanupRecording()}removeVideoPreview(){if(this.host.closeDialogA11y(),this.videoPreview){const e=this.videoPreview.querySelector("video");e?.src&&URL.revokeObjectURL(e.src),this.videoPreview.remove(),this.videoPreview=null}document.removeEventListener("keydown",this.host.boundKeyDown)}async submitVideoFeedback(e,i){if(!this.recordedBlob||this.isSendingVideo)return;this.isSendingVideo=!0,i.disabled=!0,i.textContent="Sending...";const t=new FormData;t.append("video",this.recordedBlob,`recording.${this.recordedBlob.type.includes("mp4")?"mp4":"webm"}`),t.append("pageUrl",window.location.href),t.append("visitorId",this.host.visitorId),this.host.config.apiKey&&t.append("apiKey",this.host.config.apiKey),e&&t.append("message",e),this.host.consoleCapture&&t.append("consoleErrors",JSON.stringify(this.host.consoleCapture.errors)),this.networkCapture&&t.append("networkErrors",JSON.stringify(this.networkCapture.errors));let o=null,r=null;try{const s=await fetch(`${this.host.config.endpoint}/video`,{method:"POST",body:t});if(s.ok){this.host.announceMsg("Recording sent");try{o=(await s.json())?.id??null}catch{}}else console.error("Failed to submit video feedback:",await s.text()),r=s.status===413?"This recording is too large to send. Try a shorter one.":"Your recording could not be sent."}catch(s){console.error("Failed to submit video feedback:",s),r="Your recording could not be sent. Check your connection and try again."}if(this.isSendingVideo=!1,r){this.showSendError(r,i);return}this.removeVideoPreview(),this.cleanupRecording(),await this.host.tryLaunchQuest("video",o)}showSendError(e,i){this.host.announceMsg(`Failed to send recording. ${e}`,!0),i.disabled=!1,i.textContent="Send";const t=this.videoPreview?.querySelector(".qaid-video-preview-actions");if(t){let o=this.videoPreview.querySelector(".qaid-video-error");o||(o=n("p",{class:"qaid-video-error"}),t.before(o)),o.textContent=e}}cleanupRecording(){this.isRecording=!1,this.removeRecordingIndicator(),this.videoRecorder&&(this.videoRecorder.destroy(),this.videoRecorder=null),this.networkCapture&&(this.networkCapture.restore(),this.networkCapture=null),this.recordedBlob&&(this.recordedBlob=null),this.host.setButtonsDisabled(!1),this.host.overlayShadowHost&&this.host.state==="IDLE"&&(this.host.overlayShadowHost.style.pointerEvents="none")}}const y=v;export{w as RecordingController,y as styles};
2
+ //# sourceMappingURL=recording-BUw5-5Rf.js.map