@qaiddev/thumbs-embed 1.9.1 → 1.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,12 +20,21 @@ export interface QuestInstance {
20
20
  export interface LaunchedQuestConfig {
21
21
  endpoint: string;
22
22
  configUrl: string;
23
+ /** The definition, when it was fetched ahead of time (wins over configUrl). */
24
+ questionnaire?: unknown;
23
25
  apiKey?: string;
24
- metadata?: Record<string, unknown>;
26
+ /** A promise only when the loaded module says it accepts one. */
27
+ metadata?: Record<string, unknown> | Promise<Record<string, unknown> | undefined>;
25
28
  onComplete?: (answers: Record<string, unknown>) => void;
26
29
  onClose?: () => void;
27
30
  }
28
- type QuestsConstructor = new (config: LaunchedQuestConfig) => QuestInstance;
31
+ interface QuestsConstructor {
32
+ new (config: LaunchedQuestConfig): QuestInstance;
33
+ /** quests-embed 1.7+: `asyncMetadata` means `metadata` may be a promise. */
34
+ supports?: {
35
+ asyncMetadata?: boolean;
36
+ };
37
+ }
29
38
  /** Shape of the quests module's default/entry exports. */
30
39
  export interface QuestsModule {
31
40
  QaidQuests: QuestsConstructor;
@@ -37,6 +46,14 @@ type Importer = (url: string) => Promise<unknown>;
37
46
  * from the package entry, so it isn't public API.
38
47
  */
39
48
  export declare function _setQuestsImporter(fn: Importer | null): void;
49
+ /** Where the quest service serves a quest's live definition. */
50
+ export declare function questDefinitionUrl(base: string, questId: string): string;
51
+ /**
52
+ * Fetch a quest's definition before anyone clicks, so the quest opens from
53
+ * memory. Never rejects: a failed fetch is forgotten, and the quests widget
54
+ * then loads the definition itself, the way it did before this existed.
55
+ */
56
+ export declare function prefetchQuestDefinition(url: string): Promise<void>;
40
57
  /**
41
58
  * Import the quests module, caching the promise per URL. A failed load
42
59
  * clears the cache so a later trigger can retry (e.g. after a transient
@@ -52,8 +69,11 @@ export interface LaunchQuestOptions {
52
69
  apiKey?: string;
53
70
  /** ES-module URL to load the quests widget from. */
54
71
  moduleUrl: string;
55
- /** Feedback record id to correlate the response with (optional). */
56
- feedbackId?: string | number | null;
72
+ /**
73
+ * Feedback record id to correlate the response with (optional). A promise
74
+ * lets the quest open before the feedback POST has answered.
75
+ */
76
+ feedbackId?: string | number | null | Promise<string | number | null>;
57
77
  /** Called when the quest embed is torn down. */
58
78
  onClose?: () => void;
59
79
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qaiddev/thumbs-embed",
3
- "version": "1.9.1",
3
+ "version": "1.10.0",
4
4
  "description": "Precision User Feedback",
5
5
  "type": "module",
6
6
  "main": "./dist/qaid.umd.cjs",
@@ -1 +0,0 @@
1
- {"version":3,"file":"loader-DepVS4i5.js","sources":["../../src/styles.ts","../../src/a11y.ts","../../src/modal-positioning.ts","../../src/console-capture.ts","../../src/quest-launcher.ts","../../src/embed.ts","../../src/bootstrap.ts","../../src/loader.ts"],"sourcesContent":["/**\n * CSS styles for the feedback embed\n * Uses .qaid- prefix to avoid conflicts\n */\n\n// Import CSS as strings (vite handles minification in production)\nimport shadowStyles from \"./styles-shadow.css?inline\";\nimport lightStyles from \"./styles-light.css?inline\";\n\nlet instanceCount = 0;\n\n/** Default button styles included in shadow root */\nconst DEFAULT_BUTTON_STYLES = `button.qaid-btn{width:var(--qaid-btn-size);height:var(--qaid-btn-size);border-radius:50%;border:none;background:#f3f4f6;color:#374151;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 4px 6px -1px rgba(0,0,0,.1),0 2px 4px -1px rgba(0,0,0,.06);transition:background-color .2s,color .2s,transform .2s;-webkit-appearance:none;appearance:none;--qaid-hover-up-bg:var(--qaid-positive);--qaid-hover-up-color:#fff;--qaid-hover-down-bg:var(--qaid-negative);--qaid-hover-down-color:#fff}button.qaid-btn:hover{transform:scale(1.05)}button.qaid-btn-up:hover{background:var(--qaid-hover-up-bg);color:var(--qaid-hover-up-color)}button.qaid-btn-down:hover{background:var(--qaid-hover-down-bg);color:var(--qaid-hover-down-color)}button.qaid-btn-feedback:hover{background:var(--qaid-marker,#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.\n *\n * These helpers are intentionally framework-free and self-contained (no CSS\n * dependency) so they can be dropped into any open shadow root. They cover the\n * cross-cutting WCAG 2.2 AA infrastructure called for in the embed\n * accessibility plan: live-region announcements, focus management (trap,\n * save/restore), dialog semantics, and background isolation.\n */\n\n/** Host for the live regions: either a shadow root or a plain element. */\nexport type AnnounceRoot = ShadowRoot | HTMLElement;\n\n/** Options accepted by {@link announce}. */\nexport interface AnnounceOptions {\n /** Route the message through the assertive (role=\"alert\") region. */\n assertive?: boolean;\n}\n\n/** Options accepted by {@link applyDialog}. */\nexport interface ApplyDialogOptions {\n /** id of the element that labels the dialog (wired via aria-labelledby). */\n labelledbyId?: string;\n /** id of the element that describes the dialog (wired via aria-describedby). */\n describedbyId?: string;\n /** Fallback accessible name when no labelling element exists. */\n label?: string;\n}\n\n/** Handle returned by {@link createFocusTrap}. */\nexport interface FocusTrap {\n /** Remove the trap's key handler and clean up any tabindex it added. */\n release(): void;\n}\n\nconst POLITE_ATTR = \"data-qaid-a11y-live\";\n\nconst VISUALLY_HIDDEN_CSS =\n \"position:absolute;width:1px;height:1px;margin:-1px;padding:0;\" +\n \"border:0;overflow:hidden;clip:rect(0 0 0 0);clip-path:inset(50%);\" +\n \"white-space:nowrap;\";\n\n/**\n * Selector for natively focusable / author-focusable elements. Elements that\n * opt out with tabindex=\"-1\" are excluded below in {@link getFocusable}.\n */\nconst FOCUSABLE_SELECTOR = [\n \"a[href]\",\n \"button\",\n \"input\",\n \"textarea\",\n \"select\",\n \"[tabindex]\",\n].join(\",\");\n\nfunction ownerDoc(root: AnnounceRoot): Document {\n return root.ownerDocument || document;\n}\n\nfunction getLiveRegion(root: AnnounceRoot, assertive: boolean): HTMLElement {\n const kind = assertive ? \"assertive\" : \"polite\";\n const existing = root.querySelector<HTMLElement>(\n `[${POLITE_ATTR}=\"${kind}\"]`\n );\n if (existing) return existing;\n\n const doc = ownerDoc(root);\n const region = doc.createElement(\"div\");\n region.setAttribute(POLITE_ATTR, kind);\n region.setAttribute(\"role\", assertive ? \"alert\" : \"status\");\n region.setAttribute(\"aria-live\", assertive ? \"assertive\" : \"polite\");\n region.setAttribute(\"aria-atomic\", \"true\");\n region.style.cssText = VISUALLY_HIDDEN_CSS;\n root.appendChild(region);\n return region;\n}\n\n/**\n * Announce a message to assistive technology via a visually-hidden live region\n * mounted inside `root`. The two regions (polite role=\"status\" and assertive\n * role=\"alert\") are created lazily on first use and reused thereafter.\n *\n * The target region is cleared before the new text is written so that repeated\n * identical messages are re-announced rather than coalesced.\n */\nexport function announce(\n root: AnnounceRoot,\n message: string,\n opts: AnnounceOptions = {}\n): void {\n const region = getLiveRegion(root, !!opts.assertive);\n // Clear-then-set so an identical repeat is still perceived as a change.\n region.textContent = \"\";\n region.textContent = message;\n}\n\nfunction isDisabled(el: HTMLElement): boolean {\n if (el.hasAttribute(\"disabled\")) return true;\n const asInput = el as HTMLElement & { disabled?: boolean };\n return asInput.disabled === true;\n}\n\nfunction isHidden(el: HTMLElement): boolean {\n let node: HTMLElement | null = el;\n while (node) {\n if (node.hasAttribute(\"hidden\")) return true;\n const style = node.style;\n if (\n style &&\n (style.display === \"none\" ||\n style.visibility === \"hidden\" ||\n style.visibility === \"collapse\")\n ) {\n return true;\n }\n node = node.parentElement;\n }\n return false;\n}\n\n/**\n * Collect the focusable descendants of `container` in DOM order, excluding\n * disabled controls, elements opted out with tabindex=\"-1\", and elements that\n * are hidden (via the hidden attribute or an inline display/visibility rule on\n * themselves or an ancestor up to the document root).\n */\nexport function getFocusable(container: HTMLElement): HTMLElement[] {\n const nodes = Array.from(\n container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)\n );\n return nodes.filter((el) => {\n if (el.getAttribute(\"tabindex\") === \"-1\") return false;\n if (el instanceof HTMLInputElement && el.type === \"hidden\") return false;\n if (el instanceof HTMLAnchorElement && !el.getAttribute(\"href\")) return false;\n if (isDisabled(el)) return false;\n if (isHidden(el)) return false;\n return true;\n });\n}\n\n/** Resolve the deepest active element, drilling through open shadow roots. */\nfunction getDeepActiveElement(doc: Document): HTMLElement | null {\n let active: Element | null = doc.activeElement;\n while (active && active.shadowRoot && active.shadowRoot.activeElement) {\n active = active.shadowRoot.activeElement;\n }\n return active instanceof HTMLElement ? active : null;\n}\n\n/**\n * Trap keyboard focus inside `container`: Tab / Shift+Tab cycle between the\n * first and last focusable descendants and can never leave the container. On\n * creation focus moves to the first focusable element, or to the container\n * itself (made programmatically focusable) when it has no focusable children.\n *\n * Call {@link FocusTrap.release} to remove the handler; pair it with\n * {@link restoreFocus} to return focus to the invoking control.\n */\nexport function createFocusTrap(container: HTMLElement): FocusTrap {\n const doc = container.ownerDocument || document;\n let addedTabindex = false;\n\n const onKeydown = (event: KeyboardEvent): void => {\n if (event.key !== \"Tab\") return;\n\n const focusable = getFocusable(container);\n if (focusable.length === 0) {\n // Nothing to move to — keep focus pinned on the container.\n event.preventDefault();\n container.focus();\n return;\n }\n\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n const active = getDeepActiveElement(doc);\n const withinTrap = active ? focusable.indexOf(active) !== -1 : false;\n\n if (event.shiftKey) {\n if (!withinTrap || active === first) {\n event.preventDefault();\n last.focus();\n }\n } else {\n if (!withinTrap || active === last) {\n event.preventDefault();\n first.focus();\n }\n }\n };\n\n container.addEventListener(\"keydown\", onKeydown);\n\n const initial = getFocusable(container);\n if (initial.length > 0) {\n initial[0].focus();\n } else {\n if (!container.hasAttribute(\"tabindex\")) {\n container.setAttribute(\"tabindex\", \"-1\");\n addedTabindex = true;\n }\n container.focus();\n }\n\n return {\n release(): void {\n container.removeEventListener(\"keydown\", onKeydown);\n if (addedTabindex) {\n container.removeAttribute(\"tabindex\");\n addedTabindex = false;\n }\n },\n };\n}\n\n/**\n * Capture the currently focused element (drilling through shadow roots) so it\n * can be restored later with {@link restoreFocus}. Returns null when focus is\n * on nothing focusable.\n */\nexport function saveFocus(): HTMLElement | null {\n return getDeepActiveElement(document);\n}\n\n/**\n * Restore focus to a previously saved element. Safe to call with null or an\n * element that has since been detached (a missing/throwing focus is ignored).\n */\nexport function restoreFocus(el: HTMLElement | null): void {\n if (!el || typeof el.focus !== \"function\") return;\n try {\n el.focus();\n } catch {\n // The element may have been removed; nothing more to do.\n }\n}\n\n/**\n * Apply dialog semantics to `el`: role=\"dialog\", aria-modal=\"true\", and the\n * naming/description wiring described by `opts`. Prefer aria-labelledby /\n * aria-describedby pointing at visible title/subtitle elements; fall back to\n * aria-label when no visible label element exists.\n */\nexport function applyDialog(el: HTMLElement, opts: ApplyDialogOptions = {}): void {\n el.setAttribute(\"role\", \"dialog\");\n el.setAttribute(\"aria-modal\", \"true\");\n if (opts.labelledbyId) {\n el.setAttribute(\"aria-labelledby\", opts.labelledbyId);\n }\n if (opts.describedbyId) {\n el.setAttribute(\"aria-describedby\", opts.describedbyId);\n }\n if (opts.label) {\n el.setAttribute(\"aria-label\", opts.label);\n }\n}\n\n/** Walk up to the body-level ancestor of `el`, crossing shadow boundaries. */\nfunction topLevelAncestor(el: HTMLElement, body: HTMLElement): HTMLElement | null {\n let node: Node | null = el;\n while (node && node !== body) {\n const parent: Node | null = node.parentNode;\n if (parent === body) return node as HTMLElement;\n if (parent && (parent as ShadowRoot).host) {\n node = (parent as ShadowRoot).host;\n continue;\n }\n if (!parent) return null;\n node = parent;\n }\n return null;\n}\n\n/**\n * Isolate the background from assistive technology while a dialog is open by\n * marking every top-level sibling of the dialog inert (with an aria-hidden\n * fallback). `except` is the open dialog (or any element inside it); the\n * top-level element that contains it is left interactive.\n *\n * Returns a restore function that reverts every attribute this call changed,\n * leaving elements that were already inert/hidden untouched.\n */\nexport function setBackgroundInert(except: HTMLElement): () => void {\n const doc = except.ownerDocument || document;\n const body = doc.body;\n if (!body) return () => {};\n\n const keep = topLevelAncestor(except, body);\n const changed: Array<{\n el: HTMLElement;\n prevInert: boolean;\n prevAriaHidden: string | null;\n }> = [];\n\n Array.from(body.children).forEach((child) => {\n if (!(child instanceof HTMLElement)) return;\n if (keep && child === keep) return;\n\n const prevInert = child.inert === true;\n const prevAriaHidden = child.getAttribute(\"aria-hidden\");\n // Only record (and later revert) elements we actually change.\n if (prevInert && prevAriaHidden === \"true\") return;\n\n child.inert = true;\n child.setAttribute(\"aria-hidden\", \"true\");\n changed.push({ el: child, prevInert, prevAriaHidden });\n });\n\n return function restore(): void {\n while (changed.length) {\n // The loop guard guarantees pop() returns an entry.\n const entry = changed.pop()!;\n entry.el.inert = entry.prevInert;\n if (entry.prevAriaHidden === null) {\n entry.el.removeAttribute(\"aria-hidden\");\n } else {\n entry.el.setAttribute(\"aria-hidden\", entry.prevAriaHidden);\n }\n }\n };\n}\n","/**\n * Modal positioning utilities\n */\n\nimport type { SelectedBounds } from \"./types\";\n\nexport interface ModalPosition {\n top: number;\n left: number;\n position: \"above\" | \"below\";\n}\n\nexport interface ArrowPosition {\n left: number;\n}\n\nexport interface ModalDimensions {\n width: number;\n height: number;\n arrowHeight: number;\n gap: number;\n viewportPadding: number;\n}\n\nconst DEFAULT_DIMENSIONS: ModalDimensions = {\n width: 400,\n height: 280,\n arrowHeight: 12,\n gap: 8,\n viewportPadding: 16,\n};\n\n/**\n * Calculate whether modal should go above or below the target element\n */\nexport function calculateVerticalPosition(\n bounds: SelectedBounds,\n viewportHeight: number,\n totalHeight: number,\n gap: number,\n viewportPadding: number\n): { top: number; position: \"above\" | \"below\" } {\n const spaceAbove = bounds.y;\n const spaceBelow = viewportHeight - (bounds.y + bounds.height);\n\n // Prefer below if there's enough space\n if (spaceBelow >= totalHeight + gap) {\n return {\n top: bounds.y + bounds.height + gap,\n position: \"below\",\n };\n }\n\n // Try above if there's enough space\n if (spaceAbove >= totalHeight + gap) {\n return {\n top: bounds.y - totalHeight - gap,\n position: \"above\",\n };\n }\n\n // Neither fits perfectly - clamp to viewport\n const position = spaceBelow > spaceAbove ? \"below\" : \"above\";\n let top: number;\n\n if (position === \"below\") {\n top = Math.min(\n bounds.y + bounds.height + gap,\n viewportHeight - totalHeight - viewportPadding\n );\n } else {\n top = Math.max(viewportPadding, bounds.y - totalHeight - gap);\n }\n\n return { top, position };\n}\n\n/**\n * Calculate horizontal position of modal, clamped to viewport\n */\nexport function calculateHorizontalPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n modalWidth: number,\n viewportPadding: number\n): number {\n const centerX = bounds.x + bounds.width / 2;\n let left = centerX - modalWidth / 2;\n\n // Clamp to viewport\n left = Math.max(viewportPadding, Math.min(left, viewportWidth - modalWidth - viewportPadding));\n\n return left;\n}\n\n/**\n * Calculate arrow position relative to modal\n * Points at the click position, not the element center\n */\nexport function calculateArrowPosition(\n bounds: SelectedBounds,\n modalLeft: number,\n modalWidth: number,\n minOffset = 24,\n arrowWidth = 24\n): number {\n // Use click position for arrow, not element center\n const targetX = bounds.clickX;\n // Subtract half the arrow width to center it on the target\n const arrowLeft = targetX - modalLeft - arrowWidth / 2;\n\n // Clamp arrow to stay within modal bounds\n return Math.max(minOffset, Math.min(arrowLeft, modalWidth - minOffset - arrowWidth / 2));\n}\n\n/**\n * Calculate complete modal position based on selected element bounds\n */\nexport function calculateModalPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n viewportHeight: number,\n dimensions: ModalDimensions = DEFAULT_DIMENSIONS\n): ModalPosition {\n const totalHeight = dimensions.height + dimensions.arrowHeight;\n\n const vertical = calculateVerticalPosition(\n bounds,\n viewportHeight,\n totalHeight,\n dimensions.gap,\n dimensions.viewportPadding\n );\n\n const left = calculateHorizontalPosition(\n bounds,\n viewportWidth,\n dimensions.width,\n dimensions.viewportPadding\n );\n\n return {\n top: vertical.top,\n left,\n position: vertical.position,\n };\n}\n\nexport interface TooltipPositionOptions {\n /** Gap in pixels between anchor and tooltip, and from viewport edges */\n gap?: number;\n}\n\n/**\n * Calculate tooltip position relative to an anchor, clamped to the viewport.\n * Pure function: no DOM access — caller passes measured rects and viewport size.\n *\n * Strategy:\n * - Place below the anchor by default\n * - Flip above if below would overflow vertically\n * - Clamp horizontally to viewport, then vertically to viewport\n */\nexport function calculateTooltipPosition(\n anchor: { top: number; bottom: number; left: number },\n tooltip: { width: number; height: number },\n viewport: { width: number; height: number },\n options: TooltipPositionOptions = {}\n): { top: number; left: number } {\n const gap = options.gap ?? 8;\n\n let top = anchor.bottom + gap;\n\n // Flip above if below overflows\n if (top + tooltip.height > viewport.height - gap) {\n top = anchor.top - tooltip.height - gap;\n }\n\n // Clamp horizontally\n let left = anchor.left;\n if (left < gap) {\n left = gap;\n } else if (left + tooltip.width > viewport.width - gap) {\n left = viewport.width - tooltip.width - gap;\n }\n\n // Clamp vertically\n if (top < gap) {\n top = gap;\n } else if (top + tooltip.height > viewport.height - gap) {\n top = viewport.height - tooltip.height - gap;\n }\n\n return { top, left };\n}\n\n/**\n * Calculate both modal and arrow positions\n */\nexport function calculateModalAndArrowPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n viewportHeight: number,\n dimensions: ModalDimensions = DEFAULT_DIMENSIONS\n): { modal: ModalPosition; arrow: ArrowPosition } {\n const modal = calculateModalPosition(bounds, viewportWidth, viewportHeight, dimensions);\n\n const arrowLeft = calculateArrowPosition(\n bounds,\n modal.left,\n dimensions.width\n );\n\n return {\n modal,\n arrow: { left: arrowLeft },\n };\n}\n","/**\n * Console capture utilities\n */\n\nimport type { ConsoleError } from \"./types\";\n\nconst MAX_MESSAGES = 20;\n\nexport interface ConsoleCapture {\n errors: ConsoleError[];\n restore: () => void;\n}\n\ntype ConsoleLevel = \"error\" | \"warn\" | \"log\";\n\n/**\n * Wrap console methods to capture messages\n */\nexport function captureConsoleErrors(\n onError?: (error: ConsoleError) => void\n): ConsoleCapture {\n const errors: ConsoleError[] = [];\n const originalError = console.error;\n const originalWarn = console.warn;\n const originalLog = console.log;\n\n const capture = (level: ConsoleLevel, args: unknown[]) => {\n const error: ConsoleError = {\n message: args.map((arg) => String(arg)).join(\" \"),\n timestamp: Date.now(),\n level,\n };\n\n // Keep max messages\n if (errors.length >= MAX_MESSAGES) {\n errors.shift();\n }\n errors.push(error);\n\n // Call callback if provided\n if (onError) {\n onError(error);\n }\n };\n\n console.error = function (...args: unknown[]) {\n capture(\"error\", args);\n originalError.apply(console, args);\n };\n\n console.warn = function (...args: unknown[]) {\n capture(\"warn\", args);\n originalWarn.apply(console, args);\n };\n\n console.log = function (...args: unknown[]) {\n capture(\"log\", args);\n originalLog.apply(console, args);\n };\n\n return {\n errors,\n restore: () => {\n console.error = originalError;\n console.warn = originalWarn;\n console.log = originalLog;\n },\n };\n}\n\n/**\n * Add an error to the captured errors array\n */\nexport function addError(errors: ConsoleError[], error: ConsoleError): void {\n if (errors.length >= MAX_MESSAGES) {\n errors.shift();\n }\n errors.push(error);\n}\n\n/**\n * Format console error for display\n */\nexport function formatError(error: ConsoleError): string {\n const date = new Date(error.timestamp);\n const time = date.toLocaleTimeString();\n const levelPrefix = error.level === \"error\" ? \"ERR\" : error.level === \"warn\" ? \"WRN\" : \"LOG\";\n return `[${time}] [${levelPrefix}] ${error.message}`;\n}\n","/**\n * Lazy loader + launcher for `@qaiddev/quests-embed`.\n *\n * `thumbs-embed` links a button to a quest but owns no questionnaire code\n * and takes no build-time dependency on the quests package. Instead the\n * quests widget is imported from a CDN the first time a quest is triggered,\n * so the shipped bundle stays zero-dependency and small.\n *\n * Only the tiny slice of the quests public API that we actually use is\n * modelled here structurally, so a version bump of the quests package that\n * keeps this surface stable needs no change in thumbs-embed.\n */\n\n/** Default ES-module URL, pinned to a compatible major on unpkg. */\nexport const DEFAULT_QUESTS_MODULE_URL =\n \"https://unpkg.com/@qaiddev/quests-embed@1/dist/qaid-quests.js\";\n\n/** The bit of a QaidQuests instance we hold onto. */\nexport interface QuestInstance {\n destroy(): void;\n}\n\n/** The bit of QaidQuests config we pass. Mirrors QuestsConfig loosely. */\nexport interface LaunchedQuestConfig {\n endpoint: string;\n configUrl: string;\n apiKey?: string;\n metadata?: Record<string, unknown>;\n onComplete?: (answers: Record<string, unknown>) => void;\n onClose?: () => void;\n}\n\ntype QuestsConstructor = new (config: LaunchedQuestConfig) => QuestInstance;\n\n/** Shape of the quests module's default/entry exports. */\nexport interface QuestsModule {\n QaidQuests: QuestsConstructor;\n}\n\ntype Importer = (url: string) => Promise<unknown>;\n\nconst defaultImporter: Importer = (url) =>\n // The URL is a runtime value, not a static specifier — keep Vite from\n // trying to analyze/bundle it.\n import(/* @vite-ignore */ url);\n\nlet importer: Importer = defaultImporter;\nlet modulePromise: Promise<QuestsModule> | null = null;\nlet cachedUrl: string | null = null;\n\n/**\n * @internal Test seam: swap the dynamic importer and clear the cache.\n * Pass `null` to restore the real dynamic `import()`. Not re-exported\n * from the package entry, so it isn't public API.\n */\nexport function _setQuestsImporter(fn: Importer | null): void {\n importer = fn ?? defaultImporter;\n modulePromise = null;\n cachedUrl = null;\n}\n\n/**\n * Import the quests module, caching the promise per URL. A failed load\n * clears the cache so a later trigger can retry (e.g. after a transient\n * network error) rather than being stuck with a rejected promise.\n */\nexport function loadQuestsModule(moduleUrl: string): Promise<QuestsModule> {\n if (modulePromise && cachedUrl === moduleUrl) return modulePromise;\n cachedUrl = moduleUrl;\n modulePromise = Promise.resolve(importer(moduleUrl))\n .then((mod) => {\n const m = mod as Partial<QuestsModule>;\n if (!m || typeof m.QaidQuests !== \"function\") {\n throw new Error(\"quests module has no QaidQuests export\");\n }\n return m as QuestsModule;\n })\n .catch((err) => {\n modulePromise = null;\n cachedUrl = null;\n throw err;\n });\n return modulePromise;\n}\n\nexport interface LaunchQuestOptions {\n /** Quest id to launch (the `[id]` in `{base}/{id}/definition`). */\n questId: string;\n /** Quest-service base URL, e.g. \"https://qaid.dev/api/quests\". */\n base: string;\n /** API key for the quest service (optional). */\n apiKey?: string;\n /** ES-module URL to load the quests widget from. */\n moduleUrl: string;\n /** Feedback record id to correlate the response with (optional). */\n feedbackId?: string | number | null;\n /** Called when the quest embed is torn down. */\n onClose?: () => void;\n}\n\n/**\n * Load the quests widget (if not already loaded) and open the given quest\n * as its own centered modal. Rejects if the module can't be loaded — the\n * caller should fall back to its normal UI.\n */\nexport async function launchQuest(opts: LaunchQuestOptions): Promise<QuestInstance> {\n const mod = await loadQuestsModule(opts.moduleUrl);\n const base = opts.base.replace(/\\/+$/, \"\");\n const metadata =\n opts.feedbackId != null ? { feedbackId: opts.feedbackId } : undefined;\n return new mod.QaidQuests({\n endpoint: `${base}/responses`,\n configUrl: `${base}/${encodeURIComponent(opts.questId)}/definition`,\n apiKey: opts.apiKey || undefined,\n metadata,\n onClose: opts.onClose,\n });\n}\n","import type {\n FeedbackConfig,\n ResolvedFeedbackConfig,\n FeedbackData,\n FeedbackType,\n SelectedBounds,\n EmbedState,\n FeedbackPayload,\n FeedbackResponse,\n} from \"./types\";\nimport { THUMBS_UP_ICON, THUMBS_DOWN_ICON, RECORD_ICON, FEEDBACK_ICON } from \"./icons\";\nimport { injectStyles, removeStyles, buildCssVars, applyCssVars, getEmbedStyles } from \"./styles\";\n// The element-targeting subsystem (with element-selector, ~14 KB) lives in a\n// lazily-loaded chunk (targeting.ts), pulled in the first time the user targets.\nimport type { TargetingController, TargetingHost } from \"./targeting\";\nimport {\n announce,\n createFocusTrap,\n saveFocus,\n restoreFocus,\n applyDialog,\n setBackgroundInert,\n type FocusTrap,\n} from \"./a11y\";\nimport { calculateTooltipPosition } from \"./modal-positioning\";\nimport type { ModalController, ModalHost } from \"./modal\";\nimport { captureConsoleErrors, type ConsoleCapture } from \"./console-capture\";\n// The whole video-recording subsystem lives in a lazily-loaded chunk\n// (recording.ts), pulled in the first time the record button is used. Only the\n// types are imported eagerly (erased at build time).\nimport type { RecordingController, RecordingHost } from \"./recording\";\nimport { isMobileViewport } from \"./dom-utils\";\n// Screenshot capture and the annotation editor are loaded on demand the first\n// time a screenshot is taken — see submitFeedback() / openAnnotationEditor().\nimport {\n launchQuest,\n DEFAULT_QUESTS_MODULE_URL,\n type QuestInstance,\n} from \"./quest-launcher\";\n\nconst VISITOR_ID_KEY = \"qaid_visitor_id\";\nconst HIDE_FEEDBACK_KEY = \"qaid_hide_feedback\";\n/** Default annotation swatches: red, amber, green, blue, near-black, white. */\nconst DEFAULT_ANNOTATION_PALETTE = [\n \"#ef4444\",\n \"#f59e0b\",\n \"#22c55e\",\n \"#3b82f6\",\n \"#111827\",\n \"#ffffff\",\n];\n\n// True when the primary pointer is touch (phone/tablet). On these devices the\n// Screen Capture API (getDisplayMedia) shows an intrusive \"start capturing\"\n// system prompt, dims the screen, and on iOS returns a rotated frame — so the\n// permission-free DOM/canvas screenshot is the right default there.\nfunction isTouchPrimaryDevice(): boolean {\n return (\n typeof window.matchMedia === \"function\" &&\n window.matchMedia(\"(pointer: coarse)\").matches\n );\n}\n\nfunction getHideKey(apiKey?: string): string {\n return apiKey ? `${HIDE_FEEDBACK_KEY}_${apiKey}` : HIDE_FEEDBACK_KEY;\n}\n\nexport function isHiddenByUser(apiKey?: string): boolean {\n try {\n return localStorage.getItem(getHideKey(apiKey)) === \"1\";\n } catch {\n return false;\n }\n}\n\nexport function setHiddenByUser(apiKey?: string, hidden = true): void {\n try {\n if (hidden) {\n localStorage.setItem(getHideKey(apiKey), \"1\");\n } else {\n localStorage.removeItem(getHideKey(apiKey));\n }\n } catch {\n // localStorage not available\n }\n}\n\n/**\n * 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 */\nexport class QaidFeedback {\n private config: ResolvedFeedbackConfig;\n private state: EmbedState = \"IDLE\";\n private feedbackData: FeedbackData = {\n feedbackType: null,\n elementSelector: null,\n elementText: null,\n consoleErrors: [],\n };\n private selectedBounds: SelectedBounds = {\n x: 0,\n y: 0,\n width: 0,\n height: 0,\n clickX: 0,\n clickY: 0,\n visible: false,\n };\n private feedbackId: number | null = null;\n // A quest launched from a button (in place of the message box), if any.\n private activeQuest: QuestInstance | null = null;\n private isMobile = false;\n private visitorId: string;\n\n // Console capture\n private consoleCapture: ConsoleCapture | null = null;\n\n // Video recording — the whole subsystem lives in a lazily-loaded chunk\n // (recording.ts); a thumbs-only visitor never downloads it.\n private recording: RecordingController | null = null;\n // Element targeting — also a lazily-loaded chunk (targeting.ts).\n private targeting: TargetingController | null = null;\n private targetingPrewarmed = false;\n // Preload-on-intent: warm the lazily-split feature chunks before first use.\n private prewarmHandle: number | null = null;\n private prewarmIsTimeout = false;\n private videoPrewarmed = false;\n private screenshotPrewarmed = false;\n\n // Shadow DOM\n private shadowHost: HTMLDivElement | null = null;\n private shadowRoot: ShadowRoot | null = null;\n\n // Overlay shadow DOM (always on document.body for full-page coverage)\n private overlayShadowHost: HTMLDivElement | null = null;\n private overlayShadowRoot: ShadowRoot | null = null;\n\n // DOM elements (inside shadow root)\n private buttonsContainer: HTMLDivElement | null = null;\n private isUserProvidedContainer = false;\n // The message modal lives in a lazily-loaded chunk (modal.ts).\n private modal: ModalController | null = null;\n private modalPrewarmed = false;\n private dismissBtn: HTMLButtonElement | null = null;\n\n // Per-instance CSS variables\n private cssVars: Record<string, string> = {};\n\n private activeThumbBtn: HTMLElement | null = null;\n // Tracks whether the pending activation came from the keyboard (Enter/Space)\n // rather than a pointer, so targeting can avoid elementFromPoint(0,0).\n private keyboardActivation = false;\n\n // Accessibility: dialog focus management\n private dialogTrigger: HTMLElement | null = null;\n private dialogTrap: FocusTrap | null = null;\n private dialogRestoreInert: (() => void) | null = null;\n\n // Unique id suffix for aria-labelledby/describedby references\n private readonly uid = Math.random().toString(36).slice(2, 9);\n\n // Bound event handlers\n private boundKeyDown: (e: KeyboardEvent) => void;\n private boundResize: () => void;\n\n // Start with buttons slid off-screen (localStorage dismiss, no animation)\n private _startDismissed = false;\n\n // DOM persistence (survives framework client-side navigation)\n private destroyed = false;\n private domObserver: MutationObserver | null = null;\n private boundBeforeSwap: ((e: Event) => void) | null = null;\n\n constructor(config: FeedbackConfig) {\n this.config = {\n endpoint: config.endpoint,\n apiKey: config.apiKey ?? \"\",\n container: config.container ?? \"\",\n buttonClass: config.buttonClass ?? \"\",\n direction: config.direction ?? \"horizontal\",\n position: config.position ?? \"bottom-right\",\n offset: {\n x: config.offset?.x ?? 16,\n y: config.offset?.y ?? 16,\n },\n zIndex: config.zIndex ?? 50,\n skipTargeting: config.skipTargeting ?? false,\n singleButton: config.singleButton ?? false,\n feedbackMode: config.feedbackMode ?? \"target\",\n colors: {\n positive: config.colors?.positive ?? \"rgb(0, 200, 83)\",\n negative: config.colors?.negative ?? \"rgb(255, 0, 0)\",\n marker: config.colors?.marker ?? \"#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 /**\n * Turn a transient surface into an accessible modal dialog: save the\n * invoking control, apply dialog semantics, trap focus, and inert the\n * background. Paired with closeDialogA11y() on every close path.\n */\n private openDialogA11y(\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string; label?: string }\n ): void {\n this.dialogTrigger = saveFocus();\n applyDialog(container, opts);\n this.dialogTrap = createFocusTrap(container);\n this.dialogRestoreInert = setBackgroundInert(container);\n }\n\n private closeDialogA11y(): void {\n this.dialogTrap?.release();\n this.dialogTrap = null;\n if (this.dialogRestoreInert) {\n this.dialogRestoreInert();\n this.dialogRestoreInert = null;\n }\n restoreFocus(this.dialogTrigger);\n this.dialogTrigger = null;\n }\n\n private clearActiveThumb(): void {\n if (this.activeThumbBtn) {\n this.activeThumbBtn.setAttribute(\"aria-pressed\", \"false\");\n this.activeThumbBtn = null;\n }\n }\n\n private init(): void {\n // Inject shared light DOM styles (cursor + highlight, reference counted)\n injectStyles();\n\n // Build per-instance CSS variables\n this.cssVars = buildCssVars({\n positiveColor: this.config.colors.positive,\n negativeColor: this.config.colors.negative,\n markerColor: this.config.colors.marker,\n buttonSize: this.config.buttonSize,\n modalWidth: this.config.modalWidth,\n backdropOpacity: this.config.backdropOpacity,\n fontFamily: this.config.fontFamily,\n fontSize: this.config.fontSize,\n });\n\n // Restore dismiss preference from localStorage (skip if hideDismiss)\n if (!this.config.hideDismiss && isHiddenByUser(this.config.apiKey)) {\n this._startDismissed = true;\n }\n\n // Check mobile\n this.checkMobile();\n window.addEventListener(\"resize\", this.boundResize);\n\n // Create shadow host and embed\n this.createEmbed();\n\n // Capture console errors\n this.consoleCapture = captureConsoleErrors((_error) => {\n this.feedbackData.consoleErrors = this.consoleCapture?.errors ?? [];\n });\n this.feedbackData.consoleErrors = this.consoleCapture.errors;\n\n // Persist across client-side navigations (Astro View Transitions, etc.)\n this.observeDom();\n\n // Preload split feature chunks on idle when their config flags are set, so\n // the first screenshot / recording doesn't wait on a chunk fetch. Hovering\n // the record button also warms the video chunk (see createEmbed).\n if (\n (this.config.captureVideo && this.videoSupported()) ||\n this.config.captureScreenshot\n ) {\n this.schedulePrewarm(() => {\n if (this.config.captureVideo && this.videoSupported()) this.prewarmVideo();\n if (this.config.captureScreenshot) this.prewarmScreenshot();\n });\n }\n }\n\n /**\n * Best-effort preload of a lazily-split feature chunk so its first use is\n * instant. Warming fetches + compiles (and defines) the module; the feature\n * modules have no load-time side effects, so this is safe. Errors are\n * swallowed — a failed preload just falls back to an on-demand load.\n */\n private prewarmVideo(): void {\n if (this.videoPrewarmed) return;\n this.videoPrewarmed = true;\n // Warm both the recording controller chunk and the capture chunk it pulls\n // in on start, so the first recording begins without waiting on either.\n import(\"./recording\").catch(() => {});\n import(\"./video-capture\").catch(() => {});\n }\n\n private prewarmScreenshot(): void {\n if (this.screenshotPrewarmed) return;\n this.screenshotPrewarmed = true;\n (this.shouldCaptureViaDom()\n ? import(\"./screenshot-dom\")\n : import(\"./screenshot\")\n ).catch(() => {});\n if (this.config.annotate) import(\"./annotate\").catch(() => {});\n }\n\n /** Run fn when the main thread is idle; cancelled by destroy(). */\n private schedulePrewarm(fn: () => void): void {\n const w = window as unknown as {\n requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;\n };\n const guarded = (): void => {\n if (!this.destroyed) fn();\n };\n if (typeof w.requestIdleCallback === \"function\") {\n this.prewarmIsTimeout = false;\n this.prewarmHandle = w.requestIdleCallback(guarded, { timeout: 2000 });\n } else {\n this.prewarmIsTimeout = true;\n this.prewarmHandle = window.setTimeout(guarded, 1200);\n }\n }\n\n /**\n * Watch for the shadow hosts being removed from the DOM by framework\n * client-side navigation (e.g. Astro View Transitions swapping <body>\n * contents, or any SPA router that replaces DOM subtrees). If the host\n * is disconnected and destroy() wasn't called, re-append it.\n *\n * Also hooks into Astro's `astro:before-swap` when available, which\n * lets us carry elements into the new document before the swap happens\n * (avoids a flash of the widget disappearing and reappearing).\n */\n private observeDom(): void {\n // Astro View Transitions: carry hosts into the new document pre-swap\n this.boundBeforeSwap = (e: Event) => {\n const newDoc = (e as any).newDocument as Document | undefined;\n if (!newDoc || this.destroyed) return;\n if (this.shadowHost) newDoc.body.appendChild(this.shadowHost);\n if (this.overlayShadowHost) newDoc.body.appendChild(this.overlayShadowHost);\n };\n document.addEventListener(\"astro:before-swap\", this.boundBeforeSwap);\n\n // Generic fallback: MutationObserver to catch any framework removing our hosts\n this.domObserver = new MutationObserver(() => {\n if (this.destroyed) return;\n if (this.shadowHost && !this.shadowHost.isConnected) {\n document.body.appendChild(this.shadowHost);\n }\n if (this.overlayShadowHost && !this.overlayShadowHost.isConnected) {\n document.body.appendChild(this.overlayShadowHost);\n }\n });\n this.domObserver.observe(document.body, { childList: true });\n }\n\n private checkMobile(): void {\n this.isMobile = isMobileViewport();\n }\n\n private handleResize(): void {\n this.checkMobile();\n }\n\n private createEmbed(): void {\n // Create the shadow host element\n this.shadowHost = document.createElement(\"div\");\n this.shadowHost.setAttribute(\"data-qaid-embed\", \"\");\n this.shadowHost.style.position = \"static\";\n this.shadowHost.style.display = \"contents\";\n\n // Check if user provided a container selector\n let userContainer: HTMLElement | null = null;\n if (this.config.container) {\n userContainer = document.querySelector(this.config.container);\n }\n\n if (userContainer) {\n userContainer.appendChild(this.shadowHost);\n this.isUserProvidedContainer = true;\n // Container mode never needs a dismiss button\n this.config.hideDismiss = true;\n } else {\n // Set shadow host to fixed positioning for auto-created containers\n this.shadowHost.style.position = \"fixed\";\n this.shadowHost.style.display = \"block\";\n this.shadowHost.style.inset = \"0\";\n this.shadowHost.style.pointerEvents = \"none\";\n this.shadowHost.style.zIndex = String(this.config.zIndex);\n document.body.appendChild(this.shadowHost);\n }\n\n // Attach shadow root\n this.shadowRoot = this.shadowHost.attachShadow({ mode: \"open\" });\n\n // Inject base styles into shadow root\n const baseStyle = document.createElement(\"style\");\n baseStyle.textContent = getEmbedStyles();\n this.shadowRoot.appendChild(baseStyle);\n\n // Inject theme CSS if provided\n if (this.config.css) {\n const themeStyle = document.createElement(\"style\");\n themeStyle.textContent = this.config.css;\n this.shadowRoot.appendChild(themeStyle);\n }\n\n // Create buttons container inside shadow root\n const dirClass = this.config.direction === \"vertical\" ? \"qaid-vertical\" : \"\";\n if (this.isUserProvidedContainer) {\n this.buttonsContainer = document.createElement(\"div\");\n this.buttonsContainer.className = `qaid-buttons qaid-${this.config.position} ${dirClass}`.trim();\n if (this.config.incognito) {\n this.buttonsContainer.classList.add(\"qaid-incognito\");\n }\n } else {\n this.buttonsContainer = document.createElement(\"div\");\n this.buttonsContainer.className = `qaid-buttons qaid-auto-container qaid-${this.config.position} ${dirClass}${this.config.incognito ? \" qaid-incognito\" : \"\"}`.trim();\n this.buttonsContainer.style.pointerEvents = \"auto\";\n // Apply custom offset\n const { x: offsetX, y: offsetY } = this.config.offset;\n if (this.config.position.includes(\"right\")) {\n this.buttonsContainer.style.right = `${offsetX}px`;\n } else {\n this.buttonsContainer.style.left = `${offsetX}px`;\n }\n if (this.config.position.includes(\"bottom\")) {\n this.buttonsContainer.style.bottom = `${offsetY}px`;\n } else {\n this.buttonsContainer.style.top = `${offsetY}px`;\n }\n }\n\n // Apply per-instance CSS variables to buttons container\n this.applyVars(this.buttonsContainer);\n this.shadowRoot.appendChild(this.buttonsContainer);\n\n // Track input modality so a keyboard-activated control (Enter/Space) can be\n // distinguished from a pointer click. A keyboard-fired synthetic click has\n // clientX/clientY===0, which would break elementFromPoint targeting.\n this.buttonsContainer.addEventListener(\"keydown\", (ev) => {\n if (ev.key === \"Enter\" || ev.key === \" \" || ev.key === \"Spacebar\") {\n this.keyboardActivation = true;\n }\n });\n this.buttonsContainer.addEventListener(\"mousedown\", () => {\n this.keyboardActivation = false;\n });\n this.buttonsContainer.addEventListener(\"pointerdown\", () => {\n this.keyboardActivation = false;\n });\n\n // Determine button classes\n const useCustomClass = !!this.config.buttonClass;\n const btnBaseClass = useCustomClass\n ? `qaid-btn-structural ${this.config.buttonClass}`\n : \"qaid-btn\";\n\n // Determine tooltip text\n const defaultTooltip = \"Feedback for us?\";\n const tooltipText = this.config.text.tooltip || defaultTooltip;\n\n // Create shared tooltip element (inside shadow root)\n const tooltip = document.createElement(\"div\");\n tooltip.className = \"qaid-tooltip-text\";\n tooltip.textContent = tooltipText;\n this.applyVars(tooltip);\n this.shadowRoot.appendChild(tooltip);\n this.tooltipElement = tooltip;\n\n // Single sentiment-free \"Feedback\" button, or the thumbs up/down pair.\n if (this.config.singleButton) {\n const fbWrapper = document.createElement(\"div\");\n fbWrapper.className = \"qaid-tooltip-wrapper\";\n\n const fbBtn = document.createElement(\"button\");\n fbBtn.type = \"button\";\n fbBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-feedback` : \"qaid-btn qaid-btn-feedback\";\n fbBtn.setAttribute(\"aria-label\", this.config.text.feedbackLabel);\n fbBtn.innerHTML = this.config.feedbackIcon || FEEDBACK_ICON;\n fbBtn.addEventListener(\"click\", (e) => this.handleThumbClick(\"neutral\", e.currentTarget as HTMLElement, e));\n fbBtn.addEventListener(\"mouseenter\", () => {\n this.prewarmTargeting();\n this.showTooltip(fbBtn);\n });\n fbBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n fbWrapper.appendChild(fbBtn);\n\n this.buttonsContainer.appendChild(fbWrapper);\n } else if (!this.config.hideThumbs) {\n // Thumbs up button\n const upWrapper = document.createElement(\"div\");\n upWrapper.className = \"qaid-tooltip-wrapper\";\n\n const upBtn = document.createElement(\"button\");\n upBtn.type = \"button\";\n upBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-up` : \"qaid-btn qaid-btn-up\";\n upBtn.setAttribute(\"aria-label\", this.config.text.positiveLabel);\n upBtn.innerHTML = this.config.positiveIcon || THUMBS_UP_ICON;\n upBtn.addEventListener(\"click\", (e) => this.handleThumbClick(\"up\", e.currentTarget as HTMLElement, e));\n upBtn.addEventListener(\"mouseenter\", () => {\n this.prewarmTargeting();\n this.showTooltip(upBtn);\n });\n upBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n upWrapper.appendChild(upBtn);\n\n // Thumbs down button\n const downWrapper = document.createElement(\"div\");\n downWrapper.className = \"qaid-tooltip-wrapper\";\n\n const downBtn = document.createElement(\"button\");\n downBtn.type = \"button\";\n downBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-down` : \"qaid-btn qaid-btn-down\";\n downBtn.setAttribute(\"aria-label\", this.config.text.negativeLabel);\n downBtn.innerHTML = this.config.negativeIcon || THUMBS_DOWN_ICON;\n downBtn.addEventListener(\"click\", (e) => this.handleThumbClick(\"down\", e.currentTarget as HTMLElement, e));\n downBtn.addEventListener(\"mouseenter\", () => {\n this.prewarmTargeting();\n this.showTooltip(downBtn);\n });\n downBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n downWrapper.appendChild(downBtn);\n\n this.buttonsContainer.appendChild(upWrapper);\n this.buttonsContainer.appendChild(downWrapper);\n }\n\n // Record button (only when captureVideo is true and browser supports it)\n if (this.config.captureVideo && this.videoSupported()) {\n const recordWrapper = document.createElement(\"div\");\n recordWrapper.className = \"qaid-tooltip-wrapper\";\n\n const recordBtn = document.createElement(\"button\");\n recordBtn.type = \"button\";\n recordBtn.className = useCustomClass ? `${btnBaseClass} qaid-btn-record` : \"qaid-btn qaid-btn-record\";\n recordBtn.setAttribute(\"aria-label\", this.config.text.recordLabel);\n recordBtn.innerHTML = this.config.recordIcon || RECORD_ICON;\n recordBtn.addEventListener(\"click\", () => {\n void this.ensureRecording().then((rec) =>\n this.config.videoOptions.redaction ? rec.startPicking() : rec.startRecording()\n );\n });\n // Warm the video chunk on hover/focus/touch — the ~200ms before a click —\n // so recording starts without waiting on the chunk fetch.\n const warmVideo = (): void => this.prewarmVideo();\n recordBtn.addEventListener(\"mouseenter\", () => {\n warmVideo();\n this.showTooltip(recordBtn);\n });\n recordBtn.addEventListener(\"focus\", warmVideo);\n recordBtn.addEventListener(\"touchstart\", warmVideo, { passive: true });\n recordBtn.addEventListener(\"mouseleave\", () => this.hideTooltip());\n recordWrapper.appendChild(recordBtn);\n\n this.buttonsContainer.appendChild(recordWrapper);\n }\n\n // Dismiss (X) button — only in body/fixed mode (hidden for container embeds)\n if (!this.config.hideDismiss) {\n this.dismissBtn = document.createElement(\"button\");\n this.dismissBtn.type = \"button\";\n this.dismissBtn.className = \"qaid-dismiss-btn\";\n this.dismissBtn.setAttribute(\"aria-label\", this.config.text.dismissLabel);\n this.dismissBtn.title = this.config.text.dismissLabel;\n this.dismissBtn.innerHTML = `<svg width=\"12\" height=\"12\" viewBox=\"0 0 12 12\" fill=\"none\" xmlns=\"http://www.w3.org/2000/svg\"><path d=\"M2 2l8 8M10 2l-8 8\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\"/></svg>`;\n this.dismissBtn.addEventListener(\"click\", (e) => {\n e.stopPropagation();\n this.handleDismiss();\n });\n // Insert as first child so it sits to the left of thumb buttons\n this.buttonsContainer.insertBefore(this.dismissBtn, this.buttonsContainer.firstChild);\n\n // If previously dismissed via localStorage, start fully hidden so it\n // doesn't flash back on hover — matching the dismiss behavior.\n if (this._startDismissed) {\n this.buttonsContainer.classList.add(\"qaid-dismissed\");\n }\n }\n }\n\n /**\n * Lazily create a separate overlay shadow host on document.body.\n * This host contains all full-page elements (targeting overlay, marker,\n * backdrop, modal, recording indicator, video preview) so they escape\n * clip-path / transform containing blocks in user containers.\n */\n private ensureOverlayHost(): ShadowRoot {\n if (this.overlayShadowRoot) return this.overlayShadowRoot;\n\n this.overlayShadowHost = document.createElement(\"div\");\n this.overlayShadowHost.setAttribute(\"data-qaid-embed-overlay\", \"\");\n this.overlayShadowHost.style.position = \"fixed\";\n this.overlayShadowHost.style.inset = \"0\";\n this.overlayShadowHost.style.pointerEvents = \"none\";\n this.overlayShadowHost.style.zIndex = String(this.config.zIndex);\n document.body.appendChild(this.overlayShadowHost);\n\n this.overlayShadowRoot = this.overlayShadowHost.attachShadow({ mode: \"open\" });\n\n // Inject base styles into overlay shadow root\n const baseStyle = document.createElement(\"style\");\n baseStyle.textContent = getEmbedStyles();\n this.overlayShadowRoot.appendChild(baseStyle);\n\n // Inject theme CSS if provided\n if (this.config.css) {\n const themeStyle = document.createElement(\"style\");\n themeStyle.textContent = this.config.css;\n this.overlayShadowRoot.appendChild(themeStyle);\n }\n\n return this.overlayShadowRoot;\n }\n\n private tooltipElement: HTMLElement | null = null;\n\n private showTooltip(anchor: HTMLElement): void {\n const tooltip = this.tooltipElement!;\n\n // Make visible to measure\n tooltip.style.visibility = \"hidden\";\n tooltip.classList.add(\"qaid-tooltip-visible\");\n\n const anchorRect = anchor.getBoundingClientRect();\n const tooltipRect = tooltip.getBoundingClientRect();\n const { top, left } = calculateTooltipPosition(\n anchorRect,\n tooltipRect,\n { width: window.innerWidth, height: window.innerHeight }\n );\n\n tooltip.style.top = `${top}px`;\n tooltip.style.left = `${left}px`;\n tooltip.style.visibility = \"visible\";\n }\n\n private hideTooltip(): void {\n this.tooltipElement!.classList.remove(\"qaid-tooltip-visible\");\n }\n\n private handleDismiss(): void {\n // Fully remove the widget. It does not linger as a hover-reveal ghost\n // (that's `qaid-incognito`); once dismissed it stays gone until the\n // visitor clears the stored preference.\n this.buttonsContainer!.classList.add(\"qaid-dismissed\");\n setHiddenByUser(this.config.apiKey, true);\n }\n\n private handleThumbClick(type: FeedbackType, buttonEl: HTMLElement, e: MouseEvent): void {\n // If user clicks a thumb while in incognito mode, they want it back.\n // (Dismissed widgets are `display:none`, so this can't fire for them.)\n if (this.buttonsContainer?.classList.contains(\"qaid-incognito\")) {\n this.buttonsContainer.classList.remove(\"qaid-incognito\");\n setHiddenByUser(this.config.apiKey, false);\n }\n // A message modal follows this feedback flow — warm its chunk now.\n this.prewarmModal();\n // \"annotate\" mode and skipTargeting both bypass element targeting and go\n // straight to the (screenshot →) modal flow.\n if (this.config.skipTargeting || this.config.feedbackMode === \"annotate\") {\n this.submitDirectFeedback(type, buttonEl);\n } else {\n // Expose targeting on/off state on the trigger\n this.activeThumbBtn = buttonEl;\n buttonEl.setAttribute(\"aria-pressed\", \"true\");\n // A keyboard-activated <button> fires a synthetic click whose clientX/\n // clientY are (0,0). Route those through the keyboard path instead of\n // elementFromPoint(0,0). `keyboardActivation` is set by a preceding\n // Enter/Space keydown and cleared by any pointerdown/mousedown.\n const keyboard = this.keyboardActivation;\n this.keyboardActivation = false;\n // Load the targeting chunk (pre-warmed on hover) then start it.\n void this.ensureTargeting().then((t) => {\n if (this.destroyed) return;\n if (keyboard) t.startKeyboard(type);\n else t.startPointer(type, e);\n });\n }\n }\n\n private submitDirectFeedback(type: FeedbackType, buttonEl: HTMLElement): void {\n this.feedbackData.feedbackType = type;\n this.feedbackData.elementSelector = null;\n this.feedbackData.elementText = null;\n\n // Use the button's position for modal placement\n const rect = buttonEl.getBoundingClientRect();\n this.selectedBounds = {\n x: rect.left,\n y: rect.top,\n width: rect.width,\n height: rect.height,\n clickX: rect.left + rect.width / 2,\n clickY: rect.top + rect.height / 2,\n visible: false,\n };\n this.submitFeedback();\n }\n\n\n private handleKeyDown(e: KeyboardEvent): void {\n if (e.key === \"Escape\") {\n // The recording controller owns Escape while recording / in preview /\n // picking; let it consume the key first.\n if (this.recording?.handleEscape()) return;\n if (this.state === \"TARGETING\") {\n this.targeting?.cancel();\n } else if (this.state === \"MODAL_OPEN\") {\n this.modal?.close();\n }\n }\n }\n\n\n /** Whether to capture the screenshot with the DOM/canvas method (html2canvas)\n * instead of the permission-based Screen Capture API. Explicit \"dom\" wins;\n * otherwise DOM is used on touch devices to avoid the getDisplayMedia prompt. */\n private shouldCaptureViaDom(): boolean {\n return this.config.screenshotMethod === \"dom\" || isTouchPrimaryDevice();\n }\n\n /**\n * Open the full-screen annotation editor over the captured screenshot,\n * reusing the overlay shadow host and the shared dialog a11y helpers.\n * Resolves with the composited WebP data URL, or null when the user skips\n * (caller keeps the original). Pointer events on the overlay host are\n * enabled while the editor is open and restored on close.\n */\n private async openAnnotationEditor(screenshot: string): Promise<string | null> {\n const root = this.ensureOverlayHost();\n const host = this.overlayShadowHost!;\n const prevPointerEvents = host.style.pointerEvents;\n host.style.pointerEvents = \"auto\";\n try {\n const { openAnnotationEditor } = await import(\"./annotate\");\n return await openAnnotationEditor({\n dataUrl: screenshot,\n root,\n quality: this.config.screenshotOptions.quality,\n color: this.config.annotationColor,\n palette: this.config.annotationPalette,\n applyVars: (el) => this.applyVars(el),\n announce: (msg, assertive) => this.announceMsg(msg, assertive),\n openDialog: (container, opts) => this.openDialogA11y(container, opts),\n closeDialog: () => this.closeDialogA11y(),\n });\n } catch (err) {\n // The annotate chunk failed to load / the editor threw — keep the\n // original screenshot rather than aborting the whole submission.\n console.error(\"Annotation editor failed to open:\", err);\n return null;\n } finally {\n host.style.pointerEvents = prevPointerEvents;\n }\n }\n\n private async submitFeedback(): Promise<void> {\n // Capture screenshot if enabled (server will gate by plan). \"annotate\" mode\n // always captures one to mark up, even without captureScreenshot set.\n let screenshot: string | null = null;\n const wantScreenshot =\n this.config.captureScreenshot || this.config.feedbackMode === \"annotate\";\n if (wantScreenshot) {\n // Loaded on demand so visitors who never submit a screenshot never\n // download the capture + annotation code. A capture failure (denied\n // permission, chunk load error) must never abort the feedback — we just\n // submit without a screenshot so the user still reaches the modal.\n try {\n if (this.shouldCaptureViaDom()) {\n const { captureDomScreenshot } = await import(\"./screenshot-dom\");\n screenshot = await captureDomScreenshot(this.config.screenshotOptions);\n } else {\n const { captureScreenshot } = await import(\"./screenshot\");\n screenshot = await captureScreenshot(this.config.screenshotOptions);\n }\n if (screenshot) this.announceMsg(\"Screenshot captured\");\n } catch (err) {\n console.error(\"Screenshot capture failed:\", err);\n screenshot = null;\n }\n }\n\n // Let the user mark up / redact the screenshot before it is submitted.\n // The message modal only opens after the POST below, so the composited\n // result lands in the same request — no backend change needed. On skip\n // the editor resolves null and the original screenshot is kept.\n if (screenshot && this.config.annotate) {\n screenshot = (await this.openAnnotationEditor(screenshot)) ?? screenshot;\n }\n\n // Include element bounds for server-side screenshot fallback\n // Only include if we have an element selector (element was targeted)\n const elementBounds = this.feedbackData.elementSelector\n ? {\n x: this.selectedBounds.x,\n y: this.selectedBounds.y,\n width: this.selectedBounds.width,\n height: this.selectedBounds.height,\n }\n : null;\n\n const payload: FeedbackPayload = {\n feedbackType: this.feedbackData.feedbackType!,\n pageUrl: window.location.href,\n apiKey: this.config.apiKey || undefined,\n elementSelector: this.feedbackData.elementSelector,\n elementText: this.feedbackData.elementText,\n consoleErrors: [...this.feedbackData.consoleErrors],\n screenWidth: window.innerWidth,\n screenHeight: window.innerHeight,\n clickX: this.selectedBounds.clickX,\n clickY: this.selectedBounds.clickY,\n scrollX: window.scrollX,\n scrollY: window.scrollY,\n screenshot,\n visitorId: this.visitorId,\n // Include element bounds and user agent for server-side screenshot fallback\n elementBounds,\n userAgent: navigator.userAgent,\n };\n\n try {\n const response = await fetch(this.config.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n\n if (response.ok) {\n const data: FeedbackResponse = await response.json();\n this.feedbackId = data.id;\n this.announceMsg(\"Feedback sent\");\n }\n } catch (error) {\n console.error(\"Failed to submit feedback:\", error);\n this.announceMsg(\"Failed to send feedback\", true);\n }\n\n // If this button is linked to a quest, launch it in place of the\n // message box. The feedback record already exists, so on success we\n // just tear down the targeting UI and hand off. On any load failure we\n // fall through to the classic message box so the user can still leave\n // an optional message.\n const type = this.feedbackData.feedbackType;\n // Quest links are keyed by up/down/video; neutral single-button feedback\n // has no quest mapping, so it always falls through to the message box.\n if (type && type !== \"neutral\" && (await this.tryLaunchQuest(type, this.feedbackId))) {\n this.resetFeedbackUi();\n return;\n }\n\n // Always show the message modal as the terminal state (even if the API\n // failed — useful for demos).\n this.state = \"MODAL_OPEN\";\n try {\n // The modal chunk loads async; bail if the embed was destroyed meanwhile,\n // so a raced modal never opens (and never leaks a listener) post-destroy.\n const modal = await this.ensureModal();\n if (this.destroyed) return;\n modal.open();\n\n // Enable pointer events on overlay host for modal\n if (this.overlayShadowHost) {\n this.overlayShadowHost.style.pointerEvents = \"auto\";\n }\n } catch (err) {\n // The modal chunk failed to load/open. Never leave the user stuck in a\n // re-targetable limbo: thank them and reset to IDLE so a fresh click\n // starts a clean flow (the feedback itself was already POSTed above).\n console.error(\"Failed to open the feedback modal:\", err);\n this.announceMsg(\"Thank you for your feedback!\", true);\n this.resetFeedbackUi();\n }\n }\n\n /**\n * Quest id linked to `type`, or \"\" when quest launching is disabled\n * (no `base`) or this button has no quest configured.\n */\n private questIdFor(type: \"up\" | \"down\" | \"video\"): string {\n const q = this.config.quests;\n return q.base ? q[type] || \"\" : \"\";\n }\n\n /**\n * Launch the quest linked to `type`, if any. Resolves `true` when a quest\n * was configured and the widget launched; `false` when no quest is\n * configured or the widget failed to load (caller falls back to its\n * normal UI). The created feedback record id is passed through so the\n * quest response can be joined back to it server-side.\n */\n private async tryLaunchQuest(\n type: \"up\" | \"down\" | \"video\",\n feedbackId: number | string | null,\n ): Promise<boolean> {\n const questId = this.questIdFor(type);\n if (!questId) return false;\n try {\n this.activeQuest?.destroy();\n this.activeQuest = await launchQuest({\n questId,\n base: this.config.quests.base,\n apiKey: this.config.quests.apiKey || undefined,\n moduleUrl: this.config.quests.moduleUrl,\n feedbackId,\n onClose: () => {\n this.activeQuest = null;\n },\n });\n return true;\n } catch (error) {\n console.error(\"Failed to launch quest:\", error);\n this.activeQuest = null;\n return false;\n }\n }\n\n /**\n * Reset the thumbs targeting/marker UI back to idle without opening or\n * closing the message modal. Shared by closeModal() and the quest-launch\n * path (which bypasses the modal entirely).\n */\n private resetFeedbackUi(): void {\n this.targeting?.hideMarker();\n if (this.overlayShadowHost) {\n this.overlayShadowHost.style.pointerEvents = \"none\";\n }\n this.state = \"IDLE\";\n this.feedbackId = null;\n this.feedbackData.feedbackType = null;\n this.feedbackData.elementSelector = null;\n this.feedbackData.elementText = null;\n this.selectedBounds.visible = false;\n }\n\n\n /**\n * Lazily load and instantiate the modal controller. The message modal lives\n * in a separate chunk, fetched the first time it opens (and pre-warmed while\n * the user targets an element — see prewarmModal).\n */\n private async ensureModal(): Promise<ModalController> {\n if (!this.modal) {\n const { ModalController } = await import(\"./modal\");\n this.modal = new ModalController(this.makeModalHost());\n }\n return this.modal;\n }\n\n /** Narrow view of the embed the modal controller talks back through. */\n private makeModalHost(): ModalHost {\n const self = this;\n return {\n get config() {\n return self.config;\n },\n get uid() {\n return self.uid;\n },\n get isMobile() {\n return self.isMobile;\n },\n get state() {\n return self.state;\n },\n get boundKeyDown() {\n return self.boundKeyDown;\n },\n get feedbackData() {\n return self.feedbackData;\n },\n get selectedBounds() {\n return self.selectedBounds;\n },\n get feedbackId() {\n return self.feedbackId;\n },\n setFeedbackId: (id) => {\n self.feedbackId = id;\n },\n ensureOverlayHost: () => self.ensureOverlayHost(),\n applyVars: (el) => self.applyVars(el),\n announceMsg: (message, assertive) => self.announceMsg(message, assertive),\n openDialogA11y: (container, opts) => self.openDialogA11y(container, opts),\n closeDialogA11y: () => self.closeDialogA11y(),\n resetFeedbackUi: () => self.resetFeedbackUi(),\n };\n }\n\n /** Warm the modal chunk while the user is targeting, so it opens instantly. */\n private prewarmModal(): void {\n if (this.modalPrewarmed) return;\n this.modalPrewarmed = true;\n import(\"./modal\").catch(() => {});\n }\n\n /**\n * Lazily load and instantiate the targeting controller. The subsystem (with\n * element-selector) lives in a separate chunk, fetched the first time the\n * user targets — pre-warmed on thumb-button hover (see prewarmTargeting).\n */\n private async ensureTargeting(): Promise<TargetingController> {\n if (!this.targeting) {\n const { TargetingController } = await import(\"./targeting\");\n this.targeting = new TargetingController(this.makeTargetingHost());\n }\n return this.targeting;\n }\n\n /** Narrow view of the embed the targeting controller talks back through. */\n private makeTargetingHost(): TargetingHost {\n const self = this;\n return {\n get config() {\n return self.config;\n },\n get cssVars() {\n return self.cssVars;\n },\n get state() {\n return self.state;\n },\n get shadowHost() {\n return self.shadowHost;\n },\n get overlayShadowHost() {\n return self.overlayShadowHost;\n },\n get boundKeyDown() {\n return self.boundKeyDown;\n },\n get feedbackData() {\n return self.feedbackData;\n },\n get selectedBounds() {\n return self.selectedBounds;\n },\n setState: (state) => {\n self.state = state;\n },\n ensureOverlayHost: () => self.ensureOverlayHost(),\n applyVars: (el) => self.applyVars(el),\n announceMsg: (message, assertive) => self.announceMsg(message, assertive),\n clearActiveThumb: () => self.clearActiveThumb(),\n submitFeedback: () => self.submitFeedback(),\n };\n }\n\n /** Warm the targeting chunk on thumb-button hover, before the click. */\n private prewarmTargeting(): void {\n if (this.targetingPrewarmed || this.config.skipTargeting) return;\n this.targetingPrewarmed = true;\n import(\"./targeting\").catch(() => {});\n }\n\n // ==================== Video Recording ====================\n\n /**\n * Cheap synchronous capability check so the record button can render without\n * pulling in the (lazily-loaded) video subsystem. Mirrors\n * isVideoRecordingSupported() in video-capture.ts.\n */\n private videoSupported(): boolean {\n return (\n typeof navigator !== \"undefined\" &&\n !!navigator.mediaDevices &&\n typeof navigator.mediaDevices.getDisplayMedia === \"function\" &&\n typeof MediaRecorder !== \"undefined\"\n );\n }\n\n\n /**\n * Lazily load and instantiate the recording controller. The whole recording\n * subsystem lives in a separate chunk, fetched only the first time the record\n * button is used (and pre-warmed on hover — see prewarmVideo).\n */\n private async ensureRecording(): Promise<RecordingController> {\n if (!this.recording) {\n const { RecordingController } = await import(\"./recording\");\n this.recording = new RecordingController(this.makeRecordingHost());\n }\n return this.recording;\n }\n\n /** Narrow view of the embed the recording controller talks back through. */\n private makeRecordingHost(): RecordingHost {\n const self = this;\n return {\n get config() {\n return self.config;\n },\n get visitorId() {\n return self.visitorId;\n },\n get uid() {\n return self.uid;\n },\n get overlayShadowHost() {\n return self.overlayShadowHost;\n },\n get consoleCapture() {\n return self.consoleCapture;\n },\n get boundKeyDown() {\n return self.boundKeyDown;\n },\n get state() {\n return self.state;\n },\n setState: (state) => {\n self.state = state;\n },\n ensureOverlayHost: () => self.ensureOverlayHost(),\n applyVars: (el) => self.applyVars(el),\n announceMsg: (message, assertive) => self.announceMsg(message, assertive),\n openDialogA11y: (container, opts) => self.openDialogA11y(container, opts),\n closeDialogA11y: () => self.closeDialogA11y(),\n setButtonsDisabled: (disabled) => self.setButtonsDisabled(disabled),\n tryLaunchQuest: (type, feedbackId) => self.tryLaunchQuest(type, feedbackId),\n };\n }\n\n private setButtonsDisabled(disabled: boolean): void {\n if (!this.buttonsContainer) return;\n const buttons = this.buttonsContainer.querySelectorAll<HTMLButtonElement>(\"button.qaid-btn, button.qaid-btn-structural\");\n buttons.forEach((btn) => {\n if (disabled) {\n // Don't disable the record button itself (it has its own state)\n if (!btn.classList.contains(\"qaid-btn-record\")) {\n btn.disabled = true;\n btn.style.opacity = \"0.5\";\n }\n } else {\n btn.disabled = false;\n btn.style.opacity = \"\";\n }\n });\n }\n\n /**\n * Destroy the embed and clean up all resources\n */\n public destroy(): void {\n // Flag as destroyed so the DOM observer doesn't re-attach hosts\n this.destroyed = true;\n\n // Disconnect DOM persistence observers\n if (this.domObserver) {\n this.domObserver.disconnect();\n this.domObserver = null;\n }\n if (this.boundBeforeSwap) {\n document.removeEventListener(\"astro:before-swap\", this.boundBeforeSwap);\n this.boundBeforeSwap = null;\n }\n\n // Tear down the targeting subsystem + release any open dialog focus state\n this.targeting?.destroy();\n this.targeting = null;\n this.clearActiveThumb();\n this.closeDialogA11y();\n\n // Cancel any pending idle preload\n if (this.prewarmHandle !== null) {\n const w = window as unknown as { cancelIdleCallback?: (h: number) => void };\n if (this.prewarmIsTimeout) clearTimeout(this.prewarmHandle);\n else w.cancelIdleCallback?.(this.prewarmHandle);\n this.prewarmHandle = null;\n }\n\n // Tear down the recording subsystem (recorder, picker, preview) if loaded.\n this.recording?.destroy();\n this.recording = null;\n // Tear down the message modal if it was loaded/open.\n this.modal?.destroy();\n this.modal = null;\n\n // Tear down any quest launched from a button\n this.activeQuest?.destroy();\n this.activeQuest = null;\n\n // Restore console.error\n if (this.consoleCapture) {\n this.consoleCapture.restore();\n this.consoleCapture = null;\n }\n\n // Remove event listeners\n window.removeEventListener(\"resize\", this.boundResize);\n document.removeEventListener(\"keydown\", this.boundKeyDown);\n\n document.body.classList.remove(\"qaid-targeting\", \"qaid-type-up\");\n document.body.style.removeProperty(\"--qaid-positive\");\n document.body.style.removeProperty(\"--qaid-negative\");\n\n // Remove shadow hosts from DOM (this removes shadow roots and all their contents)\n if (this.shadowHost) {\n this.shadowHost.remove();\n this.shadowHost = null;\n this.shadowRoot = null;\n }\n if (this.overlayShadowHost) {\n this.overlayShadowHost.remove();\n this.overlayShadowHost = null;\n this.overlayShadowRoot = null;\n }\n this.buttonsContainer = null;\n this.dismissBtn = null;\n this.tooltipElement = null;\n\n // Remove light DOM styles (reference counted)\n removeStyles();\n }\n}\n","/**\n * Auto-initialization from a `<script>` tag.\n *\n * Shared by both delivery entries: the legacy UMD/API entry (`index.ts`) and\n * the minimal ESM loader (`loader.ts`). Kept out of `index.ts` so the loader\n * can auto-init without pulling in `index.ts`'s feature re-exports — that\n * re-export graph is what anchors screenshot/video/annotate into the main\n * chunk and defeats code-splitting.\n */\n\nimport { QaidFeedback } from \"./embed\";\nimport type { FeedbackConfig } from \"./types\";\n\n/**\n * Find theme CSS from an element matched by a CSS selector.\n * Used by data-css-selector attribute and JSON cssSelector property.\n */\nfunction findCssFromSelector(selector: string): string {\n const el = document.querySelector(selector);\n return el?.textContent?.trim() ?? \"\";\n}\n\n/**\n * Parse JSON config from a separate script tag with type=\"application/json\"\n * Looks for: <script type=\"application/json\" data-feedback-config>{ ... }</script>\n */\nfunction parseJsonConfig(): Partial<FeedbackConfig> | null {\n const configScript = document.querySelector(\n 'script[type=\"application/json\"][data-feedback-config]'\n );\n if (!configScript) return null;\n\n const textContent = configScript.textContent?.trim();\n if (!textContent) return null;\n\n try {\n const parsed = JSON.parse(textContent);\n // Resolve cssSelector → css\n if (parsed.cssSelector && !parsed.css) {\n parsed.css = findCssFromSelector(parsed.cssSelector);\n delete parsed.cssSelector;\n }\n return parsed;\n } catch {\n return null;\n }\n}\n\n/**\n * 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","/**\n * Minimal ESM loader entry for progressive delivery.\n *\n * ```html\n * <script type=\"module\" src=\"…/loader.js\" data-endpoint=\"/api/feedback\"></script>\n * ```\n *\n * Ships only the core (thumbs buttons, modal, element targeting, submit).\n * Screenshot capture, the annotation editor, and the video subsystem\n * (including redaction) load on demand as separate chunks the first time each\n * is used — so a visitor who only gives a thumbs-up never downloads them.\n *\n * The full programmatic API (createVideoRecorder, openAnnotationEditor, …)\n * lives on the package's main entry (`@qaiddev/thumbs-embed`).\n */\n\nimport { QaidFeedback } from \"./embed\";\nimport { autoInit } from \"./bootstrap\";\n\nexport { QaidFeedback };\nexport type { FeedbackConfig } from \"./types\";\n\nautoInit();\n"],"names":["instanceCount","DEFAULT_BUTTON_STYLES","BUTTON_SIZES","ICON_SIZES","getLuminance","r","g","b","rs","gs","bs","c","parseColor","color","hex","fullHex","num","match","getContrastTextColor","bgColor","rgb","buildCssVars","options","positiveColor","negativeColor","markerColor","buttonSize","modalWidth","backdropOpacity","fontFamily","fontSize","btnSize","iconSize","markerTextColor","applyCssVars","el","vars","name","value","getEmbedStyles","shadowStyles","injectStyles","style","lightStyles","removeStyles","POLITE_ATTR","VISUALLY_HIDDEN_CSS","FOCUSABLE_SELECTOR","ownerDoc","root","getLiveRegion","assertive","kind","existing","region","announce","message","opts","isDisabled","isHidden","node","getFocusable","container","getDeepActiveElement","doc","active","createFocusTrap","addedTabindex","onKeydown","event","focusable","first","last","withinTrap","initial","saveFocus","restoreFocus","applyDialog","topLevelAncestor","body","parent","setBackgroundInert","except","keep","changed","child","prevInert","prevAriaHidden","entry","DEFAULT_DIMENSIONS","calculateVerticalPosition","bounds","viewportHeight","totalHeight","gap","viewportPadding","spaceAbove","spaceBelow","position","top","calculateHorizontalPosition","viewportWidth","left","calculateArrowPosition","modalLeft","minOffset","arrowWidth","arrowLeft","calculateModalPosition","dimensions","vertical","calculateTooltipPosition","anchor","tooltip","viewport","calculateModalAndArrowPosition","modal","MAX_MESSAGES","captureConsoleErrors","onError","errors","originalError","originalWarn","originalLog","capture","level","args","error","arg","DEFAULT_QUESTS_MODULE_URL","defaultImporter","url","importer","modulePromise","cachedUrl","loadQuestsModule","moduleUrl","mod","m","err","launchQuest","base","metadata","VISITOR_ID_KEY","HIDE_FEEDBACK_KEY","DEFAULT_ANNOTATION_PALETTE","isTouchPrimaryDevice","getHideKey","apiKey","isHiddenByUser","setHiddenByUser","hidden","randomId","bytes","i","getOrCreateVisitorId","visitorId","QaidFeedback","config","_error","n","fn","w","guarded","e","newDoc","isMobileViewport","userContainer","baseStyle","themeStyle","dirClass","offsetX","offsetY","ev","useCustomClass","btnBaseClass","tooltipText","fbWrapper","fbBtn","FEEDBACK_ICON","upWrapper","upBtn","THUMBS_UP_ICON","downWrapper","downBtn","THUMBS_DOWN_ICON","recordWrapper","recordBtn","RECORD_ICON","rec","warmVideo","anchorRect","tooltipRect","type","buttonEl","keyboard","t","rect","screenshot","host","prevPointerEvents","openAnnotationEditor","msg","captureDomScreenshot","captureScreenshot","elementBounds","payload","response","data","q","feedbackId","questId","ModalController","self","id","TargetingController","state","RecordingController","disabled","btn","findCssFromSelector","selector","parseJsonConfig","configScript","textContent","parsed","warnIgnored","attr","expected","splitTopLevel","parts","depth","current","ch","parseColorList","raw","list","parseLabel","parseDataAttributes","script","endpoint","zIndex","buttonClass","skipTargeting","hideConfirmation","singleButton","feedbackMode","incognito","modalTitle","confirmationTitle","confirmationMessage","confirmationClose","errorTitle","errorMessage","modalSubtitle","placeholder","submitButton","skipButton","positiveIcon","negativeIcon","feedbackIcon","feedbackLabel","annotate","annotationColor","screenshotQuality","screenshotMaxWidth","screenshotMaxHeight","captureVideo","redaction","hideThumbs","hideDismiss","videoMaxDuration","screenshotMethod","direction","cssSelector","css","positiveLabel","negativeLabel","recordLabel","dismissLabel","annotationPalette","recordIcon","questBase","questUp","questDown","questVideo","questApiKey","questModuleUrl","autoInit","run"],"mappings":";;AASA,IAAIA,IAAgB;AAGpB,MAAMC,KAAwB,m6BAmBxBC,KAAe;AAAA,EACnB,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,OAAO;AACT,GAEMC,KAAa;AAAA,EACjB,OAAO;AAAA,EACP,QAA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AAa;AAErC,QAAMC,IAAM,MAAY;AAGtB,UAAMlD,IACH,SAAS,iBACV,SAAS,cAAiC,uBAAuB,GAI7DjF,IAASgE,SAAsBiB,IAASD,GAAoBC,CAAM,IAAI;AAE5E,IAAIjF,GAAQ,YACV,IAAID,GAAaC,CAAwB;AAAA,EAE7C;AAEA,EAAI,SAAS,eAAe,YAC1B,SAAS,iBAAiB,oBAAoBmI,CAAG,IAEjDA,EAAA;AAEJ;AC1SAD,GAAA;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"modal-CEfcaIQR.js","sources":["../../src/modal.ts"],"sourcesContent":["/**\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 {\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 readonly feedbackId: number | null;\n setFeedbackId(id: number | null): void;\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\n constructor(private host: ModalHost) {}\n\n open(): void {\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 if (this.host.state === \"MODAL_OPEN\" && this.host.feedbackId) {\n fetch(`${this.host.config.endpoint}/${this.host.feedbackId}`, {\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 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\n if (this.host.feedbackId) {\n fetch(`${this.host.config.endpoint}/${this.host.feedbackId}`, {\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 if (this.host.feedbackId) {\n try {\n const response = await fetch(`${this.host.config.endpoint}/${this.host.feedbackId}`, {\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 // Clear feedbackId so close() doesn't send another PATCH.\n this.host.setFeedbackId(null);\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"],"names":["ModalController","host","root","err","sheet","h","modal","arrow","calculateModalAndArrowPosition","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"],"mappings":";;;AAgDO,MAAMA,EAAgB;AAAA,EAI3B,YAAoBC,GAAiB;AAAjB,SAAA,OAAAA;AAAA,EAAkB;AAAA,EAAlB;AAAA,EAHZ,iBAAwC;AAAA,EACxC,WAAkC;AAAA,EAI1C,OAAa;AACX,UAAMC,IAAO,KAAK,KAAK,kBAAA;AAGvB,SAAK,WAAW,SAAS,cAAc,KAAK,GAC5C,KAAK,SAAS,YAAY,iBAC1B,KAAK,SAAS,MAAM,SAAS,OAAO,KAAK,KAAK,OAAO,SAAS,CAAC,GAC/D,KAAK,SAAS,MAAM,aAAa,iBAAiB,KAAK,KAAK,OAAO,eAAe,KAClF,KAAK,SAAS,iBAAiB,SAAS,MAAM,KAAK,OAAO,GAC1D,KAAK,KAAK,UAAU,KAAK,QAAQ,GAE7B,KAAK,KAAK,WACZ,KAAK,gBAAA,IAEL,KAAK,oBAAA,GAGPA,EAAK,YAAY,KAAK,QAAQ,GAC9B,SAAS,iBAAiB,WAAW,KAAK,KAAK,YAAY;AAAA,EAC7D;AAAA;AAAA,EAGA,QAAc;AAEZ,IAAI,KAAK,KAAK,UAAU,gBAAgB,KAAK,KAAK,cAChD,MAAM,GAAG,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