@qaiddev/thumbs-embed 1.11.0 → 1.12.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.
- package/dist/a11y-dialog.d.ts +77 -0
- package/dist/a11y.d.ts +6 -65
- package/dist/chunks/annotate-DGyRcgPt.js +2 -0
- package/dist/chunks/{annotate-5zJWs-aB.js.map → annotate-DGyRcgPt.js.map} +1 -1
- package/dist/chunks/core-BsR7oV99.js +26 -0
- package/dist/chunks/core-BsR7oV99.js.map +1 -0
- package/dist/chunks/dom-scpOS8nl.js +2 -0
- package/dist/chunks/{dom-DvdtcUS8.js.map → dom-scpOS8nl.js.map} +1 -1
- package/dist/chunks/modal-DYxcs1Gm.js +2 -0
- package/dist/chunks/modal-DYxcs1Gm.js.map +1 -0
- package/dist/chunks/recording-BUw5-5Rf.js +2 -0
- package/dist/chunks/{recording-CPzxRL7f.js.map → recording-BUw5-5Rf.js.map} +1 -1
- package/dist/chunks/screenshot-CNe1irEz.js +2 -0
- package/dist/chunks/{screenshot-DYOKg2bS.js.map → screenshot-CNe1irEz.js.map} +1 -1
- package/dist/chunks/screenshot-dom-ZYP2w2h0.js +2 -0
- package/dist/chunks/{screenshot-dom-CME7tYRE.js.map → screenshot-dom-ZYP2w2h0.js.map} +1 -1
- package/dist/chunks/send-C26DRoYc.js +2 -0
- package/dist/chunks/send-C26DRoYc.js.map +1 -0
- package/dist/chunks/targeting-CMUEe-7C.js +6 -0
- package/dist/chunks/{targeting-mahtuPpo.js.map → targeting-CMUEe-7C.js.map} +1 -1
- package/dist/chunks/video-BSP4s2te.js +2 -0
- package/dist/chunks/{video-Bd_29-rK.js.map → video-BSP4s2te.js.map} +1 -1
- package/dist/embed.d.ts +26 -31
- package/dist/index.js +1495 -1390
- package/dist/index.js.map +1 -1
- package/dist/loader.d.ts +6 -4
- package/dist/loader.js +1 -6
- package/dist/loader.js.map +1 -1
- package/dist/modal-positioning.d.ts +0 -27
- package/dist/qaid.umd.cjs +14 -14
- package/dist/qaid.umd.cjs.map +1 -1
- package/dist/quest-config.d.ts +2 -0
- package/dist/quest-launcher.d.ts +1 -3
- package/dist/send.d.ts +60 -0
- package/dist/tooltip-positioning.d.ts +31 -0
- package/package.json +1 -1
- package/dist/chunks/annotate-5zJWs-aB.js +0 -357
- package/dist/chunks/core-CL1dwdaN.js +0 -1342
- package/dist/chunks/core-CL1dwdaN.js.map +0 -1
- package/dist/chunks/dom-DvdtcUS8.js +0 -17
- package/dist/chunks/modal-DccueVYZ.js +0 -222
- package/dist/chunks/modal-DccueVYZ.js.map +0 -1
- package/dist/chunks/recording-CPzxRL7f.js +0 -323
- package/dist/chunks/screenshot-DYOKg2bS.js +0 -33
- package/dist/chunks/screenshot-dom-CME7tYRE.js +0 -63
- package/dist/chunks/targeting-mahtuPpo.js +0 -298
- package/dist/chunks/video-Bd_29-rK.js +0 -214
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"targeting-mahtuPpo.js","sources":["../../src/element-selector.ts","../../src/targeting.ts"],"sourcesContent":["/**\n * Element selector generation utilities\n */\n\n/** Data attributes to look for (in priority order) */\nexport const DATA_ATTRS = [\"data-comp\", \"data-qa\", \"data-testid\", \"data-id\"];\n\nexport interface ElementInfo {\n selector: string;\n text: string;\n dataAttr: string | null;\n}\n\n/**\n * Find the first matching data attribute on an element or its ancestors\n */\nexport function findDataAttribute(\n element: Element,\n stopAt: Element = document.body\n): string | null {\n let current: Element | null = element;\n\n while (current && current !== stopAt) {\n for (const attr of DATA_ATTRS) {\n const value = current.getAttribute(attr);\n if (value) {\n return `${attr}=\"${value}\"`;\n }\n }\n current = current.parentElement;\n }\n\n return null;\n}\n\n/**\n * Get truncated text content from an element\n */\nexport function getTruncatedText(element: Element, maxLength = 100): string {\n const textContent = element.textContent?.trim().slice(0, maxLength) || \"\";\n return textContent.length === maxLength ? textContent + \"...\" : textContent;\n}\n\n/**\n * Get the nth-child index of an element among its siblings\n */\nfunction getNthChildIndex(element: Element): number {\n let index = 1;\n let sibling = element.previousElementSibling;\n while (sibling) {\n index++;\n sibling = sibling.previousElementSibling;\n }\n return index;\n}\n\n/**\n * Generate an nth-child path from body to the element\n * This is always a valid CSS selector and uniquely identifies the element\n * Exported for testing\n */\nexport function generateNthChildPath(element: Element): string {\n const path: string[] = [];\n let current: Element | null = element;\n\n while (current && current !== document.body && current !== document.documentElement) {\n const tag = current.tagName.toLowerCase();\n const index = getNthChildIndex(current);\n path.unshift(`${tag}:nth-child(${index})`);\n current = current.parentElement;\n }\n\n return path.length > 0 ? `body > ${path.join(\" > \")}` : \"body\";\n}\n\n/**\n * Escape special CSS characters in a string (for IDs with special chars)\n */\nfunction escapeCSSIdentifier(str: string): string {\n return str.replace(/([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~])/g, \"\\\\$1\");\n}\n\n/**\n * Generate a selector string for an element\n * Priority: data attribute > ID > nth-child path\n */\nexport function generateSelector(element: Element): string {\n // Try data attribute first (on element or ancestors) - most stable\n const dataAttr = findDataAttribute(element);\n if (dataAttr) {\n return `[${dataAttr}]`;\n }\n\n // Try ID (escaped for special characters)\n if (element.id) {\n return `#${escapeCSSIdentifier(element.id)}`;\n }\n\n // Fall back to nth-child path - always valid and unique\n return generateNthChildPath(element);\n}\n\n/**\n * Generate complete element info for feedback\n */\nexport function generateElementInfo(element: Element): ElementInfo {\n const text = getTruncatedText(element);\n const dataAttr = findDataAttribute(element);\n const selector = generateSelector(element);\n\n return { selector, text, dataAttr };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Keyboard element targeting */\n/* */\n/* The mouse targeting path in embed.ts resolves the target with */\n/* elementFromPoint(clientX, clientY). A keyboard-activated thumb produces a */\n/* synthetic click at (0, 0), so a keyboard-only user can never point at a */\n/* real element. This controller provides a coordinate-free alternative: */\n/* Tab / arrow keys move a highlight between candidate elements (seeded from */\n/* document.activeElement), Enter / Space selects, Escape cancels. It never */\n/* hides the cursor — it drives the *native* focus ring instead, so both */\n/* sighted keyboard users and screen readers can follow the highlight. */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Default set of \"targetable\" elements for keyboard navigation: focusable\n * controls, ARIA-role'd nodes, common semantic content, and anything already\n * carrying one of the stable data attributes we key selectors off of.\n */\nexport const TARGETABLE_SELECTOR: string = [\n \"a[href]\",\n \"button\",\n \"input:not([type=hidden])\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"[tabindex]\",\n \"[role]\",\n \"img\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"h5\",\n \"h6\",\n \"p\",\n \"li\",\n \"label\",\n ...DATA_ATTRS.map((attr) => `[${attr}]`),\n].join(\",\");\n\n/** Tag names that already take keyboard focus without an added tabindex. */\nconst NATIVELY_FOCUSABLE = /^(?:A|BUTTON|INPUT|SELECT|TEXTAREA|SUMMARY)$/;\n\n/**\n * Best-effort visibility test used to keep invisible nodes out of the keyboard\n * candidate list. Deliberately layout-free (no getBoundingClientRect) so it is\n * stable in headless/test environments: it only rejects nodes that are\n * explicitly hidden via the `hidden` attribute, `aria-hidden`, or a computed\n * `display:none` / `visibility:hidden`.\n */\nexport function isElementVisible(element: Element): boolean {\n if (element.hasAttribute(\"hidden\")) return false;\n if (element.getAttribute(\"aria-hidden\") === \"true\") return false;\n const view = element.ownerDocument?.defaultView;\n if (view && typeof view.getComputedStyle === \"function\") {\n const style = view.getComputedStyle(element);\n if (style.display === \"none\" || style.visibility === \"hidden\") return false;\n }\n return true;\n}\n\nexport interface CollectTargetableOptions {\n /** Where to search for candidates (default `document.body`). */\n root?: ParentNode;\n /** CSS selector for candidate elements (default {@link TARGETABLE_SELECTOR}). */\n selector?: string;\n /** Return true to drop an element (e.g. the embed's own shadow hosts). */\n isExcluded?: (element: Element) => boolean;\n /** Visibility predicate (default {@link isElementVisible}). */\n isVisible?: (element: Element) => boolean;\n}\n\n/**\n * Collect the ordered list of elements a keyboard user can target. Document\n * order matches the natural Tab order closely enough for feedback targeting.\n */\nexport function collectTargetableElements(\n options: CollectTargetableOptions = {}\n): Element[] {\n const root = options.root ?? document.body;\n const selector = options.selector ?? TARGETABLE_SELECTOR;\n const isExcluded = options.isExcluded ?? (() => false);\n const isVisible = options.isVisible ?? isElementVisible;\n\n return Array.from(root.querySelectorAll(selector)).filter(\n (element) => !isExcluded(element) && isVisible(element)\n );\n}\n\nexport interface KeyboardTargetingOptions {\n /**\n * Explicit candidate list. When omitted, candidates are collected via\n * {@link collectTargetableElements} using `root` / `selector` / `isExcluded`\n * / `isVisible`.\n */\n candidates?: Element[];\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n root?: ParentNode;\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n selector?: string;\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n isExcluded?: (element: Element) => boolean;\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n isVisible?: (element: Element) => boolean;\n /**\n * Element to start the highlight on. Defaults to `document.activeElement`\n * when it is one of the candidates, otherwise the first candidate.\n */\n initial?: Element | null;\n /**\n * Move native focus to the highlighted element (default true). This is what\n * keeps a screen reader / focus ring on the highlight; non-focusable nodes\n * get a temporary `tabindex=\"-1\"` that is removed on {@link stop}. The cursor\n * is never hidden.\n */\n moveFocus?: boolean;\n /** Where the keydown listener is attached (default `document`). */\n eventTarget?: Document | HTMLElement;\n /** Fired whenever the highlighted candidate changes (and once on start). */\n onHighlight?: (element: Element, index: number) => void;\n /** Fired when the user commits a selection (Enter / Space). Auto-stops first. */\n onSelect: (element: Element) => void;\n /** Fired when the user cancels (Escape). Auto-stops first. */\n onCancel?: () => void;\n}\n\nexport interface KeyboardTargetingController {\n /** The (frozen) candidate list being navigated. */\n readonly candidates: readonly Element[];\n /** Index of the highlighted candidate, or -1 when there are none. */\n getIndex(): number;\n /** The highlighted candidate, or null when there are none. */\n getCurrent(): Element | null;\n /** Highlight the next candidate (wraps to the first). */\n next(): void;\n /** Highlight the previous candidate (wraps to the last). */\n prev(): void;\n /** Highlight a specific index (wraps out-of-range values). */\n moveTo(index: number): void;\n /** Commit the current candidate (fires onSelect) and stop. */\n select(): void;\n /** Cancel (fires onCancel) and stop. */\n cancel(): void;\n /**\n * Handle a keydown. Wired automatically to `eventTarget`; exposed so a host\n * can forward events from another surface (e.g. the embed's shadow root).\n */\n handleKey(event: KeyboardEvent): void;\n /** Remove the listener and restore any temporary tabindex. Idempotent. */\n stop(): void;\n}\n\n/**\n * Start a keyboard element-targeting session. The returned controller wires its\n * own capture-phase keydown listener on `eventTarget` and emits the initial\n * highlight synchronously before returning.\n */\nexport function startKeyboardTargeting(\n options: KeyboardTargetingOptions\n): KeyboardTargetingController {\n const candidates =\n options.candidates ??\n collectTargetableElements({\n root: options.root,\n selector: options.selector,\n isExcluded: options.isExcluded,\n isVisible: options.isVisible,\n });\n\n const moveFocus = options.moveFocus ?? true;\n const target: EventTarget = options.eventTarget ?? document;\n const addedTabindex = new Set<Element>();\n\n let index = -1;\n let stopped = false;\n\n // Seed the highlight from the currently focused element when it is a\n // candidate; this makes \"Tab to a control, then hit the thumb\" land on that\n // control rather than the top of the page.\n const seed =\n options.initial !== undefined\n ? options.initial\n : typeof document !== \"undefined\"\n ? document.activeElement\n : null;\n if (seed) {\n const seedIndex = candidates.indexOf(seed);\n if (seedIndex >= 0) index = seedIndex;\n }\n if (index < 0 && candidates.length > 0) index = 0;\n\n function focusCurrent(element: Element): void {\n if (!moveFocus) return;\n const focusable = element as HTMLElement;\n if (typeof focusable.focus !== \"function\") return;\n // Make non-focusable content (p, img, li, …) programmatically focusable so\n // the native focus ring and AT follow the highlight. Never hide the cursor.\n if (\n element.getAttribute(\"tabindex\") === null &&\n !NATIVELY_FOCUSABLE.test(element.tagName)\n ) {\n element.setAttribute(\"tabindex\", \"-1\");\n addedTabindex.add(element);\n }\n try {\n focusable.focus();\n } catch {\n /* focus can throw in detached/headless cases — highlight still works */\n }\n }\n\n function emitHighlight(): void {\n const element = candidates[index];\n if (!element) return;\n focusCurrent(element);\n options.onHighlight?.(element, index);\n }\n\n function moveTo(nextIndex: number): void {\n if (stopped || candidates.length === 0) return;\n const len = candidates.length;\n index = ((nextIndex % len) + len) % len; // wrap in both directions\n emitHighlight();\n }\n\n function next(): void {\n moveTo(index + 1);\n }\n\n function prev(): void {\n moveTo(index - 1);\n }\n\n function getCurrent(): Element | null {\n return candidates[index] ?? null;\n }\n\n function stop(): void {\n if (stopped) return;\n stopped = true;\n target.removeEventListener(\"keydown\", handleKey as EventListener, true);\n addedTabindex.forEach((element) => element.removeAttribute(\"tabindex\"));\n addedTabindex.clear();\n }\n\n function select(): void {\n if (stopped) return;\n const element = getCurrent();\n stop();\n if (element) options.onSelect(element);\n }\n\n function cancel(): void {\n if (stopped) return;\n stop();\n options.onCancel?.();\n }\n\n function handleKey(event: KeyboardEvent): void {\n if (stopped) return;\n switch (event.key) {\n case \"Tab\":\n event.preventDefault();\n event.stopPropagation();\n if (event.shiftKey) prev();\n else next();\n break;\n case \"ArrowDown\":\n case \"ArrowRight\":\n event.preventDefault();\n event.stopPropagation();\n next();\n break;\n case \"ArrowUp\":\n case \"ArrowLeft\":\n event.preventDefault();\n event.stopPropagation();\n prev();\n break;\n case \"Enter\":\n case \" \":\n case \"Spacebar\": // legacy key value\n event.preventDefault();\n event.stopPropagation();\n select();\n break;\n case \"Escape\":\n case \"Esc\": // legacy key value\n event.preventDefault();\n event.stopPropagation();\n cancel();\n break;\n default:\n break;\n }\n }\n\n target.addEventListener(\"keydown\", handleKey as EventListener, true);\n\n // Emit the initial highlight so the caller can position its highlight box.\n if (index >= 0) emitHighlight();\n\n return {\n candidates,\n getIndex: () => index,\n getCurrent,\n next,\n prev,\n moveTo,\n select,\n cancel,\n handleKey,\n stop,\n };\n}\n","/**\n * Element-targeting subsystem — extracted from embed.ts into its own lazily\n * loaded chunk (it also carries `element-selector`, ~14 KB). It's fetched the\n * first time the user starts targeting (and pre-warmed on thumb-button hover,\n * so the reticle appears without a perceptible wait).\n *\n * The controller owns the reticle/overlay, the mouse/touch/keyboard targeting\n * flows, and the selected-element marker; it talks back to the embed through\n * the narrow `TargetingHost` interface.\n */\n\nimport {\n generateElementInfo,\n startKeyboardTargeting,\n type KeyboardTargetingController,\n} from \"./element-selector\";\nimport {\n getElementAtPointUnderOverlay,\n isEmbedElement,\n getElementBounds,\n} from \"./dom-utils\";\nimport type {\n ResolvedFeedbackConfig,\n EmbedState,\n FeedbackData,\n FeedbackType,\n SelectedBounds,\n} from \"./types\";\nimport featureStyles from \"./styles-targeting.css?inline\";\n\n/** A touch that moves more than this (px) is a scroll, not a tap-to-select. */\nconst TOUCH_TAP_SLOP = 12;\n\n/** The slice of the embed the targeting subsystem needs. */\nexport interface TargetingHost {\n readonly config: ResolvedFeedbackConfig;\n readonly cssVars: Record<string, string>;\n readonly state: EmbedState;\n readonly shadowHost: HTMLDivElement | null;\n readonly overlayShadowHost: HTMLDivElement | null;\n readonly boundKeyDown: (e: KeyboardEvent) => void;\n /** Live references, mutated in place. */\n readonly feedbackData: FeedbackData;\n readonly selectedBounds: SelectedBounds;\n setState(state: EmbedState): void;\n ensureOverlayHost(): ShadowRoot;\n applyVars(el: HTMLElement): void;\n announceMsg(message: string, assertive?: boolean): void;\n clearActiveThumb(): void;\n submitFeedback(): Promise<void>;\n}\n\nexport class TargetingController {\n private mousePos = { x: 0, y: 0 };\n private touchStartPos: { x: number; y: number } | null = null;\n private overlayContainer: HTMLDivElement | null = null;\n private captureLayer: HTMLDivElement | null = null;\n private crosshairH: HTMLDivElement | null = null;\n private crosshairV: HTMLDivElement | null = null;\n private scope: HTMLDivElement | null = null;\n private highlightBox: HTMLDivElement | null = null;\n private marker: HTMLDivElement | null = null;\n private keyboardController: KeyboardTargetingController | null = null;\n\n private boundMouseMove = (e: MouseEvent): void => this.handleMouseMove(e);\n private boundClick = (e: MouseEvent): void => this.handleClick(e);\n private boundTouchStart = (e: TouchEvent): void => this.handleTouchStart(e);\n private boundTouchEnd = (e: TouchEvent): void => this.handleTouchEnd(e);\n\n constructor(private host: TargetingHost) {}\n\n startPointer(type: FeedbackType, e: MouseEvent): void {\n this.host.setState(\"TARGETING\");\n this.host.feedbackData.feedbackType = type;\n this.host.feedbackData.elementSelector = null;\n this.host.feedbackData.elementText = null;\n this.host.selectedBounds.visible = false;\n\n // Track initial mouse position from the click event\n this.mousePos.x = e.clientX;\n this.mousePos.y = e.clientY;\n\n // Add class to body (light DOM — for cursor override)\n document.body.classList.add(\"qaid-targeting\");\n if (type === \"up\") {\n document.body.classList.add(\"qaid-type-up\");\n } else {\n document.body.classList.remove(\"qaid-type-up\");\n }\n\n // Set targeting colors on body so .qaid-highlight rules can resolve them\n document.body.style.setProperty(\"--qaid-positive\", this.host.cssVars[\"--qaid-positive\"]);\n document.body.style.setProperty(\"--qaid-negative\", this.host.cssVars[\"--qaid-negative\"]);\n\n this.createTargetingOverlay();\n\n // Add event listeners on document — overlay is pointer-events:none so scroll works naturally\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n document.addEventListener(\"mousemove\", this.boundMouseMove);\n document.addEventListener(\"click\", this.boundClick, true);\n // Touch: tap to select (scrolling stays enabled). touchstart is passive\n // (we only read the point); touchend is non-passive so a tap can\n // preventDefault the synthesised click that would otherwise activate the\n // targeted element.\n document.addEventListener(\"touchstart\", this.boundTouchStart, { passive: true });\n document.addEventListener(\"touchend\", this.boundTouchEnd, { passive: false });\n }\n\n /**\n * Keyboard-driven targeting. Mirrors startPointer minus the mouse plumbing:\n * no `qaid-targeting` body class (keeps the cursor visible for keyboard\n * users), no mouse reticle, and no document mouse/click listeners. The\n * KeyboardTargetingController owns Tab/Arrow/Enter/Space/Escape.\n */\n startKeyboard(type: FeedbackType): void {\n this.host.setState(\"TARGETING\");\n this.host.feedbackData.feedbackType = type;\n this.host.feedbackData.elementSelector = null;\n this.host.feedbackData.elementText = null;\n this.host.selectedBounds.visible = false;\n\n document.body.style.setProperty(\"--qaid-positive\", this.host.cssVars[\"--qaid-positive\"]);\n document.body.style.setProperty(\"--qaid-negative\", this.host.cssVars[\"--qaid-negative\"]);\n\n // Build the highlight box, then hide the mouse reticle (meaningless here)\n this.createTargetingOverlay();\n if (this.crosshairH) this.crosshairH.style.display = \"none\";\n if (this.crosshairV) this.crosshairV.style.display = \"none\";\n if (this.scope) this.scope.style.display = \"none\";\n\n this.keyboardController = startKeyboardTargeting({\n isExcluded: (el) => isEmbedElement(el),\n onHighlight: (el) => {\n const rect = el.getBoundingClientRect();\n const b = this.highlightBox;\n if (b) {\n b.style.transform = `translate(${rect.left}px, ${rect.top}px)`;\n b.style.width = `${rect.width}px`;\n b.style.height = `${rect.height}px`;\n b.style.display = \"block\";\n }\n const { text } = generateElementInfo(el);\n this.host.announceMsg(`Targeting ${text || el.tagName.toLowerCase()}`);\n },\n onSelect: (el) => this.selectKeyboardTarget(el),\n onCancel: () => this.cancel(),\n });\n }\n\n private selectKeyboardTarget(el: Element): void {\n const bounds = getElementBounds(el, 8);\n Object.assign(this.host.selectedBounds, bounds, {\n clickX: bounds.x + bounds.width / 2,\n clickY: bounds.y + bounds.height / 2,\n visible: true,\n });\n\n const { selector, text } = generateElementInfo(el);\n this.host.feedbackData.elementSelector = selector;\n this.host.feedbackData.elementText = text;\n\n // Teardown (controller has already auto-stopped before onSelect fired)\n this.removeTargetingOverlay();\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 this.keyboardController = null;\n this.host.clearActiveThumb();\n\n this.host.setState(\"SELECTED\");\n this.showSelectedMarker();\n void this.host.submitFeedback();\n }\n\n private createTargetingOverlay(): void {\n const root = this.host.ensureOverlayHost();\n\n this.overlayContainer = document.createElement(\"div\");\n this.overlayContainer.className = `qaid-targeting-overlay qaid-type-${this.host.feedbackData.feedbackType}`;\n\n // Capture layer (pointer-events:none — scroll passes through naturally)\n this.captureLayer = document.createElement(\"div\");\n this.captureLayer.className = \"qaid-capture-layer\";\n\n // Vignette\n const vignette = document.createElement(\"div\");\n vignette.className = \"qaid-vignette\";\n\n // Crosshairs\n this.crosshairH = document.createElement(\"div\");\n this.crosshairH.className = \"qaid-crosshair-h\";\n\n this.crosshairV = document.createElement(\"div\");\n this.crosshairV.className = \"qaid-crosshair-v\";\n\n // Scope\n this.scope = document.createElement(\"div\");\n this.scope.className = \"qaid-scope\";\n this.scope.innerHTML = `\n <div class=\"qaid-scope-ring\"></div>\n <div class=\"qaid-scope-ring-inner\"></div>\n <div class=\"qaid-scope-dot\"></div>\n `;\n\n // Highlight box overlay (positioned over hovered elements)\n this.highlightBox = document.createElement(\"div\");\n this.highlightBox.className = \"qaid-highlight-box\";\n\n this.overlayContainer.appendChild(this.captureLayer);\n this.overlayContainer.appendChild(vignette);\n this.overlayContainer.appendChild(this.highlightBox);\n this.overlayContainer.appendChild(this.crosshairH);\n this.overlayContainer.appendChild(this.crosshairV);\n this.overlayContainer.appendChild(this.scope);\n\n // Position crosshairs immediately at current mouse position\n this.crosshairH.style.top = `${this.mousePos.y}px`;\n this.crosshairV.style.left = `${this.mousePos.x}px`;\n this.scope.style.left = `${this.mousePos.x}px`;\n this.scope.style.top = `${this.mousePos.y}px`;\n\n this.host.applyVars(this.overlayContainer);\n root.appendChild(this.overlayContainer);\n }\n\n private handleMouseMove(e: MouseEvent): void {\n this.updateReticleAt(e.clientX, e.clientY);\n }\n\n /** Move the crosshair/scope reticle and highlight the element under (x, y). */\n private updateReticleAt(x: number, y: number): void {\n this.mousePos.x = x;\n this.mousePos.y = y;\n\n if (this.crosshairH) this.crosshairH.style.top = `${y}px`;\n if (this.crosshairV) this.crosshairV.style.left = `${x}px`;\n if (this.scope) {\n this.scope.style.left = `${x}px`;\n this.scope.style.top = `${y}px`;\n }\n\n // Find element underneath — hide both shadow hosts\n if (this.captureLayer && this.host.shadowHost) {\n const hosts = [this.host.shadowHost, this.host.overlayShadowHost].filter(Boolean) as HTMLElement[];\n const elementUnder = getElementAtPointUnderOverlay(x, y, hosts);\n\n if (elementUnder && !isEmbedElement(elementUnder)) {\n if (this.highlightBox) {\n const rect = elementUnder.getBoundingClientRect();\n this.highlightBox.style.transform = `translate(${rect.left}px, ${rect.top}px)`;\n this.highlightBox.style.width = `${rect.width}px`;\n this.highlightBox.style.height = `${rect.height}px`;\n this.highlightBox.style.display = \"block\";\n }\n } else if (this.highlightBox) {\n this.highlightBox.style.display = \"none\";\n }\n }\n }\n\n private handleClick(e: MouseEvent): void {\n e.preventDefault();\n e.stopPropagation();\n this.selectAt(e.clientX, e.clientY);\n }\n\n // ---- Touch targeting (iOS/iPadOS) ----\n private handleTouchStart(e: TouchEvent): void {\n const t = e.touches[0];\n if (!t) return;\n this.touchStartPos = { x: t.clientX, y: t.clientY };\n // Preview what's under the finger; don't preventDefault so scrolling works.\n this.updateReticleAt(t.clientX, t.clientY);\n }\n\n private handleTouchEnd(e: TouchEvent): void {\n // touches is empty on touchend; the lifted point is in changedTouches.\n const t = e.changedTouches[0];\n const start = this.touchStartPos;\n this.touchStartPos = null;\n if (!t || !start) return;\n // A drag beyond the slop threshold is a scroll, not a selection — ignore it.\n const moved = Math.hypot(t.clientX - start.x, t.clientY - start.y);\n if (moved > TOUCH_TAP_SLOP) return;\n e.preventDefault(); // suppress the tap's synthesised click\n this.selectAt(t.clientX, t.clientY);\n }\n\n /** Select the element under (x, y) and tear down targeting. */\n private selectAt(x: number, y: number): void {\n const hosts = [this.host.shadowHost, this.host.overlayShadowHost].filter(Boolean) as HTMLElement[];\n const target = getElementAtPointUnderOverlay(x, y, hosts);\n\n if (!target || isEmbedElement(target)) {\n return;\n }\n\n const bounds = getElementBounds(target, 8);\n Object.assign(this.host.selectedBounds, bounds, { clickX: x, clickY: y, visible: true });\n\n const { selector, text } = generateElementInfo(target);\n this.host.feedbackData.elementSelector = selector;\n this.host.feedbackData.elementText = text;\n\n // Remove targeting overlay and document listeners\n this.stopTargetingListeners();\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 this.host.setState(\"SELECTED\");\n this.host.clearActiveThumb();\n\n this.showSelectedMarker();\n void this.host.submitFeedback();\n }\n\n private stopTargetingListeners(): void {\n this.removeTargetingOverlay();\n this.touchStartPos = null;\n document.removeEventListener(\"mousemove\", this.boundMouseMove);\n document.removeEventListener(\"click\", this.boundClick, true);\n document.removeEventListener(\"touchstart\", this.boundTouchStart);\n document.removeEventListener(\"touchend\", this.boundTouchEnd);\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n cancel(): void {\n this.keyboardController?.stop();\n this.keyboardController = null;\n this.stopTargetingListeners();\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 this.host.clearActiveThumb();\n\n this.host.setState(\"IDLE\");\n this.host.feedbackData.feedbackType = null;\n this.host.feedbackData.elementSelector = null;\n this.host.feedbackData.elementText = null;\n this.host.selectedBounds.visible = false;\n }\n\n private removeTargetingOverlay(): void {\n if (this.overlayContainer) {\n this.overlayContainer.remove();\n this.overlayContainer = null;\n }\n this.captureLayer = null;\n this.crosshairH = null;\n this.crosshairV = null;\n this.scope = null;\n }\n\n private showSelectedMarker(): void {\n const root = this.host.ensureOverlayHost();\n\n this.marker = document.createElement(\"div\");\n this.marker.className = \"qaid-selected-marker\";\n this.marker.style.left = `${this.host.selectedBounds.x}px`;\n this.marker.style.top = `${this.host.selectedBounds.y}px`;\n this.marker.style.width = `${this.host.selectedBounds.width}px`;\n this.marker.style.height = `${this.host.selectedBounds.height}px`;\n this.marker.style.zIndex = String(this.host.config.zIndex + 1);\n\n this.host.applyVars(this.marker);\n root.appendChild(this.marker);\n }\n\n hideMarker(): void {\n if (this.marker) {\n this.marker.remove();\n this.marker = null;\n }\n }\n\n /** Full teardown for embed.destroy(). */\n destroy(): void {\n this.keyboardController?.stop();\n this.keyboardController = null;\n this.stopTargetingListeners();\n this.hideMarker();\n }\n}\n\n/** This feature's shadow-DOM styles; the embed adds them when it loads the chunk. */\nexport const styles = featureStyles;\n"],"names":["DATA_ATTRS","findDataAttribute","element","stopAt","current","attr","value","getTruncatedText","maxLength","textContent","getNthChildIndex","index","sibling","generateNthChildPath","path","tag","escapeCSSIdentifier","str","generateSelector","dataAttr","generateElementInfo","text","TARGETABLE_SELECTOR","NATIVELY_FOCUSABLE","isElementVisible","view","style","collectTargetableElements","options","root","selector","isExcluded","isVisible","startKeyboardTargeting","candidates","moveFocus","target","addedTabindex","stopped","seed","seedIndex","focusCurrent","focusable","emitHighlight","moveTo","nextIndex","len","next","prev","getCurrent","stop","handleKey","select","cancel","event","TOUCH_TAP_SLOP","TargetingController","host","e","type","el","isEmbedElement","rect","b","bounds","getElementBounds","vignette","x","y","hosts","elementUnder","getElementAtPointUnderOverlay","t","start","styles","featureStyles"],"mappings":";AAKO,MAAMA,IAAa,CAAC,aAAa,WAAW,eAAe,SAAS;AAWpE,SAASC,EACdC,GACAC,IAAkB,SAAS,MACZ;AACf,MAAIC,IAA0BF;AAE9B,SAAOE,KAAWA,MAAYD,KAAQ;AACpC,eAAWE,KAAQL,GAAY;AAC7B,YAAMM,IAAQF,EAAQ,aAAaC,CAAI;AACvC,UAAIC;AACF,eAAO,GAAGD,CAAI,KAAKC,CAAK;AAAA,IAE5B;AACA,IAAAF,IAAUA,EAAQ;AAAA,EACpB;AAEA,SAAO;AACT;AAKO,SAASG,EAAiBL,GAAkBM,IAAY,KAAa;AAC1E,QAAMC,IAAcP,EAAQ,aAAa,KAAA,EAAO,MAAM,GAAGM,CAAS,KAAK;AACvE,SAAOC,EAAY,WAAWD,IAAYC,IAAc,QAAQA;AAClE;AAKA,SAASC,EAAiBR,GAA0B;AAClD,MAAIS,IAAQ,GACRC,IAAUV,EAAQ;AACtB,SAAOU;AACL,IAAAD,KACAC,IAAUA,EAAQ;AAEpB,SAAOD;AACT;AAOO,SAASE,EAAqBX,GAA0B;AAC7D,QAAMY,IAAiB,CAA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,MAAM,GAC/BA,EAAK,YAAY,KAAK,MAAM;AAAA,EAC9B;AAAA,EAEA,aAAmB;AACjB,IAAI,KAAK,WACP,KAAK,OAAO,OAAA,GACZ,KAAK,SAAS;AAAA,EAElB;AAAA;AAAA,EAGA,UAAgB;AACd,SAAK,oBAAoB,KAAA,GACzB,KAAK,qBAAqB,MAC1B,KAAK,uBAAA,GACL,KAAK,WAAA;AAAA,EACP;AACF;AAGO,MAAM6C,IAASC;"}
|
|
1
|
+
{"version":3,"file":"targeting-CMUEe-7C.js","sources":["../../src/element-selector.ts","../../src/targeting.ts"],"sourcesContent":["/**\n * Element selector generation utilities\n */\n\n/** Data attributes to look for (in priority order) */\nexport const DATA_ATTRS = [\"data-comp\", \"data-qa\", \"data-testid\", \"data-id\"];\n\nexport interface ElementInfo {\n selector: string;\n text: string;\n dataAttr: string | null;\n}\n\n/**\n * Find the first matching data attribute on an element or its ancestors\n */\nexport function findDataAttribute(\n element: Element,\n stopAt: Element = document.body\n): string | null {\n let current: Element | null = element;\n\n while (current && current !== stopAt) {\n for (const attr of DATA_ATTRS) {\n const value = current.getAttribute(attr);\n if (value) {\n return `${attr}=\"${value}\"`;\n }\n }\n current = current.parentElement;\n }\n\n return null;\n}\n\n/**\n * Get truncated text content from an element\n */\nexport function getTruncatedText(element: Element, maxLength = 100): string {\n const textContent = element.textContent?.trim().slice(0, maxLength) || \"\";\n return textContent.length === maxLength ? textContent + \"...\" : textContent;\n}\n\n/**\n * Get the nth-child index of an element among its siblings\n */\nfunction getNthChildIndex(element: Element): number {\n let index = 1;\n let sibling = element.previousElementSibling;\n while (sibling) {\n index++;\n sibling = sibling.previousElementSibling;\n }\n return index;\n}\n\n/**\n * Generate an nth-child path from body to the element\n * This is always a valid CSS selector and uniquely identifies the element\n * Exported for testing\n */\nexport function generateNthChildPath(element: Element): string {\n const path: string[] = [];\n let current: Element | null = element;\n\n while (current && current !== document.body && current !== document.documentElement) {\n const tag = current.tagName.toLowerCase();\n const index = getNthChildIndex(current);\n path.unshift(`${tag}:nth-child(${index})`);\n current = current.parentElement;\n }\n\n return path.length > 0 ? `body > ${path.join(\" > \")}` : \"body\";\n}\n\n/**\n * Escape special CSS characters in a string (for IDs with special chars)\n */\nfunction escapeCSSIdentifier(str: string): string {\n return str.replace(/([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~])/g, \"\\\\$1\");\n}\n\n/**\n * Generate a selector string for an element\n * Priority: data attribute > ID > nth-child path\n */\nexport function generateSelector(element: Element): string {\n // Try data attribute first (on element or ancestors) - most stable\n const dataAttr = findDataAttribute(element);\n if (dataAttr) {\n return `[${dataAttr}]`;\n }\n\n // Try ID (escaped for special characters)\n if (element.id) {\n return `#${escapeCSSIdentifier(element.id)}`;\n }\n\n // Fall back to nth-child path - always valid and unique\n return generateNthChildPath(element);\n}\n\n/**\n * Generate complete element info for feedback\n */\nexport function generateElementInfo(element: Element): ElementInfo {\n const text = getTruncatedText(element);\n const dataAttr = findDataAttribute(element);\n const selector = generateSelector(element);\n\n return { selector, text, dataAttr };\n}\n\n/* -------------------------------------------------------------------------- */\n/* Keyboard element targeting */\n/* */\n/* The mouse targeting path in embed.ts resolves the target with */\n/* elementFromPoint(clientX, clientY). A keyboard-activated thumb produces a */\n/* synthetic click at (0, 0), so a keyboard-only user can never point at a */\n/* real element. This controller provides a coordinate-free alternative: */\n/* Tab / arrow keys move a highlight between candidate elements (seeded from */\n/* document.activeElement), Enter / Space selects, Escape cancels. It never */\n/* hides the cursor — it drives the *native* focus ring instead, so both */\n/* sighted keyboard users and screen readers can follow the highlight. */\n/* -------------------------------------------------------------------------- */\n\n/**\n * Default set of \"targetable\" elements for keyboard navigation: focusable\n * controls, ARIA-role'd nodes, common semantic content, and anything already\n * carrying one of the stable data attributes we key selectors off of.\n */\nexport const TARGETABLE_SELECTOR: string = [\n \"a[href]\",\n \"button\",\n \"input:not([type=hidden])\",\n \"select\",\n \"textarea\",\n \"summary\",\n \"[tabindex]\",\n \"[role]\",\n \"img\",\n \"h1\",\n \"h2\",\n \"h3\",\n \"h4\",\n \"h5\",\n \"h6\",\n \"p\",\n \"li\",\n \"label\",\n ...DATA_ATTRS.map((attr) => `[${attr}]`),\n].join(\",\");\n\n/** Tag names that already take keyboard focus without an added tabindex. */\nconst NATIVELY_FOCUSABLE = /^(?:A|BUTTON|INPUT|SELECT|TEXTAREA|SUMMARY)$/;\n\n/**\n * Best-effort visibility test used to keep invisible nodes out of the keyboard\n * candidate list. Deliberately layout-free (no getBoundingClientRect) so it is\n * stable in headless/test environments: it only rejects nodes that are\n * explicitly hidden via the `hidden` attribute, `aria-hidden`, or a computed\n * `display:none` / `visibility:hidden`.\n */\nexport function isElementVisible(element: Element): boolean {\n if (element.hasAttribute(\"hidden\")) return false;\n if (element.getAttribute(\"aria-hidden\") === \"true\") return false;\n const view = element.ownerDocument?.defaultView;\n if (view && typeof view.getComputedStyle === \"function\") {\n const style = view.getComputedStyle(element);\n if (style.display === \"none\" || style.visibility === \"hidden\") return false;\n }\n return true;\n}\n\nexport interface CollectTargetableOptions {\n /** Where to search for candidates (default `document.body`). */\n root?: ParentNode;\n /** CSS selector for candidate elements (default {@link TARGETABLE_SELECTOR}). */\n selector?: string;\n /** Return true to drop an element (e.g. the embed's own shadow hosts). */\n isExcluded?: (element: Element) => boolean;\n /** Visibility predicate (default {@link isElementVisible}). */\n isVisible?: (element: Element) => boolean;\n}\n\n/**\n * Collect the ordered list of elements a keyboard user can target. Document\n * order matches the natural Tab order closely enough for feedback targeting.\n */\nexport function collectTargetableElements(\n options: CollectTargetableOptions = {}\n): Element[] {\n const root = options.root ?? document.body;\n const selector = options.selector ?? TARGETABLE_SELECTOR;\n const isExcluded = options.isExcluded ?? (() => false);\n const isVisible = options.isVisible ?? isElementVisible;\n\n return Array.from(root.querySelectorAll(selector)).filter(\n (element) => !isExcluded(element) && isVisible(element)\n );\n}\n\nexport interface KeyboardTargetingOptions {\n /**\n * Explicit candidate list. When omitted, candidates are collected via\n * {@link collectTargetableElements} using `root` / `selector` / `isExcluded`\n * / `isVisible`.\n */\n candidates?: Element[];\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n root?: ParentNode;\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n selector?: string;\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n isExcluded?: (element: Element) => boolean;\n /** Passed through to {@link collectTargetableElements} when `candidates` is omitted. */\n isVisible?: (element: Element) => boolean;\n /**\n * Element to start the highlight on. Defaults to `document.activeElement`\n * when it is one of the candidates, otherwise the first candidate.\n */\n initial?: Element | null;\n /**\n * Move native focus to the highlighted element (default true). This is what\n * keeps a screen reader / focus ring on the highlight; non-focusable nodes\n * get a temporary `tabindex=\"-1\"` that is removed on {@link stop}. The cursor\n * is never hidden.\n */\n moveFocus?: boolean;\n /** Where the keydown listener is attached (default `document`). */\n eventTarget?: Document | HTMLElement;\n /** Fired whenever the highlighted candidate changes (and once on start). */\n onHighlight?: (element: Element, index: number) => void;\n /** Fired when the user commits a selection (Enter / Space). Auto-stops first. */\n onSelect: (element: Element) => void;\n /** Fired when the user cancels (Escape). Auto-stops first. */\n onCancel?: () => void;\n}\n\nexport interface KeyboardTargetingController {\n /** The (frozen) candidate list being navigated. */\n readonly candidates: readonly Element[];\n /** Index of the highlighted candidate, or -1 when there are none. */\n getIndex(): number;\n /** The highlighted candidate, or null when there are none. */\n getCurrent(): Element | null;\n /** Highlight the next candidate (wraps to the first). */\n next(): void;\n /** Highlight the previous candidate (wraps to the last). */\n prev(): void;\n /** Highlight a specific index (wraps out-of-range values). */\n moveTo(index: number): void;\n /** Commit the current candidate (fires onSelect) and stop. */\n select(): void;\n /** Cancel (fires onCancel) and stop. */\n cancel(): void;\n /**\n * Handle a keydown. Wired automatically to `eventTarget`; exposed so a host\n * can forward events from another surface (e.g. the embed's shadow root).\n */\n handleKey(event: KeyboardEvent): void;\n /** Remove the listener and restore any temporary tabindex. Idempotent. */\n stop(): void;\n}\n\n/**\n * Start a keyboard element-targeting session. The returned controller wires its\n * own capture-phase keydown listener on `eventTarget` and emits the initial\n * highlight synchronously before returning.\n */\nexport function startKeyboardTargeting(\n options: KeyboardTargetingOptions\n): KeyboardTargetingController {\n const candidates =\n options.candidates ??\n collectTargetableElements({\n root: options.root,\n selector: options.selector,\n isExcluded: options.isExcluded,\n isVisible: options.isVisible,\n });\n\n const moveFocus = options.moveFocus ?? true;\n const target: EventTarget = options.eventTarget ?? document;\n const addedTabindex = new Set<Element>();\n\n let index = -1;\n let stopped = false;\n\n // Seed the highlight from the currently focused element when it is a\n // candidate; this makes \"Tab to a control, then hit the thumb\" land on that\n // control rather than the top of the page.\n const seed =\n options.initial !== undefined\n ? options.initial\n : typeof document !== \"undefined\"\n ? document.activeElement\n : null;\n if (seed) {\n const seedIndex = candidates.indexOf(seed);\n if (seedIndex >= 0) index = seedIndex;\n }\n if (index < 0 && candidates.length > 0) index = 0;\n\n function focusCurrent(element: Element): void {\n if (!moveFocus) return;\n const focusable = element as HTMLElement;\n if (typeof focusable.focus !== \"function\") return;\n // Make non-focusable content (p, img, li, …) programmatically focusable so\n // the native focus ring and AT follow the highlight. Never hide the cursor.\n if (\n element.getAttribute(\"tabindex\") === null &&\n !NATIVELY_FOCUSABLE.test(element.tagName)\n ) {\n element.setAttribute(\"tabindex\", \"-1\");\n addedTabindex.add(element);\n }\n try {\n focusable.focus();\n } catch {\n /* focus can throw in detached/headless cases — highlight still works */\n }\n }\n\n function emitHighlight(): void {\n const element = candidates[index];\n if (!element) return;\n focusCurrent(element);\n options.onHighlight?.(element, index);\n }\n\n function moveTo(nextIndex: number): void {\n if (stopped || candidates.length === 0) return;\n const len = candidates.length;\n index = ((nextIndex % len) + len) % len; // wrap in both directions\n emitHighlight();\n }\n\n function next(): void {\n moveTo(index + 1);\n }\n\n function prev(): void {\n moveTo(index - 1);\n }\n\n function getCurrent(): Element | null {\n return candidates[index] ?? null;\n }\n\n function stop(): void {\n if (stopped) return;\n stopped = true;\n target.removeEventListener(\"keydown\", handleKey as EventListener, true);\n addedTabindex.forEach((element) => element.removeAttribute(\"tabindex\"));\n addedTabindex.clear();\n }\n\n function select(): void {\n if (stopped) return;\n const element = getCurrent();\n stop();\n if (element) options.onSelect(element);\n }\n\n function cancel(): void {\n if (stopped) return;\n stop();\n options.onCancel?.();\n }\n\n function handleKey(event: KeyboardEvent): void {\n if (stopped) return;\n switch (event.key) {\n case \"Tab\":\n event.preventDefault();\n event.stopPropagation();\n if (event.shiftKey) prev();\n else next();\n break;\n case \"ArrowDown\":\n case \"ArrowRight\":\n event.preventDefault();\n event.stopPropagation();\n next();\n break;\n case \"ArrowUp\":\n case \"ArrowLeft\":\n event.preventDefault();\n event.stopPropagation();\n prev();\n break;\n case \"Enter\":\n case \" \":\n case \"Spacebar\": // legacy key value\n event.preventDefault();\n event.stopPropagation();\n select();\n break;\n case \"Escape\":\n case \"Esc\": // legacy key value\n event.preventDefault();\n event.stopPropagation();\n cancel();\n break;\n default:\n break;\n }\n }\n\n target.addEventListener(\"keydown\", handleKey as EventListener, true);\n\n // Emit the initial highlight so the caller can position its highlight box.\n if (index >= 0) emitHighlight();\n\n return {\n candidates,\n getIndex: () => index,\n getCurrent,\n next,\n prev,\n moveTo,\n select,\n cancel,\n handleKey,\n stop,\n };\n}\n","/**\n * Element-targeting subsystem — extracted from embed.ts into its own lazily\n * loaded chunk (it also carries `element-selector`, ~14 KB). It's fetched the\n * first time the user starts targeting (and pre-warmed on thumb-button hover,\n * so the reticle appears without a perceptible wait).\n *\n * The controller owns the reticle/overlay, the mouse/touch/keyboard targeting\n * flows, and the selected-element marker; it talks back to the embed through\n * the narrow `TargetingHost` interface.\n */\n\nimport {\n generateElementInfo,\n startKeyboardTargeting,\n type KeyboardTargetingController,\n} from \"./element-selector\";\nimport {\n getElementAtPointUnderOverlay,\n isEmbedElement,\n getElementBounds,\n} from \"./dom-utils\";\nimport type {\n ResolvedFeedbackConfig,\n EmbedState,\n FeedbackData,\n FeedbackType,\n SelectedBounds,\n} from \"./types\";\nimport featureStyles from \"./styles-targeting.css?inline\";\n\n/** A touch that moves more than this (px) is a scroll, not a tap-to-select. */\nconst TOUCH_TAP_SLOP = 12;\n\n/** The slice of the embed the targeting subsystem needs. */\nexport interface TargetingHost {\n readonly config: ResolvedFeedbackConfig;\n readonly cssVars: Record<string, string>;\n readonly state: EmbedState;\n readonly shadowHost: HTMLDivElement | null;\n readonly overlayShadowHost: HTMLDivElement | null;\n readonly boundKeyDown: (e: KeyboardEvent) => void;\n /** Live references, mutated in place. */\n readonly feedbackData: FeedbackData;\n readonly selectedBounds: SelectedBounds;\n setState(state: EmbedState): void;\n ensureOverlayHost(): ShadowRoot;\n applyVars(el: HTMLElement): void;\n announceMsg(message: string, assertive?: boolean): void;\n clearActiveThumb(): void;\n submitFeedback(): Promise<void>;\n}\n\nexport class TargetingController {\n private mousePos = { x: 0, y: 0 };\n private touchStartPos: { x: number; y: number } | null = null;\n private overlayContainer: HTMLDivElement | null = null;\n private captureLayer: HTMLDivElement | null = null;\n private crosshairH: HTMLDivElement | null = null;\n private crosshairV: HTMLDivElement | null = null;\n private scope: HTMLDivElement | null = null;\n private highlightBox: HTMLDivElement | null = null;\n private marker: HTMLDivElement | null = null;\n private keyboardController: KeyboardTargetingController | null = null;\n\n private boundMouseMove = (e: MouseEvent): void => this.handleMouseMove(e);\n private boundClick = (e: MouseEvent): void => this.handleClick(e);\n private boundTouchStart = (e: TouchEvent): void => this.handleTouchStart(e);\n private boundTouchEnd = (e: TouchEvent): void => this.handleTouchEnd(e);\n\n constructor(private host: TargetingHost) {}\n\n startPointer(type: FeedbackType, e: MouseEvent): void {\n this.host.setState(\"TARGETING\");\n this.host.feedbackData.feedbackType = type;\n this.host.feedbackData.elementSelector = null;\n this.host.feedbackData.elementText = null;\n this.host.selectedBounds.visible = false;\n\n // Track initial mouse position from the click event\n this.mousePos.x = e.clientX;\n this.mousePos.y = e.clientY;\n\n // Add class to body (light DOM — for cursor override)\n document.body.classList.add(\"qaid-targeting\");\n if (type === \"up\") {\n document.body.classList.add(\"qaid-type-up\");\n } else {\n document.body.classList.remove(\"qaid-type-up\");\n }\n\n // Set targeting colors on body so .qaid-highlight rules can resolve them\n document.body.style.setProperty(\"--qaid-positive\", this.host.cssVars[\"--qaid-positive\"]);\n document.body.style.setProperty(\"--qaid-negative\", this.host.cssVars[\"--qaid-negative\"]);\n\n this.createTargetingOverlay();\n\n // Add event listeners on document — overlay is pointer-events:none so scroll works naturally\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n document.addEventListener(\"mousemove\", this.boundMouseMove);\n document.addEventListener(\"click\", this.boundClick, true);\n // Touch: tap to select (scrolling stays enabled). touchstart is passive\n // (we only read the point); touchend is non-passive so a tap can\n // preventDefault the synthesised click that would otherwise activate the\n // targeted element.\n document.addEventListener(\"touchstart\", this.boundTouchStart, { passive: true });\n document.addEventListener(\"touchend\", this.boundTouchEnd, { passive: false });\n }\n\n /**\n * Keyboard-driven targeting. Mirrors startPointer minus the mouse plumbing:\n * no `qaid-targeting` body class (keeps the cursor visible for keyboard\n * users), no mouse reticle, and no document mouse/click listeners. The\n * KeyboardTargetingController owns Tab/Arrow/Enter/Space/Escape.\n */\n startKeyboard(type: FeedbackType): void {\n this.host.setState(\"TARGETING\");\n this.host.feedbackData.feedbackType = type;\n this.host.feedbackData.elementSelector = null;\n this.host.feedbackData.elementText = null;\n this.host.selectedBounds.visible = false;\n\n document.body.style.setProperty(\"--qaid-positive\", this.host.cssVars[\"--qaid-positive\"]);\n document.body.style.setProperty(\"--qaid-negative\", this.host.cssVars[\"--qaid-negative\"]);\n\n // Build the highlight box, then hide the mouse reticle (meaningless here)\n this.createTargetingOverlay();\n if (this.crosshairH) this.crosshairH.style.display = \"none\";\n if (this.crosshairV) this.crosshairV.style.display = \"none\";\n if (this.scope) this.scope.style.display = \"none\";\n\n this.keyboardController = startKeyboardTargeting({\n isExcluded: (el) => isEmbedElement(el),\n onHighlight: (el) => {\n const rect = el.getBoundingClientRect();\n const b = this.highlightBox;\n if (b) {\n b.style.transform = `translate(${rect.left}px, ${rect.top}px)`;\n b.style.width = `${rect.width}px`;\n b.style.height = `${rect.height}px`;\n b.style.display = \"block\";\n }\n const { text } = generateElementInfo(el);\n this.host.announceMsg(`Targeting ${text || el.tagName.toLowerCase()}`);\n },\n onSelect: (el) => this.selectKeyboardTarget(el),\n onCancel: () => this.cancel(),\n });\n }\n\n private selectKeyboardTarget(el: Element): void {\n const bounds = getElementBounds(el, 8);\n Object.assign(this.host.selectedBounds, bounds, {\n clickX: bounds.x + bounds.width / 2,\n clickY: bounds.y + bounds.height / 2,\n visible: true,\n });\n\n const { selector, text } = generateElementInfo(el);\n this.host.feedbackData.elementSelector = selector;\n this.host.feedbackData.elementText = text;\n\n // Teardown (controller has already auto-stopped before onSelect fired)\n this.removeTargetingOverlay();\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 this.keyboardController = null;\n this.host.clearActiveThumb();\n\n this.host.setState(\"SELECTED\");\n this.showSelectedMarker();\n void this.host.submitFeedback();\n }\n\n private createTargetingOverlay(): void {\n const root = this.host.ensureOverlayHost();\n\n this.overlayContainer = document.createElement(\"div\");\n this.overlayContainer.className = `qaid-targeting-overlay qaid-type-${this.host.feedbackData.feedbackType}`;\n\n // Capture layer (pointer-events:none — scroll passes through naturally)\n this.captureLayer = document.createElement(\"div\");\n this.captureLayer.className = \"qaid-capture-layer\";\n\n // Vignette\n const vignette = document.createElement(\"div\");\n vignette.className = \"qaid-vignette\";\n\n // Crosshairs\n this.crosshairH = document.createElement(\"div\");\n this.crosshairH.className = \"qaid-crosshair-h\";\n\n this.crosshairV = document.createElement(\"div\");\n this.crosshairV.className = \"qaid-crosshair-v\";\n\n // Scope\n this.scope = document.createElement(\"div\");\n this.scope.className = \"qaid-scope\";\n this.scope.innerHTML = `\n <div class=\"qaid-scope-ring\"></div>\n <div class=\"qaid-scope-ring-inner\"></div>\n <div class=\"qaid-scope-dot\"></div>\n `;\n\n // Highlight box overlay (positioned over hovered elements)\n this.highlightBox = document.createElement(\"div\");\n this.highlightBox.className = \"qaid-highlight-box\";\n\n this.overlayContainer.appendChild(this.captureLayer);\n this.overlayContainer.appendChild(vignette);\n this.overlayContainer.appendChild(this.highlightBox);\n this.overlayContainer.appendChild(this.crosshairH);\n this.overlayContainer.appendChild(this.crosshairV);\n this.overlayContainer.appendChild(this.scope);\n\n // Position crosshairs immediately at current mouse position\n this.crosshairH.style.top = `${this.mousePos.y}px`;\n this.crosshairV.style.left = `${this.mousePos.x}px`;\n this.scope.style.left = `${this.mousePos.x}px`;\n this.scope.style.top = `${this.mousePos.y}px`;\n\n this.host.applyVars(this.overlayContainer);\n root.appendChild(this.overlayContainer);\n }\n\n private handleMouseMove(e: MouseEvent): void {\n this.updateReticleAt(e.clientX, e.clientY);\n }\n\n /** Move the crosshair/scope reticle and highlight the element under (x, y). */\n private updateReticleAt(x: number, y: number): void {\n this.mousePos.x = x;\n this.mousePos.y = y;\n\n if (this.crosshairH) this.crosshairH.style.top = `${y}px`;\n if (this.crosshairV) this.crosshairV.style.left = `${x}px`;\n if (this.scope) {\n this.scope.style.left = `${x}px`;\n this.scope.style.top = `${y}px`;\n }\n\n // Find element underneath — hide both shadow hosts\n if (this.captureLayer && this.host.shadowHost) {\n const hosts = [this.host.shadowHost, this.host.overlayShadowHost].filter(Boolean) as HTMLElement[];\n const elementUnder = getElementAtPointUnderOverlay(x, y, hosts);\n\n if (elementUnder && !isEmbedElement(elementUnder)) {\n if (this.highlightBox) {\n const rect = elementUnder.getBoundingClientRect();\n this.highlightBox.style.transform = `translate(${rect.left}px, ${rect.top}px)`;\n this.highlightBox.style.width = `${rect.width}px`;\n this.highlightBox.style.height = `${rect.height}px`;\n this.highlightBox.style.display = \"block\";\n }\n } else if (this.highlightBox) {\n this.highlightBox.style.display = \"none\";\n }\n }\n }\n\n private handleClick(e: MouseEvent): void {\n e.preventDefault();\n e.stopPropagation();\n this.selectAt(e.clientX, e.clientY);\n }\n\n // ---- Touch targeting (iOS/iPadOS) ----\n private handleTouchStart(e: TouchEvent): void {\n const t = e.touches[0];\n if (!t) return;\n this.touchStartPos = { x: t.clientX, y: t.clientY };\n // Preview what's under the finger; don't preventDefault so scrolling works.\n this.updateReticleAt(t.clientX, t.clientY);\n }\n\n private handleTouchEnd(e: TouchEvent): void {\n // touches is empty on touchend; the lifted point is in changedTouches.\n const t = e.changedTouches[0];\n const start = this.touchStartPos;\n this.touchStartPos = null;\n if (!t || !start) return;\n // A drag beyond the slop threshold is a scroll, not a selection — ignore it.\n const moved = Math.hypot(t.clientX - start.x, t.clientY - start.y);\n if (moved > TOUCH_TAP_SLOP) return;\n e.preventDefault(); // suppress the tap's synthesised click\n this.selectAt(t.clientX, t.clientY);\n }\n\n /** Select the element under (x, y) and tear down targeting. */\n private selectAt(x: number, y: number): void {\n const hosts = [this.host.shadowHost, this.host.overlayShadowHost].filter(Boolean) as HTMLElement[];\n const target = getElementAtPointUnderOverlay(x, y, hosts);\n\n if (!target || isEmbedElement(target)) {\n return;\n }\n\n const bounds = getElementBounds(target, 8);\n Object.assign(this.host.selectedBounds, bounds, { clickX: x, clickY: y, visible: true });\n\n const { selector, text } = generateElementInfo(target);\n this.host.feedbackData.elementSelector = selector;\n this.host.feedbackData.elementText = text;\n\n // Remove targeting overlay and document listeners\n this.stopTargetingListeners();\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 this.host.setState(\"SELECTED\");\n this.host.clearActiveThumb();\n\n this.showSelectedMarker();\n void this.host.submitFeedback();\n }\n\n private stopTargetingListeners(): void {\n this.removeTargetingOverlay();\n this.touchStartPos = null;\n document.removeEventListener(\"mousemove\", this.boundMouseMove);\n document.removeEventListener(\"click\", this.boundClick, true);\n document.removeEventListener(\"touchstart\", this.boundTouchStart);\n document.removeEventListener(\"touchend\", this.boundTouchEnd);\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n cancel(): void {\n this.keyboardController?.stop();\n this.keyboardController = null;\n this.stopTargetingListeners();\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 this.host.clearActiveThumb();\n\n this.host.setState(\"IDLE\");\n this.host.feedbackData.feedbackType = null;\n this.host.feedbackData.elementSelector = null;\n this.host.feedbackData.elementText = null;\n this.host.selectedBounds.visible = false;\n }\n\n private removeTargetingOverlay(): void {\n if (this.overlayContainer) {\n this.overlayContainer.remove();\n this.overlayContainer = null;\n }\n this.captureLayer = null;\n this.crosshairH = null;\n this.crosshairV = null;\n this.scope = null;\n }\n\n private showSelectedMarker(): void {\n const root = this.host.ensureOverlayHost();\n\n this.marker = document.createElement(\"div\");\n this.marker.className = \"qaid-selected-marker\";\n this.marker.style.left = `${this.host.selectedBounds.x}px`;\n this.marker.style.top = `${this.host.selectedBounds.y}px`;\n this.marker.style.width = `${this.host.selectedBounds.width}px`;\n this.marker.style.height = `${this.host.selectedBounds.height}px`;\n this.marker.style.zIndex = String(this.host.config.zIndex + 1);\n\n this.host.applyVars(this.marker);\n root.appendChild(this.marker);\n }\n\n hideMarker(): void {\n if (this.marker) {\n this.marker.remove();\n this.marker = null;\n }\n }\n\n /** Full teardown for embed.destroy(). */\n destroy(): void {\n this.keyboardController?.stop();\n this.keyboardController = null;\n this.stopTargetingListeners();\n this.hideMarker();\n }\n}\n\n/** This feature's shadow-DOM styles; the embed adds them when it loads the chunk. */\nexport const styles = featureStyles;\n"],"names":["DATA_ATTRS","findDataAttribute","element","stopAt","current","attr","value","getTruncatedText","maxLength","textContent","getNthChildIndex","index","sibling","generateNthChildPath","path","tag","escapeCSSIdentifier","str","generateSelector","dataAttr","generateElementInfo","text","TARGETABLE_SELECTOR","NATIVELY_FOCUSABLE","isElementVisible","view","style","collectTargetableElements","options","root","selector","isExcluded","isVisible","startKeyboardTargeting","candidates","moveFocus","target","addedTabindex","stopped","seed","seedIndex","focusCurrent","focusable","emitHighlight","moveTo","nextIndex","len","next","prev","getCurrent","stop","handleKey","select","cancel","event","TOUCH_TAP_SLOP","TargetingController","host","e","type","el","isEmbedElement","rect","b","bounds","getElementBounds","vignette","x","y","hosts","elementUnder","getElementAtPointUnderOverlay","t","start","styles","featureStyles"],"mappings":"qDAKO,MAAMA,EAAa,CAAC,YAAa,UAAW,cAAe,SAAS,EAWpE,SAASC,EACdC,EACAC,EAAkB,SAAS,KACZ,CACf,IAAIC,EAA0BF,EAE9B,KAAOE,GAAWA,IAAYD,GAAQ,CACpC,UAAWE,KAAQL,EAAY,CAC7B,MAAMM,EAAQF,EAAQ,aAAaC,CAAI,EACvC,GAAIC,EACF,MAAO,GAAGD,CAAI,KAAKC,CAAK,GAE5B,CACAF,EAAUA,EAAQ,aACpB,CAEA,OAAO,IACT,CAKO,SAASG,EAAiBL,EAAkBM,EAAY,IAAa,CAC1E,MAAMC,EAAcP,EAAQ,aAAa,KAAA,EAAO,MAAM,EAAGM,CAAS,GAAK,GACvE,OAAOC,EAAY,SAAWD,EAAYC,EAAc,MAAQA,CAClE,CAKA,SAASC,EAAiBR,EAA0B,CAClD,IAAIS,EAAQ,EACRC,EAAUV,EAAQ,uBACtB,KAAOU,GACLD,IACAC,EAAUA,EAAQ,uBAEpB,OAAOD,CACT,CAOO,SAASE,EAAqBX,EAA0B,CAC7D,MAAMY,EAAiB,CAAA,EACvB,IAAIV,EAA0BF,EAE9B,KAAOE,GAAWA,IAAY,SAAS,MAAQA,IAAY,SAAS,iBAAiB,CACnF,MAAMW,EAAMX,EAAQ,QAAQ,YAAA,EACtBO,EAAQD,EAAiBN,CAAO,EACtCU,EAAK,QAAQ,GAAGC,CAAG,cAAcJ,CAAK,GAAG,EACzCP,EAAUA,EAAQ,aACpB,CAEA,OAAOU,EAAK,OAAS,EAAI,UAAUA,EAAK,KAAK,KAAK,CAAC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,KAAK,SACP,KAAK,OAAO,OAAA,EACZ,KAAK,OAAS,KAElB,CAGA,SAAgB,CACd,KAAK,oBAAoB,KAAA,EACzB,KAAK,mBAAqB,KAC1B,KAAK,uBAAA,EACL,KAAK,WAAA,CACP,CACF,CAGO,MAAM6C,EAASC"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function x(){const e=navigator.userAgent||"";return/iP(hone|ad|od)/.test(e)||navigator.platform==="MacIntel"&&(navigator.maxTouchPoints||0)>1}function C(e,a,r,d,s){const t=e>=a,o=r>=d;return t===o?{width:e,height:a,rotate:0}:{width:a,height:e,rotate:s===270?-90:90}}function F(e,a,r){if(r.rotate===0){e.drawImage(a,0,0,r.width,r.height);return}e.save(),r.rotate===90?(e.translate(r.width,0),e.rotate(Math.PI/2)):(e.translate(0,r.height),e.rotate(-Math.PI/2)),e.drawImage(a,0,0,r.height,r.width),e.restore()}function B(){const e=typeof screen<"u"?screen.orientation:void 0;return e&&typeof e.angle=="number"?e.angle:0}function E(e){return new Promise(a=>{if(e.videoWidth>0){a();return}e.addEventListener("loadedmetadata",()=>a(),{once:!0})})}async function I(e){try{await e.play()}catch{}}async function O(e,a=15){const r=document.createElement("canvas");if(typeof r.captureStream!="function")return null;const d=r.getContext("2d");if(!d)return null;const s=document.createElement("video");s.muted=!0,s.playsInline=!0,s.srcObject=e,await E(s);const t=C(s.videoWidth,s.videoHeight,window.innerWidth,window.innerHeight,B());r.width=t.width,r.height=t.height,await I(s);let o=0;const c=()=>{F(d,s,t),o=requestAnimationFrame(c)};c();const n=r.captureStream(a);return{stream:n,stop:()=>{o&&cancelAnimationFrame(o),o=0,n.getTracks().forEach(u=>u.stop()),s.pause(),s.srcObject=null}}}function P(e,a,r,d,s){const t=Math.max(0,Math.min(d,e.left*a)),o=Math.max(0,Math.min(s,e.top*r)),c=Math.max(0,Math.min(d,(e.left+e.width)*a)),n=Math.max(0,Math.min(s,(e.top+e.height)*r)),u=c-t,i=n-o;return u<=0||i<=0?null:{x:t,y:o,w:u,h:i}}function L(e,a,r,d,s,t,o){e.drawImage(a,0,0,d,s);const c=d/Math.max(1,window.innerWidth),n=s/Math.max(1,window.innerHeight);for(const u of r){const i=P(u.getBoundingClientRect(),c,n,d,s);i&&(e.save(),o?(e.filter=`blur(${t}px)`,e.drawImage(a,i.x,i.y,i.w,i.h,i.x,i.y,i.w,i.h)):(e.fillStyle="#0b0b0b",e.fillRect(i.x,i.y,i.w,i.h)),e.restore())}}async function j(e,a,r={}){const d=r.frameRate??15,s=r.blurRadius??12,t=document.createElement("canvas");if(typeof t.captureStream!="function")return null;const o=t.getContext("2d");if(!o)return null;const c="filter"in o,n=document.createElement("video");n.muted=!0,n.playsInline=!0,n.srcObject=e,await E(n),t.width=n.videoWidth,t.height=n.videoHeight,await I(n);let u=0;const i=()=>{L(o,n,a,t.width,t.height,s,c),u=requestAnimationFrame(i)};i();const h=t.captureStream(d);return{stream:h,stop:()=>{u&&cancelAnimationFrame(u),u=0,h.getTracks().forEach(p=>p.stop()),n.pause(),n.srcObject=null}}}const k="This browser cannot blur the areas you picked, so the recording was not started.";function V(){return typeof navigator<"u"&&!!navigator.mediaDevices&&typeof navigator.mediaDevices.getDisplayMedia=="function"&&typeof MediaRecorder<"u"}function D(){if(typeof MediaRecorder>"u")return"";const e=["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"];for(const a of e)if(MediaRecorder.isTypeSupported(a))return a;return""}function q(e={}){const a=e.maxDuration??15,r=e.videoBitsPerSecond??8e5,d=e.redactionElements??[],s=e.redactionBlurRadius;let t=null,o=null,c=null,n=null,u=[],i=null,h=null,p=null,R=0,w=null,g=null,S=!1,v=null;function A(){p!==null&&(clearInterval(p),p=null),v!==null&&(clearTimeout(v),v=null),o&&(o.stop(),o=null),c&&(c.stop(),c=null),t&&(t.getTracks().forEach(f=>f.stop()),t=null),n=null,u=[],i=null,h=null,w=null,g=null}function y(){S||(S=!0,n&&n.state!=="inactive"&&n.stop())}return{async start(){S=!1,u=[];const f=D();if(!f)throw new Error("No supported video MIME type found");t=await navigator.mediaDevices.getDisplayMedia({video:{frameRate:15,displaySurface:"browser"},audio:!1,preferCurrentTab:!0,selfBrowserSurface:"include",monitorTypeSurfaces:"exclude",surfaceSwitching:"exclude"});const m=t.getVideoTracks()[0],T=m?.getSettings?.()?.displaySurface;if(T==="monitor"||T==="window")throw t.getTracks().forEach(l=>l.stop()),t=null,new Error("qaid records only the current tab \u2014 please share this tab, not a window or your whole screen.");m&&m.addEventListener("ended",()=>{y()});let b=t;if(x()){const l=await O(t);l&&(o=l,b=l.stream)}if(d.length>0){const l=await j(b,d,{blurRadius:s});if(!l)throw o&&(o.stop(),o=null),t.getTracks().forEach(M=>M.stop()),t=null,new Error(k);c=l,b=l.stream}n=new MediaRecorder(b,{mimeType:f,videoBitsPerSecond:r}),n.ondataavailable=l=>{l.data.size>0&&u.push(l.data)},n.onstop=()=>{const l=new Blob(u,{type:f});w&&w(l),h&&h(l),o&&(o.stop(),o=null),c&&(c.stop(),c=null),t&&t.getTracks().forEach(M=>M.stop())},n.onerror=()=>{g&&g(new Error("MediaRecorder error"))},n.start(1e3),R=Date.now(),p=setInterval(()=>{const l=Math.floor((Date.now()-R)/1e3);i&&i(l)},1e3),v=setTimeout(()=>{y()},a*1e3)},stop(){return new Promise((f,m)=>{w=f,g=m,y()})},onTick(f){i=f},onStop(f){h=f},destroy(){y(),A()}}}export{k as REDACTION_UNAVAILABLE,q as createVideoRecorder,D as getSupportedMimeType,V as isVideoRecordingSupported};
|
|
2
|
+
//# sourceMappingURL=video-BSP4s2te.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"video-Bd_29-rK.js","sources":["../../src/video-orientation.ts","../../src/video-redaction.ts","../../src/video-capture.ts"],"sourcesContent":["/**\n * iOS/iPadOS screen-recording orientation fix.\n *\n * On iOS/iPadOS, `getDisplayMedia` + `MediaRecorder` writes a device-orientation\n * rotation into the recorded file (even for screen captures). Players disagree\n * on whether to honour it — the widget's own preview `<video>` renders it\n * sideways, and so does the dashboard. Re-encoding the *live* decoded frames\n * (which carry no container rotation) through a canvas produces a file whose\n * pixels are already upright with no rotation metadata, so it renders the same\n * everywhere.\n *\n * If the live frames themselves come back with swapped dimensions (portrait\n * frame while the viewport is landscape, or vice versa), we additionally rotate\n * the canvas 90° to match the viewport. That branch only triggers on a clear\n * orientation mismatch, so a correctly-oriented recording is never rotated.\n */\n\nexport interface OrientationTransform {\n /** Output canvas width in px. */\n width: number;\n /** Output canvas height in px. */\n height: number;\n /** Clockwise rotation to apply while drawing: 0, 90, or -90. */\n rotate: 0 | 90 | -90;\n}\n\nexport interface OrientationCorrectedStream {\n /** Canvas-sourced stream to hand to MediaRecorder. */\n stream: MediaStream;\n /** Stop drawing and release the canvas stream + source video. */\n stop: () => void;\n}\n\n/** True on iPhone/iPad/iPod, including iPadOS 13+ which reports as desktop Mac. */\nexport function isIOSDevice(): boolean {\n const ua = navigator.userAgent || \"\";\n return (\n /iP(hone|ad|od)/.test(ua) ||\n // iPadOS 13+ masquerades as \"MacIntel\" but is a multi-touch device.\n (navigator.platform === \"MacIntel\" && (navigator.maxTouchPoints || 0) > 1)\n );\n}\n\n/**\n * Decide the output canvas size and rotation needed to render a `frameW×frameH`\n * capture upright for a `viewportW×viewportH` viewport. When the frame and\n * viewport share an orientation, no rotation is applied (a straight re-encode,\n * which still strips the bad container rotation). Otherwise rotate 90°, its\n * direction chosen from the screen orientation angle.\n */\nexport function computeOrientationTransform(\n frameW: number,\n frameH: number,\n viewportW: number,\n viewportH: number,\n screenAngle: number\n): OrientationTransform {\n const frameLandscape = frameW >= frameH;\n const viewportLandscape = viewportW >= viewportH;\n\n if (frameLandscape === viewportLandscape) {\n return { width: frameW, height: frameH, rotate: 0 };\n }\n\n // Landscape-secondary (angle 270) is turned the opposite way to primary (90).\n const rotate: 90 | -90 = screenAngle === 270 ? -90 : 90;\n return { width: frameH, height: frameW, rotate };\n}\n\n/** Draw one video frame onto the canvas context, applying the transform. */\nexport function drawRotatedFrame(\n ctx: CanvasRenderingContext2D,\n source: CanvasImageSource,\n t: OrientationTransform\n): void {\n if (t.rotate === 0) {\n ctx.drawImage(source, 0, 0, t.width, t.height);\n return;\n }\n\n ctx.save();\n if (t.rotate === 90) {\n ctx.translate(t.width, 0);\n ctx.rotate(Math.PI / 2);\n } else {\n ctx.translate(0, t.height);\n ctx.rotate(-Math.PI / 2);\n }\n // The source is drawn at its natural (unrotated) extents, which are the\n // output dimensions swapped back.\n ctx.drawImage(source, 0, 0, t.height, t.width);\n ctx.restore();\n}\n\nfunction getScreenAngle(): number {\n const orientation =\n typeof screen !== \"undefined\" ? screen.orientation : undefined;\n return orientation && typeof orientation.angle === \"number\"\n ? orientation.angle\n : 0;\n}\n\nexport function waitForVideoDimensions(video: HTMLVideoElement): Promise<void> {\n return new Promise<void>((resolve) => {\n if (video.videoWidth > 0) {\n resolve();\n return;\n }\n video.addEventListener(\"loadedmetadata\", () => resolve(), { once: true });\n });\n}\n\nexport async function playSilently(video: HTMLVideoElement): Promise<void> {\n try {\n await video.play();\n } catch {\n // Autoplay can reject without a gesture; the element still produces frames\n // for the canvas, so this is non-fatal.\n }\n}\n\n/**\n * Build a canvas-backed, orientation-normalised copy of a display-capture\n * stream. Returns null when the browser can't support the canvas pipeline, in\n * which case the caller should record the original stream directly.\n */\nexport async function buildOrientationCorrectedStream(\n displayStream: MediaStream,\n frameRate = 15\n): Promise<OrientationCorrectedStream | null> {\n const canvas = document.createElement(\"canvas\");\n if (typeof canvas.captureStream !== \"function\") return null;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return null;\n\n const video = document.createElement(\"video\");\n video.muted = true;\n video.playsInline = true;\n video.srcObject = displayStream;\n\n await waitForVideoDimensions(video);\n\n const transform = computeOrientationTransform(\n video.videoWidth,\n video.videoHeight,\n window.innerWidth,\n window.innerHeight,\n getScreenAngle()\n );\n canvas.width = transform.width;\n canvas.height = transform.height;\n\n await playSilently(video);\n\n let rafId = 0;\n const draw = (): void => {\n drawRotatedFrame(ctx, video, transform);\n rafId = requestAnimationFrame(draw);\n };\n draw();\n\n const stream = canvas.captureStream(frameRate);\n\n return {\n stream,\n stop: (): void => {\n if (rafId) cancelAnimationFrame(rafId);\n rafId = 0;\n stream.getTracks().forEach((t) => t.stop());\n video.pause();\n video.srcObject = null;\n },\n };\n}\n","/**\n * Live video redaction.\n *\n * Blurs the on-screen bounding boxes of chosen elements while the current tab\n * is recorded. Every frame re-reads each element's `getBoundingClientRect()`,\n * so the blur tracks the content as the page scrolls or reflows — no pixel\n * tracking and no post-recording re-encode. The captured frame is the tab's\n * viewport (video-capture restricts capture to the current tab), so viewport\n * CSS coordinates map onto the frame with a single scale factor.\n *\n * The display stream is drawn to a canvas, the tracked regions are blurred on\n * top, and MediaRecorder records the canvas stream instead of the raw capture —\n * mirroring the iOS orientation pipeline in `video-orientation.ts`.\n */\n\nimport { waitForVideoDimensions, playSilently } from \"./video-orientation\";\n\nexport interface RedactedStream {\n /** Canvas-sourced stream to hand to MediaRecorder. */\n stream: MediaStream;\n /** Stop drawing and release the canvas stream + source video. */\n stop: () => void;\n}\n\nexport interface RedactionOptions {\n /** Output frame rate of the redacted stream. Default: 15. */\n frameRate?: number;\n /** Gaussian blur radius in px applied to each region. Default: 12. */\n blurRadius?: number;\n}\n\ninterface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Map a viewport rect (CSS px, from `getBoundingClientRect()`) onto the\n * captured frame, clamped to the frame bounds. Returns null when the rect is\n * fully outside the viewport (the element scrolled away) or has no area.\n */\nexport function mapRectToFrame(\n rect: { left: number; top: number; width: number; height: number },\n scaleX: number,\n scaleY: number,\n frameW: number,\n frameH: number\n): Box | null {\n const x = Math.max(0, Math.min(frameW, rect.left * scaleX));\n const y = Math.max(0, Math.min(frameH, rect.top * scaleY));\n const right = Math.max(0, Math.min(frameW, (rect.left + rect.width) * scaleX));\n const bottom = Math.max(0, Math.min(frameH, (rect.top + rect.height) * scaleY));\n const w = right - x;\n const h = bottom - y;\n if (w <= 0 || h <= 0) return null;\n return { x, y, w, h };\n}\n\n/**\n * Draw one frame: the full capture, then each element's live bounding box\n * blurred on top. Exported for unit testing the per-frame logic without a real\n * capture stream. When the 2D context can't apply a blur filter, the region is\n * filled solid instead so sensitive content is still hidden.\n */\nexport function drawRedactedFrame(\n ctx: CanvasRenderingContext2D,\n video: CanvasImageSource,\n elements: Element[],\n frameW: number,\n frameH: number,\n blurRadius: number,\n supportsFilter: boolean\n): void {\n ctx.drawImage(video, 0, 0, frameW, frameH);\n\n // The current-tab capture is the viewport, so this scale is ~devicePixelRatio;\n // deriving it live also absorbs viewport resizes mid-recording.\n const scaleX = frameW / Math.max(1, window.innerWidth);\n const scaleY = frameH / Math.max(1, window.innerHeight);\n\n for (const el of elements) {\n const box = mapRectToFrame(\n el.getBoundingClientRect(),\n scaleX,\n scaleY,\n frameW,\n frameH\n );\n if (!box) continue; // scrolled out of view\n\n ctx.save();\n if (supportsFilter) {\n ctx.filter = `blur(${blurRadius}px)`;\n // Re-sample just this region from the live frame so the blur source is\n // the region itself.\n ctx.drawImage(video, box.x, box.y, box.w, box.h, box.x, box.y, box.w, box.h);\n } else {\n // No canvas filter support — hide the region with a solid fill.\n ctx.fillStyle = \"#0b0b0b\";\n ctx.fillRect(box.x, box.y, box.w, box.h);\n }\n ctx.restore();\n }\n}\n\n/**\n * Build a canvas-backed copy of a display-capture stream that blurs the live\n * bounding boxes of `elements`. Returns null when the browser can't support the\n * canvas pipeline (no `captureStream` / 2D context), in which case the caller\n * should record the original stream unredacted.\n */\nexport async function buildRedactedStream(\n displayStream: MediaStream,\n elements: Element[],\n options: RedactionOptions = {}\n): Promise<RedactedStream | null> {\n const frameRate = options.frameRate ?? 15;\n const blurRadius = options.blurRadius ?? 12;\n\n const canvas = document.createElement(\"canvas\");\n if (typeof canvas.captureStream !== \"function\") return null;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return null;\n\n // Feature-detect canvas blur; fall back to solid fill where unsupported.\n const supportsFilter = \"filter\" in ctx;\n\n const video = document.createElement(\"video\");\n video.muted = true;\n video.playsInline = true;\n video.srcObject = displayStream;\n\n await waitForVideoDimensions(video);\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n\n await playSilently(video);\n\n let rafId = 0;\n const draw = (): void => {\n drawRedactedFrame(\n ctx,\n video,\n elements,\n canvas.width,\n canvas.height,\n blurRadius,\n supportsFilter\n );\n rafId = requestAnimationFrame(draw);\n };\n draw();\n\n const stream = canvas.captureStream(frameRate);\n\n return {\n stream,\n stop: (): void => {\n if (rafId) cancelAnimationFrame(rafId);\n rafId = 0;\n stream.getTracks().forEach((t) => t.stop());\n video.pause();\n video.srcObject = null;\n },\n };\n}\n","/**\n * Video capture utilities\n * Uses getDisplayMedia + MediaRecorder for screen recording\n */\n\nimport {\n isIOSDevice,\n buildOrientationCorrectedStream,\n type OrientationCorrectedStream,\n} from \"./video-orientation\";\nimport { buildRedactedStream, type RedactedStream } from \"./video-redaction\";\n\n/**\n * Thrown by `start()` when areas were picked for redaction but this browser\n * cannot run the canvas pipeline that blurs them. The recording is refused\n * rather than made without the blur.\n */\nexport const REDACTION_UNAVAILABLE =\n \"This browser cannot blur the areas you picked, so the recording was not started.\";\n\nexport interface VideoRecorderOptions {\n /** Max recording duration in seconds. Default: 15 */\n maxDuration?: number;\n /** Video bitrate in bps. Default: 800000 (800kbps) */\n videoBitsPerSecond?: number;\n /**\n * Elements whose live bounding boxes are blurred out of the recording. The\n * blur tracks each element as the page scrolls. Empty/omitted = no redaction.\n */\n redactionElements?: Element[];\n /** Blur radius in px for redacted regions. Default: 12. */\n redactionBlurRadius?: number;\n}\n\nexport interface VideoRecorder {\n /** Start recording. Requests getDisplayMedia if not already started. */\n start(): Promise<void>;\n /** Stop recording and return the video blob. */\n stop(): Promise<Blob>;\n /** Register a callback for each second tick (receives seconds elapsed). */\n onTick(callback: (elapsed: number) => void): void;\n /** Register a callback for when recording stops (e.g., browser stop button, max duration). */\n onStop(callback: (blob: Blob | null) => void): void;\n /** Clean up all resources. */\n destroy(): void;\n}\n\n/**\n * Check if video recording is supported in this browser\n */\nexport function isVideoRecordingSupported(): 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 * Detect the best supported MIME type for recording\n */\nexport function getSupportedMimeType(): string {\n if (typeof MediaRecorder === \"undefined\") return \"\";\n\n const candidates = [\n \"video/webm;codecs=vp9\",\n \"video/webm;codecs=vp8\",\n \"video/webm\",\n \"video/mp4\",\n ];\n\n for (const type of candidates) {\n if (MediaRecorder.isTypeSupported(type)) {\n return type;\n }\n }\n\n return \"\";\n}\n\n/**\n * Create a video recorder that captures the screen\n */\nexport function createVideoRecorder(options: VideoRecorderOptions = {}): VideoRecorder {\n const maxDuration = options.maxDuration ?? 15;\n const videoBitsPerSecond = options.videoBitsPerSecond ?? 800_000;\n const redactionElements = options.redactionElements ?? [];\n const redactionBlurRadius = options.redactionBlurRadius;\n\n let stream: MediaStream | null = null;\n let orientationCorrection: OrientationCorrectedStream | null = null;\n let redaction: RedactedStream | null = null;\n let recorder: MediaRecorder | null = null;\n let chunks: Blob[] = [];\n let tickCallback: ((elapsed: number) => void) | null = null;\n let stopCallback: ((blob: Blob | null) => void) | null = null;\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n let startTime = 0;\n let resolveStop: ((blob: Blob) => void) | null = null;\n let rejectStop: ((err: Error) => void) | null = null;\n let stopped = false;\n let autoStopTimeout: ReturnType<typeof setTimeout> | null = null;\n\n function cleanup(): void {\n if (tickInterval !== null) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n if (autoStopTimeout !== null) {\n clearTimeout(autoStopTimeout);\n autoStopTimeout = null;\n }\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n if (redaction) {\n redaction.stop();\n redaction = null;\n }\n if (stream) {\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n }\n recorder = null;\n chunks = [];\n tickCallback = null;\n stopCallback = null;\n resolveStop = null;\n rejectStop = null;\n }\n\n function finishRecording(): void {\n if (stopped) return;\n stopped = true;\n\n if (recorder && recorder.state !== \"inactive\") {\n recorder.stop();\n }\n }\n\n return {\n async start(): Promise<void> {\n stopped = false;\n chunks = [];\n\n const mimeType = getSupportedMimeType();\n if (!mimeType) {\n throw new Error(\"No supported video MIME type found\");\n }\n\n // Request screen capture, restricted to the current tab (the page the\n // embed is running on). `preferCurrentTab` collapses the Chromium picker\n // to a single \"share this tab\" choice; the other hints drop window and\n // whole-screen options where the browser honours them. These keys are\n // not in the DOM types yet.\n stream = await navigator.mediaDevices.getDisplayMedia({\n video: {\n frameRate: 15,\n displaySurface: \"browser\",\n },\n audio: false,\n // @ts-expect-error preferCurrentTab is not in the TS types yet\n preferCurrentTab: true,\n selfBrowserSurface: \"include\",\n monitorTypeSurfaces: \"exclude\",\n surfaceSwitching: \"exclude\",\n });\n\n // Enforce tab-only capture. In browsers that ignore the hints above and\n // still let the user share a window or the whole screen, reject it — qaid\n // records only the tab it is embedded in, never other windows or the\n // desktop.\n const videoTrack = stream.getVideoTracks()[0];\n const surface = videoTrack?.getSettings?.()?.displaySurface;\n if (surface === \"monitor\" || surface === \"window\") {\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n throw new Error(\n \"qaid records only the current tab — please share this tab, not a window or your whole screen.\",\n );\n }\n\n // Handle browser \"Stop sharing\" button\n if (videoTrack) {\n videoTrack.addEventListener(\"ended\", () => {\n finishRecording();\n });\n }\n\n // Route the raw capture through canvas pipelines when needed. On\n // iOS/iPadOS the captured file is rotated by the OS, so first re-encode\n // the live frames upright (falling back to the raw stream if the canvas\n // pipeline isn't available). Then, if the user marked regions to redact,\n // blur their live bounding boxes into whatever the first step produced.\n //\n // Redaction used to sit in an `else` of the iOS branch, so on an iPhone\n // or iPad the picker drew its outlines and the recording went out\n // unblurred. The upright frame matches the viewport, which is what the\n // redaction mapping assumes, so the two chain cleanly.\n let recordStream: MediaStream = stream;\n if (isIOSDevice()) {\n const corrected = await buildOrientationCorrectedStream(stream);\n if (corrected) {\n orientationCorrection = corrected;\n recordStream = corrected.stream;\n }\n }\n if (redactionElements.length > 0) {\n const redacted = await buildRedactedStream(recordStream, redactionElements, {\n blurRadius: redactionBlurRadius,\n });\n if (!redacted) {\n // The visitor was promised a blur. Recording the areas in the clear\n // would break that promise, so refuse to record instead.\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n throw new Error(REDACTION_UNAVAILABLE);\n }\n redaction = redacted;\n recordStream = redacted.stream;\n }\n\n recorder = new MediaRecorder(recordStream, {\n mimeType,\n videoBitsPerSecond,\n });\n\n recorder.ondataavailable = (e: BlobEvent) => {\n if (e.data.size > 0) {\n chunks.push(e.data);\n }\n };\n\n recorder.onstop = () => {\n const blob = new Blob(chunks, { type: mimeType });\n if (resolveStop) {\n resolveStop(blob);\n }\n // Notify via callback (for unexpected stops like browser stop button)\n if (stopCallback) {\n stopCallback(blob);\n }\n // Stop the canvas pipeline (iOS orientation / redaction) and the\n // display stream tracks.\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n if (redaction) {\n redaction.stop();\n redaction = null;\n }\n if (stream) {\n stream.getTracks().forEach((t) => t.stop());\n }\n };\n\n recorder.onerror = () => {\n if (rejectStop) {\n rejectStop(new Error(\"MediaRecorder error\"));\n }\n };\n\n recorder.start(1000); // collect data every second\n startTime = Date.now();\n\n // Start tick interval\n tickInterval = setInterval(() => {\n const elapsed = Math.floor((Date.now() - startTime) / 1000);\n if (tickCallback) {\n tickCallback(elapsed);\n }\n }, 1000);\n\n // Auto-stop at max duration\n autoStopTimeout = setTimeout(() => {\n finishRecording();\n }, maxDuration * 1000);\n },\n\n stop(): Promise<Blob> {\n return new Promise<Blob>((resolve, reject) => {\n resolveStop = resolve;\n rejectStop = reject;\n finishRecording();\n });\n },\n\n onTick(callback: (elapsed: number) => void): void {\n tickCallback = callback;\n },\n\n onStop(callback: (blob: Blob | null) => void): void {\n stopCallback = callback;\n },\n\n destroy(): void {\n finishRecording();\n cleanup();\n },\n };\n}\n"],"names":["isIOSDevice","ua","computeOrientationTransform","frameW","frameH","viewportW","viewportH","screenAngle","frameLandscape","viewportLandscape","drawRotatedFrame","ctx","source","t","getScreenAngle","orientation","waitForVideoDimensions","video","resolve","playSilently","buildOrientationCorrectedStream","displayStream","frameRate","canvas","transform","rafId","draw","stream","mapRectToFrame","rect","scaleX","scaleY","x","y","right","bottom","w","h","drawRedactedFrame","elements","blurRadius","supportsFilter","el","box","buildRedactedStream","options","REDACTION_UNAVAILABLE","isVideoRecordingSupported","getSupportedMimeType","candidates","type","createVideoRecorder","maxDuration","videoBitsPerSecond","redactionElements","redactionBlurRadius","orientationCorrection","redaction","recorder","chunks","tickCallback","stopCallback","tickInterval","startTime","resolveStop","rejectStop","stopped","autoStopTimeout","cleanup","finishRecording","mimeType","videoTrack","surface","recordStream","corrected","redacted","e","blob","elapsed","reject","callback"],"mappings":"AAkCO,SAASA,IAAuB;AACrC,QAAMC,IAAK,UAAU,aAAa;AAClC,SACE,iBAAiB,KAAKA,CAAE;AAAA,EAEvB,UAAU,aAAa,eAAe,UAAU,kBAAkB,KAAK;AAE5E;AASO,SAASC,EACdC,GACAC,GACAC,GACAC,GACAC,GACsB;AACtB,QAAMC,IAAiBL,KAAUC,GAC3BK,IAAoBJ,KAAaC;AAEvC,SAAIE,MAAmBC,IACd,EAAE,OAAON,GAAQ,QAAQC,GAAQ,QAAQ,EAAA,IAK3C,EAAE,OAAOA,GAAQ,QAAQD,GAAQ,QADfI,MAAgB,MAAM,MAAM,GACb;AAC1C;AAGO,SAASG,EACdC,GACAC,GACAC,GACM;AACN,MAAIA,EAAE,WAAW,GAAG;AAClB,IAAAF,EAAI,UAAUC,GAAQ,GAAG,GAAGC,E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AAac,GACbV,EAAA;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IAEA,OAAOW,GAA2C;AAChD,MAAApB,IAAeoB;AAAA,IACjB;AAAA,IAEA,OAAOA,GAA6C;AAClD,MAAAnB,IAAemB;AAAA,IACjB;AAAA,IAEA,UAAgB;AACd,MAAAX,EAAA,GACAD,EAAA;AAAA,IACF;AAAA,EAAA;AAEJ;"}
|
|
1
|
+
{"version":3,"file":"video-BSP4s2te.js","sources":["../../src/video-orientation.ts","../../src/video-redaction.ts","../../src/video-capture.ts"],"sourcesContent":["/**\n * iOS/iPadOS screen-recording orientation fix.\n *\n * On iOS/iPadOS, `getDisplayMedia` + `MediaRecorder` writes a device-orientation\n * rotation into the recorded file (even for screen captures). Players disagree\n * on whether to honour it — the widget's own preview `<video>` renders it\n * sideways, and so does the dashboard. Re-encoding the *live* decoded frames\n * (which carry no container rotation) through a canvas produces a file whose\n * pixels are already upright with no rotation metadata, so it renders the same\n * everywhere.\n *\n * If the live frames themselves come back with swapped dimensions (portrait\n * frame while the viewport is landscape, or vice versa), we additionally rotate\n * the canvas 90° to match the viewport. That branch only triggers on a clear\n * orientation mismatch, so a correctly-oriented recording is never rotated.\n */\n\nexport interface OrientationTransform {\n /** Output canvas width in px. */\n width: number;\n /** Output canvas height in px. */\n height: number;\n /** Clockwise rotation to apply while drawing: 0, 90, or -90. */\n rotate: 0 | 90 | -90;\n}\n\nexport interface OrientationCorrectedStream {\n /** Canvas-sourced stream to hand to MediaRecorder. */\n stream: MediaStream;\n /** Stop drawing and release the canvas stream + source video. */\n stop: () => void;\n}\n\n/** True on iPhone/iPad/iPod, including iPadOS 13+ which reports as desktop Mac. */\nexport function isIOSDevice(): boolean {\n const ua = navigator.userAgent || \"\";\n return (\n /iP(hone|ad|od)/.test(ua) ||\n // iPadOS 13+ masquerades as \"MacIntel\" but is a multi-touch device.\n (navigator.platform === \"MacIntel\" && (navigator.maxTouchPoints || 0) > 1)\n );\n}\n\n/**\n * Decide the output canvas size and rotation needed to render a `frameW×frameH`\n * capture upright for a `viewportW×viewportH` viewport. When the frame and\n * viewport share an orientation, no rotation is applied (a straight re-encode,\n * which still strips the bad container rotation). Otherwise rotate 90°, its\n * direction chosen from the screen orientation angle.\n */\nexport function computeOrientationTransform(\n frameW: number,\n frameH: number,\n viewportW: number,\n viewportH: number,\n screenAngle: number\n): OrientationTransform {\n const frameLandscape = frameW >= frameH;\n const viewportLandscape = viewportW >= viewportH;\n\n if (frameLandscape === viewportLandscape) {\n return { width: frameW, height: frameH, rotate: 0 };\n }\n\n // Landscape-secondary (angle 270) is turned the opposite way to primary (90).\n const rotate: 90 | -90 = screenAngle === 270 ? -90 : 90;\n return { width: frameH, height: frameW, rotate };\n}\n\n/** Draw one video frame onto the canvas context, applying the transform. */\nexport function drawRotatedFrame(\n ctx: CanvasRenderingContext2D,\n source: CanvasImageSource,\n t: OrientationTransform\n): void {\n if (t.rotate === 0) {\n ctx.drawImage(source, 0, 0, t.width, t.height);\n return;\n }\n\n ctx.save();\n if (t.rotate === 90) {\n ctx.translate(t.width, 0);\n ctx.rotate(Math.PI / 2);\n } else {\n ctx.translate(0, t.height);\n ctx.rotate(-Math.PI / 2);\n }\n // The source is drawn at its natural (unrotated) extents, which are the\n // output dimensions swapped back.\n ctx.drawImage(source, 0, 0, t.height, t.width);\n ctx.restore();\n}\n\nfunction getScreenAngle(): number {\n const orientation =\n typeof screen !== \"undefined\" ? screen.orientation : undefined;\n return orientation && typeof orientation.angle === \"number\"\n ? orientation.angle\n : 0;\n}\n\nexport function waitForVideoDimensions(video: HTMLVideoElement): Promise<void> {\n return new Promise<void>((resolve) => {\n if (video.videoWidth > 0) {\n resolve();\n return;\n }\n video.addEventListener(\"loadedmetadata\", () => resolve(), { once: true });\n });\n}\n\nexport async function playSilently(video: HTMLVideoElement): Promise<void> {\n try {\n await video.play();\n } catch {\n // Autoplay can reject without a gesture; the element still produces frames\n // for the canvas, so this is non-fatal.\n }\n}\n\n/**\n * Build a canvas-backed, orientation-normalised copy of a display-capture\n * stream. Returns null when the browser can't support the canvas pipeline, in\n * which case the caller should record the original stream directly.\n */\nexport async function buildOrientationCorrectedStream(\n displayStream: MediaStream,\n frameRate = 15\n): Promise<OrientationCorrectedStream | null> {\n const canvas = document.createElement(\"canvas\");\n if (typeof canvas.captureStream !== \"function\") return null;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return null;\n\n const video = document.createElement(\"video\");\n video.muted = true;\n video.playsInline = true;\n video.srcObject = displayStream;\n\n await waitForVideoDimensions(video);\n\n const transform = computeOrientationTransform(\n video.videoWidth,\n video.videoHeight,\n window.innerWidth,\n window.innerHeight,\n getScreenAngle()\n );\n canvas.width = transform.width;\n canvas.height = transform.height;\n\n await playSilently(video);\n\n let rafId = 0;\n const draw = (): void => {\n drawRotatedFrame(ctx, video, transform);\n rafId = requestAnimationFrame(draw);\n };\n draw();\n\n const stream = canvas.captureStream(frameRate);\n\n return {\n stream,\n stop: (): void => {\n if (rafId) cancelAnimationFrame(rafId);\n rafId = 0;\n stream.getTracks().forEach((t) => t.stop());\n video.pause();\n video.srcObject = null;\n },\n };\n}\n","/**\n * Live video redaction.\n *\n * Blurs the on-screen bounding boxes of chosen elements while the current tab\n * is recorded. Every frame re-reads each element's `getBoundingClientRect()`,\n * so the blur tracks the content as the page scrolls or reflows — no pixel\n * tracking and no post-recording re-encode. The captured frame is the tab's\n * viewport (video-capture restricts capture to the current tab), so viewport\n * CSS coordinates map onto the frame with a single scale factor.\n *\n * The display stream is drawn to a canvas, the tracked regions are blurred on\n * top, and MediaRecorder records the canvas stream instead of the raw capture —\n * mirroring the iOS orientation pipeline in `video-orientation.ts`.\n */\n\nimport { waitForVideoDimensions, playSilently } from \"./video-orientation\";\n\nexport interface RedactedStream {\n /** Canvas-sourced stream to hand to MediaRecorder. */\n stream: MediaStream;\n /** Stop drawing and release the canvas stream + source video. */\n stop: () => void;\n}\n\nexport interface RedactionOptions {\n /** Output frame rate of the redacted stream. Default: 15. */\n frameRate?: number;\n /** Gaussian blur radius in px applied to each region. Default: 12. */\n blurRadius?: number;\n}\n\ninterface Box {\n x: number;\n y: number;\n w: number;\n h: number;\n}\n\n/**\n * Map a viewport rect (CSS px, from `getBoundingClientRect()`) onto the\n * captured frame, clamped to the frame bounds. Returns null when the rect is\n * fully outside the viewport (the element scrolled away) or has no area.\n */\nexport function mapRectToFrame(\n rect: { left: number; top: number; width: number; height: number },\n scaleX: number,\n scaleY: number,\n frameW: number,\n frameH: number\n): Box | null {\n const x = Math.max(0, Math.min(frameW, rect.left * scaleX));\n const y = Math.max(0, Math.min(frameH, rect.top * scaleY));\n const right = Math.max(0, Math.min(frameW, (rect.left + rect.width) * scaleX));\n const bottom = Math.max(0, Math.min(frameH, (rect.top + rect.height) * scaleY));\n const w = right - x;\n const h = bottom - y;\n if (w <= 0 || h <= 0) return null;\n return { x, y, w, h };\n}\n\n/**\n * Draw one frame: the full capture, then each element's live bounding box\n * blurred on top. Exported for unit testing the per-frame logic without a real\n * capture stream. When the 2D context can't apply a blur filter, the region is\n * filled solid instead so sensitive content is still hidden.\n */\nexport function drawRedactedFrame(\n ctx: CanvasRenderingContext2D,\n video: CanvasImageSource,\n elements: Element[],\n frameW: number,\n frameH: number,\n blurRadius: number,\n supportsFilter: boolean\n): void {\n ctx.drawImage(video, 0, 0, frameW, frameH);\n\n // The current-tab capture is the viewport, so this scale is ~devicePixelRatio;\n // deriving it live also absorbs viewport resizes mid-recording.\n const scaleX = frameW / Math.max(1, window.innerWidth);\n const scaleY = frameH / Math.max(1, window.innerHeight);\n\n for (const el of elements) {\n const box = mapRectToFrame(\n el.getBoundingClientRect(),\n scaleX,\n scaleY,\n frameW,\n frameH\n );\n if (!box) continue; // scrolled out of view\n\n ctx.save();\n if (supportsFilter) {\n ctx.filter = `blur(${blurRadius}px)`;\n // Re-sample just this region from the live frame so the blur source is\n // the region itself.\n ctx.drawImage(video, box.x, box.y, box.w, box.h, box.x, box.y, box.w, box.h);\n } else {\n // No canvas filter support — hide the region with a solid fill.\n ctx.fillStyle = \"#0b0b0b\";\n ctx.fillRect(box.x, box.y, box.w, box.h);\n }\n ctx.restore();\n }\n}\n\n/**\n * Build a canvas-backed copy of a display-capture stream that blurs the live\n * bounding boxes of `elements`. Returns null when the browser can't support the\n * canvas pipeline (no `captureStream` / 2D context), in which case the caller\n * should record the original stream unredacted.\n */\nexport async function buildRedactedStream(\n displayStream: MediaStream,\n elements: Element[],\n options: RedactionOptions = {}\n): Promise<RedactedStream | null> {\n const frameRate = options.frameRate ?? 15;\n const blurRadius = options.blurRadius ?? 12;\n\n const canvas = document.createElement(\"canvas\");\n if (typeof canvas.captureStream !== \"function\") return null;\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) return null;\n\n // Feature-detect canvas blur; fall back to solid fill where unsupported.\n const supportsFilter = \"filter\" in ctx;\n\n const video = document.createElement(\"video\");\n video.muted = true;\n video.playsInline = true;\n video.srcObject = displayStream;\n\n await waitForVideoDimensions(video);\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n\n await playSilently(video);\n\n let rafId = 0;\n const draw = (): void => {\n drawRedactedFrame(\n ctx,\n video,\n elements,\n canvas.width,\n canvas.height,\n blurRadius,\n supportsFilter\n );\n rafId = requestAnimationFrame(draw);\n };\n draw();\n\n const stream = canvas.captureStream(frameRate);\n\n return {\n stream,\n stop: (): void => {\n if (rafId) cancelAnimationFrame(rafId);\n rafId = 0;\n stream.getTracks().forEach((t) => t.stop());\n video.pause();\n video.srcObject = null;\n },\n };\n}\n","/**\n * Video capture utilities\n * Uses getDisplayMedia + MediaRecorder for screen recording\n */\n\nimport {\n isIOSDevice,\n buildOrientationCorrectedStream,\n type OrientationCorrectedStream,\n} from \"./video-orientation\";\nimport { buildRedactedStream, type RedactedStream } from \"./video-redaction\";\n\n/**\n * Thrown by `start()` when areas were picked for redaction but this browser\n * cannot run the canvas pipeline that blurs them. The recording is refused\n * rather than made without the blur.\n */\nexport const REDACTION_UNAVAILABLE =\n \"This browser cannot blur the areas you picked, so the recording was not started.\";\n\nexport interface VideoRecorderOptions {\n /** Max recording duration in seconds. Default: 15 */\n maxDuration?: number;\n /** Video bitrate in bps. Default: 800000 (800kbps) */\n videoBitsPerSecond?: number;\n /**\n * Elements whose live bounding boxes are blurred out of the recording. The\n * blur tracks each element as the page scrolls. Empty/omitted = no redaction.\n */\n redactionElements?: Element[];\n /** Blur radius in px for redacted regions. Default: 12. */\n redactionBlurRadius?: number;\n}\n\nexport interface VideoRecorder {\n /** Start recording. Requests getDisplayMedia if not already started. */\n start(): Promise<void>;\n /** Stop recording and return the video blob. */\n stop(): Promise<Blob>;\n /** Register a callback for each second tick (receives seconds elapsed). */\n onTick(callback: (elapsed: number) => void): void;\n /** Register a callback for when recording stops (e.g., browser stop button, max duration). */\n onStop(callback: (blob: Blob | null) => void): void;\n /** Clean up all resources. */\n destroy(): void;\n}\n\n/**\n * Check if video recording is supported in this browser\n */\nexport function isVideoRecordingSupported(): 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 * Detect the best supported MIME type for recording\n */\nexport function getSupportedMimeType(): string {\n if (typeof MediaRecorder === \"undefined\") return \"\";\n\n const candidates = [\n \"video/webm;codecs=vp9\",\n \"video/webm;codecs=vp8\",\n \"video/webm\",\n \"video/mp4\",\n ];\n\n for (const type of candidates) {\n if (MediaRecorder.isTypeSupported(type)) {\n return type;\n }\n }\n\n return \"\";\n}\n\n/**\n * Create a video recorder that captures the screen\n */\nexport function createVideoRecorder(options: VideoRecorderOptions = {}): VideoRecorder {\n const maxDuration = options.maxDuration ?? 15;\n const videoBitsPerSecond = options.videoBitsPerSecond ?? 800_000;\n const redactionElements = options.redactionElements ?? [];\n const redactionBlurRadius = options.redactionBlurRadius;\n\n let stream: MediaStream | null = null;\n let orientationCorrection: OrientationCorrectedStream | null = null;\n let redaction: RedactedStream | null = null;\n let recorder: MediaRecorder | null = null;\n let chunks: Blob[] = [];\n let tickCallback: ((elapsed: number) => void) | null = null;\n let stopCallback: ((blob: Blob | null) => void) | null = null;\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n let startTime = 0;\n let resolveStop: ((blob: Blob) => void) | null = null;\n let rejectStop: ((err: Error) => void) | null = null;\n let stopped = false;\n let autoStopTimeout: ReturnType<typeof setTimeout> | null = null;\n\n function cleanup(): void {\n if (tickInterval !== null) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n if (autoStopTimeout !== null) {\n clearTimeout(autoStopTimeout);\n autoStopTimeout = null;\n }\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n if (redaction) {\n redaction.stop();\n redaction = null;\n }\n if (stream) {\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n }\n recorder = null;\n chunks = [];\n tickCallback = null;\n stopCallback = null;\n resolveStop = null;\n rejectStop = null;\n }\n\n function finishRecording(): void {\n if (stopped) return;\n stopped = true;\n\n if (recorder && recorder.state !== \"inactive\") {\n recorder.stop();\n }\n }\n\n return {\n async start(): Promise<void> {\n stopped = false;\n chunks = [];\n\n const mimeType = getSupportedMimeType();\n if (!mimeType) {\n throw new Error(\"No supported video MIME type found\");\n }\n\n // Request screen capture, restricted to the current tab (the page the\n // embed is running on). `preferCurrentTab` collapses the Chromium picker\n // to a single \"share this tab\" choice; the other hints drop window and\n // whole-screen options where the browser honours them. These keys are\n // not in the DOM types yet.\n stream = await navigator.mediaDevices.getDisplayMedia({\n video: {\n frameRate: 15,\n displaySurface: \"browser\",\n },\n audio: false,\n // @ts-expect-error preferCurrentTab is not in the TS types yet\n preferCurrentTab: true,\n selfBrowserSurface: \"include\",\n monitorTypeSurfaces: \"exclude\",\n surfaceSwitching: \"exclude\",\n });\n\n // Enforce tab-only capture. In browsers that ignore the hints above and\n // still let the user share a window or the whole screen, reject it — qaid\n // records only the tab it is embedded in, never other windows or the\n // desktop.\n const videoTrack = stream.getVideoTracks()[0];\n const surface = videoTrack?.getSettings?.()?.displaySurface;\n if (surface === \"monitor\" || surface === \"window\") {\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n throw new Error(\n \"qaid records only the current tab — please share this tab, not a window or your whole screen.\",\n );\n }\n\n // Handle browser \"Stop sharing\" button\n if (videoTrack) {\n videoTrack.addEventListener(\"ended\", () => {\n finishRecording();\n });\n }\n\n // Route the raw capture through canvas pipelines when needed. On\n // iOS/iPadOS the captured file is rotated by the OS, so first re-encode\n // the live frames upright (falling back to the raw stream if the canvas\n // pipeline isn't available). Then, if the user marked regions to redact,\n // blur their live bounding boxes into whatever the first step produced.\n //\n // Redaction used to sit in an `else` of the iOS branch, so on an iPhone\n // or iPad the picker drew its outlines and the recording went out\n // unblurred. The upright frame matches the viewport, which is what the\n // redaction mapping assumes, so the two chain cleanly.\n let recordStream: MediaStream = stream;\n if (isIOSDevice()) {\n const corrected = await buildOrientationCorrectedStream(stream);\n if (corrected) {\n orientationCorrection = corrected;\n recordStream = corrected.stream;\n }\n }\n if (redactionElements.length > 0) {\n const redacted = await buildRedactedStream(recordStream, redactionElements, {\n blurRadius: redactionBlurRadius,\n });\n if (!redacted) {\n // The visitor was promised a blur. Recording the areas in the clear\n // would break that promise, so refuse to record instead.\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n stream.getTracks().forEach((t) => t.stop());\n stream = null;\n throw new Error(REDACTION_UNAVAILABLE);\n }\n redaction = redacted;\n recordStream = redacted.stream;\n }\n\n recorder = new MediaRecorder(recordStream, {\n mimeType,\n videoBitsPerSecond,\n });\n\n recorder.ondataavailable = (e: BlobEvent) => {\n if (e.data.size > 0) {\n chunks.push(e.data);\n }\n };\n\n recorder.onstop = () => {\n const blob = new Blob(chunks, { type: mimeType });\n if (resolveStop) {\n resolveStop(blob);\n }\n // Notify via callback (for unexpected stops like browser stop button)\n if (stopCallback) {\n stopCallback(blob);\n }\n // Stop the canvas pipeline (iOS orientation / redaction) and the\n // display stream tracks.\n if (orientationCorrection) {\n orientationCorrection.stop();\n orientationCorrection = null;\n }\n if (redaction) {\n redaction.stop();\n redaction = null;\n }\n if (stream) {\n stream.getTracks().forEach((t) => t.stop());\n }\n };\n\n recorder.onerror = () => {\n if (rejectStop) {\n rejectStop(new Error(\"MediaRecorder error\"));\n }\n };\n\n recorder.start(1000); // collect data every second\n startTime = Date.now();\n\n // Start tick interval\n tickInterval = setInterval(() => {\n const elapsed = Math.floor((Date.now() - startTime) / 1000);\n if (tickCallback) {\n tickCallback(elapsed);\n }\n }, 1000);\n\n // Auto-stop at max duration\n autoStopTimeout = setTimeout(() => {\n finishRecording();\n }, maxDuration * 1000);\n },\n\n stop(): Promise<Blob> {\n return new Promise<Blob>((resolve, reject) => {\n resolveStop = resolve;\n rejectStop = reject;\n finishRecording();\n });\n },\n\n onTick(callback: (elapsed: number) => void): void {\n tickCallback = callback;\n },\n\n onStop(callback: (blob: Blob | null) => void): void {\n stopCallback = callback;\n },\n\n destroy(): void {\n finishRecording();\n cleanup();\n },\n };\n}\n"],"names":["isIOSDevice","ua","computeOrientationTransform","frameW","frameH","viewportW","viewportH","screenAngle","frameLandscape","viewportLandscape","drawRotatedFrame","ctx","source","t","getScreenAngle","orientation","waitForVideoDimensions","video","resolve","playSilently","buildOrientationCorrectedStream","displayStream","frameRate","canvas","transform","rafId","draw","stream","mapRectToFrame","rect","scaleX","scaleY","x","y","right","bottom","w","h","drawRedactedFrame","elements","blurRadius","supportsFilter","el","box","buildRedactedStream","options","REDACTION_UNAVAILABLE","isVideoRecordingSupported","getSupportedMimeType","candidates","type","createVideoRecorder","maxDuration","videoBitsPerSecond","redactionElements","redactionBlurRadius","orientationCorrection","redaction","recorder","chunks","tickCallback","stopCallback","tickInterval","startTime","resolveStop","rejectStop","stopped","autoStopTimeout","cleanup","finishRecording","mimeType","videoTrack","surface","recordStream","corrected","redacted","e","blob","elapsed","reject","callback"],"mappings":"AAkCO,SAASA,GAAuB,CACrC,MAAMC,EAAK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 -34,7 +34,7 @@ export declare class QaidFeedback {
|
|
|
34
34
|
private consoleCapture;
|
|
35
35
|
private recording;
|
|
36
36
|
private targeting;
|
|
37
|
-
private
|
|
37
|
+
private clickPathPrewarmed;
|
|
38
38
|
private prewarmHandle;
|
|
39
39
|
private prewarmIsTimeout;
|
|
40
40
|
private videoPrewarmed;
|
|
@@ -46,14 +46,12 @@ export declare class QaidFeedback {
|
|
|
46
46
|
private buttonsContainer;
|
|
47
47
|
private isUserProvidedContainer;
|
|
48
48
|
private modal;
|
|
49
|
-
private modalPrewarmed;
|
|
50
49
|
private dismissBtn;
|
|
51
50
|
private cssVars;
|
|
52
51
|
private activeThumbBtn;
|
|
53
52
|
private keyboardActivation;
|
|
54
|
-
private
|
|
55
|
-
private
|
|
56
|
-
private dialogRestoreInert;
|
|
53
|
+
private dialogModule;
|
|
54
|
+
private dialogClose;
|
|
57
55
|
private readonly uid;
|
|
58
56
|
private boundKeyDown;
|
|
59
57
|
private boundResize;
|
|
@@ -70,15 +68,26 @@ export declare class QaidFeedback {
|
|
|
70
68
|
* while a dialog aria-hides the main button host.
|
|
71
69
|
*/
|
|
72
70
|
private announceMsg;
|
|
71
|
+
/** Load the dialog a11y helpers; every surface that opens a dialog awaits this first. */
|
|
72
|
+
private loadDialogA11y;
|
|
73
73
|
/**
|
|
74
74
|
* Turn a transient surface into an accessible modal dialog: save the
|
|
75
75
|
* invoking control, apply dialog semantics, trap focus, and inert the
|
|
76
|
-
* background. Paired with closeDialogA11y() on every close path.
|
|
76
|
+
* background. Paired with closeDialogA11y() on every close path. Callers
|
|
77
|
+
* reach it only after loadDialogA11y() has resolved.
|
|
77
78
|
*/
|
|
78
79
|
private openDialogA11y;
|
|
79
80
|
private closeDialogA11y;
|
|
80
81
|
private clearActiveThumb;
|
|
81
82
|
private init;
|
|
83
|
+
/**
|
|
84
|
+
* Warm everything a thumb click needs: the send flow, the dialog helpers,
|
|
85
|
+
* the message box, and targeting (unless it is skipped). Runs once, on the
|
|
86
|
+
* first of: pointer or focus entering the buttons, or the idle callback.
|
|
87
|
+
*/
|
|
88
|
+
private prewarmClickPath;
|
|
89
|
+
/** "annotate" mode and skipTargeting both go straight to the send flow. */
|
|
90
|
+
private skipsTargeting;
|
|
82
91
|
/**
|
|
83
92
|
* Best-effort preload of a lazily-split feature chunk so its first use is
|
|
84
93
|
* instant. Warming fetches + compiles (and defines) the module; the feature
|
|
@@ -139,29 +148,19 @@ export declare class QaidFeedback {
|
|
|
139
148
|
* otherwise DOM is used on touch devices to avoid the getDisplayMedia prompt. */
|
|
140
149
|
private shouldCaptureViaDom;
|
|
141
150
|
/**
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
145
|
-
*
|
|
146
|
-
* enabled while the editor is open and restored on close.
|
|
151
|
+
* Run the send flow (send.ts, loaded on demand and pre-warmed before the
|
|
152
|
+
* click): screenshot, markup, POST, then a linked quest or the message box.
|
|
153
|
+
* If its chunk will not load, say so and reset rather than leave the
|
|
154
|
+
* visitor stuck mid-flow.
|
|
147
155
|
*/
|
|
148
|
-
private openAnnotationEditor;
|
|
149
156
|
private submitFeedback;
|
|
150
|
-
/** POST the feedback. Resolves to the new record's id, or null if it failed. */
|
|
151
|
-
private postFeedback;
|
|
152
|
-
/**
|
|
153
|
-
* Quest id linked to `type`, or "" when quest launching is disabled
|
|
154
|
-
* (no `base`) or this button has no quest configured.
|
|
155
|
-
*/
|
|
156
|
-
private questIdFor;
|
|
157
157
|
/**
|
|
158
|
-
* Launch the quest linked to `type
|
|
159
|
-
*
|
|
160
|
-
* configured or the widget failed to load (caller falls back to its
|
|
161
|
-
* normal UI). The created feedback record id is passed through so the
|
|
162
|
-
* quest response can be joined back to it server-side.
|
|
158
|
+
* Launch the quest linked to `type` through the send chunk. Resolves false
|
|
159
|
+
* when none is linked, or when the chunk or the quest will not load.
|
|
163
160
|
*/
|
|
164
161
|
private tryLaunchQuest;
|
|
162
|
+
/** Narrow view of the embed the send flow talks back through. */
|
|
163
|
+
private makeSendHost;
|
|
165
164
|
/**
|
|
166
165
|
* Reset the thumbs targeting/marker UI back to idle without opening or
|
|
167
166
|
* closing the message modal. Shared by closeModal() and the quest-launch
|
|
@@ -170,24 +169,20 @@ export declare class QaidFeedback {
|
|
|
170
169
|
private resetFeedbackUi;
|
|
171
170
|
/**
|
|
172
171
|
* Lazily load and instantiate the modal controller. The message modal lives
|
|
173
|
-
* in a separate chunk, fetched the first time it opens (and pre-warmed
|
|
174
|
-
* the
|
|
172
|
+
* in a separate chunk, fetched the first time it opens (and pre-warmed
|
|
173
|
+
* before the click — see prewarmClickPath).
|
|
175
174
|
*/
|
|
176
175
|
private ensureModal;
|
|
177
176
|
/** Narrow view of the embed the modal controller talks back through. */
|
|
178
177
|
private makeModalHost;
|
|
179
|
-
/** Warm the modal chunk while the user is targeting, so it opens instantly. */
|
|
180
|
-
private prewarmModal;
|
|
181
178
|
/**
|
|
182
179
|
* Lazily load and instantiate the targeting controller. The subsystem (with
|
|
183
180
|
* element-selector) lives in a separate chunk, fetched the first time the
|
|
184
|
-
* user targets — pre-warmed
|
|
181
|
+
* user targets — pre-warmed before the click (see prewarmClickPath).
|
|
185
182
|
*/
|
|
186
183
|
private ensureTargeting;
|
|
187
184
|
/** Narrow view of the embed the targeting controller talks back through. */
|
|
188
185
|
private makeTargetingHost;
|
|
189
|
-
/** Warm the targeting chunk on thumb-button hover, before the click. */
|
|
190
|
-
private prewarmTargeting;
|
|
191
186
|
/**
|
|
192
187
|
* Cheap synchronous capability check so the record button can render without
|
|
193
188
|
* pulling in the (lazily-loaded) video subsystem. Mirrors
|