@qaiddev/thumbs-embed 1.12.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +67 -13
  2. package/dist/bootstrap.d.ts +29 -4
  3. package/dist/chunks/annotate-1zompTEi.js +2 -0
  4. package/dist/chunks/annotate-1zompTEi.js.map +1 -0
  5. package/dist/chunks/core-vu1EieDc.js +26 -0
  6. package/dist/chunks/core-vu1EieDc.js.map +1 -0
  7. package/dist/chunks/dom-kdwHduNo.js +2 -0
  8. package/dist/chunks/dom-kdwHduNo.js.map +1 -0
  9. package/dist/chunks/html2canvas.esm-Csbr1w14.js +6 -0
  10. package/dist/chunks/html2canvas.esm-Csbr1w14.js.map +1 -0
  11. package/dist/chunks/modal-5G2DhiUE.js +2 -0
  12. package/dist/chunks/modal-5G2DhiUE.js.map +1 -0
  13. package/dist/chunks/{recording-BUw5-5Rf.js → recording-CVwPTtB0.js} +2 -2
  14. package/dist/chunks/{recording-BUw5-5Rf.js.map → recording-CVwPTtB0.js.map} +1 -1
  15. package/dist/chunks/screenshot-dom-DO-0UlOz.js +2 -0
  16. package/dist/chunks/screenshot-dom-DO-0UlOz.js.map +1 -0
  17. package/dist/chunks/send-C3IvslZA.js +2 -0
  18. package/dist/chunks/send-C3IvslZA.js.map +1 -0
  19. package/dist/chunks/{targeting-CMUEe-7C.js → targeting-Bpbt68Pp.js} +2 -6
  20. package/dist/chunks/{targeting-CMUEe-7C.js.map → targeting-Bpbt68Pp.js.map} +1 -1
  21. package/dist/dom.d.ts +0 -2
  22. package/dist/embed-loader.d.ts +7 -0
  23. package/dist/embed.js +1 -1
  24. package/dist/embed.js.map +1 -1
  25. package/dist/icons.d.ts +2 -0
  26. package/dist/index.js +6628 -1530
  27. package/dist/index.js.map +1 -1
  28. package/dist/loader.js +1 -1
  29. package/dist/loader.js.map +1 -1
  30. package/dist/origin-key.d.ts +7 -0
  31. package/dist/qaid.umd.cjs +17 -17
  32. package/dist/qaid.umd.cjs.map +1 -1
  33. package/dist/quest-config.d.ts +27 -2
  34. package/dist/quest-launcher.d.ts +12 -0
  35. package/dist/screenshot-dom.d.ts +7 -5
  36. package/dist/svg-sanitize.d.ts +35 -0
  37. package/dist/trusted-types.d.ts +29 -0
  38. package/package.json +4 -2
  39. package/dist/chunks/annotate-DGyRcgPt.js +0 -2
  40. package/dist/chunks/annotate-DGyRcgPt.js.map +0 -1
  41. package/dist/chunks/core-BsR7oV99.js +0 -26
  42. package/dist/chunks/core-BsR7oV99.js.map +0 -1
  43. package/dist/chunks/dom-scpOS8nl.js +0 -2
  44. package/dist/chunks/dom-scpOS8nl.js.map +0 -1
  45. package/dist/chunks/modal-DYxcs1Gm.js +0 -2
  46. package/dist/chunks/modal-DYxcs1Gm.js.map +0 -1
  47. package/dist/chunks/screenshot-dom-ZYP2w2h0.js +0 -2
  48. package/dist/chunks/screenshot-dom-ZYP2w2h0.js.map +0 -1
  49. package/dist/chunks/send-C26DRoYc.js +0 -2
  50. package/dist/chunks/send-C26DRoYc.js.map +0 -1
@@ -0,0 +1,2 @@
1
+ import{h as s}from"./dom-kdwHduNo.js";import{i as c,s as f,F as b,T as m,e as p,b as g,E as q}from"./core-vu1EieDc.js";const u={width:400,height:280,arrowHeight:12,gap:8,viewportPadding:16};function x(n,i,e,t,o){const a=n.y,r=i-(n.y+n.height);if(r>=e+t)return{top:n.y+n.height+t,position:"below"};if(a>=e+t)return{top:n.y-e-t,position:"above"};const d=r>a?"below":"above";let l;return d==="below"?l=Math.min(n.y+n.height+t,i-e-o):l=Math.max(o,n.y-e-t),{top:l,position:d}}function y(n,i,e,t){let a=n.x+n.width/2-e/2;return a=Math.max(t,Math.min(a,i-e-t)),a}function k(n,i,e,t=24,o=24){const r=n.clickX-i-o/2;return Math.max(t,Math.min(r,e-t-o/2))}function v(n,i,e,t=u){const o=t.height+t.arrowHeight,a=x(n,e,o,t.gap,t.viewportPadding),r=y(n,i,t.width,t.viewportPadding);return{top:a.top,left:r,position:a.position}}function w(n,i,e,t=u){const o=v(n,i,e,t),a=k(n,o.left,t.width);return{modal:o,arrow:{left:a}}}const C=".qaid-backdrop{position:fixed;inset:0;z-index:45;background:#0000004d}.qaid-modal-container{position:fixed;z-index:50;display:flex;flex-direction:column;align-items:flex-start;max-height:calc(100vh - 32px);font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:var(--qaid-font-size, 16px)}.qaid-modal-container.qaid-above{flex-direction:column-reverse}.qaid-modal-arrow{width:0;height:0;border-left:12px solid transparent;border-right:12px solid transparent;position:relative;align-self:flex-start}.qaid-modal-container.qaid-below .qaid-modal-arrow{border-bottom:12px solid light-dark(#ffffff,#1f2937)}.qaid-modal-container.qaid-above .qaid-modal-arrow{border-top:12px solid light-dark(#ffffff,#1f2937)}.qaid-modal-box{color-scheme:inherit;background:light-dark(#ffffff,#1f2937);border-radius:1rem;padding:1.5rem;box-shadow:0 25px 50px -12px light-dark(rgba(0,0,0,.25),rgba(0,0,0,.5));width:var(--qaid-modal-width, 400px);max-width:calc(100vw - 32px);max-height:calc(100vh - 60px);overflow-y:auto}.qaid-modal-header{display:flex;align-items:flex-start;gap:.75rem;margin-bottom:1rem}button.qaid-type-toggle{border:none;display:flex;align-items:center;justify-content:center;cursor:pointer;transition:all .2s;flex-shrink:0;-webkit-appearance:none;appearance:none}button.qaid-type-toggle:hover{transform:scale(1.1)}button.qaid-type-toggle:not(.qaid-type-toggle-custom){width:2.5rem;height:2.5rem;border-radius:50%}button.qaid-type-toggle:not(.qaid-type-toggle-custom) svg{width:1.25rem;height:1.25rem}button.qaid-type-toggle.qaid-type-up{background:var(--qaid-positive);color:#fff}button.qaid-type-toggle.qaid-type-down{background:var(--qaid-negative);color:#fff}.qaid-type-static{width:2.5rem;height:2.5rem;border-radius:50%;display:flex;align-items:center;justify-content:center;flex-shrink:0;background:var(--qaid-marker, #6365f1);color:var(--qaid-marker-text, white)}.qaid-type-static svg{width:1.25rem;height:1.25rem}.qaid-modal-header-text{flex:1;min-width:0}.qaid-modal-title{font-size:calc(var(--qaid-font-size, 16px) * 1.125);font-weight:700;margin:0 0 .25rem;color:light-dark(#1f2937,#f9fafb)}.qaid-modal-subtitle{color:light-dark(#6b7280,#9ca3af);margin:0;font-size:calc(var(--qaid-font-size, 16px) * .875)}.qaid-textarea{width:100%;height:6rem;padding:.75rem;border:1px solid light-dark(#d1d5db,#374151);border-radius:.5rem;font-family:inherit;font-size:var(--qaid-font-size, 16px);resize:vertical;margin-bottom:1rem;box-sizing:border-box;background:light-dark(#ffffff,#111827);color:light-dark(#1f2937,#f9fafb)}.qaid-textarea:focus{outline:none;border-color:var(--qaid-marker);box-shadow:0 0 0 3px color-mix(in srgb,var(--qaid-marker) 20%,transparent)}.qaid-btn-row{display:flex;gap:.5rem;justify-content:flex-end}button.qaid-btn-submit{padding:.5rem 1rem;background:var(--qaid-marker);color:var(--qaid-marker-text, white);border:none;border-radius:.5rem;font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;cursor:pointer;transition:background-color .2s,filter .2s;-webkit-appearance:none;appearance:none}button.qaid-btn-submit:hover{filter:brightness(.85)}button.qaid-btn-submit:focus{outline:none;box-shadow:0 0 0 3px color-mix(in srgb,var(--qaid-marker) 30%,transparent)}.qaid-bottom-sheet{position:fixed;bottom:0;left:0;right:0;z-index:50;animation:qaid-slideUpSheet .3s ease-out;font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:var(--qaid-font-size, 16px)}.qaid-bottom-sheet-content{background:light-dark(#ffffff,#1f2937);border-radius:1rem 1rem 0 0;padding:1.5rem;padding-bottom:max(1.5rem,env(safe-area-inset-bottom))}.qaid-bottom-sheet-handle{width:36px;height:4px;background:light-dark(rgba(0,0,0,.2),rgba(255,255,255,.2));border-radius:2px;margin:0 auto 1rem}@keyframes qaid-slideUpSheet{0%{transform:translateY(100%)}to{transform:translateY(0)}}.qaid-confirm{display:flex;flex-direction:column;align-items:center;text-align:center;gap:.5rem;padding:.5rem 0}.qaid-confirm-icon{display:flex;align-items:center;justify-content:center;width:44px;height:44px;border-radius:9999px;color:#fff;background:var(--qaid-success, #22c55e);margin-bottom:.25rem;animation:qaid-confirm-pop .28s cubic-bezier(.34,1.56,.64,1)}.qaid-confirm-icon .qaid-icon{width:24px;height:24px}.qaid-confirm-error .qaid-confirm-icon{background:var(--qaid-error, #dc2626)}.qaid-confirm-title{margin:0;font-size:var(--qaid-font-size, 16px);font-weight:600;color:var(--qaid-text, light-dark(#111827, #f9fafb))}.qaid-confirm-title:focus-visible{outline:2px solid var(--qaid-primary, #6365f1);outline-offset:3px;border-radius:4px}.qaid-confirm-message{margin:0;font-size:calc(var(--qaid-font-size, 16px) * .875);color:var(--qaid-text-muted, light-dark(#6b7280, #9ca3af))}.qaid-confirm .qaid-confirm-close{margin-top:.5rem;min-width:96px}@keyframes qaid-confirm-pop{0%{transform:scale(.6);opacity:0}to{transform:scale(1);opacity:1}}@media(prefers-reduced-motion:reduce){.qaid-confirm-icon{animation:none}}.qaid-textarea:focus-visible,button.qaid-btn-submit:focus-visible{outline:2px solid var(--qaid-marker, #6365f1);outline-offset:2px}@media(forced-colors:active){.qaid-textarea:focus,button.qaid-btn-submit:focus{outline:2px solid CanvasText;outline-offset:2px}}";class z{constructor(i){this.host=i}host;modalContainer=null;backdrop=null;finalized=!1;open(){this.finalized=!1;const i=this.host.ensureOverlayHost();this.backdrop=document.createElement("div"),this.backdrop.className="qaid-backdrop",this.backdrop.style.zIndex=String(this.host.config.zIndex+2),this.backdrop.style.background=`rgba(0, 0, 0, ${this.host.config.backdropOpacity})`,this.backdrop.addEventListener("click",()=>this.close()),this.host.applyVars(this.backdrop),this.host.isMobile?this.showBottomSheet():this.showPositionedModal(),i.appendChild(this.backdrop),document.addEventListener("keydown",this.host.boundKeyDown)}close(){this.host.state==="MODAL_OPEN"&&!this.finalized&&(this.finalized=!0,this.host.whenFeedbackId().then(i=>{i&&fetch(`${this.host.config.endpoint}/${i}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:null})}).catch(e=>console.error("Failed to finalize feedback:",e))})),this.teardown(),this.host.resetFeedbackUi()}destroy(){this.teardown()}teardown(){this.host.closeDialogA11y(),this.modalContainer&&(this.modalContainer.remove(),this.modalContainer=null),this.backdrop&&(this.backdrop.remove(),this.backdrop=null),document.removeEventListener("keydown",this.host.boundKeyDown)}showBottomSheet(){const i=this.host.ensureOverlayHost(),e=document.createElement("div");e.className="qaid-bottom-sheet",e.style.zIndex=String(this.host.config.zIndex+3),e.appendChild(s("div",{class:"qaid-bottom-sheet-content"},s("div",{class:"qaid-bottom-sheet-handle"}),this.buildModalContent())),this.host.applyVars(e),i.appendChild(e),this.modalContainer=e,this.setupModalInteractions()}showPositionedModal(){const i=this.host.ensureOverlayHost(),{modal:e,arrow:t}=w(this.host.selectedBounds,window.innerWidth,window.innerHeight,{width:this.host.config.modalWidth,height:280,arrowHeight:12,gap:8,viewportPadding:16});this.modalContainer=document.createElement("div"),this.modalContainer.className=`qaid-modal-container qaid-${e.position}`,this.modalContainer.style.top=`${e.top}px`,this.modalContainer.style.left=`${e.left}px`,this.modalContainer.style.zIndex=String(this.host.config.zIndex+3);const o=document.createElement("div");o.className="qaid-modal-arrow",o.style.left=`${t.left}px`;const a=document.createElement("div");a.className="qaid-modal-box",a.appendChild(this.buildModalContent()),this.modalContainer.appendChild(o),this.modalContainer.appendChild(a),this.host.applyVars(this.modalContainer),i.appendChild(this.modalContainer),this.setupModalInteractions()}buildModalContent(){const{config:i,uid:e}=this.host,t=i.text,o=this.host.feedbackData.feedbackType,a=o==="up",r=i.buttonClass?`qaid-type-toggle qaid-type-toggle-custom ${i.buttonClass} ${a?"qaid-btn-up":"qaid-btn-down"}`:`qaid-type-toggle ${a?"qaid-type-up":"qaid-type-down"}`,d=a?"Feedback type: positive":"Feedback type: negative",l=o==="neutral"?s("span",{class:"qaid-type-static",attrs:{"aria-hidden":"true"}},c(i.feedbackIcon,b)):s("button",{class:r,attrs:{type:"button",title:"Click to switch","aria-pressed":String(a),"aria-label":d}},a?c(i.positiveIcon,m):c(i.negativeIcon,p)),h=document.createDocumentFragment();return h.append(s("div",{class:"qaid-modal-header"},l,s("div",{class:"qaid-modal-header-text"},s("h3",{class:"qaid-modal-title",text:t.modalTitle,attrs:{id:`qaid-modal-title-${e}`}}),s("p",{class:"qaid-modal-subtitle",text:t.modalSubtitle,attrs:{id:`qaid-modal-subtitle-${e}`}}))),s("textarea",{class:"qaid-textarea",attrs:{"aria-label":t.modalSubtitle,placeholder:t.placeholder}}),s("div",{class:"qaid-btn-row"},s("button",{class:"qaid-btn-submit",text:t.skipButton,attrs:{type:"button"}}))),h}setupModalInteractions(){this.host.openDialogA11y(this.modalContainer,{labelledbyId:`qaid-modal-title-${this.host.uid}`,describedbyId:`qaid-modal-subtitle-${this.host.uid}`});const i=this.modalContainer.querySelector(".qaid-textarea"),e=this.modalContainer.querySelector(".qaid-btn-submit");i&&(setTimeout(()=>i.focus(),100),i.addEventListener("input",()=>{e&&(e.textContent=i.value.trim()?this.host.config.text.submitButton:this.host.config.text.skipButton)})),e&&e.addEventListener("click",()=>{const o=i?.value.trim()||null;this.submitMessage(o)});const t=this.modalContainer.querySelector(".qaid-type-toggle");t&&t.addEventListener("click",()=>{const o=this.host.feedbackData.feedbackType==="up"?"down":"up";this.host.feedbackData.feedbackType=o,this.host.config.buttonClass?(t.classList.toggle("qaid-btn-up",o==="up"),t.classList.toggle("qaid-btn-down",o==="down")):(t.classList.toggle("qaid-type-up",o==="up"),t.classList.toggle("qaid-type-down",o==="down")),o==="up"?f(t,this.host.config.positiveIcon,m):f(t,this.host.config.negativeIcon,p);const a=o==="up"?"Feedback type: positive":"Feedback type: negative";t.setAttribute("aria-pressed",String(o==="up")),t.setAttribute("aria-label",a),this.host.announceMsg(a),this.host.whenFeedbackId().then(r=>{r&&fetch(`${this.host.config.endpoint}/${r}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({feedbackType:o})}).catch(d=>console.error("Failed to update feedback type:",d))})})}async submitMessage(i){let e=null;this.finalized=!0;const t=await this.host.whenFeedbackId();if(t)try{const o=await fetch(`${this.host.config.endpoint}/${t}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:i})});e=o.ok,o.ok||console.error("Failed to submit feedback message: HTTP",o.status)}catch(o){console.error("Failed to submit feedback message:",o),e=!1}if(e===!1){this.showResult(!1);return}if(e&&!this.host.config.hideConfirmation){this.showResult(!0);return}this.close()}showResult(i){const e=this.modalContainer?.querySelector(".qaid-modal-box")??this.modalContainer?.querySelector(".qaid-bottom-sheet-content")??this.modalContainer;if(!e){this.close();return}const t=this.host.config.text,o=i?t.confirmationTitle:t.errorTitle,a=i?t.confirmationMessage:t.errorMessage,r=s("h3",{class:"qaid-confirm-title",text:o,attrs:{id:`qaid-confirm-title-${this.host.uid}`,tabindex:"-1"}});e.textContent="",e.appendChild(s("div",{class:i?"qaid-confirm":"qaid-confirm qaid-confirm-error"},s("span",{class:"qaid-confirm-icon",attrs:{"aria-hidden":"true"}},c(null,i?g:q)),r,s("p",{class:"qaid-confirm-message",text:a}),s("button",{class:"qaid-btn-submit qaid-confirm-close",text:t.confirmationClose,attrs:{type:"button"},on:{click:()=>this.close()}}))),requestAnimationFrame(()=>r.focus()),this.host.announceMsg(`${o} ${a}`,!0)}}const M=C;export{z as ModalController,M as styles};
2
+ //# sourceMappingURL=modal-5G2DhiUE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"modal-5G2DhiUE.js","sources":["../../src/modal-positioning.ts","../../src/modal.ts"],"sourcesContent":["/**\n * Modal positioning utilities\n */\n\nimport type { SelectedBounds } from \"./types\";\n\nexport interface ModalPosition {\n top: number;\n left: number;\n position: \"above\" | \"below\";\n}\n\nexport interface ArrowPosition {\n left: number;\n}\n\nexport interface ModalDimensions {\n width: number;\n height: number;\n arrowHeight: number;\n gap: number;\n viewportPadding: number;\n}\n\nconst DEFAULT_DIMENSIONS: ModalDimensions = {\n width: 400,\n height: 280,\n arrowHeight: 12,\n gap: 8,\n viewportPadding: 16,\n};\n\n/**\n * Calculate whether modal should go above or below the target element\n */\nexport function calculateVerticalPosition(\n bounds: SelectedBounds,\n viewportHeight: number,\n totalHeight: number,\n gap: number,\n viewportPadding: number\n): { top: number; position: \"above\" | \"below\" } {\n const spaceAbove = bounds.y;\n const spaceBelow = viewportHeight - (bounds.y + bounds.height);\n\n // Prefer below if there's enough space\n if (spaceBelow >= totalHeight + gap) {\n return {\n top: bounds.y + bounds.height + gap,\n position: \"below\",\n };\n }\n\n // Try above if there's enough space\n if (spaceAbove >= totalHeight + gap) {\n return {\n top: bounds.y - totalHeight - gap,\n position: \"above\",\n };\n }\n\n // Neither fits perfectly - clamp to viewport\n const position = spaceBelow > spaceAbove ? \"below\" : \"above\";\n let top: number;\n\n if (position === \"below\") {\n top = Math.min(\n bounds.y + bounds.height + gap,\n viewportHeight - totalHeight - viewportPadding\n );\n } else {\n top = Math.max(viewportPadding, bounds.y - totalHeight - gap);\n }\n\n return { top, position };\n}\n\n/**\n * Calculate horizontal position of modal, clamped to viewport\n */\nexport function calculateHorizontalPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n modalWidth: number,\n viewportPadding: number\n): number {\n const centerX = bounds.x + bounds.width / 2;\n let left = centerX - modalWidth / 2;\n\n // Clamp to viewport\n left = Math.max(viewportPadding, Math.min(left, viewportWidth - modalWidth - viewportPadding));\n\n return left;\n}\n\n/**\n * Calculate arrow position relative to modal\n * Points at the click position, not the element center\n */\nexport function calculateArrowPosition(\n bounds: SelectedBounds,\n modalLeft: number,\n modalWidth: number,\n minOffset = 24,\n arrowWidth = 24\n): number {\n // Use click position for arrow, not element center\n const targetX = bounds.clickX;\n // Subtract half the arrow width to center it on the target\n const arrowLeft = targetX - modalLeft - arrowWidth / 2;\n\n // Clamp arrow to stay within modal bounds\n return Math.max(minOffset, Math.min(arrowLeft, modalWidth - minOffset - arrowWidth / 2));\n}\n\n/**\n * Calculate complete modal position based on selected element bounds\n */\nexport function calculateModalPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n viewportHeight: number,\n dimensions: ModalDimensions = DEFAULT_DIMENSIONS\n): ModalPosition {\n const totalHeight = dimensions.height + dimensions.arrowHeight;\n\n const vertical = calculateVerticalPosition(\n bounds,\n viewportHeight,\n totalHeight,\n dimensions.gap,\n dimensions.viewportPadding\n );\n\n const left = calculateHorizontalPosition(\n bounds,\n viewportWidth,\n dimensions.width,\n dimensions.viewportPadding\n );\n\n return {\n top: vertical.top,\n left,\n position: vertical.position,\n };\n}\n\n/**\n * Calculate both modal and arrow positions\n */\nexport function calculateModalAndArrowPosition(\n bounds: SelectedBounds,\n viewportWidth: number,\n viewportHeight: number,\n dimensions: ModalDimensions = DEFAULT_DIMENSIONS\n): { modal: ModalPosition; arrow: ArrowPosition } {\n const modal = calculateModalPosition(bounds, viewportWidth, viewportHeight, dimensions);\n\n const arrowLeft = calculateArrowPosition(\n bounds,\n modal.left,\n dimensions.width\n );\n\n return {\n modal,\n arrow: { left: arrowLeft },\n };\n}\n","/**\n * Feedback message modal — extracted from embed.ts into its own lazily-loaded\n * chunk. It's fetched the first time a message modal opens (after feedback is\n * submitted), and pre-warmed while the user is targeting an element.\n *\n * The controller owns the modal/backdrop DOM and the message PATCH flow, and\n * talks back to the embed through the narrow `ModalHost` interface.\n */\n\nimport { calculateModalAndArrowPosition } from \"./modal-positioning\";\nimport { h } from \"./dom\";\nimport { iconNode, setIcon } from \"./svg-sanitize\";\nimport featureStyles from \"./styles-modal.css?inline\";\nimport {\n THUMBS_UP_ICON,\n THUMBS_DOWN_ICON,\n FEEDBACK_ICON,\n DONE_ICON,\n ERROR_ICON,\n} from \"./icons\";\nimport type {\n ResolvedFeedbackConfig,\n EmbedState,\n FeedbackData,\n SelectedBounds,\n} from \"./types\";\n\n/** The slice of the embed the modal needs. */\nexport interface ModalHost {\n readonly config: ResolvedFeedbackConfig;\n readonly uid: string;\n readonly isMobile: boolean;\n readonly state: EmbedState;\n readonly boundKeyDown: (e: KeyboardEvent) => void;\n /** Live references — the toggle mutates feedbackType; positioning reads bounds. */\n readonly feedbackData: FeedbackData;\n readonly selectedBounds: SelectedBounds;\n /**\n * The id of this feedback's record. The modal opens while the POST that\n * creates it is still in flight, so every PATCH waits on this; null when\n * the POST failed.\n */\n whenFeedbackId(): Promise<number | null>;\n ensureOverlayHost(): ShadowRoot;\n applyVars(el: HTMLElement): void;\n announceMsg(message: string, assertive?: boolean): void;\n openDialogA11y(\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string; label?: string }\n ): void;\n closeDialogA11y(): void;\n resetFeedbackUi(): void;\n}\n\nexport class ModalController {\n private modalContainer: HTMLDivElement | null = null;\n private backdrop: HTMLDivElement | null = null;\n /** Set once the message is sent, so closing does not PATCH over it. */\n private finalized = false;\n\n constructor(private host: ModalHost) {}\n\n open(): void {\n this.finalized = false;\n const root = this.host.ensureOverlayHost();\n\n // Create backdrop\n this.backdrop = document.createElement(\"div\");\n this.backdrop.className = \"qaid-backdrop\";\n this.backdrop.style.zIndex = String(this.host.config.zIndex + 2);\n this.backdrop.style.background = `rgba(0, 0, 0, ${this.host.config.backdropOpacity})`;\n this.backdrop.addEventListener(\"click\", () => this.close());\n this.host.applyVars(this.backdrop);\n\n if (this.host.isMobile) {\n this.showBottomSheet();\n } else {\n this.showPositionedModal();\n }\n\n root.appendChild(this.backdrop);\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n /** Escape / external close. Runs the finalize-PATCH + teardown. */\n close(): void {\n // If the modal is open and we're closing without submitting, still finalize.\n // Taken before the reset below, which starts the next feedback afresh.\n if (this.host.state === \"MODAL_OPEN\" && !this.finalized) {\n this.finalized = true;\n void this.host.whenFeedbackId().then((id) => {\n if (!id) return;\n fetch(`${this.host.config.endpoint}/${id}`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ message: null }),\n }).catch((err) => console.error(\"Failed to finalize feedback:\", err));\n });\n }\n\n this.teardown();\n this.host.resetFeedbackUi();\n }\n\n /** DOM/listener teardown only — no PATCH, no state reset (for embed destroy). */\n destroy(): void {\n this.teardown();\n }\n\n private teardown(): void {\n this.host.closeDialogA11y();\n if (this.modalContainer) {\n this.modalContainer.remove();\n this.modalContainer = null;\n }\n if (this.backdrop) {\n this.backdrop.remove();\n this.backdrop = null;\n }\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n private showBottomSheet(): void {\n const root = this.host.ensureOverlayHost();\n\n const sheet = document.createElement(\"div\");\n sheet.className = \"qaid-bottom-sheet\";\n sheet.style.zIndex = String(this.host.config.zIndex + 3);\n\n sheet.appendChild(\n h(\n \"div\",\n { class: \"qaid-bottom-sheet-content\" },\n h(\"div\", { class: \"qaid-bottom-sheet-handle\" }),\n this.buildModalContent()\n )\n );\n\n this.host.applyVars(sheet);\n root.appendChild(sheet);\n this.modalContainer = sheet;\n\n this.setupModalInteractions();\n }\n\n private showPositionedModal(): void {\n const root = this.host.ensureOverlayHost();\n\n const { modal, arrow } = calculateModalAndArrowPosition(\n this.host.selectedBounds,\n window.innerWidth,\n window.innerHeight,\n {\n width: this.host.config.modalWidth,\n height: 280,\n arrowHeight: 12,\n gap: 8,\n viewportPadding: 16,\n }\n );\n\n this.modalContainer = document.createElement(\"div\");\n this.modalContainer.className = `qaid-modal-container qaid-${modal.position}`;\n this.modalContainer.style.top = `${modal.top}px`;\n this.modalContainer.style.left = `${modal.left}px`;\n this.modalContainer.style.zIndex = String(this.host.config.zIndex + 3);\n\n const arrowEl = document.createElement(\"div\");\n arrowEl.className = \"qaid-modal-arrow\";\n arrowEl.style.left = `${arrow.left}px`;\n\n const box = document.createElement(\"div\");\n box.className = \"qaid-modal-box\";\n box.appendChild(this.buildModalContent());\n\n this.modalContainer.appendChild(arrowEl);\n this.modalContainer.appendChild(box);\n this.host.applyVars(this.modalContainer);\n root.appendChild(this.modalContainer);\n\n this.setupModalInteractions();\n }\n\n /**\n * The modal's contents, built as nodes rather than an HTML string.\n *\n * Every piece of copy (title, subtitle, placeholder, button) goes in as\n * text, so a `<`, `&` or `\"` in a translation shows as written instead of\n * being parsed as markup or cutting an attribute short. Only the icons are\n * markup, because they are documented as SVG/HTML strings.\n */\n private buildModalContent(): DocumentFragment {\n const { config, uid } = this.host;\n const text = config.text;\n const type = this.host.feedbackData.feedbackType;\n const isUp = type === \"up\";\n const toggleClass = config.buttonClass\n ? `qaid-type-toggle qaid-type-toggle-custom ${config.buttonClass} ${isUp ? \"qaid-btn-up\" : \"qaid-btn-down\"}`\n : `qaid-type-toggle ${isUp ? \"qaid-type-up\" : \"qaid-type-down\"}`;\n const toggleLabel = isUp ? \"Feedback type: positive\" : \"Feedback type: negative\";\n // Neutral (single-button) feedback has no sentiment to toggle — show a\n // static feedback icon in place of the up/down toggle.\n const header =\n type === \"neutral\"\n ? h(\n \"span\",\n { class: \"qaid-type-static\", attrs: { \"aria-hidden\": \"true\" } },\n iconNode(config.feedbackIcon, FEEDBACK_ICON)\n )\n : h(\n \"button\",\n {\n class: toggleClass,\n attrs: {\n type: \"button\",\n title: \"Click to switch\",\n \"aria-pressed\": String(isUp),\n \"aria-label\": toggleLabel,\n },\n },\n isUp\n ? iconNode(config.positiveIcon, THUMBS_UP_ICON)\n : iconNode(config.negativeIcon, THUMBS_DOWN_ICON)\n );\n\n const fragment = document.createDocumentFragment();\n fragment.append(\n h(\n \"div\",\n { class: \"qaid-modal-header\" },\n header,\n h(\n \"div\",\n { class: \"qaid-modal-header-text\" },\n h(\"h3\", {\n class: \"qaid-modal-title\",\n text: text.modalTitle,\n attrs: { id: `qaid-modal-title-${uid}` },\n }),\n h(\"p\", {\n class: \"qaid-modal-subtitle\",\n text: text.modalSubtitle,\n attrs: { id: `qaid-modal-subtitle-${uid}` },\n })\n )\n ),\n h(\"textarea\", {\n class: \"qaid-textarea\",\n attrs: { \"aria-label\": text.modalSubtitle, placeholder: text.placeholder },\n }),\n h(\n \"div\",\n { class: \"qaid-btn-row\" },\n h(\"button\", {\n class: \"qaid-btn-submit\",\n text: text.skipButton,\n attrs: { type: \"button\" },\n })\n )\n );\n return fragment;\n }\n\n private setupModalInteractions(): void {\n // Dialog semantics + focus trap + background inert\n this.host.openDialogA11y(this.modalContainer!, {\n labelledbyId: `qaid-modal-title-${this.host.uid}`,\n describedbyId: `qaid-modal-subtitle-${this.host.uid}`,\n });\n\n const textarea =\n this.modalContainer!.querySelector<HTMLTextAreaElement>(\".qaid-textarea\");\n const submitBtn =\n this.modalContainer!.querySelector<HTMLButtonElement>(\".qaid-btn-submit\");\n if (textarea) {\n // Auto-focus\n setTimeout(() => textarea.focus(), 100);\n\n // Update button text based on content\n textarea.addEventListener(\"input\", () => {\n if (submitBtn) {\n submitBtn.textContent = textarea.value.trim()\n ? this.host.config.text.submitButton\n : this.host.config.text.skipButton;\n }\n });\n }\n\n if (submitBtn) {\n submitBtn.addEventListener(\"click\", () => {\n const message = textarea?.value.trim() || null;\n this.submitMessage(message);\n });\n }\n\n // Handle feedback type toggle\n const typeToggle = this.modalContainer!.querySelector<HTMLButtonElement>(\".qaid-type-toggle\");\n if (typeToggle) {\n typeToggle.addEventListener(\"click\", () => {\n const newType = this.host.feedbackData.feedbackType === \"up\" ? \"down\" : \"up\";\n this.host.feedbackData.feedbackType = newType;\n\n // Update UI — use different classes depending on custom buttonClass\n if (this.host.config.buttonClass) {\n typeToggle.classList.toggle(\"qaid-btn-up\", newType === \"up\");\n typeToggle.classList.toggle(\"qaid-btn-down\", newType === \"down\");\n } else {\n typeToggle.classList.toggle(\"qaid-type-up\", newType === \"up\");\n typeToggle.classList.toggle(\"qaid-type-down\", newType === \"down\");\n }\n if (newType === \"up\") setIcon(typeToggle, this.host.config.positiveIcon, THUMBS_UP_ICON);\n else setIcon(typeToggle, this.host.config.negativeIcon, THUMBS_DOWN_ICON);\n\n // Update accessible state and announce the change\n const toggleLabel = newType === \"up\" ? \"Feedback type: positive\" : \"Feedback type: negative\";\n typeToggle.setAttribute(\"aria-pressed\", String(newType === \"up\"));\n typeToggle.setAttribute(\"aria-label\", toggleLabel);\n this.host.announceMsg(toggleLabel);\n\n // Update feedback on server, once the record exists\n void this.host.whenFeedbackId().then((id) => {\n if (!id) return;\n fetch(`${this.host.config.endpoint}/${id}`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ feedbackType: newType }),\n }).catch((err) => console.error(\"Failed to update feedback type:\", err));\n });\n });\n }\n }\n\n private async submitMessage(message: string | null): Promise<void> {\n // null = nothing was attempted (the initial POST never produced an id);\n // otherwise whether the server accepted the PATCH.\n let delivered: boolean | null = null;\n\n // Before the await: an Escape while the POST is still out must not send\n // a second, empty PATCH over this message.\n this.finalized = true;\n const id = await this.host.whenFeedbackId();\n if (id) {\n try {\n const response = await fetch(`${this.host.config.endpoint}/${id}`, {\n method: \"PATCH\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ message }),\n });\n // fetch resolves on any HTTP reply. A 4xx/5xx means the server\n // refused or lost the message, so it is not a success.\n delivered = response.ok;\n if (!response.ok) {\n console.error(\"Failed to submit feedback message: HTTP\", response.status);\n }\n } catch (error) {\n console.error(\"Failed to submit feedback message:\", error);\n delivered = false;\n }\n }\n\n // The message was lost. Closing quietly reads as success, so say so —\n // even with hideConfirmation, which only opts out of the success screen.\n if (delivered === false) {\n this.showResult(false);\n return;\n }\n\n // A submit that simply removes the modal reads as a failure — nothing\n // acknowledges that the message was sent. Show a success screen unless the\n // host opted out.\n //\n // With no feedbackId the initial POST never landed and there was nothing\n // to send the message to; that path closes exactly as it did before.\n if (delivered && !this.host.config.hideConfirmation) {\n this.showResult(true);\n return;\n }\n this.close();\n }\n\n /**\n * Replace the modal's contents with the outcome: a checkmark and a short\n * acknowledgement, or an error mark and a \"not sent\" notice.\n *\n * The submit button that had focus is gone by this point, so focus moves to\n * the heading (WCAG 2.4.3) and the message is announced. Mirrors the quests\n * embed's thank-you screen so the two products confirm the same way. Copy\n * goes in as text, never markup.\n */\n private showResult(delivered: boolean): void {\n const box = this.modalContainer?.querySelector(\".qaid-modal-box\")\n ?? this.modalContainer?.querySelector(\".qaid-bottom-sheet-content\")\n ?? this.modalContainer;\n\n if (!box) {\n // Nothing to draw into — never strand the user with an open modal.\n this.close();\n return;\n }\n\n const text = this.host.config.text;\n const heading = delivered ? text.confirmationTitle : text.errorTitle;\n const body = delivered ? text.confirmationMessage : text.errorMessage;\n\n const title = h(\"h3\", {\n class: \"qaid-confirm-title\",\n text: heading,\n attrs: { id: `qaid-confirm-title-${this.host.uid}`, tabindex: \"-1\" },\n });\n\n box.textContent = \"\";\n box.appendChild(\n h(\n \"div\",\n { class: delivered ? \"qaid-confirm\" : \"qaid-confirm qaid-confirm-error\" },\n h(\n \"span\",\n { class: \"qaid-confirm-icon\", attrs: { \"aria-hidden\": \"true\" } },\n iconNode(null, delivered ? DONE_ICON : ERROR_ICON)\n ),\n title,\n h(\"p\", { class: \"qaid-confirm-message\", text: body }),\n h(\"button\", {\n class: \"qaid-btn-submit qaid-confirm-close\",\n text: text.confirmationClose,\n attrs: { type: \"button\" },\n on: { click: () => this.close() },\n })\n )\n );\n\n // Focus after paint, matching the quests embed.\n requestAnimationFrame(() => title.focus());\n this.host.announceMsg(`${heading} ${body}`, true);\n }\n}\n\n/** This feature's shadow-DOM styles; the embed adds them when it loads the chunk. */\nexport const styles = featureStyles;\n"],"names":["DEFAULT_DIMENSIONS","calculateVerticalPosition","bounds","viewportHeight","totalHeight","gap","viewportPadding","spaceAbove","spaceBelow","position","top","calculateHorizontalPosition","viewportWidth","modalWidth","left","calculateArrowPosition","modalLeft","minOffset","arrowWidth","arrowLeft","calculateModalPosition","dimensions","vertical","calculateModalAndArrowPosition","modal","ModalController","host","root","id","err","sheet","h","arrow","arrowEl","box","config","uid","text","type","isUp","toggleClass","toggleLabel","header","iconNode","FEEDBACK_ICON","THUMBS_UP_ICON","THUMBS_DOWN_ICON","fragment","textarea","submitBtn","message","typeToggle","newType","setIcon","delivered","response","error","heading","body","title","DONE_ICON","ERROR_ICON","styles","featureStyles"],"mappings":"uHAwBA,MAAMA,EAAsC,CAC1C,MAAO,IACP,OAAQ,IACR,YAAa,GACb,IAAK,EACL,gBAAiB,EACnB,EAKO,SAASC,EACdC,EACAC,EACAC,EACAC,EACAC,EAC8C,CAC9C,MAAMC,EAAaL,EAAO,EACpBM,EAAaL,GAAkBD,EAAO,EAAIA,EAAO,QAGvD,GAAIM,GAAcJ,EAAcC,EAC9B,MAAO,CACL,IAAKH,EAAO,EAAIA,EAAO,OAASG,EAChC,SAAU,OAAA,EAKd,GAAIE,GAAcH,EAAcC,EAC9B,MAAO,CACL,IAAKH,EAAO,EAAIE,EAAcC,EAC9B,SAAU,OAAA,EAKd,MAAMI,EAAWD,EAAaD,EAAa,QAAU,QACrD,IAAIG,EAEJ,OAAID,IAAa,QACfC,EAAM,KAAK,IACTR,EAAO,EAAIA,EAAO,OAASG,EAC3BF,EAAiBC,EAAcE,CAAA,EAGjCI,EAAM,KAAK,IAAIJ,EAAiBJ,EAAO,EAAIE,EAAcC,CAAG,EAGvD,CAAE,IAAAK,EAAK,SAAAD,CAAA,CAChB,CAKO,SAASE,EACdT,EACAU,EACAC,EACAP,EACQ,CAER,IAAIQ,EADYZ,EAAO,EAAIA,EAAO,MAAQ,EACrBW,EAAa,EAGlC,OAAAC,EAAO,KAAK,IAAIR,EAAiB,KAAK,IAAIQ,EAAMF,EAAgBC,EAAaP,CAAe,CAAC,EAEtFQ,CACT,CAMO,SAASC,EACdb,EACAc,EACAH,EACAI,EAAY,GACZC,EAAa,GACL,CAIR,MAAMC,EAFUjB,EAAO,OAEKc,EAAYE,EAAa,EAGrD,OAAO,KAAK,IAAID,EAAW,KAAK,IAAIE,EAAWN,EAAaI,EAAYC,EAAa,CAAC,CAAC,CACzF,CAKO,SAASE,EACdlB,EACAU,EACAT,EACAkB,EAA8BrB,EACf,CACf,MAAMI,EAAciB,EAAW,OAASA,EAAW,YAE7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ACrB,MACF,CAQA,GAAIA,GAAa,CAAC,KAAK,KAAK,OAAO,iBAAkB,CACnD,KAAK,WAAW,EAAI,EACpB,MACF,CACA,KAAK,MAAA,CACP,CAWQ,WAAWA,EAA0B,CAC3C,MAAMpB,EAAM,KAAK,gBAAgB,cAAc,iBAAiB,GAC3D,KAAK,gBAAgB,cAAc,4BAA4B,GAC/D,KAAK,eAEV,GAAI,CAACA,EAAK,CAER,KAAK,MAAA,EACL,MACF,CAEA,MAAMG,EAAO,KAAK,KAAK,OAAO,KACxBoB,EAAUH,EAAYjB,EAAK,kBAAoBA,EAAK,WACpDqB,EAAOJ,EAAYjB,EAAK,oBAAsBA,EAAK,aAEnDsB,EAAQ5B,EAAE,KAAM,CACpB,MAAO,qBACP,KAAM0B,EACN,MAAO,CAAE,GAAI,sBAAsB,KAAK,KAAK,GAAG,GAAI,SAAU,IAAA,CAAK,CACpE,EAEDvB,EAAI,YAAc,GAClBA,EAAI,YACFH,EACE,MACA,CAAE,MAAOuB,EAAY,eAAiB,iCAAA,EACtCvB,EACE,OACA,CAAE,MAAO,oBAAqB,MAAO,CAAE,cAAe,OAAO,EAC7DY,EAAS,KAAMW,EAAYM,EAAYC,CAAU,CAAA,EAEnDF,EACA5B,EAAE,IAAK,CAAE,MAAO,uBAAwB,KAAM2B,EAAM,EACpD3B,EAAE,SAAU,CACV,MAAO,qCACP,KAAMM,EAAK,kBACX,MAAO,CAAE,KAAM,QAAA,EACf,GAAI,CAAE,MAAO,IAAM,KAAK,OAAM,CAAE,CACjC,CAAA,CACH,EAIF,sBAAsB,IAAMsB,EAAM,OAAO,EACzC,KAAK,KAAK,YAAY,GAAGF,CAAO,IAAIC,CAAI,GAAI,EAAI,CAClD,CACF,CAGO,MAAMI,EAASC"}
@@ -1,2 +1,2 @@
1
- import{h as n}from"./dom-scpOS8nl.js";import{i as g}from"./core-BsR7oV99.js";const v=".qaid-recording-indicator{position:fixed;pointer-events:auto;top:12px;left:50%;transform:translate(-50%);display:flex;align-items:center;gap:.5rem;padding:.5rem 1rem;background:light-dark(#1f2937,#374151);color:#fff;border-radius:9999px;font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;box-shadow:0 4px 12px #0000004d;z-index:99999;animation:qaid-slideDown .2s ease-out}.qaid-recording-dot{width:10px;height:10px;background:#dc2626;border-radius:50%;animation:qaid-dotPulse 1.5s ease-in-out infinite}@keyframes qaid-dotPulse{0%,to{opacity:1}50%{opacity:.3}}.qaid-recording-time{font-variant-numeric:tabular-nums;min-width:2.5rem;text-align:center}button.qaid-recording-stop{padding:.25rem .75rem;background:#dc2626;color:#fff;border:none;border-radius:9999px;font-size:calc(var(--qaid-font-size, 16px) * .75);font-weight:600;cursor:pointer;transition:background-color .2s;-webkit-appearance:none;appearance:none}button.qaid-recording-stop:hover{background:#b91c1c}.qaid-video-preview{position:fixed;inset:0 0 auto;height:100vh;height:100dvh;display:flex;align-items:center;justify-content:center;padding:16px;padding-top:max(16px,env(safe-area-inset-top));padding-bottom:max(16px,env(safe-area-inset-bottom));box-sizing:border-box;background:#0009;z-index:99998;animation:qaid-fadeIn .2s ease-out}@keyframes qaid-fadeIn{0%{opacity:0}to{opacity:1}}.qaid-video-preview-box{color-scheme:inherit;background:light-dark(#ffffff,#1f2937);border-radius:1rem;padding:1.5rem;box-shadow:0 25px 50px -12px #00000080;width:560px;max-width:100%;max-height:100%;overflow-y:auto;font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:var(--qaid-font-size, 16px)}.qaid-video-preview-box h3{font-size:calc(var(--qaid-font-size, 16px) * 1.125);font-weight:700;margin:0 0 1rem;color:light-dark(#1f2937,#f9fafb)}.qaid-video-preview-box video{width:100%;max-height:50vh;max-height:50dvh;object-fit:contain;border-radius:.5rem;background:#000;margin-bottom:1rem}.qaid-video-preview-box textarea{width:100%;height:4rem;padding:.75rem;border:1px solid light-dark(#d1d5db,#374151);border-radius:.5rem;font-family:inherit;font-size:calc(var(--qaid-font-size, 16px) * .875);resize:vertical;margin-bottom:1rem;box-sizing:border-box;background:light-dark(#ffffff,#111827);color:light-dark(#1f2937,#f9fafb)}.qaid-video-preview-box textarea:focus{outline:none;border-color:var(--qaid-marker);box-shadow:0 0 0 3px color-mix(in srgb,var(--qaid-marker) 20%,transparent)}.qaid-video-error{margin:0 0 .75rem;font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;color:light-dark(#b91c1c,#fca5a5)}.qaid-video-preview-actions{display:flex;gap:.5rem;justify-content:flex-end}button.qaid-video-btn{padding:.5rem 1rem;border:none;border-radius:.5rem;font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;cursor:pointer;transition:background-color .2s,filter .2s;-webkit-appearance:none;appearance:none}button.qaid-video-btn-cancel{background:light-dark(#f3f4f6,#374151);color:light-dark(#374151,#d1d5db)}button.qaid-video-btn-cancel:hover{background:light-dark(#e5e7eb,#4b5563)}button.qaid-video-btn-rerecord{background:light-dark(#fef3c7,#78350f);color:light-dark(#92400e,#fde68a)}button.qaid-video-btn-rerecord:hover{filter:brightness(.9)}button.qaid-video-btn-send{background:var(--qaid-marker);color:var(--qaid-marker-text, white)}button.qaid-video-btn-send:hover{filter:brightness(.85)}button.qaid-video-btn-send:disabled{opacity:.5;cursor:not-allowed}.qaid-video-sending{display:flex;align-items:center;gap:.5rem;font-size:calc(var(--qaid-font-size, 16px) * .875);color:light-dark(#6b7280,#9ca3af)}@keyframes qaid-slideDown{0%{transform:translateY(-100%)}to{transform:translateY(0)}}button.qaid-recording-stop{min-height:24px}.qaid-video-preview-box textarea:focus-visible{outline:2px solid var(--qaid-marker, #6365f1);outline-offset:2px}@media(forced-colors:active){.qaid-video-preview-box textarea:focus{outline:2px solid CanvasText;outline-offset:2px}}",b=20,u=4096;function l(d){const e=typeof d=="string"?d:JSON.stringify(d);return e.length>u?e.slice(0,u)+"\u2026[truncated]":e}function p(d,e){d.length>=b&&d.shift(),d.push(e)}async function m(d){try{const e=await d.clone().text();return l(e)}catch{return}}function x(){const d=[],e=window.fetch;window.fetch=async function(o,r){const s=typeof o=="string"?o:o instanceof URL?o.toString():o.url,a=r?.method??(typeof o=="object"&&"method"in o?o.method:"GET");let c;r?.body&&(c=l(r.body));const h=await e.apply(window,[o,r]);if(h.status>=400){const f=await m(h);p(d,{url:s,method:a.toUpperCase(),status:h.status,statusText:h.statusText,requestBody:c,responseBody:f,timestamp:Date.now()})}return h};const i=XMLHttpRequest.prototype.open,t=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(o,r,...s){return this._qaid_method=o,this._qaid_url=typeof r=="string"?r:r.toString(),i.apply(this,[o,r,...s])},XMLHttpRequest.prototype.send=function(o){const r=this,s=o?l(o):void 0;return r.addEventListener("load",function(){r.status>=400&&p(d,{url:r._qaid_url,method:r._qaid_method.toUpperCase(),status:r.status,statusText:r.statusText,requestBody:s,responseBody:l(r.responseText),timestamp:Date.now()})}),t.apply(this,[o])},{errors:d,restore:()=>{window.fetch=e,XMLHttpRequest.prototype.open=i,XMLHttpRequest.prototype.send=t}}}class w{constructor(e){this.host=e}host;videoRecorder=null;networkCapture=null;recordedBlob=null;recordingIndicator=null;videoPreview=null;isRecording=!1;isSendingVideo=!1;redactPicks=[];redactPickerRoot=null;redactRafId=0;boundRedactClick=e=>this.handleRedactPickClick(e);handleEscape(){return this.isRecording?(this.stopRecording(),!0):this.videoPreview?(this.cancelRecordingPreview(),!0):this.redactPickerRoot?(this.finishRedactionPicking(!1),!0):!1}destroy(){this.redactRafId&&cancelAnimationFrame(this.redactRafId),this.redactRafId=0,document.removeEventListener("click",this.boundRedactClick,!0),this.redactPickerRoot&&(this.redactPickerRoot.remove(),this.redactPickerRoot=null),this.redactPicks=[],this.cleanupRecording(),this.removeVideoPreview()}async startRecording(e=[]){if(!(this.isRecording||this.host.state!=="IDLE"))try{this.networkCapture=x();const{createVideoRecorder:i}=await import("./video-BSP4s2te.js");this.videoRecorder=i({maxDuration:this.host.config.videoOptions.maxDuration,redactionElements:e}),this.videoRecorder.onTick(t=>{this.updateRecordingTimer(t)}),this.videoRecorder.onStop(t=>{this.isRecording&&(this.recordedBlob=t,this.isRecording=!1,this.host.announceMsg("Recording stopped"),this.removeRecordingIndicator(),document.removeEventListener("keydown",this.host.boundKeyDown),this.host.setButtonsDisabled(!1),t&&t.size>0?this.showRecordingPreview():this.cleanupRecording())}),await this.videoRecorder.start(),this.isRecording=!0,this.host.announceMsg("Recording started"),this.host.setButtonsDisabled(!0),this.showRecordingIndicator(),document.addEventListener("keydown",this.host.boundKeyDown)}catch(i){i instanceof Error&&/current tab|cannot blur/i.test(i.message)&&this.host.announceMsg(i.message),this.cleanupRecording()}}async stopRecording(){try{this.recordedBlob=await this.videoRecorder.stop()}catch{this.recordedBlob=null}this.isRecording=!1,this.host.announceMsg("Recording stopped"),this.removeRecordingIndicator(),document.removeEventListener("keydown",this.host.boundKeyDown),this.recordedBlob&&this.recordedBlob.size>0?this.showRecordingPreview():this.cleanupRecording()}startPicking(){if(this.isRecording||this.host.state!=="IDLE")return;this.host.setState("REDACT_PICKING"),this.redactPicks=[];const e=this.host.ensureOverlayHost(),i=n("div",{style:"position:absolute;inset:0;"}),t=n("div",{class:"qaid-redact-picker",style:"position:fixed;inset:0;pointer-events:none;"},i,n("div",{style:"position:fixed;left:50%;bottom:24px;transform:translateX(-50%);display:flex;gap:12px;align-items:center;pointer-events:auto;background:#0b1220;color:#fff;border:1px solid #ff6b6b;border-radius:9999px;padding:10px 16px;font:600 13px system-ui,sans-serif;box-shadow:0 8px 30px rgba(0,0,0,.5);"},n("span",{text:"Click sensitive areas to blur",attrs:{"data-qaid-redact-label":""}}),n("button",{text:"Start recording",attrs:{type:"button"},style:"cursor:pointer;border:0;border-radius:9999px;padding:8px 14px;background:#ff6b6b;color:#0b1220;font:inherit;",on:{click:()=>this.finishRedactionPicking(!0)}}),n("button",{text:"Cancel",attrs:{type:"button"},style:"cursor:pointer;border:0;background:transparent;color:#9fb3c8;font:inherit;",on:{click:()=>this.finishRedactionPicking(!1)}})));e.appendChild(t),this.redactPickerRoot=t;const o=()=>{this.renderRedactPicks(i),this.redactRafId=requestAnimationFrame(o)};o(),document.addEventListener("click",this.boundRedactClick,!0),document.addEventListener("keydown",this.host.boundKeyDown),this.host.announceMsg("Click sensitive areas to blur, then start recording")}handleRedactPickClick(e){const i=e.target instanceof Element?e.target:null;if(!i||g(i)||this.redactPickerRoot?.contains(i))return;e.preventDefault(),e.stopPropagation();const t=this.redactPicks.indexOf(i);t>=0?this.redactPicks.splice(t,1):this.redactPicks.push(i);const o=this.redactPickerRoot?.querySelector("[data-qaid-redact-label]");if(o){const r=this.redactPicks.length;o.textContent=r===0?"Click sensitive areas to blur":`${r} area${r===1?"":"s"} will be blurred`}}renderRedactPicks(e){e.textContent="";for(const i of this.redactPicks){const t=i.getBoundingClientRect();t.width<=0||t.height<=0||e.appendChild(n("div",{style:`position:fixed;left:${t.left}px;top:${t.top}px;width:${t.width}px;height:${t.height}px;border:2px solid #ff6b6b;border-radius:4px;background:rgba(255,107,107,.18);pointer-events:none;`}))}}finishRedactionPicking(e){this.redactRafId&&cancelAnimationFrame(this.redactRafId),this.redactRafId=0,document.removeEventListener("click",this.boundRedactClick,!0),document.removeEventListener("keydown",this.host.boundKeyDown),this.redactPickerRoot&&(this.redactPickerRoot.remove(),this.redactPickerRoot=null);const i=this.redactPicks;this.redactPicks=[],this.host.setState("IDLE"),e&&this.startRecording(i)}showRecordingIndicator(){const e=this.host.ensureOverlayHost();this.recordingIndicator=n("div",{class:"qaid-recording-indicator",style:`z-index:${this.host.config.zIndex+100}`},n("div",{class:"qaid-recording-dot"}),n("span",{class:"qaid-recording-time",text:this.formatTime(this.host.config.videoOptions.maxDuration)}),n("button",{class:"qaid-recording-stop",text:"Stop",attrs:{type:"button"},on:{click:()=>this.stopRecording()}})),this.host.applyVars(this.recordingIndicator),e.appendChild(this.recordingIndicator)}updateRecordingTimer(e){if(!this.recordingIndicator)return;const i=this.recordingIndicator.querySelector(".qaid-recording-time");if(i){const t=Math.max(0,this.host.config.videoOptions.maxDuration-e);i.textContent=this.formatTime(t),t>0&&t<=5&&this.host.announceMsg(`${t} second${t===1?"":"s"} remaining`)}}formatTime(e){const i=Math.floor(e/60),t=e%60;return`${i}:${t.toString().padStart(2,"0")}`}removeRecordingIndicator(){this.recordingIndicator&&(this.recordingIndicator.remove(),this.recordingIndicator=null)}showRecordingPreview(){const e=this.host.ensureOverlayHost(),i=URL.createObjectURL(this.recordedBlob),t=`qaid-video-title-${this.host.uid}`,o=n("h3",{text:"Review your recording",attrs:{id:t}}),r=n("video");r.src=i,r.controls=!0,r.autoplay=!0,r.muted=!0;const s=n("textarea",{attrs:{placeholder:"Optional: Describe the issue you recorded...","aria-label":"Describe the issue you recorded"}}),a=n("button",{class:"qaid-video-btn qaid-video-btn-send",text:"Send",attrs:{type:"button"},on:{click:()=>this.submitVideoFeedback(s.value.trim()||null,a)}}),c=n("div",{class:"qaid-video-preview-box"},o,r,s,n("div",{class:"qaid-video-preview-actions"},n("button",{class:"qaid-video-btn qaid-video-btn-cancel",text:"Cancel",attrs:{type:"button"},on:{click:()=>this.cancelRecordingPreview()}}),n("button",{class:"qaid-video-btn qaid-video-btn-rerecord",text:"Re-record",attrs:{type:"button"},on:{click:()=>{this.cancelRecordingPreview(),this.startRecording()}}}),a));this.videoPreview=n("div",{class:"qaid-video-preview",style:`z-index:${this.host.config.zIndex+100}`},c),this.host.applyVars(this.videoPreview),this.host.overlayShadowHost&&(this.host.overlayShadowHost.style.pointerEvents="auto"),e.appendChild(this.videoPreview),this.host.openDialogA11y(c,{labelledbyId:o.id}),document.addEventListener("keydown",this.host.boundKeyDown)}cancelRecordingPreview(){this.removeVideoPreview(),this.cleanupRecording()}removeVideoPreview(){if(this.host.closeDialogA11y(),this.videoPreview){const e=this.videoPreview.querySelector("video");e?.src&&URL.revokeObjectURL(e.src),this.videoPreview.remove(),this.videoPreview=null}document.removeEventListener("keydown",this.host.boundKeyDown)}async submitVideoFeedback(e,i){if(!this.recordedBlob||this.isSendingVideo)return;this.isSendingVideo=!0,i.disabled=!0,i.textContent="Sending...";const t=new FormData;t.append("video",this.recordedBlob,`recording.${this.recordedBlob.type.includes("mp4")?"mp4":"webm"}`),t.append("pageUrl",window.location.href),t.append("visitorId",this.host.visitorId),this.host.config.apiKey&&t.append("apiKey",this.host.config.apiKey),e&&t.append("message",e),this.host.consoleCapture&&t.append("consoleErrors",JSON.stringify(this.host.consoleCapture.errors)),this.networkCapture&&t.append("networkErrors",JSON.stringify(this.networkCapture.errors));let o=null,r=null;try{const s=await fetch(`${this.host.config.endpoint}/video`,{method:"POST",body:t});if(s.ok){this.host.announceMsg("Recording sent");try{o=(await s.json())?.id??null}catch{}}else console.error("Failed to submit video feedback:",await s.text()),r=s.status===413?"This recording is too large to send. Try a shorter one.":"Your recording could not be sent."}catch(s){console.error("Failed to submit video feedback:",s),r="Your recording could not be sent. Check your connection and try again."}if(this.isSendingVideo=!1,r){this.showSendError(r,i);return}this.removeVideoPreview(),this.cleanupRecording(),await this.host.tryLaunchQuest("video",o)}showSendError(e,i){this.host.announceMsg(`Failed to send recording. ${e}`,!0),i.disabled=!1,i.textContent="Send";const t=this.videoPreview?.querySelector(".qaid-video-preview-actions");if(t){let o=this.videoPreview.querySelector(".qaid-video-error");o||(o=n("p",{class:"qaid-video-error"}),t.before(o)),o.textContent=e}}cleanupRecording(){this.isRecording=!1,this.removeRecordingIndicator(),this.videoRecorder&&(this.videoRecorder.destroy(),this.videoRecorder=null),this.networkCapture&&(this.networkCapture.restore(),this.networkCapture=null),this.recordedBlob&&(this.recordedBlob=null),this.host.setButtonsDisabled(!1),this.host.overlayShadowHost&&this.host.state==="IDLE"&&(this.host.overlayShadowHost.style.pointerEvents="none")}}const y=v;export{w as RecordingController,y as styles};
2
- //# sourceMappingURL=recording-BUw5-5Rf.js.map
1
+ import{h as n}from"./dom-kdwHduNo.js";import{h as g}from"./core-vu1EieDc.js";const v=".qaid-recording-indicator{position:fixed;pointer-events:auto;top:12px;left:50%;transform:translate(-50%);display:flex;align-items:center;gap:.5rem;padding:.5rem 1rem;background:light-dark(#1f2937,#374151);color:#fff;border-radius:9999px;font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;box-shadow:0 4px 12px #0000004d;z-index:99999;animation:qaid-slideDown .2s ease-out}.qaid-recording-dot{width:10px;height:10px;background:#dc2626;border-radius:50%;animation:qaid-dotPulse 1.5s ease-in-out infinite}@keyframes qaid-dotPulse{0%,to{opacity:1}50%{opacity:.3}}.qaid-recording-time{font-variant-numeric:tabular-nums;min-width:2.5rem;text-align:center}button.qaid-recording-stop{padding:.25rem .75rem;background:#dc2626;color:#fff;border:none;border-radius:9999px;font-size:calc(var(--qaid-font-size, 16px) * .75);font-weight:600;cursor:pointer;transition:background-color .2s;-webkit-appearance:none;appearance:none}button.qaid-recording-stop:hover{background:#b91c1c}.qaid-video-preview{position:fixed;inset:0 0 auto;height:100vh;height:100dvh;display:flex;align-items:center;justify-content:center;padding:16px;padding-top:max(16px,env(safe-area-inset-top));padding-bottom:max(16px,env(safe-area-inset-bottom));box-sizing:border-box;background:#0009;z-index:99998;animation:qaid-fadeIn .2s ease-out}@keyframes qaid-fadeIn{0%{opacity:0}to{opacity:1}}.qaid-video-preview-box{color-scheme:inherit;background:light-dark(#ffffff,#1f2937);border-radius:1rem;padding:1.5rem;box-shadow:0 25px 50px -12px #00000080;width:560px;max-width:100%;max-height:100%;overflow-y:auto;font-family:var(--qaid-font-family, system-ui, -apple-system, sans-serif);font-size:var(--qaid-font-size, 16px)}.qaid-video-preview-box h3{font-size:calc(var(--qaid-font-size, 16px) * 1.125);font-weight:700;margin:0 0 1rem;color:light-dark(#1f2937,#f9fafb)}.qaid-video-preview-box video{width:100%;max-height:50vh;max-height:50dvh;object-fit:contain;border-radius:.5rem;background:#000;margin-bottom:1rem}.qaid-video-preview-box textarea{width:100%;height:4rem;padding:.75rem;border:1px solid light-dark(#d1d5db,#374151);border-radius:.5rem;font-family:inherit;font-size:calc(var(--qaid-font-size, 16px) * .875);resize:vertical;margin-bottom:1rem;box-sizing:border-box;background:light-dark(#ffffff,#111827);color:light-dark(#1f2937,#f9fafb)}.qaid-video-preview-box textarea:focus{outline:none;border-color:var(--qaid-marker);box-shadow:0 0 0 3px color-mix(in srgb,var(--qaid-marker) 20%,transparent)}.qaid-video-error{margin:0 0 .75rem;font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;color:light-dark(#b91c1c,#fca5a5)}.qaid-video-preview-actions{display:flex;gap:.5rem;justify-content:flex-end}button.qaid-video-btn{padding:.5rem 1rem;border:none;border-radius:.5rem;font-size:calc(var(--qaid-font-size, 16px) * .875);font-weight:500;cursor:pointer;transition:background-color .2s,filter .2s;-webkit-appearance:none;appearance:none}button.qaid-video-btn-cancel{background:light-dark(#f3f4f6,#374151);color:light-dark(#374151,#d1d5db)}button.qaid-video-btn-cancel:hover{background:light-dark(#e5e7eb,#4b5563)}button.qaid-video-btn-rerecord{background:light-dark(#fef3c7,#78350f);color:light-dark(#92400e,#fde68a)}button.qaid-video-btn-rerecord:hover{filter:brightness(.9)}button.qaid-video-btn-send{background:var(--qaid-marker);color:var(--qaid-marker-text, white)}button.qaid-video-btn-send:hover{filter:brightness(.85)}button.qaid-video-btn-send:disabled{opacity:.5;cursor:not-allowed}.qaid-video-sending{display:flex;align-items:center;gap:.5rem;font-size:calc(var(--qaid-font-size, 16px) * .875);color:light-dark(#6b7280,#9ca3af)}@keyframes qaid-slideDown{0%{transform:translateY(-100%)}to{transform:translateY(0)}}button.qaid-recording-stop{min-height:24px}.qaid-video-preview-box textarea:focus-visible{outline:2px solid var(--qaid-marker, #6365f1);outline-offset:2px}@media(forced-colors:active){.qaid-video-preview-box textarea:focus{outline:2px solid CanvasText;outline-offset:2px}}",b=20,u=4096;function l(d){const e=typeof d=="string"?d:JSON.stringify(d);return e.length>u?e.slice(0,u)+"\u2026[truncated]":e}function p(d,e){d.length>=b&&d.shift(),d.push(e)}async function m(d){try{const e=await d.clone().text();return l(e)}catch{return}}function x(){const d=[],e=window.fetch;window.fetch=async function(o,r){const s=typeof o=="string"?o:o instanceof URL?o.toString():o.url,a=r?.method??(typeof o=="object"&&"method"in o?o.method:"GET");let c;r?.body&&(c=l(r.body));const h=await e.apply(window,[o,r]);if(h.status>=400){const f=await m(h);p(d,{url:s,method:a.toUpperCase(),status:h.status,statusText:h.statusText,requestBody:c,responseBody:f,timestamp:Date.now()})}return h};const i=XMLHttpRequest.prototype.open,t=XMLHttpRequest.prototype.send;return XMLHttpRequest.prototype.open=function(o,r,...s){return this._qaid_method=o,this._qaid_url=typeof r=="string"?r:r.toString(),i.apply(this,[o,r,...s])},XMLHttpRequest.prototype.send=function(o){const r=this,s=o?l(o):void 0;return r.addEventListener("load",function(){r.status>=400&&p(d,{url:r._qaid_url,method:r._qaid_method.toUpperCase(),status:r.status,statusText:r.statusText,requestBody:s,responseBody:l(r.responseText),timestamp:Date.now()})}),t.apply(this,[o])},{errors:d,restore:()=>{window.fetch=e,XMLHttpRequest.prototype.open=i,XMLHttpRequest.prototype.send=t}}}class w{constructor(e){this.host=e}host;videoRecorder=null;networkCapture=null;recordedBlob=null;recordingIndicator=null;videoPreview=null;isRecording=!1;isSendingVideo=!1;redactPicks=[];redactPickerRoot=null;redactRafId=0;boundRedactClick=e=>this.handleRedactPickClick(e);handleEscape(){return this.isRecording?(this.stopRecording(),!0):this.videoPreview?(this.cancelRecordingPreview(),!0):this.redactPickerRoot?(this.finishRedactionPicking(!1),!0):!1}destroy(){this.redactRafId&&cancelAnimationFrame(this.redactRafId),this.redactRafId=0,document.removeEventListener("click",this.boundRedactClick,!0),this.redactPickerRoot&&(this.redactPickerRoot.remove(),this.redactPickerRoot=null),this.redactPicks=[],this.cleanupRecording(),this.removeVideoPreview()}async startRecording(e=[]){if(!(this.isRecording||this.host.state!=="IDLE"))try{this.networkCapture=x();const{createVideoRecorder:i}=await import("./video-BSP4s2te.js");this.videoRecorder=i({maxDuration:this.host.config.videoOptions.maxDuration,redactionElements:e}),this.videoRecorder.onTick(t=>{this.updateRecordingTimer(t)}),this.videoRecorder.onStop(t=>{this.isRecording&&(this.recordedBlob=t,this.isRecording=!1,this.host.announceMsg("Recording stopped"),this.removeRecordingIndicator(),document.removeEventListener("keydown",this.host.boundKeyDown),this.host.setButtonsDisabled(!1),t&&t.size>0?this.showRecordingPreview():this.cleanupRecording())}),await this.videoRecorder.start(),this.isRecording=!0,this.host.announceMsg("Recording started"),this.host.setButtonsDisabled(!0),this.showRecordingIndicator(),document.addEventListener("keydown",this.host.boundKeyDown)}catch(i){i instanceof Error&&/current tab|cannot blur/i.test(i.message)&&this.host.announceMsg(i.message),this.cleanupRecording()}}async stopRecording(){try{this.recordedBlob=await this.videoRecorder.stop()}catch{this.recordedBlob=null}this.isRecording=!1,this.host.announceMsg("Recording stopped"),this.removeRecordingIndicator(),document.removeEventListener("keydown",this.host.boundKeyDown),this.recordedBlob&&this.recordedBlob.size>0?this.showRecordingPreview():this.cleanupRecording()}startPicking(){if(this.isRecording||this.host.state!=="IDLE")return;this.host.setState("REDACT_PICKING"),this.redactPicks=[];const e=this.host.ensureOverlayHost(),i=n("div",{style:"position:absolute;inset:0;"}),t=n("div",{class:"qaid-redact-picker",style:"position:fixed;inset:0;pointer-events:none;"},i,n("div",{style:"position:fixed;left:50%;bottom:24px;transform:translateX(-50%);display:flex;gap:12px;align-items:center;pointer-events:auto;background:#0b1220;color:#fff;border:1px solid #ff6b6b;border-radius:9999px;padding:10px 16px;font:600 13px system-ui,sans-serif;box-shadow:0 8px 30px rgba(0,0,0,.5);"},n("span",{text:"Click sensitive areas to blur",attrs:{"data-qaid-redact-label":""}}),n("button",{text:"Start recording",attrs:{type:"button"},style:"cursor:pointer;border:0;border-radius:9999px;padding:8px 14px;background:#ff6b6b;color:#0b1220;font:inherit;",on:{click:()=>this.finishRedactionPicking(!0)}}),n("button",{text:"Cancel",attrs:{type:"button"},style:"cursor:pointer;border:0;background:transparent;color:#9fb3c8;font:inherit;",on:{click:()=>this.finishRedactionPicking(!1)}})));e.appendChild(t),this.redactPickerRoot=t;const o=()=>{this.renderRedactPicks(i),this.redactRafId=requestAnimationFrame(o)};o(),document.addEventListener("click",this.boundRedactClick,!0),document.addEventListener("keydown",this.host.boundKeyDown),this.host.announceMsg("Click sensitive areas to blur, then start recording")}handleRedactPickClick(e){const i=e.target instanceof Element?e.target:null;if(!i||g(i)||this.redactPickerRoot?.contains(i))return;e.preventDefault(),e.stopPropagation();const t=this.redactPicks.indexOf(i);t>=0?this.redactPicks.splice(t,1):this.redactPicks.push(i);const o=this.redactPickerRoot?.querySelector("[data-qaid-redact-label]");if(o){const r=this.redactPicks.length;o.textContent=r===0?"Click sensitive areas to blur":`${r} area${r===1?"":"s"} will be blurred`}}renderRedactPicks(e){e.textContent="";for(const i of this.redactPicks){const t=i.getBoundingClientRect();t.width<=0||t.height<=0||e.appendChild(n("div",{style:`position:fixed;left:${t.left}px;top:${t.top}px;width:${t.width}px;height:${t.height}px;border:2px solid #ff6b6b;border-radius:4px;background:rgba(255,107,107,.18);pointer-events:none;`}))}}finishRedactionPicking(e){this.redactRafId&&cancelAnimationFrame(this.redactRafId),this.redactRafId=0,document.removeEventListener("click",this.boundRedactClick,!0),document.removeEventListener("keydown",this.host.boundKeyDown),this.redactPickerRoot&&(this.redactPickerRoot.remove(),this.redactPickerRoot=null);const i=this.redactPicks;this.redactPicks=[],this.host.setState("IDLE"),e&&this.startRecording(i)}showRecordingIndicator(){const e=this.host.ensureOverlayHost();this.recordingIndicator=n("div",{class:"qaid-recording-indicator",style:`z-index:${this.host.config.zIndex+100}`},n("div",{class:"qaid-recording-dot"}),n("span",{class:"qaid-recording-time",text:this.formatTime(this.host.config.videoOptions.maxDuration)}),n("button",{class:"qaid-recording-stop",text:"Stop",attrs:{type:"button"},on:{click:()=>this.stopRecording()}})),this.host.applyVars(this.recordingIndicator),e.appendChild(this.recordingIndicator)}updateRecordingTimer(e){if(!this.recordingIndicator)return;const i=this.recordingIndicator.querySelector(".qaid-recording-time");if(i){const t=Math.max(0,this.host.config.videoOptions.maxDuration-e);i.textContent=this.formatTime(t),t>0&&t<=5&&this.host.announceMsg(`${t} second${t===1?"":"s"} remaining`)}}formatTime(e){const i=Math.floor(e/60),t=e%60;return`${i}:${t.toString().padStart(2,"0")}`}removeRecordingIndicator(){this.recordingIndicator&&(this.recordingIndicator.remove(),this.recordingIndicator=null)}showRecordingPreview(){const e=this.host.ensureOverlayHost(),i=URL.createObjectURL(this.recordedBlob),t=`qaid-video-title-${this.host.uid}`,o=n("h3",{text:"Review your recording",attrs:{id:t}}),r=n("video");r.src=i,r.controls=!0,r.autoplay=!0,r.muted=!0;const s=n("textarea",{attrs:{placeholder:"Optional: Describe the issue you recorded...","aria-label":"Describe the issue you recorded"}}),a=n("button",{class:"qaid-video-btn qaid-video-btn-send",text:"Send",attrs:{type:"button"},on:{click:()=>this.submitVideoFeedback(s.value.trim()||null,a)}}),c=n("div",{class:"qaid-video-preview-box"},o,r,s,n("div",{class:"qaid-video-preview-actions"},n("button",{class:"qaid-video-btn qaid-video-btn-cancel",text:"Cancel",attrs:{type:"button"},on:{click:()=>this.cancelRecordingPreview()}}),n("button",{class:"qaid-video-btn qaid-video-btn-rerecord",text:"Re-record",attrs:{type:"button"},on:{click:()=>{this.cancelRecordingPreview(),this.startRecording()}}}),a));this.videoPreview=n("div",{class:"qaid-video-preview",style:`z-index:${this.host.config.zIndex+100}`},c),this.host.applyVars(this.videoPreview),this.host.overlayShadowHost&&(this.host.overlayShadowHost.style.pointerEvents="auto"),e.appendChild(this.videoPreview),this.host.openDialogA11y(c,{labelledbyId:o.id}),document.addEventListener("keydown",this.host.boundKeyDown)}cancelRecordingPreview(){this.removeVideoPreview(),this.cleanupRecording()}removeVideoPreview(){if(this.host.closeDialogA11y(),this.videoPreview){const e=this.videoPreview.querySelector("video");e?.src&&URL.revokeObjectURL(e.src),this.videoPreview.remove(),this.videoPreview=null}document.removeEventListener("keydown",this.host.boundKeyDown)}async submitVideoFeedback(e,i){if(!this.recordedBlob||this.isSendingVideo)return;this.isSendingVideo=!0,i.disabled=!0,i.textContent="Sending...";const t=new FormData;t.append("video",this.recordedBlob,`recording.${this.recordedBlob.type.includes("mp4")?"mp4":"webm"}`),t.append("pageUrl",window.location.href),t.append("visitorId",this.host.visitorId),this.host.config.apiKey&&t.append("apiKey",this.host.config.apiKey),e&&t.append("message",e),this.host.consoleCapture&&t.append("consoleErrors",JSON.stringify(this.host.consoleCapture.errors)),this.networkCapture&&t.append("networkErrors",JSON.stringify(this.networkCapture.errors));let o=null,r=null;try{const s=await fetch(`${this.host.config.endpoint}/video`,{method:"POST",body:t});if(s.ok){this.host.announceMsg("Recording sent");try{o=(await s.json())?.id??null}catch{}}else console.error("Failed to submit video feedback:",await s.text()),r=s.status===413?"This recording is too large to send. Try a shorter one.":"Your recording could not be sent."}catch(s){console.error("Failed to submit video feedback:",s),r="Your recording could not be sent. Check your connection and try again."}if(this.isSendingVideo=!1,r){this.showSendError(r,i);return}this.removeVideoPreview(),this.cleanupRecording(),await this.host.tryLaunchQuest("video",o)}showSendError(e,i){this.host.announceMsg(`Failed to send recording. ${e}`,!0),i.disabled=!1,i.textContent="Send";const t=this.videoPreview?.querySelector(".qaid-video-preview-actions");if(t){let o=this.videoPreview.querySelector(".qaid-video-error");o||(o=n("p",{class:"qaid-video-error"}),t.before(o)),o.textContent=e}}cleanupRecording(){this.isRecording=!1,this.removeRecordingIndicator(),this.videoRecorder&&(this.videoRecorder.destroy(),this.videoRecorder=null),this.networkCapture&&(this.networkCapture.restore(),this.networkCapture=null),this.recordedBlob&&(this.recordedBlob=null),this.host.setButtonsDisabled(!1),this.host.overlayShadowHost&&this.host.state==="IDLE"&&(this.host.overlayShadowHost.style.pointerEvents="none")}}const y=v;export{w as RecordingController,y as styles};
2
+ //# sourceMappingURL=recording-CVwPTtB0.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"recording-BUw5-5Rf.js","sources":["../../src/network-capture.ts","../../src/recording.ts"],"sourcesContent":["/**\n * Network capture utilities\n * Intercepts fetch() and XMLHttpRequest to capture 4xx/5xx errors\n */\n\nimport type { NetworkError } from \"./types\";\n\nconst MAX_ENTRIES = 20;\nconst MAX_BODY_SIZE = 4096; // 4KB\n\nexport interface NetworkCapture {\n errors: NetworkError[];\n restore: () => void;\n}\n\n/**\n * Truncate a body to max size. Callers must guard against null/undefined.\n */\nexport function truncateBody(body: unknown): string {\n const str = typeof body === \"string\" ? body : JSON.stringify(body);\n if (str.length > MAX_BODY_SIZE) {\n return str.slice(0, MAX_BODY_SIZE) + \"…[truncated]\";\n }\n return str;\n}\n\n/**\n * Add an error to the buffer, evicting oldest if at capacity\n */\nexport function addEntry(errors: NetworkError[], entry: NetworkError): void {\n if (errors.length >= MAX_ENTRIES) {\n errors.shift();\n }\n errors.push(entry);\n}\n\n/**\n * Read response body as text, with size limit\n */\nasync function safeReadBody(response: Response): Promise<string | undefined> {\n try {\n const text = await response.clone().text();\n return truncateBody(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Intercept fetch() and XMLHttpRequest to capture network errors (4xx/5xx)\n */\nexport function captureNetworkErrors(): NetworkCapture {\n const errors: NetworkError[] = [];\n const originalFetch = window.fetch;\n\n // Monkey-patch fetch\n window.fetch = async function (input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n const method = init?.method ?? (typeof input === \"object\" && \"method\" in input ? input.method : \"GET\");\n let requestBody: string | undefined;\n if (init?.body) {\n requestBody = truncateBody(init.body);\n }\n\n const response = await originalFetch.apply(window, [input, init]);\n\n if (response.status >= 400) {\n const responseBody = await safeReadBody(response);\n addEntry(errors, {\n url,\n method: method.toUpperCase(),\n status: response.status,\n statusText: response.statusText,\n requestBody,\n responseBody,\n timestamp: Date.now(),\n });\n }\n\n return response;\n };\n\n // Monkey-patch XMLHttpRequest\n const originalXHROpen = XMLHttpRequest.prototype.open;\n const originalXHRSend = XMLHttpRequest.prototype.send;\n\n XMLHttpRequest.prototype.open = function (method: string, url: string | URL, ...rest: unknown[]) {\n (this as XMLHttpRequest & { _qaid_method: string; _qaid_url: string })._qaid_method = method;\n (this as XMLHttpRequest & { _qaid_url: string })._qaid_url = typeof url === \"string\" ? url : url.toString();\n return originalXHROpen.apply(this, [method, url, ...rest] as Parameters<typeof originalXHROpen>);\n };\n\n XMLHttpRequest.prototype.send = function (body?: Document | XMLHttpRequestBodyInit | null) {\n const xhr = this as XMLHttpRequest & { _qaid_method: string; _qaid_url: string };\n const requestBody = body ? truncateBody(body) : undefined;\n\n xhr.addEventListener(\"load\", function () {\n if (xhr.status >= 400) {\n addEntry(errors, {\n url: xhr._qaid_url,\n method: xhr._qaid_method.toUpperCase(),\n status: xhr.status,\n statusText: xhr.statusText,\n requestBody,\n responseBody: truncateBody(xhr.responseText),\n timestamp: Date.now(),\n });\n }\n });\n\n return originalXHRSend.apply(this, [body]);\n };\n\n return {\n errors,\n restore: () => {\n window.fetch = originalFetch;\n XMLHttpRequest.prototype.open = originalXHROpen;\n XMLHttpRequest.prototype.send = originalXHRSend;\n },\n };\n}\n","/**\n * Video-recording subsystem — extracted from embed.ts so it lives in its own\n * lazily-loaded chunk. A thumbs-only visitor never downloads any of this; the\n * embed dynamically imports it the first time the record button is used (and\n * warms it on hover — see embed.ts prewarmVideo).\n *\n * The controller owns all recording state and UI (recorder, redaction picker,\n * indicator, preview, submit). It talks back to the embed through the narrow\n * `RecordingHost` interface, so embed internals stay private and the coupling\n * is explicit.\n */\n\nimport { h } from \"./dom\";\nimport featureStyles from \"./styles-video.css?inline\";\nimport { isEmbedElement } from \"./dom-utils\";\nimport { captureNetworkErrors, type NetworkCapture } from \"./network-capture\";\nimport type { VideoRecorder } from \"./video-capture\";\nimport type { ResolvedFeedbackConfig, EmbedState } from \"./types\";\nimport type { ConsoleCapture } from \"./console-capture\";\n\n/** The slice of the embed the recording subsystem needs. */\nexport interface RecordingHost {\n readonly config: ResolvedFeedbackConfig;\n readonly visitorId: string;\n readonly uid: string;\n readonly overlayShadowHost: HTMLDivElement | null;\n readonly consoleCapture: ConsoleCapture | null;\n readonly boundKeyDown: (e: KeyboardEvent) => void;\n readonly state: EmbedState;\n setState(state: EmbedState): void;\n ensureOverlayHost(): ShadowRoot;\n applyVars(el: HTMLElement): void;\n announceMsg(message: string, assertive?: boolean): void;\n openDialogA11y(\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string; label?: string }\n ): void;\n closeDialogA11y(): void;\n setButtonsDisabled(disabled: boolean): void;\n tryLaunchQuest(\n type: \"up\" | \"down\" | \"video\",\n feedbackId: number | string | null\n ): Promise<boolean>;\n}\n\nexport class RecordingController {\n private videoRecorder: VideoRecorder | null = null;\n private networkCapture: NetworkCapture | null = null;\n private recordedBlob: Blob | null = null;\n private recordingIndicator: HTMLDivElement | null = null;\n private videoPreview: HTMLDivElement | null = null;\n private isRecording = false;\n private isSendingVideo = false;\n\n // Pre-recording redaction picking.\n private redactPicks: Element[] = [];\n private redactPickerRoot: HTMLDivElement | null = null;\n private redactRafId = 0;\n private boundRedactClick = (e: MouseEvent): void => this.handleRedactPickClick(e);\n\n constructor(private host: RecordingHost) {}\n\n /** Escape-key handler; returns true when it consumed the key. */\n handleEscape(): boolean {\n if (this.isRecording) {\n void this.stopRecording();\n return true;\n }\n if (this.videoPreview) {\n this.cancelRecordingPreview();\n return true;\n }\n if (this.redactPickerRoot) {\n this.finishRedactionPicking(false);\n return true;\n }\n return false;\n }\n\n destroy(): void {\n if (this.redactRafId) cancelAnimationFrame(this.redactRafId);\n this.redactRafId = 0;\n document.removeEventListener(\"click\", this.boundRedactClick, true);\n if (this.redactPickerRoot) {\n this.redactPickerRoot.remove();\n this.redactPickerRoot = null;\n }\n this.redactPicks = [];\n this.cleanupRecording();\n this.removeVideoPreview();\n }\n\n async startRecording(redactionElements: Element[] = []): Promise<void> {\n // Don't start if already recording or in a targeting/modal flow.\n if (this.isRecording || this.host.state !== \"IDLE\") return;\n\n try {\n this.networkCapture = captureNetworkErrors();\n\n const { createVideoRecorder } = await import(\"./video-capture\");\n this.videoRecorder = createVideoRecorder({\n maxDuration: this.host.config.videoOptions.maxDuration,\n redactionElements,\n });\n\n this.videoRecorder.onTick((elapsed) => {\n this.updateRecordingTimer(elapsed);\n });\n\n // Handle unexpected stops (browser stop button, max duration).\n this.videoRecorder.onStop((blob) => {\n if (this.isRecording) {\n this.recordedBlob = blob;\n this.isRecording = false;\n this.host.announceMsg(\"Recording stopped\");\n this.removeRecordingIndicator();\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n this.host.setButtonsDisabled(false);\n\n if (blob && blob.size > 0) {\n this.showRecordingPreview();\n } else {\n this.cleanupRecording();\n }\n }\n });\n\n await this.videoRecorder.start();\n this.isRecording = true;\n this.host.announceMsg(\"Recording started\");\n this.host.setButtonsDisabled(true);\n this.showRecordingIndicator();\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n } catch (error) {\n // User denied screen share, shared a disallowed surface (window / whole\n // screen), the browser cannot blur the picked areas, or another error\n // occurred. Surface the tab-only and no-blur messages so neither is a\n // silent no-op. (Matched by text: video-capture is a separate lazy\n // chunk, so importing its constant here would merge the two.)\n if (error instanceof Error && /current tab|cannot blur/i.test(error.message)) {\n this.host.announceMsg(error.message);\n }\n this.cleanupRecording();\n }\n }\n\n private async stopRecording(): Promise<void> {\n try {\n this.recordedBlob = await this.videoRecorder!.stop();\n } catch {\n this.recordedBlob = null;\n }\n\n this.isRecording = false;\n this.host.announceMsg(\"Recording stopped\");\n this.removeRecordingIndicator();\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n\n if (this.recordedBlob && this.recordedBlob.size > 0) {\n this.showRecordingPreview();\n } else {\n this.cleanupRecording();\n }\n }\n\n /**\n * Pre-recording redaction picker. The user clicks page areas to blur; each\n * gets an outline that tracks its position, then \"Start recording\" hands the\n * picks to the recorder, which blurs their live bounding boxes so the\n * redaction follows the content as the page scrolls. \"Cancel\"/Escape aborts.\n */\n startPicking(): void {\n if (this.isRecording || this.host.state !== \"IDLE\") return;\n this.host.setState(\"REDACT_PICKING\");\n this.redactPicks = [];\n\n const root = this.host.ensureOverlayHost();\n\n // Layer holding the per-pick outlines (repositioned every frame).\n const boxHost = h(\"div\", { style: \"position:absolute;inset:0;\" });\n\n const container = h(\n \"div\",\n { class: \"qaid-redact-picker\", style: \"position:fixed;inset:0;pointer-events:none;\" },\n boxHost,\n // Control bar — the only pointer-interactive part of the overlay.\n h(\n \"div\",\n {\n style:\n \"position:fixed;left:50%;bottom:24px;transform:translateX(-50%);\" +\n \"display:flex;gap:12px;align-items:center;pointer-events:auto;\" +\n \"background:#0b1220;color:#fff;border:1px solid #ff6b6b;border-radius:9999px;\" +\n \"padding:10px 16px;font:600 13px system-ui,sans-serif;box-shadow:0 8px 30px rgba(0,0,0,.5);\",\n },\n h(\"span\", {\n text: \"Click sensitive areas to blur\",\n attrs: { \"data-qaid-redact-label\": \"\" },\n }),\n h(\"button\", {\n text: \"Start recording\",\n attrs: { type: \"button\" },\n style:\n \"cursor:pointer;border:0;border-radius:9999px;padding:8px 14px;background:#ff6b6b;color:#0b1220;font:inherit;\",\n on: { click: () => this.finishRedactionPicking(true) },\n }),\n h(\"button\", {\n text: \"Cancel\",\n attrs: { type: \"button\" },\n style: \"cursor:pointer;border:0;background:transparent;color:#9fb3c8;font:inherit;\",\n on: { click: () => this.finishRedactionPicking(false) },\n }),\n ),\n );\n\n root.appendChild(container);\n this.redactPickerRoot = container;\n\n // Keep the outlines glued to their elements while the user scrolls/picks.\n const tick = (): void => {\n this.renderRedactPicks(boxHost);\n this.redactRafId = requestAnimationFrame(tick);\n };\n tick();\n\n document.addEventListener(\"click\", this.boundRedactClick, true);\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n this.host.announceMsg(\"Click sensitive areas to blur, then start recording\");\n }\n\n private handleRedactPickClick(e: MouseEvent): void {\n const target = e.target instanceof Element ? e.target : null;\n // Ignore clicks on the embed's own UI. isEmbedElement catches the retargeted\n // shadow host (real browsers compose click events to it); the contains()\n // check catches the picker's own control-bar buttons when the event isn't\n // retargeted, so their handlers still fire instead of being swallowed here.\n if (!target || isEmbedElement(target) || this.redactPickerRoot?.contains(target)) return;\n e.preventDefault();\n e.stopPropagation();\n\n const idx = this.redactPicks.indexOf(target);\n if (idx >= 0) {\n this.redactPicks.splice(idx, 1);\n } else {\n this.redactPicks.push(target);\n }\n\n const label = this.redactPickerRoot?.querySelector(\"[data-qaid-redact-label]\");\n if (label) {\n const n = this.redactPicks.length;\n label.textContent =\n n === 0 ? \"Click sensitive areas to blur\" : `${n} area${n === 1 ? \"\" : \"s\"} will be blurred`;\n }\n }\n\n private renderRedactPicks(layer: HTMLElement): void {\n // Rebuild the outline boxes to match current picks and their live positions.\n layer.textContent = \"\";\n for (const el of this.redactPicks) {\n const r = el.getBoundingClientRect();\n if (r.width <= 0 || r.height <= 0) continue;\n layer.appendChild(\n h(\"div\", {\n style:\n `position:fixed;left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;` +\n \"border:2px solid #ff6b6b;border-radius:4px;background:rgba(255,107,107,.18);pointer-events:none;\",\n }),\n );\n }\n }\n\n private finishRedactionPicking(record: boolean): void {\n if (this.redactRafId) cancelAnimationFrame(this.redactRafId);\n this.redactRafId = 0;\n document.removeEventListener(\"click\", this.boundRedactClick, true);\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n if (this.redactPickerRoot) {\n this.redactPickerRoot.remove();\n this.redactPickerRoot = null;\n }\n const picks = this.redactPicks;\n this.redactPicks = [];\n this.host.setState(\"IDLE\");\n if (record) {\n void this.startRecording(picks);\n }\n }\n\n private showRecordingIndicator(): void {\n const root = this.host.ensureOverlayHost();\n\n this.recordingIndicator = h(\n \"div\",\n { class: \"qaid-recording-indicator\", style: `z-index:${this.host.config.zIndex + 100}` },\n h(\"div\", { class: \"qaid-recording-dot\" }),\n h(\"span\", {\n class: \"qaid-recording-time\",\n text: this.formatTime(this.host.config.videoOptions.maxDuration),\n }),\n h(\"button\", {\n class: \"qaid-recording-stop\",\n text: \"Stop\",\n attrs: { type: \"button\" },\n on: { click: () => this.stopRecording() },\n }),\n );\n\n this.host.applyVars(this.recordingIndicator);\n\n // The overlay host stays pointer-events:none. It covers the whole viewport,\n // so turning it on made a clear sheet over the page for the length of the\n // recording and every click the visitor made to show the bug died on it.\n // The pill takes its own clicks (pointer-events:auto in its CSS), the way\n // the redaction picker's control bar does.\n root.appendChild(this.recordingIndicator);\n }\n\n private updateRecordingTimer(elapsed: number): void {\n if (!this.recordingIndicator) return;\n const timer = this.recordingIndicator.querySelector<HTMLSpanElement>(\".qaid-recording-time\");\n if (timer) {\n const remaining = Math.max(0, this.host.config.videoOptions.maxDuration - elapsed);\n timer.textContent = this.formatTime(remaining);\n // Announce the final countdown so it is perceivable non-visually.\n if (remaining > 0 && remaining <= 5) {\n this.host.announceMsg(`${remaining} second${remaining === 1 ? \"\" : \"s\"} remaining`);\n }\n }\n }\n\n private formatTime(seconds: number): string {\n const m = Math.floor(seconds / 60);\n const s = seconds % 60;\n return `${m}:${s.toString().padStart(2, \"0\")}`;\n }\n\n private removeRecordingIndicator(): void {\n if (this.recordingIndicator) {\n this.recordingIndicator.remove();\n this.recordingIndicator = null;\n }\n }\n\n private showRecordingPreview(): void {\n const root = this.host.ensureOverlayHost();\n\n const videoUrl = URL.createObjectURL(this.recordedBlob!);\n const titleId = `qaid-video-title-${this.host.uid}`;\n\n const title = h(\"h3\", { text: \"Review your recording\", attrs: { id: titleId } });\n\n // Boolean media props must be set as properties (the `muted` attribute is\n // unreliable for autoplay), so build the element then assign them.\n const videoEl = h(\"video\");\n videoEl.src = videoUrl;\n videoEl.controls = true;\n videoEl.autoplay = true;\n videoEl.muted = true;\n\n const textarea = h(\"textarea\", {\n attrs: {\n placeholder: \"Optional: Describe the issue you recorded...\",\n \"aria-label\": \"Describe the issue you recorded\",\n },\n });\n\n const sendBtn = h(\"button\", {\n class: \"qaid-video-btn qaid-video-btn-send\",\n text: \"Send\",\n attrs: { type: \"button\" },\n on: { click: () => this.submitVideoFeedback(textarea.value.trim() || null, sendBtn) },\n });\n\n const box = h(\n \"div\",\n { class: \"qaid-video-preview-box\" },\n title,\n videoEl,\n textarea,\n h(\n \"div\",\n { class: \"qaid-video-preview-actions\" },\n h(\"button\", {\n class: \"qaid-video-btn qaid-video-btn-cancel\",\n text: \"Cancel\",\n attrs: { type: \"button\" },\n on: { click: () => this.cancelRecordingPreview() },\n }),\n h(\"button\", {\n class: \"qaid-video-btn qaid-video-btn-rerecord\",\n text: \"Re-record\",\n attrs: { type: \"button\" },\n on: {\n click: () => {\n this.cancelRecordingPreview();\n this.startRecording();\n },\n },\n }),\n sendBtn,\n ),\n );\n\n this.videoPreview = h(\n \"div\",\n { class: \"qaid-video-preview\", style: `z-index:${this.host.config.zIndex + 100}` },\n box,\n );\n\n this.host.applyVars(this.videoPreview);\n\n // Enable pointer events on the overlay host for the video preview.\n if (this.host.overlayShadowHost) {\n this.host.overlayShadowHost.style.pointerEvents = \"auto\";\n }\n\n root.appendChild(this.videoPreview);\n\n // Dialog semantics + focus trap + background inert.\n this.host.openDialogA11y(box, { labelledbyId: title.id });\n\n // Listen for the escape key.\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n private cancelRecordingPreview(): void {\n this.removeVideoPreview();\n this.cleanupRecording();\n }\n\n private removeVideoPreview(): void {\n // Release focus trap / inert and restore focus before removing the DOM.\n this.host.closeDialogA11y();\n if (this.videoPreview) {\n const videoEl = this.videoPreview.querySelector<HTMLVideoElement>(\"video\");\n if (videoEl?.src) {\n URL.revokeObjectURL(videoEl.src);\n }\n this.videoPreview.remove();\n this.videoPreview = null;\n }\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n private async submitVideoFeedback(message: string | null, sendBtn: HTMLButtonElement): Promise<void> {\n if (!this.recordedBlob || this.isSendingVideo) return;\n\n this.isSendingVideo = true;\n sendBtn.disabled = true;\n sendBtn.textContent = \"Sending...\";\n\n const formData = new FormData();\n formData.append(\"video\", this.recordedBlob, `recording.${this.recordedBlob.type.includes(\"mp4\") ? \"mp4\" : \"webm\"}`);\n formData.append(\"pageUrl\", window.location.href);\n formData.append(\"visitorId\", this.host.visitorId);\n\n if (this.host.config.apiKey) {\n formData.append(\"apiKey\", this.host.config.apiKey);\n }\n if (message) {\n formData.append(\"message\", message);\n }\n if (this.host.consoleCapture) {\n formData.append(\"consoleErrors\", JSON.stringify(this.host.consoleCapture.errors));\n }\n if (this.networkCapture) {\n formData.append(\"networkErrors\", JSON.stringify(this.networkCapture.errors));\n }\n\n let videoFeedbackId: string | number | null = null;\n // Set when the upload failed: the reason shown to the visitor.\n let failure: string | null = null;\n try {\n const response = await fetch(`${this.host.config.endpoint}/video`, {\n method: \"POST\",\n body: formData,\n });\n\n if (response.ok) {\n this.host.announceMsg(\"Recording sent\");\n try {\n const data = (await response.json()) as { id?: string | number };\n videoFeedbackId = data?.id ?? null;\n } catch {\n // Non-JSON / no id — the quest can still launch, just unlinked.\n }\n } else {\n // A refusal (403 on a plan without video, 400, 413 too large, 429…)\n // used to close the preview exactly like a success.\n console.error(\"Failed to submit video feedback:\", await response.text());\n failure =\n response.status === 413\n ? \"This recording is too large to send. Try a shorter one.\"\n : \"Your recording could not be sent.\";\n }\n } catch (error) {\n console.error(\"Failed to submit video feedback:\", error);\n failure = \"Your recording could not be sent. Check your connection and try again.\";\n }\n\n this.isSendingVideo = false;\n\n if (failure) {\n this.showSendError(failure, sendBtn);\n return;\n }\n\n this.removeVideoPreview();\n this.cleanupRecording();\n\n // Once the recording is safely sent, launch the linked quest (if any),\n // passing the new feedback record id so its response is joinable.\n await this.host.tryLaunchQuest(\"video\", videoFeedbackId);\n }\n\n /**\n * Keep the preview open and say the upload failed. Closing it, as a success\n * does, told the visitor their recording had arrived when it had not. Send\n * is re-enabled for another try; Cancel and Re-record still work.\n */\n private showSendError(message: string, sendBtn: HTMLButtonElement): void {\n this.host.announceMsg(`Failed to send recording. ${message}`, true);\n sendBtn.disabled = false;\n sendBtn.textContent = \"Send\";\n\n const actions = this.videoPreview?.querySelector(\".qaid-video-preview-actions\");\n if (actions) {\n let note = this.videoPreview!.querySelector<HTMLElement>(\".qaid-video-error\");\n if (!note) {\n note = h(\"p\", { class: \"qaid-video-error\" });\n actions.before(note);\n }\n note.textContent = message;\n }\n }\n\n private cleanupRecording(): void {\n this.isRecording = false;\n this.removeRecordingIndicator();\n\n if (this.videoRecorder) {\n this.videoRecorder.destroy();\n this.videoRecorder = null;\n }\n if (this.networkCapture) {\n this.networkCapture.restore();\n this.networkCapture = null;\n }\n if (this.recordedBlob) {\n this.recordedBlob = null;\n }\n\n this.host.setButtonsDisabled(false);\n\n // Reset overlay host pointer events if nothing else needs them.\n if (this.host.overlayShadowHost && this.host.state === \"IDLE\") {\n this.host.overlayShadowHost.style.pointerEvents = \"none\";\n }\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":["MAX_ENTRIES","MAX_BODY_SIZE","truncateBody","body","str","addEntry","errors","entry","safeReadBody","response","text","captureNetworkErrors","originalFetch","input","init","url","method","requestBody","responseBody","originalXHROpen","originalXHRSend","rest","xhr","RecordingController","host","redactionElements","createVideoRecorder","elapsed","blob","error","root","boxHost","h","container","tick","target","isEmbedElement","idx","label","n","layer","el","r","record","picks","timer","remaining","seconds","m","s","videoUrl","titleId","title","videoEl","textarea","sendBtn","box","message","formData","videoFeedbackId","failure","actions","note","styles","featureStyles"],"mappings":"0jIAOMA,EAAc,GACdC,EAAgB,KAUf,SAASC,EAAaC,EAAuB,CAClD,MAAMC,EAAM,OAAOD,GAAS,SAAWA,EAAO,KAAK,UAAUA,CAAI,EACjE,OAAIC,EAAI,OAASH,EACRG,EAAI,MAAM,EAAGH,CAAa,EAAI,oBAEhCG,CACT,CAKO,SAASC,EAASC,EAAwBC,EAA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EtB,MAAMM,EAAU,KAAK,cAAc,cAAc,6BAA6B,EAC9E,GAAIA,EAAS,CACX,IAAIC,EAAO,KAAK,aAAc,cAA2B,mBAAmB,EACvEA,IACHA,EAAO9B,EAAE,IAAK,CAAE,MAAO,mBAAoB,EAC3C6B,EAAQ,OAAOC,CAAI,GAErBA,EAAK,YAAcL,CACrB,CACF,CAEQ,kBAAyB,CAC/B,KAAK,YAAc,GACnB,KAAK,yBAAA,EAED,KAAK,gBACP,KAAK,cAAc,QAAA,EACnB,KAAK,cAAgB,MAEnB,KAAK,iBACP,KAAK,eAAe,QAAA,EACpB,KAAK,eAAiB,MAEpB,KAAK,eACP,KAAK,aAAe,MAGtB,KAAK,KAAK,mBAAmB,EAAK,EAG9B,KAAK,KAAK,mBAAqB,KAAK,KAAK,QAAU,SACrD,KAAK,KAAK,kBAAkB,MAAM,cAAgB,OAEtD,CACF,CAGO,MAAMM,EAASC"}
1
+ {"version":3,"file":"recording-CVwPTtB0.js","sources":["../../src/network-capture.ts","../../src/recording.ts"],"sourcesContent":["/**\n * Network capture utilities\n * Intercepts fetch() and XMLHttpRequest to capture 4xx/5xx errors\n */\n\nimport type { NetworkError } from \"./types\";\n\nconst MAX_ENTRIES = 20;\nconst MAX_BODY_SIZE = 4096; // 4KB\n\nexport interface NetworkCapture {\n errors: NetworkError[];\n restore: () => void;\n}\n\n/**\n * Truncate a body to max size. Callers must guard against null/undefined.\n */\nexport function truncateBody(body: unknown): string {\n const str = typeof body === \"string\" ? body : JSON.stringify(body);\n if (str.length > MAX_BODY_SIZE) {\n return str.slice(0, MAX_BODY_SIZE) + \"…[truncated]\";\n }\n return str;\n}\n\n/**\n * Add an error to the buffer, evicting oldest if at capacity\n */\nexport function addEntry(errors: NetworkError[], entry: NetworkError): void {\n if (errors.length >= MAX_ENTRIES) {\n errors.shift();\n }\n errors.push(entry);\n}\n\n/**\n * Read response body as text, with size limit\n */\nasync function safeReadBody(response: Response): Promise<string | undefined> {\n try {\n const text = await response.clone().text();\n return truncateBody(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Intercept fetch() and XMLHttpRequest to capture network errors (4xx/5xx)\n */\nexport function captureNetworkErrors(): NetworkCapture {\n const errors: NetworkError[] = [];\n const originalFetch = window.fetch;\n\n // Monkey-patch fetch\n window.fetch = async function (input: RequestInfo | URL, init?: RequestInit): Promise<Response> {\n const url = typeof input === \"string\" ? input : input instanceof URL ? input.toString() : input.url;\n const method = init?.method ?? (typeof input === \"object\" && \"method\" in input ? input.method : \"GET\");\n let requestBody: string | undefined;\n if (init?.body) {\n requestBody = truncateBody(init.body);\n }\n\n const response = await originalFetch.apply(window, [input, init]);\n\n if (response.status >= 400) {\n const responseBody = await safeReadBody(response);\n addEntry(errors, {\n url,\n method: method.toUpperCase(),\n status: response.status,\n statusText: response.statusText,\n requestBody,\n responseBody,\n timestamp: Date.now(),\n });\n }\n\n return response;\n };\n\n // Monkey-patch XMLHttpRequest\n const originalXHROpen = XMLHttpRequest.prototype.open;\n const originalXHRSend = XMLHttpRequest.prototype.send;\n\n XMLHttpRequest.prototype.open = function (method: string, url: string | URL, ...rest: unknown[]) {\n (this as XMLHttpRequest & { _qaid_method: string; _qaid_url: string })._qaid_method = method;\n (this as XMLHttpRequest & { _qaid_url: string })._qaid_url = typeof url === \"string\" ? url : url.toString();\n return originalXHROpen.apply(this, [method, url, ...rest] as Parameters<typeof originalXHROpen>);\n };\n\n XMLHttpRequest.prototype.send = function (body?: Document | XMLHttpRequestBodyInit | null) {\n const xhr = this as XMLHttpRequest & { _qaid_method: string; _qaid_url: string };\n const requestBody = body ? truncateBody(body) : undefined;\n\n xhr.addEventListener(\"load\", function () {\n if (xhr.status >= 400) {\n addEntry(errors, {\n url: xhr._qaid_url,\n method: xhr._qaid_method.toUpperCase(),\n status: xhr.status,\n statusText: xhr.statusText,\n requestBody,\n responseBody: truncateBody(xhr.responseText),\n timestamp: Date.now(),\n });\n }\n });\n\n return originalXHRSend.apply(this, [body]);\n };\n\n return {\n errors,\n restore: () => {\n window.fetch = originalFetch;\n XMLHttpRequest.prototype.open = originalXHROpen;\n XMLHttpRequest.prototype.send = originalXHRSend;\n },\n };\n}\n","/**\n * Video-recording subsystem — extracted from embed.ts so it lives in its own\n * lazily-loaded chunk. A thumbs-only visitor never downloads any of this; the\n * embed dynamically imports it the first time the record button is used (and\n * warms it on hover — see embed.ts prewarmVideo).\n *\n * The controller owns all recording state and UI (recorder, redaction picker,\n * indicator, preview, submit). It talks back to the embed through the narrow\n * `RecordingHost` interface, so embed internals stay private and the coupling\n * is explicit.\n */\n\nimport { h } from \"./dom\";\nimport featureStyles from \"./styles-video.css?inline\";\nimport { isEmbedElement } from \"./dom-utils\";\nimport { captureNetworkErrors, type NetworkCapture } from \"./network-capture\";\nimport type { VideoRecorder } from \"./video-capture\";\nimport type { ResolvedFeedbackConfig, EmbedState } from \"./types\";\nimport type { ConsoleCapture } from \"./console-capture\";\n\n/** The slice of the embed the recording subsystem needs. */\nexport interface RecordingHost {\n readonly config: ResolvedFeedbackConfig;\n readonly visitorId: string;\n readonly uid: string;\n readonly overlayShadowHost: HTMLDivElement | null;\n readonly consoleCapture: ConsoleCapture | null;\n readonly boundKeyDown: (e: KeyboardEvent) => void;\n readonly state: EmbedState;\n setState(state: EmbedState): void;\n ensureOverlayHost(): ShadowRoot;\n applyVars(el: HTMLElement): void;\n announceMsg(message: string, assertive?: boolean): void;\n openDialogA11y(\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string; label?: string }\n ): void;\n closeDialogA11y(): void;\n setButtonsDisabled(disabled: boolean): void;\n tryLaunchQuest(\n type: \"up\" | \"down\" | \"video\",\n feedbackId: number | string | null\n ): Promise<boolean>;\n}\n\nexport class RecordingController {\n private videoRecorder: VideoRecorder | null = null;\n private networkCapture: NetworkCapture | null = null;\n private recordedBlob: Blob | null = null;\n private recordingIndicator: HTMLDivElement | null = null;\n private videoPreview: HTMLDivElement | null = null;\n private isRecording = false;\n private isSendingVideo = false;\n\n // Pre-recording redaction picking.\n private redactPicks: Element[] = [];\n private redactPickerRoot: HTMLDivElement | null = null;\n private redactRafId = 0;\n private boundRedactClick = (e: MouseEvent): void => this.handleRedactPickClick(e);\n\n constructor(private host: RecordingHost) {}\n\n /** Escape-key handler; returns true when it consumed the key. */\n handleEscape(): boolean {\n if (this.isRecording) {\n void this.stopRecording();\n return true;\n }\n if (this.videoPreview) {\n this.cancelRecordingPreview();\n return true;\n }\n if (this.redactPickerRoot) {\n this.finishRedactionPicking(false);\n return true;\n }\n return false;\n }\n\n destroy(): void {\n if (this.redactRafId) cancelAnimationFrame(this.redactRafId);\n this.redactRafId = 0;\n document.removeEventListener(\"click\", this.boundRedactClick, true);\n if (this.redactPickerRoot) {\n this.redactPickerRoot.remove();\n this.redactPickerRoot = null;\n }\n this.redactPicks = [];\n this.cleanupRecording();\n this.removeVideoPreview();\n }\n\n async startRecording(redactionElements: Element[] = []): Promise<void> {\n // Don't start if already recording or in a targeting/modal flow.\n if (this.isRecording || this.host.state !== \"IDLE\") return;\n\n try {\n this.networkCapture = captureNetworkErrors();\n\n const { createVideoRecorder } = await import(\"./video-capture\");\n this.videoRecorder = createVideoRecorder({\n maxDuration: this.host.config.videoOptions.maxDuration,\n redactionElements,\n });\n\n this.videoRecorder.onTick((elapsed) => {\n this.updateRecordingTimer(elapsed);\n });\n\n // Handle unexpected stops (browser stop button, max duration).\n this.videoRecorder.onStop((blob) => {\n if (this.isRecording) {\n this.recordedBlob = blob;\n this.isRecording = false;\n this.host.announceMsg(\"Recording stopped\");\n this.removeRecordingIndicator();\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n this.host.setButtonsDisabled(false);\n\n if (blob && blob.size > 0) {\n this.showRecordingPreview();\n } else {\n this.cleanupRecording();\n }\n }\n });\n\n await this.videoRecorder.start();\n this.isRecording = true;\n this.host.announceMsg(\"Recording started\");\n this.host.setButtonsDisabled(true);\n this.showRecordingIndicator();\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n } catch (error) {\n // User denied screen share, shared a disallowed surface (window / whole\n // screen), the browser cannot blur the picked areas, or another error\n // occurred. Surface the tab-only and no-blur messages so neither is a\n // silent no-op. (Matched by text: video-capture is a separate lazy\n // chunk, so importing its constant here would merge the two.)\n if (error instanceof Error && /current tab|cannot blur/i.test(error.message)) {\n this.host.announceMsg(error.message);\n }\n this.cleanupRecording();\n }\n }\n\n private async stopRecording(): Promise<void> {\n try {\n this.recordedBlob = await this.videoRecorder!.stop();\n } catch {\n this.recordedBlob = null;\n }\n\n this.isRecording = false;\n this.host.announceMsg(\"Recording stopped\");\n this.removeRecordingIndicator();\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n\n if (this.recordedBlob && this.recordedBlob.size > 0) {\n this.showRecordingPreview();\n } else {\n this.cleanupRecording();\n }\n }\n\n /**\n * Pre-recording redaction picker. The user clicks page areas to blur; each\n * gets an outline that tracks its position, then \"Start recording\" hands the\n * picks to the recorder, which blurs their live bounding boxes so the\n * redaction follows the content as the page scrolls. \"Cancel\"/Escape aborts.\n */\n startPicking(): void {\n if (this.isRecording || this.host.state !== \"IDLE\") return;\n this.host.setState(\"REDACT_PICKING\");\n this.redactPicks = [];\n\n const root = this.host.ensureOverlayHost();\n\n // Layer holding the per-pick outlines (repositioned every frame).\n const boxHost = h(\"div\", { style: \"position:absolute;inset:0;\" });\n\n const container = h(\n \"div\",\n { class: \"qaid-redact-picker\", style: \"position:fixed;inset:0;pointer-events:none;\" },\n boxHost,\n // Control bar — the only pointer-interactive part of the overlay.\n h(\n \"div\",\n {\n style:\n \"position:fixed;left:50%;bottom:24px;transform:translateX(-50%);\" +\n \"display:flex;gap:12px;align-items:center;pointer-events:auto;\" +\n \"background:#0b1220;color:#fff;border:1px solid #ff6b6b;border-radius:9999px;\" +\n \"padding:10px 16px;font:600 13px system-ui,sans-serif;box-shadow:0 8px 30px rgba(0,0,0,.5);\",\n },\n h(\"span\", {\n text: \"Click sensitive areas to blur\",\n attrs: { \"data-qaid-redact-label\": \"\" },\n }),\n h(\"button\", {\n text: \"Start recording\",\n attrs: { type: \"button\" },\n style:\n \"cursor:pointer;border:0;border-radius:9999px;padding:8px 14px;background:#ff6b6b;color:#0b1220;font:inherit;\",\n on: { click: () => this.finishRedactionPicking(true) },\n }),\n h(\"button\", {\n text: \"Cancel\",\n attrs: { type: \"button\" },\n style: \"cursor:pointer;border:0;background:transparent;color:#9fb3c8;font:inherit;\",\n on: { click: () => this.finishRedactionPicking(false) },\n }),\n ),\n );\n\n root.appendChild(container);\n this.redactPickerRoot = container;\n\n // Keep the outlines glued to their elements while the user scrolls/picks.\n const tick = (): void => {\n this.renderRedactPicks(boxHost);\n this.redactRafId = requestAnimationFrame(tick);\n };\n tick();\n\n document.addEventListener(\"click\", this.boundRedactClick, true);\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n this.host.announceMsg(\"Click sensitive areas to blur, then start recording\");\n }\n\n private handleRedactPickClick(e: MouseEvent): void {\n const target = e.target instanceof Element ? e.target : null;\n // Ignore clicks on the embed's own UI. isEmbedElement catches the retargeted\n // shadow host (real browsers compose click events to it); the contains()\n // check catches the picker's own control-bar buttons when the event isn't\n // retargeted, so their handlers still fire instead of being swallowed here.\n if (!target || isEmbedElement(target) || this.redactPickerRoot?.contains(target)) return;\n e.preventDefault();\n e.stopPropagation();\n\n const idx = this.redactPicks.indexOf(target);\n if (idx >= 0) {\n this.redactPicks.splice(idx, 1);\n } else {\n this.redactPicks.push(target);\n }\n\n const label = this.redactPickerRoot?.querySelector(\"[data-qaid-redact-label]\");\n if (label) {\n const n = this.redactPicks.length;\n label.textContent =\n n === 0 ? \"Click sensitive areas to blur\" : `${n} area${n === 1 ? \"\" : \"s\"} will be blurred`;\n }\n }\n\n private renderRedactPicks(layer: HTMLElement): void {\n // Rebuild the outline boxes to match current picks and their live positions.\n layer.textContent = \"\";\n for (const el of this.redactPicks) {\n const r = el.getBoundingClientRect();\n if (r.width <= 0 || r.height <= 0) continue;\n layer.appendChild(\n h(\"div\", {\n style:\n `position:fixed;left:${r.left}px;top:${r.top}px;width:${r.width}px;height:${r.height}px;` +\n \"border:2px solid #ff6b6b;border-radius:4px;background:rgba(255,107,107,.18);pointer-events:none;\",\n }),\n );\n }\n }\n\n private finishRedactionPicking(record: boolean): void {\n if (this.redactRafId) cancelAnimationFrame(this.redactRafId);\n this.redactRafId = 0;\n document.removeEventListener(\"click\", this.boundRedactClick, true);\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n if (this.redactPickerRoot) {\n this.redactPickerRoot.remove();\n this.redactPickerRoot = null;\n }\n const picks = this.redactPicks;\n this.redactPicks = [];\n this.host.setState(\"IDLE\");\n if (record) {\n void this.startRecording(picks);\n }\n }\n\n private showRecordingIndicator(): void {\n const root = this.host.ensureOverlayHost();\n\n this.recordingIndicator = h(\n \"div\",\n { class: \"qaid-recording-indicator\", style: `z-index:${this.host.config.zIndex + 100}` },\n h(\"div\", { class: \"qaid-recording-dot\" }),\n h(\"span\", {\n class: \"qaid-recording-time\",\n text: this.formatTime(this.host.config.videoOptions.maxDuration),\n }),\n h(\"button\", {\n class: \"qaid-recording-stop\",\n text: \"Stop\",\n attrs: { type: \"button\" },\n on: { click: () => this.stopRecording() },\n }),\n );\n\n this.host.applyVars(this.recordingIndicator);\n\n // The overlay host stays pointer-events:none. It covers the whole viewport,\n // so turning it on made a clear sheet over the page for the length of the\n // recording and every click the visitor made to show the bug died on it.\n // The pill takes its own clicks (pointer-events:auto in its CSS), the way\n // the redaction picker's control bar does.\n root.appendChild(this.recordingIndicator);\n }\n\n private updateRecordingTimer(elapsed: number): void {\n if (!this.recordingIndicator) return;\n const timer = this.recordingIndicator.querySelector<HTMLSpanElement>(\".qaid-recording-time\");\n if (timer) {\n const remaining = Math.max(0, this.host.config.videoOptions.maxDuration - elapsed);\n timer.textContent = this.formatTime(remaining);\n // Announce the final countdown so it is perceivable non-visually.\n if (remaining > 0 && remaining <= 5) {\n this.host.announceMsg(`${remaining} second${remaining === 1 ? \"\" : \"s\"} remaining`);\n }\n }\n }\n\n private formatTime(seconds: number): string {\n const m = Math.floor(seconds / 60);\n const s = seconds % 60;\n return `${m}:${s.toString().padStart(2, \"0\")}`;\n }\n\n private removeRecordingIndicator(): void {\n if (this.recordingIndicator) {\n this.recordingIndicator.remove();\n this.recordingIndicator = null;\n }\n }\n\n private showRecordingPreview(): void {\n const root = this.host.ensureOverlayHost();\n\n const videoUrl = URL.createObjectURL(this.recordedBlob!);\n const titleId = `qaid-video-title-${this.host.uid}`;\n\n const title = h(\"h3\", { text: \"Review your recording\", attrs: { id: titleId } });\n\n // Boolean media props must be set as properties (the `muted` attribute is\n // unreliable for autoplay), so build the element then assign them.\n const videoEl = h(\"video\");\n videoEl.src = videoUrl;\n videoEl.controls = true;\n videoEl.autoplay = true;\n videoEl.muted = true;\n\n const textarea = h(\"textarea\", {\n attrs: {\n placeholder: \"Optional: Describe the issue you recorded...\",\n \"aria-label\": \"Describe the issue you recorded\",\n },\n });\n\n const sendBtn = h(\"button\", {\n class: \"qaid-video-btn qaid-video-btn-send\",\n text: \"Send\",\n attrs: { type: \"button\" },\n on: { click: () => this.submitVideoFeedback(textarea.value.trim() || null, sendBtn) },\n });\n\n const box = h(\n \"div\",\n { class: \"qaid-video-preview-box\" },\n title,\n videoEl,\n textarea,\n h(\n \"div\",\n { class: \"qaid-video-preview-actions\" },\n h(\"button\", {\n class: \"qaid-video-btn qaid-video-btn-cancel\",\n text: \"Cancel\",\n attrs: { type: \"button\" },\n on: { click: () => this.cancelRecordingPreview() },\n }),\n h(\"button\", {\n class: \"qaid-video-btn qaid-video-btn-rerecord\",\n text: \"Re-record\",\n attrs: { type: \"button\" },\n on: {\n click: () => {\n this.cancelRecordingPreview();\n this.startRecording();\n },\n },\n }),\n sendBtn,\n ),\n );\n\n this.videoPreview = h(\n \"div\",\n { class: \"qaid-video-preview\", style: `z-index:${this.host.config.zIndex + 100}` },\n box,\n );\n\n this.host.applyVars(this.videoPreview);\n\n // Enable pointer events on the overlay host for the video preview.\n if (this.host.overlayShadowHost) {\n this.host.overlayShadowHost.style.pointerEvents = \"auto\";\n }\n\n root.appendChild(this.videoPreview);\n\n // Dialog semantics + focus trap + background inert.\n this.host.openDialogA11y(box, { labelledbyId: title.id });\n\n // Listen for the escape key.\n document.addEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n private cancelRecordingPreview(): void {\n this.removeVideoPreview();\n this.cleanupRecording();\n }\n\n private removeVideoPreview(): void {\n // Release focus trap / inert and restore focus before removing the DOM.\n this.host.closeDialogA11y();\n if (this.videoPreview) {\n const videoEl = this.videoPreview.querySelector<HTMLVideoElement>(\"video\");\n if (videoEl?.src) {\n URL.revokeObjectURL(videoEl.src);\n }\n this.videoPreview.remove();\n this.videoPreview = null;\n }\n document.removeEventListener(\"keydown\", this.host.boundKeyDown);\n }\n\n private async submitVideoFeedback(message: string | null, sendBtn: HTMLButtonElement): Promise<void> {\n if (!this.recordedBlob || this.isSendingVideo) return;\n\n this.isSendingVideo = true;\n sendBtn.disabled = true;\n sendBtn.textContent = \"Sending...\";\n\n const formData = new FormData();\n formData.append(\"video\", this.recordedBlob, `recording.${this.recordedBlob.type.includes(\"mp4\") ? \"mp4\" : \"webm\"}`);\n formData.append(\"pageUrl\", window.location.href);\n formData.append(\"visitorId\", this.host.visitorId);\n\n if (this.host.config.apiKey) {\n formData.append(\"apiKey\", this.host.config.apiKey);\n }\n if (message) {\n formData.append(\"message\", message);\n }\n if (this.host.consoleCapture) {\n formData.append(\"consoleErrors\", JSON.stringify(this.host.consoleCapture.errors));\n }\n if (this.networkCapture) {\n formData.append(\"networkErrors\", JSON.stringify(this.networkCapture.errors));\n }\n\n let videoFeedbackId: string | number | null = null;\n // Set when the upload failed: the reason shown to the visitor.\n let failure: string | null = null;\n try {\n const response = await fetch(`${this.host.config.endpoint}/video`, {\n method: \"POST\",\n body: formData,\n });\n\n if (response.ok) {\n this.host.announceMsg(\"Recording sent\");\n try {\n const data = (await response.json()) as { id?: string | number };\n videoFeedbackId = data?.id ?? null;\n } catch {\n // Non-JSON / no id — the quest can still launch, just unlinked.\n }\n } else {\n // A refusal (403 on a plan without video, 400, 413 too large, 429…)\n // used to close the preview exactly like a success.\n console.error(\"Failed to submit video feedback:\", await response.text());\n failure =\n response.status === 413\n ? \"This recording is too large to send. Try a shorter one.\"\n : \"Your recording could not be sent.\";\n }\n } catch (error) {\n console.error(\"Failed to submit video feedback:\", error);\n failure = \"Your recording could not be sent. Check your connection and try again.\";\n }\n\n this.isSendingVideo = false;\n\n if (failure) {\n this.showSendError(failure, sendBtn);\n return;\n }\n\n this.removeVideoPreview();\n this.cleanupRecording();\n\n // Once the recording is safely sent, launch the linked quest (if any),\n // passing the new feedback record id so its response is joinable.\n await this.host.tryLaunchQuest(\"video\", videoFeedbackId);\n }\n\n /**\n * Keep the preview open and say the upload failed. Closing it, as a success\n * does, told the visitor their recording had arrived when it had not. Send\n * is re-enabled for another try; Cancel and Re-record still work.\n */\n private showSendError(message: string, sendBtn: HTMLButtonElement): void {\n this.host.announceMsg(`Failed to send recording. ${message}`, true);\n sendBtn.disabled = false;\n sendBtn.textContent = \"Send\";\n\n const actions = this.videoPreview?.querySelector(\".qaid-video-preview-actions\");\n if (actions) {\n let note = this.videoPreview!.querySelector<HTMLElement>(\".qaid-video-error\");\n if (!note) {\n note = h(\"p\", { class: \"qaid-video-error\" });\n actions.before(note);\n }\n note.textContent = message;\n }\n }\n\n private cleanupRecording(): void {\n this.isRecording = false;\n this.removeRecordingIndicator();\n\n if (this.videoRecorder) {\n this.videoRecorder.destroy();\n this.videoRecorder = null;\n }\n if (this.networkCapture) {\n this.networkCapture.restore();\n this.networkCapture = null;\n }\n if (this.recordedBlob) {\n this.recordedBlob = null;\n }\n\n this.host.setButtonsDisabled(false);\n\n // Reset overlay host pointer events if nothing else needs them.\n if (this.host.overlayShadowHost && this.host.state === \"IDLE\") {\n this.host.overlayShadowHost.style.pointerEvents = \"none\";\n }\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":["MAX_ENTRIES","MAX_BODY_SIZE","truncateBody","body","str","addEntry","errors","entry","safeReadBody","response","text","captureNetworkErrors","originalFetch","input","init","url","method","requestBody","responseBody","originalXHROpen","originalXHRSend","rest","xhr","RecordingController","host","redactionElements","createVideoRecorder","elapsed","blob","error","root","boxHost","h","container","tick","target","isEmbedElement","idx","label","n","layer","el","r","record","picks","timer","remaining","seconds","m","s","videoUrl","titleId","title","videoEl","textarea","sendBtn","box","message","formData","videoFeedbackId","failure","actions","note","styles","featureStyles"],"mappings":"0jIAOMA,EAAc,GACdC,EAAgB,KAUf,SAASC,EAAaC,EAAuB,CAClD,MAAMC,EAAM,OAAOD,GAAS,SAAWA,EAAO,KAAK,UAAUA,CAAI,EACjE,OAAIC,EAAI,OAASH,EACRG,EAAI,MAAM,EAAGH,CAAa,EAAI,oBAEhCG,CACT,CAKO,SAASC,EAASC,EAAwBC,EAA2B,CACtED,EAAO,QAAUN,GACnBM,EAAO,MAAA,EAETA,EAAO,KAAKC,CAAK,CACnB,CAKA,eAAeC,EAAaC,EAAiD,CAC3E,GAAI,CACF,MAAMC,EAAO,MAAMD,EAAS,MAAA,EAAQ,KAAA,EACpC,OAAOP,EAAaQ,CAAI,CAC1B,MAAQ,CACN,MACF,CACF,CAKO,SAASC,GAAuC,CACrD,MAAML,EAAyB,CAAA,EACzBM,EAAgB,OAAO,MAG7B,OAAO,MAAQ,eAAgBC,EAA0BC,EAAuC,CAC9F,MAAMC,EAAM,OAAOF,GAAU,SAAWA,EAAQA,aAAiB,IAAMA,EAAM,SAAA,EAAaA,EAAM,IAC1FG,EAASF,GAAM,SAAW,OAAOD,GAAU,UAAY,WAAYA,EAAQA,EAAM,OAAS,OAChG,IAAII,EACAH,GAAM,OACRG,EAAcf,EAAaY,EAAK,IAAI,GAGtC,MAAML,EAAW,MAAMG,EAAc,MAAM,OAAQ,CAACC,EAAOC,CAAI,CAAC,EAEhE,GAAIL,EAAS,QAAU,IAA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){h=n??m,e=null}function p(){if(typeof document>"u"||typeof window>"u")return!1;const n=document.createElement("canvas");return typeof n.getContext=="function"&&!!n.getContext("2d")}function v(){return e||(e=h().then(n=>n.default,()=>(e=null,null)),e)}async function L(n={}){const{quality:c=.8,maxWidth:f=1280,maxHeight:g=800}=n;try{const a=await v();if(!a)return console.warn("html2canvas failed to load"),null;const i=await a(document.body,{useCORS:!0,allowTaint:!1,logging:!1,windowWidth:document.documentElement.clientWidth,windowHeight:document.documentElement.clientHeight,width:document.documentElement.clientWidth,height:document.documentElement.clientHeight,x:window.scrollX,y:window.scrollY,ignoreElements:t=>t instanceof HTMLElement?t.classList.contains("qaid-buttons")||t.classList.contains("qaid-targeting-overlay")||t.classList.contains("qaid-modal-container")||t.classList.contains("qaid-bottom-sheet")||t.classList.contains("qaid-backdrop")||t.classList.contains("qaid-selected-marker")||t.classList.contains("qaid-tooltip-text")||t.classList.contains("qaid-recording-indicator")||t.classList.contains("qaid-video-preview")||t.className?.toString().startsWith?.("qaid-"):!1}),r=i.width,d=i.height,s=Math.min(f/r,g/d,1);if(s<1){const t=Math.round(r*s),l=Math.round(d*s),o=document.createElement("canvas");o.width=t,o.height=l;const u=o.getContext("2d");return u?(u.drawImage(i,0,0,t,l),o.toDataURL("image/webp",c)):null}return i.toDataURL("image/webp",c)}catch(a){return console.warn("DOM screenshot capture failed:",a),null}}export{w as _setHtml2CanvasImporter,L as captureDomScreenshot,p as isDomScreenshotSupported};
2
+ //# sourceMappingURL=screenshot-dom-DO-0UlOz.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"screenshot-dom-DO-0UlOz.js","sources":["../../src/screenshot-dom.ts"],"sourcesContent":["/**\n * DOM-based screenshot capture using html2canvas\n * No browser permission dialog required - reconstructs the page from the DOM\n */\n\nexport interface DomScreenshotOptions {\n /** Quality of WebP compression (0-1). Default: 0.8 */\n quality?: number;\n /** Max width of the screenshot. Default: 1280 */\n maxWidth?: number;\n /** Max height of the screenshot. Default: 800 */\n maxHeight?: number;\n}\n\ntype Html2Canvas = (\n element: HTMLElement,\n options?: Record<string, unknown>\n) => Promise<HTMLCanvasElement>;\n\n/**\n * html2canvas ships inside the package: a lazy chunk of the ESM build,\n * inlined in the UMD bundle. It used to be fetched from qaid.dev at run time,\n * which put a third-party script on every partner page that no pinned\n * version or `integrity` attribute could check.\n */\nlet loadPromise: Promise<Html2Canvas | null> | null = null;\n\ntype Html2CanvasModule = { default: Html2Canvas };\n\nconst realImport = (): Promise<Html2CanvasModule> =>\n import(\"html2canvas\") as unknown as Promise<Html2CanvasModule>;\n\nlet importHtml2Canvas = realImport;\n\n/** @internal Test seam: swap the html2canvas import. Pass null to restore it. */\nexport function _setHtml2CanvasImporter(fn: (() => Promise<Html2CanvasModule>) | null): void {\n importHtml2Canvas = fn ?? realImport;\n loadPromise = null;\n}\n\n/**\n * Check if DOM screenshot capture is supported\n * Requires canvas and basic DOM APIs\n */\nexport function isDomScreenshotSupported(): boolean {\n if (typeof document === \"undefined\" || typeof window === \"undefined\") {\n return false;\n }\n // Check canvas support\n const canvas = document.createElement(\"canvas\");\n return typeof canvas.getContext === \"function\" && !!canvas.getContext(\"2d\");\n}\n\n/** Load the bundled html2canvas; null when its chunk fails to load. */\nfunction loadHtml2Canvas(): Promise<Html2Canvas | null> {\n if (loadPromise) return loadPromise;\n loadPromise = importHtml2Canvas().then(\n (mod) => mod.default,\n () => {\n // A failed chunk fetch: let the next capture try again.\n loadPromise = null;\n return null;\n }\n );\n return loadPromise;\n}\n\n/**\n * Capture a screenshot of the current page using html2canvas\n * Returns a base64-encoded WebP data URL, or null on failure\n */\nexport async function captureDomScreenshot(\n options: DomScreenshotOptions = {}\n): Promise<string | null> {\n const { quality = 0.8, maxWidth = 1280, maxHeight = 800 } = options;\n\n try {\n const html2canvas = await loadHtml2Canvas();\n if (!html2canvas) {\n console.warn(\"html2canvas failed to load\");\n return null;\n }\n\n const canvas = await html2canvas(document.body, {\n useCORS: true,\n allowTaint: false,\n logging: false,\n windowWidth: document.documentElement.clientWidth,\n windowHeight: document.documentElement.clientHeight,\n width: document.documentElement.clientWidth,\n height: document.documentElement.clientHeight,\n x: window.scrollX,\n y: window.scrollY,\n ignoreElements: (el: Element) => {\n // Hide all qaid elements from the screenshot\n if (el instanceof HTMLElement) {\n return (\n el.classList.contains(\"qaid-buttons\") ||\n el.classList.contains(\"qaid-targeting-overlay\") ||\n el.classList.contains(\"qaid-modal-container\") ||\n el.classList.contains(\"qaid-bottom-sheet\") ||\n el.classList.contains(\"qaid-backdrop\") ||\n el.classList.contains(\"qaid-selected-marker\") ||\n el.classList.contains(\"qaid-tooltip-text\") ||\n el.classList.contains(\"qaid-recording-indicator\") ||\n el.classList.contains(\"qaid-video-preview\") ||\n el.className?.toString().startsWith?.(\"qaid-\")\n );\n }\n return false;\n },\n });\n\n // Scale down if needed\n const srcWidth = canvas.width;\n const srcHeight = canvas.height;\n const scale = Math.min(maxWidth / srcWidth, maxHeight / srcHeight, 1);\n\n if (scale < 1) {\n const scaledWidth = Math.round(srcWidth * scale);\n const scaledHeight = Math.round(srcHeight * scale);\n\n const scaledCanvas = document.createElement(\"canvas\");\n scaledCanvas.width = scaledWidth;\n scaledCanvas.height = scaledHeight;\n\n const ctx = scaledCanvas.getContext(\"2d\");\n if (!ctx) return null;\n\n ctx.drawImage(canvas, 0, 0, scaledWidth, scaledHeight);\n return scaledCanvas.toDataURL(\"image/webp\", quality);\n }\n\n return canvas.toDataURL(\"image/webp\", quality);\n } catch (error) {\n console.warn(\"DOM screenshot capture failed:\", error);\n return null;\n }\n}\n"],"names":["loadPromise","realImport","importHtml2Canvas","_setHtml2CanvasImporter","fn","isDomScreenshotSupported","canvas","loadHtml2Canvas","mod","captureDomScreenshot","options","quality","maxWidth","maxHeight","html2canvas","el","srcWidth","srcHeight","scale","scaledWidth","scaledHeight","scaledCanvas","ctx","error"],"mappings":"AAyBA,IAAIA,EAAkD,KAItD,MAAMC,EAAa,IACjB,OAAO,+BAAa,EAEtB,IAAIC,EA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X,EAAO,OACnBY,EAAQ,KAAK,IAAIN,EAAWI,EAAUH,EAAYI,EAAW,CAAC,EAEpE,GAAIC,EAAQ,EAAG,CACb,MAAMC,EAAc,KAAK,MAAMH,EAAWE,CAAK,EACzCE,EAAe,KAAK,MAAMH,EAAYC,CAAK,EAE3CG,EAAe,SAAS,cAAc,QAAQ,EACpDA,EAAa,MAAQF,EACrBE,EAAa,OAASD,EAEtB,MAAME,EAAMD,EAAa,WAAW,IAAI,EACxC,OAAKC,GAELA,EAAI,UAAUhB,EAAQ,EAAG,EAAGa,EAAaC,CAAY,EAC9CC,EAAa,UAAU,aAAcV,CAAO,GAHlC,IAInB,CAEA,OAAOL,EAAO,UAAU,aAAcK,CAAO,CAC/C,OAASY,EAAO,CACd,eAAQ,KAAK,iCAAkCA,CAAK,EAC7C,IACT,CACF"}
@@ -0,0 +1,2 @@
1
+ import{t as O,D as m,a as Q}from"./core-vu1EieDc.js";const F=["a[href]","button","input","textarea","select","[tabindex]"].join(",");function U(e){return e.hasAttribute("disabled")?!0:e.disabled===!0}function q(e){let n=e;for(;n;){if(n.hasAttribute("hidden"))return!0;const t=n.style;if(t&&(t.display==="none"||t.visibility==="hidden"||t.visibility==="collapse"))return!0;n=n.parentElement}return!1}function b(e){return Array.from(e.querySelectorAll(F)).filter(t=>!(t.getAttribute("tabindex")==="-1"||t instanceof HTMLInputElement&&t.type==="hidden"||t instanceof HTMLAnchorElement&&!t.getAttribute("href")||U(t)||q(t)))}function h(e){let n=e.activeElement;for(;n&&n.shadowRoot&&n.shadowRoot.activeElement;)n=n.shadowRoot.activeElement;return n instanceof HTMLElement?n:null}function g(e){const n=e.ownerDocument||document;let t=!1;const r=i=>{if(i.key!=="Tab")return;const a=b(e);if(a.length===0){i.preventDefault(),e.focus();return}const s=a[0],l=a[a.length-1],u=h(n),c=u?a.indexOf(u)!==-1:!1;i.shiftKey?(!c||u===s)&&(i.preventDefault(),l.focus()):(!c||u===l)&&(i.preventDefault(),s.focus())};e.addEventListener("keydown",r);const o=b(e);return o.length>0?o[0].focus():(e.hasAttribute("tabindex")||(e.setAttribute("tabindex","-1"),t=!0),e.focus()),{release(){e.removeEventListener("keydown",r),t&&(e.removeAttribute("tabindex"),t=!1)}}}function w(){return h(document)}function v(e){if(!(!e||typeof e.focus!="function"))try{e.focus()}catch{}}function E(e,n={}){e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),n.labelledbyId&&e.setAttribute("aria-labelledby",n.labelledbyId),n.describedbyId&&e.setAttribute("aria-describedby",n.describedbyId),n.label&&e.setAttribute("aria-label",n.label)}function H(e,n){let t=e;for(;t&&t!==n;){const r=t.parentNode;if(r===n)return t;if(r&&r.host){t=r.host;continue}if(!r)return null;t=r}return null}function A(e){const t=(e.ownerDocument||document).body;if(!t)return()=>{};const r=H(e,t),o=[];return Array.from(t.children).forEach(i=>{if(!(i instanceof HTMLElement)||r&&i===r)return;const a=i.inert===!0,s=i.getAttribute("aria-hidden");a&&s==="true"||(i.inert=!0,i.setAttribute("aria-hidden","true"),o.push({el:i,prevInert:a,prevAriaHidden:s}))}),function(){for(;o.length;){const a=o.pop();a.el.inert=a.prevInert,a.prevAriaHidden===null?a.el.removeAttribute("aria-hidden"):a.el.setAttribute("aria-hidden",a.prevAriaHidden)}}}function x(e,n){const t=w();E(e,n);const r=g(e),o=A(e);return()=>{r.release(),o(),v(t)}}const P=Object.freeze(Object.defineProperty({__proto__:null,applyDialog:E,createFocusTrap:g,getFocusable:b,openDialog:x,restoreFocus:v,saveFocus:w,setBackgroundInert:A},Symbol.toStringTag,{value:"Module"}));function k(e,n){return new Promise((t,r)=>{const o=document.createElement("script");o.type="module",o.integrity=n,o.crossOrigin="anonymous";try{o.src=O(e)}catch{console.warn("[thumbs-embed] Trusted Types refused the quests module; add `trusted-types qaid-embed` to the page's CSP to check its hash."),t(!1);return}o.addEventListener("load",()=>{o.remove(),t(!0)}),o.addEventListener("error",()=>{o.remove(),r(new Error(`quests module failed to load or failed its integrity check: ${e}`))}),(document.head||document.documentElement).appendChild(o)})}const S=async e=>(e===m&&await k(e,Q),import(e));let T=S,d=null,f=null;const p=new Map,y=new Map;function j(e){T=e??S,d=null,f=null,p.clear(),y.clear()}function D(e,n){return`${e.replace(/\/+$/,"")}/${encodeURIComponent(n)}/definition`}function C(e){if(p.has(e))return Promise.resolve();const n=y.get(e);if(n)return n;const t=fetch(e,{headers:{Accept:"application/json"}}).then(r=>r.ok?r.json():null).then(r=>{r&&p.set(e,r)}).catch(()=>{}).finally(()=>{y.delete(e)});return y.set(e,t),t}function I(e){return d&&f===e||(f=e,d=Promise.resolve(T(e)).then(n=>{const t=n;if(!t||typeof t.QaidQuests!="function")throw new Error("quests module has no QaidQuests export");return t}).catch(n=>{throw d=null,f=null,n})),d}async function M(e){const n=await I(e.moduleUrl),t=e.base.replace(/\/+$/,""),r=D(t,e.questId),o=s=>s!=null?{feedbackId:s}:void 0;let i;const a=e.feedbackId;return a instanceof Promise?i=n.QaidQuests.supports?.asyncMetadata?a.then(o,()=>{}):o(await a.catch(()=>null)):i=o(a??null),new n.QaidQuests({endpoint:`${t}/responses`,configUrl:r,questionnaire:p.get(r),apiKey:e.apiKey||void 0,metadata:i,onClose:e.onClose})}const K=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_QUESTS_MODULE_URL:m,_setQuestsImporter:j,launchQuest:M,loadQuestsModule:I,prefetchQuestDefinition:C,preloadVerifiedModule:k,questDefinitionUrl:D},Symbol.toStringTag,{value:"Module"}));async function _(e,n){const t=e.ensureOverlayHost(),r=e.overlayShadowHost,o=r.style.pointerEvents;r.style.pointerEvents="auto";try{const{openAnnotationEditor:i,styles:a}=await import("./annotate-1zompTEi.js");return e.addFeatureStyles(a),await i({dataUrl:n,root:t,quality:e.config.screenshotOptions.quality,color:e.config.annotationColor,palette:e.config.annotationPalette,applyVars:s=>e.applyVars(s),announce:(s,l)=>e.announceMsg(s,l),openDialog:(s,l)=>e.openDialogA11y(s,l),closeDialog:()=>e.closeDialogA11y()})}catch(i){return console.error("Annotation editor failed to open:",i),null}finally{r.style.pointerEvents=o}}async function R(e){const{config:n,feedbackData:t,selectedBounds:r}=e;let o=null;if(n.captureScreenshot||n.feedbackMode==="annotate")try{if(e.shouldCaptureViaDom()){const{captureDomScreenshot:c}=await import("./screenshot-dom-DO-0UlOz.js");o=await c(n.screenshotOptions)}else{const{captureScreenshot:c}=await import("./screenshot-CNe1irEz.js");o=await c(n.screenshotOptions)}o&&e.announceMsg("Screenshot captured")}catch(c){console.error("Screenshot capture failed:",c),o=null}o&&n.annotate&&(o=await _(e,o)??o);const a=t.elementSelector?{x:r.x,y:r.y,width:r.width,height:r.height}:null,s={feedbackType:t.feedbackType,pageUrl:window.location.href,apiKey:n.apiKey||void 0,elementSelector:t.elementSelector,elementText:t.elementText,consoleErrors:[...t.consoleErrors],screenWidth:window.innerWidth,screenHeight:window.innerHeight,clickX:r.clickX,clickY:r.clickY,scrollX:window.scrollX,scrollY:window.scrollY,screenshot:o,visitorId:e.visitorId,elementBounds:a,userAgent:navigator.userAgent},l=$(e,s);e.setFeedbackId(l);const u=t.feedbackType;if(u&&u!=="neutral"&&await L(e,u,l)){e.resetFeedbackUi();return}e.setState("MODAL_OPEN");try{const c=await e.ensureModal();if(e.destroyed)return;c.open(),e.overlayShadowHost&&(e.overlayShadowHost.style.pointerEvents="auto")}catch(c){console.error("Failed to open the feedback modal:",c),e.announceMsg("Thank you for your feedback!",!0),e.resetFeedbackUi()}}async function $(e,n){try{const t=await fetch(e.config.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(t.ok){const r=await t.json();return e.announceMsg("Feedback sent"),r.id}}catch(t){console.error("Failed to submit feedback:",t),e.announceMsg("Failed to send feedback",!0)}return null}async function L(e,n,t){const r=e.config.quests,o=r.base&&r[n]||"";if(!o)return!1;try{return e.activeQuest?.destroy(),e.activeQuest=await M({questId:o,base:r.base,apiKey:r.apiKey||void 0,moduleUrl:r.moduleUrl,feedbackId:t,onClose:()=>{e.activeQuest=null}}),!0}catch(i){return console.error("Failed to launch quest:",i),e.activeQuest=null,!1}}const Y=Object.freeze(Object.defineProperty({__proto__:null,openAnnotationEditor:_,submitFeedback:R,tryLaunchQuest:L},Symbol.toStringTag,{value:"Module"}));export{P as a,K as q,Y as s};
2
+ //# sourceMappingURL=send-C3IvslZA.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"send-C3IvslZA.js","sources":["../../src/a11y-dialog.ts","../../src/quest-launcher.ts","../../src/send.ts"],"sourcesContent":["/**\n * Dialog accessibility for the qaid embeds: focus management (trap,\n * save/restore), dialog semantics, and background isolation. Split from\n * a11y.ts so the startup chunk ships only `announce`; this module loads with\n * the click path (the message box, the markup editor, the video preview).\n *\n * Framework-free and self-contained (no CSS dependency), so it can be dropped\n * into any open shadow root.\n */\n\n/** Options accepted by {@link applyDialog}. */\nexport interface ApplyDialogOptions {\n /** id of the element that labels the dialog (wired via aria-labelledby). */\n labelledbyId?: string;\n /** id of the element that describes the dialog (wired via aria-describedby). */\n describedbyId?: string;\n /** Fallback accessible name when no labelling element exists. */\n label?: string;\n}\n\n/** Handle returned by {@link createFocusTrap}. */\nexport interface FocusTrap {\n /** Remove the trap's key handler and clean up any tabindex it added. */\n release(): void;\n}\n\n/**\n * Selector for natively focusable / author-focusable elements. Elements that\n * opt out with tabindex=\"-1\" are excluded below in {@link getFocusable}.\n */\nconst FOCUSABLE_SELECTOR = [\n \"a[href]\",\n \"button\",\n \"input\",\n \"textarea\",\n \"select\",\n \"[tabindex]\",\n].join(\",\");\n\nfunction isDisabled(el: HTMLElement): boolean {\n if (el.hasAttribute(\"disabled\")) return true;\n const asInput = el as HTMLElement & { disabled?: boolean };\n return asInput.disabled === true;\n}\n\nfunction isHidden(el: HTMLElement): boolean {\n let node: HTMLElement | null = el;\n while (node) {\n if (node.hasAttribute(\"hidden\")) return true;\n const style = node.style;\n if (\n style &&\n (style.display === \"none\" ||\n style.visibility === \"hidden\" ||\n style.visibility === \"collapse\")\n ) {\n return true;\n }\n node = node.parentElement;\n }\n return false;\n}\n\n/**\n * Collect the focusable descendants of `container` in DOM order, excluding\n * disabled controls, elements opted out with tabindex=\"-1\", and elements that\n * are hidden (via the hidden attribute or an inline display/visibility rule on\n * themselves or an ancestor up to the document root).\n */\nexport function getFocusable(container: HTMLElement): HTMLElement[] {\n const nodes = Array.from(\n container.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)\n );\n return nodes.filter((el) => {\n if (el.getAttribute(\"tabindex\") === \"-1\") return false;\n if (el instanceof HTMLInputElement && el.type === \"hidden\") return false;\n if (el instanceof HTMLAnchorElement && !el.getAttribute(\"href\")) return false;\n if (isDisabled(el)) return false;\n if (isHidden(el)) return false;\n return true;\n });\n}\n\n/** Resolve the deepest active element, drilling through open shadow roots. */\nfunction getDeepActiveElement(doc: Document): HTMLElement | null {\n let active: Element | null = doc.activeElement;\n while (active && active.shadowRoot && active.shadowRoot.activeElement) {\n active = active.shadowRoot.activeElement;\n }\n return active instanceof HTMLElement ? active : null;\n}\n\n/**\n * Trap keyboard focus inside `container`: Tab / Shift+Tab cycle between the\n * first and last focusable descendants and can never leave the container. On\n * creation focus moves to the first focusable element, or to the container\n * itself (made programmatically focusable) when it has no focusable children.\n *\n * Call {@link FocusTrap.release} to remove the handler; pair it with\n * {@link restoreFocus} to return focus to the invoking control.\n */\nexport function createFocusTrap(container: HTMLElement): FocusTrap {\n const doc = container.ownerDocument || document;\n let addedTabindex = false;\n\n const onKeydown = (event: KeyboardEvent): void => {\n if (event.key !== \"Tab\") return;\n\n const focusable = getFocusable(container);\n if (focusable.length === 0) {\n // Nothing to move to — keep focus pinned on the container.\n event.preventDefault();\n container.focus();\n return;\n }\n\n const first = focusable[0];\n const last = focusable[focusable.length - 1];\n const active = getDeepActiveElement(doc);\n const withinTrap = active ? focusable.indexOf(active) !== -1 : false;\n\n if (event.shiftKey) {\n if (!withinTrap || active === first) {\n event.preventDefault();\n last.focus();\n }\n } else {\n if (!withinTrap || active === last) {\n event.preventDefault();\n first.focus();\n }\n }\n };\n\n container.addEventListener(\"keydown\", onKeydown);\n\n const initial = getFocusable(container);\n if (initial.length > 0) {\n initial[0].focus();\n } else {\n if (!container.hasAttribute(\"tabindex\")) {\n container.setAttribute(\"tabindex\", \"-1\");\n addedTabindex = true;\n }\n container.focus();\n }\n\n return {\n release(): void {\n container.removeEventListener(\"keydown\", onKeydown);\n if (addedTabindex) {\n container.removeAttribute(\"tabindex\");\n addedTabindex = false;\n }\n },\n };\n}\n\n/**\n * Capture the currently focused element (drilling through shadow roots) so it\n * can be restored later with {@link restoreFocus}. Returns null when focus is\n * on nothing focusable.\n */\nexport function saveFocus(): HTMLElement | null {\n return getDeepActiveElement(document);\n}\n\n/**\n * Restore focus to a previously saved element. Safe to call with null or an\n * element that has since been detached (a missing/throwing focus is ignored).\n */\nexport function restoreFocus(el: HTMLElement | null): void {\n if (!el || typeof el.focus !== \"function\") return;\n try {\n el.focus();\n } catch {\n // The element may have been removed; nothing more to do.\n }\n}\n\n/**\n * Apply dialog semantics to `el`: role=\"dialog\", aria-modal=\"true\", and the\n * naming/description wiring described by `opts`. Prefer aria-labelledby /\n * aria-describedby pointing at visible title/subtitle elements; fall back to\n * aria-label when no visible label element exists.\n */\nexport function applyDialog(el: HTMLElement, opts: ApplyDialogOptions = {}): void {\n el.setAttribute(\"role\", \"dialog\");\n el.setAttribute(\"aria-modal\", \"true\");\n if (opts.labelledbyId) {\n el.setAttribute(\"aria-labelledby\", opts.labelledbyId);\n }\n if (opts.describedbyId) {\n el.setAttribute(\"aria-describedby\", opts.describedbyId);\n }\n if (opts.label) {\n el.setAttribute(\"aria-label\", opts.label);\n }\n}\n\n/** Walk up to the body-level ancestor of `el`, crossing shadow boundaries. */\nfunction topLevelAncestor(el: HTMLElement, body: HTMLElement): HTMLElement | null {\n let node: Node | null = el;\n while (node && node !== body) {\n const parent: Node | null = node.parentNode;\n if (parent === body) return node as HTMLElement;\n if (parent && (parent as ShadowRoot).host) {\n node = (parent as ShadowRoot).host;\n continue;\n }\n if (!parent) return null;\n node = parent;\n }\n return null;\n}\n\n/**\n * Isolate the background from assistive technology while a dialog is open by\n * marking every top-level sibling of the dialog inert (with an aria-hidden\n * fallback). `except` is the open dialog (or any element inside it); the\n * top-level element that contains it is left interactive.\n *\n * Returns a restore function that reverts every attribute this call changed,\n * leaving elements that were already inert/hidden untouched.\n */\nexport function setBackgroundInert(except: HTMLElement): () => void {\n const doc = except.ownerDocument || document;\n const body = doc.body;\n if (!body) return () => {};\n\n const keep = topLevelAncestor(except, body);\n const changed: Array<{\n el: HTMLElement;\n prevInert: boolean;\n prevAriaHidden: string | null;\n }> = [];\n\n Array.from(body.children).forEach((child) => {\n if (!(child instanceof HTMLElement)) return;\n if (keep && child === keep) return;\n\n const prevInert = child.inert === true;\n const prevAriaHidden = child.getAttribute(\"aria-hidden\");\n // Only record (and later revert) elements we actually change.\n if (prevInert && prevAriaHidden === \"true\") return;\n\n child.inert = true;\n child.setAttribute(\"aria-hidden\", \"true\");\n changed.push({ el: child, prevInert, prevAriaHidden });\n });\n\n return function restore(): void {\n while (changed.length) {\n // The loop guard guarantees pop() returns an entry.\n const entry = changed.pop()!;\n entry.el.inert = entry.prevInert;\n if (entry.prevAriaHidden === null) {\n entry.el.removeAttribute(\"aria-hidden\");\n } else {\n entry.el.setAttribute(\"aria-hidden\", entry.prevAriaHidden);\n }\n }\n };\n}\n\n/** What {@link openDialog} needs to name the dialog. */\nexport type DialogOptions = ApplyDialogOptions;\n\n/**\n * Turn a transient surface into an accessible modal dialog: save the\n * invoking control, apply dialog semantics, trap focus, and inert the\n * background. Returns the matching close: release the trap, restore the\n * background, and return focus to the saved control.\n */\nexport function openDialog(container: HTMLElement, opts: DialogOptions): () => void {\n const trigger = saveFocus();\n applyDialog(container, opts);\n const trap = createFocusTrap(container);\n const restoreInert = setBackgroundInert(container);\n return () => {\n trap.release();\n restoreInert();\n restoreFocus(trigger);\n };\n}\n","/**\n * Lazy loader + launcher for `@qaiddev/quests-embed`.\n *\n * `thumbs-embed` links a button to a quest but owns no questionnaire code\n * and takes no build-time dependency on the quests package. Instead the\n * quests widget is imported from a CDN the first time a quest is triggered,\n * so the shipped bundle stays zero-dependency and small.\n *\n * Only the tiny slice of the quests public API that we actually use is\n * modelled here structurally, so a version bump of the quests package that\n * keeps this surface stable needs no change in thumbs-embed.\n */\n\n// The default module URL lives apart so the startup chunk can fill in the\n// config default without carrying this loader.\nexport { DEFAULT_QUESTS_MODULE_URL } from \"./quest-config\";\nimport { DEFAULT_QUESTS_MODULE_URL, DEFAULT_QUESTS_MODULE_INTEGRITY } from \"./quest-config\";\nimport { trustedScriptUrl } from \"./trusted-types\";\n\n/** The bit of a QaidQuests instance we hold onto. */\nexport interface QuestInstance {\n destroy(): void;\n}\n\n/** The bit of QaidQuests config we pass. Mirrors QuestsConfig loosely. */\nexport interface LaunchedQuestConfig {\n endpoint: string;\n configUrl: string;\n /** The definition, when it was fetched ahead of time (wins over configUrl). */\n questionnaire?: unknown;\n apiKey?: string;\n /** A promise only when the loaded module says it accepts one. */\n metadata?: Record<string, unknown> | Promise<Record<string, unknown> | undefined>;\n onComplete?: (answers: Record<string, unknown>) => void;\n onClose?: () => void;\n}\n\ninterface QuestsConstructor {\n new (config: LaunchedQuestConfig): QuestInstance;\n /** quests-embed 1.7+: `asyncMetadata` means `metadata` may be a promise. */\n supports?: { asyncMetadata?: boolean };\n}\n\n/** Shape of the quests module's default/entry exports. */\nexport interface QuestsModule {\n QaidQuests: QuestsConstructor;\n}\n\ntype Importer = (url: string) => Promise<unknown>;\n\n/**\n * Fetch and run `url` as a module script carrying `integrity`, resolving once\n * it has run and rejecting when the browser refuses it (a hash mismatch, a\n * CSP block, a network error). A module runs once per URL per page: the\n * `import()` that follows gets this verified instance from the module map\n * instead of fetching the file again.\n *\n * Resolves `false`, without loading anything, when the tag can't be made at\n * all (a Trusted Types page that doesn't allow the `qaid-embed` policy); the\n * caller then imports the pinned URL without the hash check.\n */\nexport function preloadVerifiedModule(url: string, integrity: string): Promise<boolean> {\n return new Promise<boolean>((resolve, reject) => {\n const script = document.createElement(\"script\");\n script.type = \"module\";\n script.integrity = integrity;\n script.crossOrigin = \"anonymous\";\n try {\n script.src = trustedScriptUrl(url);\n } catch {\n console.warn(\"[thumbs-embed] Trusted Types refused the quests module; add `trusted-types qaid-embed` to the page's CSP to check its hash.\");\n resolve(false);\n return;\n }\n script.addEventListener(\"load\", () => {\n script.remove();\n resolve(true);\n });\n script.addEventListener(\"error\", () => {\n script.remove();\n reject(new Error(`quests module failed to load or failed its integrity check: ${url}`));\n });\n (document.head || document.documentElement).appendChild(script);\n });\n}\n\nconst defaultImporter: Importer = async (url) => {\n // The default URL's hash is known, so check it before the module runs.\n if (url === DEFAULT_QUESTS_MODULE_URL) {\n await preloadVerifiedModule(url, DEFAULT_QUESTS_MODULE_INTEGRITY);\n }\n // The URL is a runtime value, not a static specifier — keep Vite from\n // trying to analyze/bundle it.\n return import(/* @vite-ignore */ url);\n};\n\nlet importer: Importer = defaultImporter;\nlet modulePromise: Promise<QuestsModule> | null = null;\nlet cachedUrl: string | null = null;\n\n/** Quest definitions fetched ahead of a click, by definition URL. */\nconst definitions = new Map<string, unknown>();\nconst definitionLoads = new Map<string, Promise<void>>();\n\n/**\n * @internal Test seam: swap the dynamic importer and clear the cache.\n * Pass `null` to restore the real dynamic `import()`. Not re-exported\n * from the package entry, so it isn't public API.\n */\nexport function _setQuestsImporter(fn: Importer | null): void {\n importer = fn ?? defaultImporter;\n modulePromise = null;\n cachedUrl = null;\n definitions.clear();\n definitionLoads.clear();\n}\n\n/** Where the quest service serves a quest's live definition. */\nexport function questDefinitionUrl(base: string, questId: string): string {\n return `${base.replace(/\\/+$/, \"\")}/${encodeURIComponent(questId)}/definition`;\n}\n\n/**\n * Fetch a quest's definition before anyone clicks, so the quest opens from\n * memory. Never rejects: a failed fetch is forgotten, and the quests widget\n * then loads the definition itself, the way it did before this existed.\n */\nexport function prefetchQuestDefinition(url: string): Promise<void> {\n if (definitions.has(url)) return Promise.resolve();\n const pending = definitionLoads.get(url);\n if (pending) return pending;\n const load = fetch(url, { headers: { Accept: \"application/json\" } })\n .then((res) => (res.ok ? res.json() : null))\n .then((def: unknown) => {\n if (def) definitions.set(url, def);\n })\n .catch(() => {})\n .finally(() => {\n definitionLoads.delete(url);\n });\n definitionLoads.set(url, load);\n return load;\n}\n\n/**\n * Import the quests module, caching the promise per URL. A failed load\n * clears the cache so a later trigger can retry (e.g. after a transient\n * network error) rather than being stuck with a rejected promise.\n */\nexport function loadQuestsModule(moduleUrl: string): Promise<QuestsModule> {\n if (modulePromise && cachedUrl === moduleUrl) return modulePromise;\n cachedUrl = moduleUrl;\n modulePromise = Promise.resolve(importer(moduleUrl))\n .then((mod) => {\n const m = mod as Partial<QuestsModule>;\n if (!m || typeof m.QaidQuests !== \"function\") {\n throw new Error(\"quests module has no QaidQuests export\");\n }\n return m as QuestsModule;\n })\n .catch((err) => {\n modulePromise = null;\n cachedUrl = null;\n throw err;\n });\n return modulePromise;\n}\n\nexport interface LaunchQuestOptions {\n /** Quest id to launch (the `[id]` in `{base}/{id}/definition`). */\n questId: string;\n /** Quest-service base URL, e.g. \"https://qaid.dev/api/quests\". */\n base: string;\n /** API key for the quest service (optional). */\n apiKey?: string;\n /** ES-module URL to load the quests widget from. */\n moduleUrl: string;\n /**\n * Feedback record id to correlate the response with (optional). A promise\n * lets the quest open before the feedback POST has answered.\n */\n feedbackId?: string | number | null | Promise<string | number | null>;\n /** Called when the quest embed is torn down. */\n onClose?: () => void;\n}\n\n/**\n * Load the quests widget (if not already loaded) and open the given quest\n * as its own centered modal. Rejects if the module can't be loaded — the\n * caller should fall back to its normal UI.\n */\nexport async function launchQuest(opts: LaunchQuestOptions): Promise<QuestInstance> {\n const mod = await loadQuestsModule(opts.moduleUrl);\n const base = opts.base.replace(/\\/+$/, \"\");\n const configUrl = questDefinitionUrl(base, opts.questId);\n const toMetadata = (id: string | number | null): Record<string, unknown> | undefined =>\n id != null ? { feedbackId: id } : undefined;\n\n let metadata: LaunchedQuestConfig[\"metadata\"];\n const id = opts.feedbackId;\n if (id instanceof Promise) {\n // A quests build that takes a promise opens now and sends the id when it\n // lands. An older one (a pinned moduleUrl) would serialise the promise as\n // {} and lose the id, so for it we wait, as before.\n metadata = mod.QaidQuests.supports?.asyncMetadata\n ? id.then(toMetadata, () => undefined)\n : toMetadata(await id.catch(() => null));\n } else {\n metadata = toMetadata(id ?? null);\n }\n\n return new mod.QaidQuests({\n endpoint: `${base}/responses`,\n configUrl,\n // Only a definition already in hand. One still loading is left to the\n // widget, which shows its own loading state instead of nothing.\n questionnaire: definitions.get(configUrl),\n apiKey: opts.apiKey || undefined,\n metadata,\n onClose: opts.onClose,\n });\n}\n","/**\n * The feedback send flow — extracted from embed.ts into its own lazily-loaded\n * chunk. It runs only after a thumb click (or a targeted element), so it is\n * pre-warmed when the pointer or focus reaches the buttons, or on idle,\n * whichever comes first.\n *\n * It captures (and lets the visitor mark up) a screenshot when configured,\n * POSTs the feedback, then opens the linked quest or the message box. It talks\n * back to the embed through the narrow `SendHost` interface.\n */\n\nimport { launchQuest, type QuestInstance } from \"./quest-launcher\";\nimport type { ModalController } from \"./modal\";\nimport type {\n ResolvedFeedbackConfig,\n EmbedState,\n FeedbackData,\n SelectedBounds,\n FeedbackPayload,\n FeedbackResponse,\n} from \"./types\";\n\n/** The slice of the embed the send flow needs. */\nexport interface SendHost {\n readonly config: ResolvedFeedbackConfig;\n readonly visitorId: string;\n /** Live references, filled in by the click or the targeting controller. */\n readonly feedbackData: FeedbackData;\n readonly selectedBounds: SelectedBounds;\n readonly destroyed: boolean;\n readonly overlayShadowHost: HTMLDivElement | null;\n /** A quest launched from a button, so destroy() can tear it down. */\n activeQuest: QuestInstance | null;\n setState(state: EmbedState): void;\n /** Record the pending POST, which the message box's PATCHes wait on. */\n setFeedbackId(id: Promise<number | null>): void;\n shouldCaptureViaDom(): boolean;\n ensureOverlayHost(): ShadowRoot;\n ensureModal(): Promise<ModalController>;\n addFeatureStyles(css: string): void;\n applyVars(el: HTMLElement): void;\n announceMsg(message: string, assertive?: boolean): void;\n openDialogA11y(\n container: HTMLElement,\n opts: { labelledbyId?: string; describedbyId?: string; label?: string }\n ): void;\n closeDialogA11y(): void;\n resetFeedbackUi(): void;\n}\n\n/**\n * Open the full-screen annotation editor over the captured screenshot,\n * reusing the overlay shadow host and the shared dialog a11y helpers.\n * Resolves with the composited WebP data URL, or null when the user skips\n * (caller keeps the original). Pointer events on the overlay host are\n * enabled while the editor is open and restored on close.\n */\nexport async function openAnnotationEditor(\n host: SendHost,\n screenshot: string\n): Promise<string | null> {\n const root = host.ensureOverlayHost();\n const overlay = host.overlayShadowHost!;\n const prevPointerEvents = overlay.style.pointerEvents;\n overlay.style.pointerEvents = \"auto\";\n try {\n const { openAnnotationEditor, styles } = await import(\"./annotate\");\n host.addFeatureStyles(styles);\n return await openAnnotationEditor({\n dataUrl: screenshot,\n root,\n quality: host.config.screenshotOptions.quality,\n color: host.config.annotationColor,\n palette: host.config.annotationPalette,\n applyVars: (el) => host.applyVars(el),\n announce: (msg, assertive) => host.announceMsg(msg, assertive),\n openDialog: (container, opts) => host.openDialogA11y(container, opts),\n closeDialog: () => host.closeDialogA11y(),\n });\n } catch (err) {\n // The annotate chunk failed to load / the editor threw — keep the\n // original screenshot rather than aborting the whole submission.\n console.error(\"Annotation editor failed to open:\", err);\n return null;\n } finally {\n overlay.style.pointerEvents = prevPointerEvents;\n }\n}\n\n/** Capture, POST, then hand off to a linked quest or the message box. */\nexport async function submitFeedback(host: SendHost): Promise<void> {\n const { config, feedbackData, selectedBounds } = host;\n // Capture screenshot if enabled (server will gate by plan). \"annotate\" mode\n // always captures one to mark up, even without captureScreenshot set.\n let screenshot: string | null = null;\n const wantScreenshot = config.captureScreenshot || config.feedbackMode === \"annotate\";\n if (wantScreenshot) {\n // Loaded on demand so visitors who never submit a screenshot never\n // download the capture + annotation code. A capture failure (denied\n // permission, chunk load error) must never abort the feedback — we just\n // submit without a screenshot so the user still reaches the modal.\n try {\n if (host.shouldCaptureViaDom()) {\n const { captureDomScreenshot } = await import(\"./screenshot-dom\");\n screenshot = await captureDomScreenshot(config.screenshotOptions);\n } else {\n const { captureScreenshot } = await import(\"./screenshot\");\n screenshot = await captureScreenshot(config.screenshotOptions);\n }\n if (screenshot) host.announceMsg(\"Screenshot captured\");\n } catch (err) {\n console.error(\"Screenshot capture failed:\", err);\n screenshot = null;\n }\n }\n\n // Let the user mark up / redact the screenshot before it is submitted.\n // The message modal only opens after the POST below, so the composited\n // result lands in the same request — no backend change needed. On skip\n // the editor resolves null and the original screenshot is kept.\n if (screenshot && config.annotate) {\n screenshot = (await openAnnotationEditor(host, screenshot)) ?? screenshot;\n }\n\n // Include element bounds for server-side screenshot fallback\n // Only include if we have an element selector (element was targeted)\n const elementBounds = feedbackData.elementSelector\n ? {\n x: selectedBounds.x,\n y: selectedBounds.y,\n width: selectedBounds.width,\n height: selectedBounds.height,\n }\n : null;\n\n const payload: FeedbackPayload = {\n feedbackType: feedbackData.feedbackType!,\n pageUrl: window.location.href,\n apiKey: config.apiKey || undefined,\n elementSelector: feedbackData.elementSelector,\n elementText: feedbackData.elementText,\n consoleErrors: [...feedbackData.consoleErrors],\n screenWidth: window.innerWidth,\n screenHeight: window.innerHeight,\n clickX: selectedBounds.clickX,\n clickY: selectedBounds.clickY,\n scrollX: window.scrollX,\n scrollY: window.scrollY,\n screenshot,\n visitorId: host.visitorId,\n // Include element bounds and user agent for server-side screenshot fallback\n elementBounds,\n userAgent: navigator.userAgent,\n };\n\n // The POST goes out in the background. The message box or linked quest\n // opens now instead of a server round trip later; what needs the new\n // record's id (the message PATCH, the quest's link back) waits on this.\n const feedbackId = postFeedback(host, payload);\n host.setFeedbackId(feedbackId);\n\n // If this button is linked to a quest, launch it in place of the\n // message box, handing it the pending id. On success we just tear down\n // the targeting UI and hand off. On any load failure we fall through to\n // the classic message box so the user can still leave an optional message.\n const type = feedbackData.feedbackType;\n // Quest links are keyed by up/down/video; neutral single-button feedback\n // has no quest mapping, so it always falls through to the message box.\n if (type && type !== \"neutral\" && (await tryLaunchQuest(host, type, feedbackId))) {\n host.resetFeedbackUi();\n return;\n }\n\n // Always show the message modal as the terminal state (even if the API\n // failed — useful for demos).\n host.setState(\"MODAL_OPEN\");\n try {\n // The modal chunk loads async; bail if the embed was destroyed meanwhile,\n // so a raced modal never opens (and never leaks a listener) post-destroy.\n const modal = await host.ensureModal();\n if (host.destroyed) return;\n modal.open();\n\n // Enable pointer events on overlay host for modal\n if (host.overlayShadowHost) {\n host.overlayShadowHost.style.pointerEvents = \"auto\";\n }\n } catch (err) {\n // The modal chunk failed to load/open. Never leave the user stuck in a\n // re-targetable limbo: thank them and reset to IDLE so a fresh click\n // starts a clean flow (the feedback itself was already POSTed above).\n console.error(\"Failed to open the feedback modal:\", err);\n host.announceMsg(\"Thank you for your feedback!\", true);\n host.resetFeedbackUi();\n }\n}\n\n/** POST the feedback. Resolves to the new record's id, or null if it failed. */\nasync function postFeedback(host: SendHost, payload: FeedbackPayload): Promise<number | null> {\n try {\n const response = await fetch(host.config.endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n });\n\n if (response.ok) {\n const data: FeedbackResponse = await response.json();\n host.announceMsg(\"Feedback sent\");\n return data.id;\n }\n } catch (error) {\n console.error(\"Failed to submit feedback:\", error);\n host.announceMsg(\"Failed to send feedback\", true);\n }\n return null;\n}\n\n/**\n * Launch the quest linked to `type`, if any. Resolves `true` when a quest\n * was configured and the widget launched; `false` when no quest is\n * configured (quest launching off: no `base`, or this button has no quest)\n * or the widget failed to load (caller falls back to its normal UI). The\n * created feedback record id is passed through so the quest response can be\n * joined back to it server-side.\n */\nexport async function tryLaunchQuest(\n host: SendHost,\n type: \"up\" | \"down\" | \"video\",\n feedbackId: number | string | null | Promise<number | string | null>,\n): Promise<boolean> {\n const q = host.config.quests;\n const questId = q.base ? q[type] || \"\" : \"\";\n if (!questId) return false;\n try {\n host.activeQuest?.destroy();\n host.activeQuest = await launchQuest({\n questId,\n base: q.base,\n apiKey: q.apiKey || undefined,\n moduleUrl: q.moduleUrl,\n feedbackId,\n onClose: () => {\n host.activeQuest = null;\n },\n });\n return true;\n } catch (error) {\n console.error(\"Failed to launch quest:\", error);\n host.activeQuest = null;\n return false;\n }\n}\n"],"names":["FOCUSABLE_SELECTOR","isDisabled","el","isHidden","node","style","getFocusable","container","getDeepActiveElement","doc","active","createFocusTrap","addedTabindex","onKeydown","event","focusable","first","last","withinTrap","initial","saveFocus","restoreFocus","applyDialog","opts","topLevelAncestor","body","parent","setBackgroundInert","except","keep","changed","child","prevInert","prevAriaHidden","entry","openDialog","trigger","trap","restoreInert","preloadVerifiedModule","url","integrity","resolve","reject","script","trustedScriptUrl","defaultImporter","DEFAULT_QUESTS_MODULE_URL","DEFAULT_QUESTS_MODULE_INTEGRITY","importer","modulePromise","cachedUrl","definitions","definitionLoads","_setQuestsImporter","fn","questDefinitionUrl","base","questId","prefetchQuestDefinition","pending","load","res","def","loadQuestsModule","moduleUrl","mod","m","err","launchQuest","configUrl","toMetadata","id","metadata","openAnnotationEditor","host","screenshot","root","overlay","prevPointerEvents","styles","msg","assertive","submitFeedback","config","feedbackData","selectedBounds","captureDomScreenshot","captureScreenshot","elementBounds","payload","feedbackId","postFeedback","type","tryLaunchQuest","modal","response","data","error","q"],"mappings":"qDA8BA,MAAMA,EAAqB,CACzB,UACA,SACA,QACA,WACA,SACA,YACF,EAAE,KAAK,GAAG,EAEV,SAASC,EAAWC,EAA0B,CAC5C,OAAIA,EAAG,aAAa,UAAU,EAAU,GACxBA,EACD,WAAa,EAC9B,CAEA,SAASC,EAASD,EAA0B,CAC1C,IAAIE,EAA2BF,EAC/B,KAAOE,GAAM,CACX,GAAIA,EAAK,aAAa,QAAQ,EAAG,MAAO,GACxC,MAAMC,EAAQD,EAAK,MACnB,GACEC,IACCA,EAAM,UAAY,QACjBA,EAAM,aAAe,UACrBA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A,QAAS,IAAM,CACbhB,EAAK,YAAc,IACrB,CAAA,CACD,EACM,EACT,OAASuB,EAAO,CACd,eAAQ,MAAM,0BAA2BA,CAAK,EAC9CvB,EAAK,YAAc,KACZ,EACT,CACF"}
@@ -1,6 +1,2 @@
1
- import{g as k,e as q,i as m}from"./core-BsR7oV99.js";const T=["data-comp","data-qa","data-testid","data-id"];function E(i,t=document.body){let e=i;for(;e&&e!==t;){for(const r of T){const o=e.getAttribute(r);if(o)return`${r}="${o}"`}e=e.parentElement}return null}function S(i,t=100){const e=i.textContent?.trim().slice(0,t)||"";return e.length===t?e+"...":e}function w(i){let t=1,e=i.previousElementSibling;for(;e;)t++,e=e.previousElementSibling;return t}function L(i){const t=[];let e=i;for(;e&&e!==document.body&&e!==document.documentElement;){const r=e.tagName.toLowerCase(),o=w(e);t.unshift(`${r}:nth-child(${o})`),e=e.parentElement}return t.length>0?`body > ${t.join(" > ")}`:"body"}function A(i){return i.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function P(i){const t=E(i);return t?`[${t}]`:i.id?`#${A(i.id)}`:L(i)}function y(i){const t=S(i),e=E(i);return{selector:P(i),text:t,dataAttr:e}}const $=["a[href]","button","input:not([type=hidden])","select","textarea","summary","[tabindex]","[role]","img","h1","h2","h3","h4","h5","h6","p","li","label",...T.map(i=>`[${i}]`)].join(","),D=/^(?:A|BUTTON|INPUT|SELECT|TEXTAREA|SUMMARY)$/;function B(i){if(i.hasAttribute("hidden")||i.getAttribute("aria-hidden")==="true")return!1;const t=i.ownerDocument?.defaultView;if(t&&typeof t.getComputedStyle=="function"){const e=t.getComputedStyle(i);if(e.display==="none"||e.visibility==="hidden")return!1}return!0}function H(i={}){const t=i.root??document.body,e=i.selector??$,r=i.isExcluded??(()=>!1),o=i.isVisible??B;return Array.from(t.querySelectorAll(e)).filter(a=>!r(a)&&o(a))}function V(i){const t=i.candidates??H({root:i.root,selector:i.selector,isExcluded:i.isExcluded,isVisible:i.isVisible}),e=i.moveFocus??!0,r=i.eventTarget??document,o=new Set;let a=-1,n=!1;const h=i.initial!==void 0?i.initial:typeof document<"u"?document.activeElement:null;if(h){const s=t.indexOf(h);s>=0&&(a=s)}a<0&&t.length>0&&(a=0);function C(s){if(!e)return;const d=s;if(typeof d.focus=="function"){s.getAttribute("tabindex")===null&&!D.test(s.tagName)&&(s.setAttribute("tabindex","-1"),o.add(s));try{d.focus()}catch{}}}function v(){const s=t[a];s&&(C(s),i.onHighlight?.(s,a))}function l(s){if(n||t.length===0)return;const d=t.length;a=(s%d+d)%d,v()}function c(){l(a+1)}function u(){l(a-1)}function b(){return t[a]??null}function p(){n||(n=!0,r.removeEventListener("keydown",g,!0),o.forEach(s=>s.removeAttribute("tabindex")),o.clear())}function f(){if(n)return;const s=b();p(),s&&i.onSelect(s)}function x(){n||(p(),i.onCancel?.())}function g(s){if(!n)switch(s.key){case"Tab":s.preventDefault(),s.stopPropagation(),s.shiftKey?u():c();break;case"ArrowDown":case"ArrowRight":s.preventDefault(),s.stopPropagation(),c();break;case"ArrowUp":case"ArrowLeft":s.preventDefault(),s.stopPropagation(),u();break;case"Enter":case" ":case"Spacebar":s.preventDefault(),s.stopPropagation(),f();break;case"Escape":case"Esc":s.preventDefault(),s.stopPropagation(),x();break}}return r.addEventListener("keydown",g,!0),a>=0&&v(),{candidates:t,getIndex:()=>a,getCurrent:b,next:c,prev:u,moveTo:l,select:f,cancel:x,handleKey:g,stop:p}}const M=".qaid-targeting-overlay{position:fixed;inset:0;z-index:40;pointer-events:none}.qaid-capture-layer{position:fixed;inset:0;pointer-events:none;z-index:9999}.qaid-vignette{position:fixed;inset:0;pointer-events:none;background:radial-gradient(ellipse at center,transparent 30%,rgba(0,0,0,.3) 70%,rgba(0,0,0,.6) 100%);z-index:41}.qaid-crosshair-h,.qaid-crosshair-v{position:fixed;pointer-events:none;z-index:42}.qaid-crosshair-h{left:0;right:0;height:1px;background:color-mix(in srgb,var(--qaid-negative) 60%,transparent)}.qaid-crosshair-v{top:0;bottom:0;width:1px;background:color-mix(in srgb,var(--qaid-negative) 60%,transparent)}.qaid-type-up .qaid-crosshair-h,.qaid-type-up .qaid-crosshair-v{background:color-mix(in srgb,var(--qaid-positive) 60%,transparent)}.qaid-highlight-box{position:fixed;top:0;left:0;pointer-events:none;z-index:41;display:none;border:3px solid color-mix(in srgb,var(--qaid-negative) 80%,transparent);border-radius:2px;background:color-mix(in srgb,var(--qaid-negative) 8%,transparent);will-change:transform,width,height}.qaid-type-up .qaid-highlight-box{border-color:color-mix(in srgb,var(--qaid-positive) 80%,transparent);background:color-mix(in srgb,var(--qaid-positive) 8%,transparent)}.qaid-scope{position:fixed;width:80px;height:80px;pointer-events:none;z-index:43;transform:translate(-50%,-50%)}.qaid-scope-ring{position:absolute;inset:10px;border:2px solid color-mix(in srgb,var(--qaid-negative) 80%,transparent);border-radius:50%}.qaid-type-up .qaid-scope-ring{border-color:color-mix(in srgb,var(--qaid-positive) 80%,transparent)}.qaid-scope-ring-inner{position:absolute;inset:20px;border:1px solid color-mix(in srgb,var(--qaid-negative) 50%,transparent);border-radius:50%}.qaid-type-up .qaid-scope-ring-inner{border-color:color-mix(in srgb,var(--qaid-positive) 50%,transparent)}.qaid-scope-dot{position:absolute;top:50%;left:50%;width:4px;height:4px;background:var(--qaid-negative);border-radius:50%;transform:translate(-50%,-50%)}.qaid-type-up .qaid-scope-dot{background:var(--qaid-positive)}.qaid-selected-marker{position:fixed;border:3px solid var(--qaid-marker, #6365f1);border-radius:50%;pointer-events:none;z-index:44;animation:qaid-markerPulse 1.5s ease-in-out infinite}@keyframes qaid-markerPulse{0%,to{opacity:1;transform:scale(1)}50%{opacity:.7;transform:scale(1.05)}}@media(forced-colors:active){.qaid-selected-marker,.qaid-highlight-box{border-color:Highlight}}",N=12;class O{constructor(t){this.host=t}host;mousePos={x:0,y:0};touchStartPos=null;overlayContainer=null;captureLayer=null;crosshairH=null;crosshairV=null;scope=null;highlightBox=null;marker=null;keyboardController=null;boundMouseMove=t=>this.handleMouseMove(t);boundClick=t=>this.handleClick(t);boundTouchStart=t=>this.handleTouchStart(t);boundTouchEnd=t=>this.handleTouchEnd(t);startPointer(t,e){this.host.setState("TARGETING"),this.host.feedbackData.feedbackType=t,this.host.feedbackData.elementSelector=null,this.host.feedbackData.elementText=null,this.host.selectedBounds.visible=!1,this.mousePos.x=e.clientX,this.mousePos.y=e.clientY,document.body.classList.add("qaid-targeting"),t==="up"?document.body.classList.add("qaid-type-up"):document.body.classList.remove("qaid-type-up"),document.body.style.setProperty("--qaid-positive",this.host.cssVars["--qaid-positive"]),document.body.style.setProperty("--qaid-negative",this.host.cssVars["--qaid-negative"]),this.createTargetingOverlay(),document.addEventListener("keydown",this.host.boundKeyDown),document.addEventListener("mousemove",this.boundMouseMove),document.addEventListener("click",this.boundClick,!0),document.addEventListener("touchstart",this.boundTouchStart,{passive:!0}),document.addEventListener("touchend",this.boundTouchEnd,{passive:!1})}startKeyboard(t){this.host.setState("TARGETING"),this.host.feedbackData.feedbackType=t,this.host.feedbackData.elementSelector=null,this.host.feedbackData.elementText=null,this.host.selectedBounds.visible=!1,document.body.style.setProperty("--qaid-positive",this.host.cssVars["--qaid-positive"]),document.body.style.setProperty("--qaid-negative",this.host.cssVars["--qaid-negative"]),this.createTargetingOverlay(),this.crosshairH&&(this.crosshairH.style.display="none"),this.crosshairV&&(this.crosshairV.style.display="none"),this.scope&&(this.scope.style.display="none"),this.keyboardController=V({isExcluded:e=>m(e),onHighlight:e=>{const r=e.getBoundingClientRect(),o=this.highlightBox;o&&(o.style.transform=`translate(${r.left}px, ${r.top}px)`,o.style.width=`${r.width}px`,o.style.height=`${r.height}px`,o.style.display="block");const{text:a}=y(e);this.host.announceMsg(`Targeting ${a||e.tagName.toLowerCase()}`)},onSelect:e=>this.selectKeyboardTarget(e),onCancel:()=>this.cancel()})}selectKeyboardTarget(t){const e=k(t,8);Object.assign(this.host.selectedBounds,e,{clickX:e.x+e.width/2,clickY:e.y+e.height/2,visible:!0});const{selector:r,text:o}=y(t);this.host.feedbackData.elementSelector=r,this.host.feedbackData.elementText=o,this.removeTargetingOverlay(),document.body.classList.remove("qaid-targeting","qaid-type-up"),document.body.style.removeProperty("--qaid-positive"),document.body.style.removeProperty("--qaid-negative"),this.keyboardController=null,this.host.clearActiveThumb(),this.host.setState("SELECTED"),this.showSelectedMarker(),this.host.submitFeedback()}createTargetingOverlay(){const t=this.host.ensureOverlayHost();this.overlayContainer=document.createElement("div"),this.overlayContainer.className=`qaid-targeting-overlay qaid-type-${this.host.feedbackData.feedbackType}`,this.captureLayer=document.createElement("div"),this.captureLayer.className="qaid-capture-layer";const e=document.createElement("div");e.className="qaid-vignette",this.crosshairH=document.createElement("div"),this.crosshairH.className="qaid-crosshair-h",this.crosshairV=document.createElement("div"),this.crosshairV.className="qaid-crosshair-v",this.scope=document.createElement("div"),this.scope.className="qaid-scope",this.scope.innerHTML=`
2
- <div class="qaid-scope-ring"></div>
3
- <div class="qaid-scope-ring-inner"></div>
4
- <div class="qaid-scope-dot"></div>
5
- `,this.highlightBox=document.createElement("div"),this.highlightBox.className="qaid-highlight-box",this.overlayContainer.appendChild(this.captureLayer),this.overlayContainer.appendChild(e),this.overlayContainer.appendChild(this.highlightBox),this.overlayContainer.appendChild(this.crosshairH),this.overlayContainer.appendChild(this.crosshairV),this.overlayContainer.appendChild(this.scope),this.crosshairH.style.top=`${this.mousePos.y}px`,this.crosshairV.style.left=`${this.mousePos.x}px`,this.scope.style.left=`${this.mousePos.x}px`,this.scope.style.top=`${this.mousePos.y}px`,this.host.applyVars(this.overlayContainer),t.appendChild(this.overlayContainer)}handleMouseMove(t){this.updateReticleAt(t.clientX,t.clientY)}updateReticleAt(t,e){if(this.mousePos.x=t,this.mousePos.y=e,this.crosshairH&&(this.crosshairH.style.top=`${e}px`),this.crosshairV&&(this.crosshairV.style.left=`${t}px`),this.scope&&(this.scope.style.left=`${t}px`,this.scope.style.top=`${e}px`),this.captureLayer&&this.host.shadowHost){const r=[this.host.shadowHost,this.host.overlayShadowHost].filter(Boolean),o=q(t,e,r);if(o&&!m(o)){if(this.highlightBox){const a=o.getBoundingClientRect();this.highlightBox.style.transform=`translate(${a.left}px, ${a.top}px)`,this.highlightBox.style.width=`${a.width}px`,this.highlightBox.style.height=`${a.height}px`,this.highlightBox.style.display="block"}}else this.highlightBox&&(this.highlightBox.style.display="none")}}handleClick(t){t.preventDefault(),t.stopPropagation(),this.selectAt(t.clientX,t.clientY)}handleTouchStart(t){const e=t.touches[0];e&&(this.touchStartPos={x:e.clientX,y:e.clientY},this.updateReticleAt(e.clientX,e.clientY))}handleTouchEnd(t){const e=t.changedTouches[0],r=this.touchStartPos;this.touchStartPos=null,!(!e||!r||Math.hypot(e.clientX-r.x,e.clientY-r.y)>N)&&(t.preventDefault(),this.selectAt(e.clientX,e.clientY))}selectAt(t,e){const r=[this.host.shadowHost,this.host.overlayShadowHost].filter(Boolean),o=q(t,e,r);if(!o||m(o))return;const a=k(o,8);Object.assign(this.host.selectedBounds,a,{clickX:t,clickY:e,visible:!0});const{selector:n,text:h}=y(o);this.host.feedbackData.elementSelector=n,this.host.feedbackData.elementText=h,this.stopTargetingListeners(),document.body.classList.remove("qaid-targeting","qaid-type-up"),document.body.style.removeProperty("--qaid-positive"),document.body.style.removeProperty("--qaid-negative"),this.host.setState("SELECTED"),this.host.clearActiveThumb(),this.showSelectedMarker(),this.host.submitFeedback()}stopTargetingListeners(){this.removeTargetingOverlay(),this.touchStartPos=null,document.removeEventListener("mousemove",this.boundMouseMove),document.removeEventListener("click",this.boundClick,!0),document.removeEventListener("touchstart",this.boundTouchStart),document.removeEventListener("touchend",this.boundTouchEnd),document.removeEventListener("keydown",this.host.boundKeyDown)}cancel(){this.keyboardController?.stop(),this.keyboardController=null,this.stopTargetingListeners(),document.body.classList.remove("qaid-targeting","qaid-type-up"),document.body.style.removeProperty("--qaid-positive"),document.body.style.removeProperty("--qaid-negative"),this.host.clearActiveThumb(),this.host.setState("IDLE"),this.host.feedbackData.feedbackType=null,this.host.feedbackData.elementSelector=null,this.host.feedbackData.elementText=null,this.host.selectedBounds.visible=!1}removeTargetingOverlay(){this.overlayContainer&&(this.overlayContainer.remove(),this.overlayContainer=null),this.captureLayer=null,this.crosshairH=null,this.crosshairV=null,this.scope=null}showSelectedMarker(){const t=this.host.ensureOverlayHost();this.marker=document.createElement("div"),this.marker.className="qaid-selected-marker",this.marker.style.left=`${this.host.selectedBounds.x}px`,this.marker.style.top=`${this.host.selectedBounds.y}px`,this.marker.style.width=`${this.host.selectedBounds.width}px`,this.marker.style.height=`${this.host.selectedBounds.height}px`,this.marker.style.zIndex=String(this.host.config.zIndex+1),this.host.applyVars(this.marker),t.appendChild(this.marker)}hideMarker(){this.marker&&(this.marker.remove(),this.marker=null)}destroy(){this.keyboardController?.stop(),this.keyboardController=null,this.stopTargetingListeners(),this.hideMarker()}}const R=M;export{O as TargetingController,R as styles};
6
- //# sourceMappingURL=targeting-CMUEe-7C.js.map
1
+ import{g as k,f as q,h as m}from"./core-vu1EieDc.js";const E=["data-comp","data-qa","data-testid","data-id"];function T(i,t=document.body){let e=i;for(;e&&e!==t;){for(const r of E){const o=e.getAttribute(r);if(o)return`${r}="${o}"`}e=e.parentElement}return null}function S(i,t=100){const e=i.textContent?.trim().slice(0,t)||"";return e.length===t?e+"...":e}function w(i){let t=1,e=i.previousElementSibling;for(;e;)t++,e=e.previousElementSibling;return t}function A(i){const t=[];let e=i;for(;e&&e!==document.body&&e!==document.documentElement;){const r=e.tagName.toLowerCase(),o=w(e);t.unshift(`${r}:nth-child(${o})`),e=e.parentElement}return t.length>0?`body > ${t.join(" > ")}`:"body"}function L(i){return i.replace(/([!"#$%&'()*+,./:;<=>?@[\\\]^`{|}~])/g,"\\$1")}function P(i){const t=T(i);return t?`[${t}]`:i.id?`#${L(i.id)}`:A(i)}function y(i){const t=S(i),e=T(i);return{selector:P(i),text:t,dataAttr:e}}const $=["a[href]","button","input:not([type=hidden])","select","textarea","summary","[tabindex]","[role]","img","h1","h2","h3","h4","h5","h6","p","li","label",...E.map(i=>`[${i}]`)].join(","),D=/^(?:A|BUTTON|INPUT|SELECT|TEXTAREA|SUMMARY)$/;function B(i){if(i.hasAttribute("hidden")||i.getAttribute("aria-hidden")==="true")return!1;const t=i.ownerDocument?.defaultView;if(t&&typeof t.getComputedStyle=="function"){const e=t.getComputedStyle(i);if(e.display==="none"||e.visibility==="hidden")return!1}return!0}function V(i={}){const t=i.root??document.body,e=i.selector??$,r=i.isExcluded??(()=>!1),o=i.isVisible??B;return Array.from(t.querySelectorAll(e)).filter(a=>!r(a)&&o(a))}function H(i){const t=i.candidates??V({root:i.root,selector:i.selector,isExcluded:i.isExcluded,isVisible:i.isVisible}),e=i.moveFocus??!0,r=i.eventTarget??document,o=new Set;let a=-1,n=!1;const h=i.initial!==void 0?i.initial:typeof document<"u"?document.activeElement:null;if(h){const s=t.indexOf(h);s>=0&&(a=s)}a<0&&t.length>0&&(a=0);function C(s){if(!e)return;const d=s;if(typeof d.focus=="function"){s.getAttribute("tabindex")===null&&!D.test(s.tagName)&&(s.setAttribute("tabindex","-1"),o.add(s));try{d.focus()}catch{}}}function b(){const s=t[a];s&&(C(s),i.onHighlight?.(s,a))}function l(s){if(n||t.length===0)return;const d=t.length;a=(s%d+d)%d,b()}function c(){l(a+1)}function u(){l(a-1)}function v(){return t[a]??null}function p(){n||(n=!0,r.removeEventListener("keydown",g,!0),o.forEach(s=>s.removeAttribute("tabindex")),o.clear())}function f(){if(n)return;const s=v();p(),s&&i.onSelect(s)}function x(){n||(p(),i.onCancel?.())}function g(s){if(!n)switch(s.key){case"Tab":s.preventDefault(),s.stopPropagation(),s.shiftKey?u():c();break;case"ArrowDown":case"ArrowRight":s.preventDefault(),s.stopPropagation(),c();break;case"ArrowUp":case"ArrowLeft":s.preventDefault(),s.stopPropagation(),u();break;case"Enter":case" ":case"Spacebar":s.preventDefault(),s.stopPropagation(),f();break;case"Escape":case"Esc":s.preventDefault(),s.stopPropagation(),x();break}}return r.addEventListener("keydown",g,!0),a>=0&&b(),{candidates:t,getIndex:()=>a,getCurrent:v,next:c,prev:u,moveTo:l,select:f,cancel:x,handleKey:g,stop:p}}const M=".qaid-targeting-overlay{position:fixed;inset:0;z-index:40;pointer-events:none}.qaid-capture-layer{position:fixed;inset:0;pointer-events:none;z-index:9999}.qaid-vignette{position:fixed;inset:0;pointer-events:none;background:radial-gradient(ellipse at center,transparent 30%,rgba(0,0,0,.3) 70%,rgba(0,0,0,.6) 100%);z-index:41}.qaid-crosshair-h,.qaid-crosshair-v{position:fixed;pointer-events:none;z-index:42}.qaid-crosshair-h{left:0;right:0;height:1px;background:color-mix(in srgb,var(--qaid-negative) 60%,transparent)}.qaid-crosshair-v{top:0;bottom:0;width:1px;background:color-mix(in srgb,var(--qaid-negative) 60%,transparent)}.qaid-type-up .qaid-crosshair-h,.qaid-type-up .qaid-crosshair-v{background:color-mix(in srgb,var(--qaid-positive) 60%,transparent)}.qaid-highlight-box{position:fixed;top:0;left:0;pointer-events:none;z-index:41;display:none;border:3px solid color-mix(in srgb,var(--qaid-negative) 80%,transparent);border-radius:2px;background:color-mix(in srgb,var(--qaid-negative) 8%,transparent);will-change:transform,width,height}.qaid-type-up .qaid-highlight-box{border-color:color-mix(in srgb,var(--qaid-positive) 80%,transparent);background:color-mix(in srgb,var(--qaid-positive) 8%,transparent)}.qaid-scope{position:fixed;width:80px;height:80px;pointer-events:none;z-index:43;transform:translate(-50%,-50%)}.qaid-scope-ring{position:absolute;inset:10px;border:2px solid color-mix(in srgb,var(--qaid-negative) 80%,transparent);border-radius:50%}.qaid-type-up .qaid-scope-ring{border-color:color-mix(in srgb,var(--qaid-positive) 80%,transparent)}.qaid-scope-ring-inner{position:absolute;inset:20px;border:1px solid color-mix(in srgb,var(--qaid-negative) 50%,transparent);border-radius:50%}.qaid-type-up .qaid-scope-ring-inner{border-color:color-mix(in srgb,var(--qaid-positive) 50%,transparent)}.qaid-scope-dot{position:absolute;top:50%;left:50%;width:4px;height:4px;background:var(--qaid-negative);border-radius:50%;transform:translate(-50%,-50%)}.qaid-type-up .qaid-scope-dot{background:var(--qaid-positive)}.qaid-selected-marker{position:fixed;border:3px solid var(--qaid-marker, #6365f1);border-radius:50%;pointer-events:none;z-index:44;animation:qaid-markerPulse 1.5s ease-in-out infinite}@keyframes qaid-markerPulse{0%,to{opacity:1;transform:scale(1)}50%{opacity:.7;transform:scale(1.05)}}@media(forced-colors:active){.qaid-selected-marker,.qaid-highlight-box{border-color:Highlight}}",N=12;class O{constructor(t){this.host=t}host;mousePos={x:0,y:0};touchStartPos=null;overlayContainer=null;captureLayer=null;crosshairH=null;crosshairV=null;scope=null;highlightBox=null;marker=null;keyboardController=null;boundMouseMove=t=>this.handleMouseMove(t);boundClick=t=>this.handleClick(t);boundTouchStart=t=>this.handleTouchStart(t);boundTouchEnd=t=>this.handleTouchEnd(t);startPointer(t,e){this.host.setState("TARGETING"),this.host.feedbackData.feedbackType=t,this.host.feedbackData.elementSelector=null,this.host.feedbackData.elementText=null,this.host.selectedBounds.visible=!1,this.mousePos.x=e.clientX,this.mousePos.y=e.clientY,document.body.classList.add("qaid-targeting"),t==="up"?document.body.classList.add("qaid-type-up"):document.body.classList.remove("qaid-type-up"),document.body.style.setProperty("--qaid-positive",this.host.cssVars["--qaid-positive"]),document.body.style.setProperty("--qaid-negative",this.host.cssVars["--qaid-negative"]),this.createTargetingOverlay(),document.addEventListener("keydown",this.host.boundKeyDown),document.addEventListener("mousemove",this.boundMouseMove),document.addEventListener("click",this.boundClick,!0),document.addEventListener("touchstart",this.boundTouchStart,{passive:!0}),document.addEventListener("touchend",this.boundTouchEnd,{passive:!1})}startKeyboard(t){this.host.setState("TARGETING"),this.host.feedbackData.feedbackType=t,this.host.feedbackData.elementSelector=null,this.host.feedbackData.elementText=null,this.host.selectedBounds.visible=!1,document.body.style.setProperty("--qaid-positive",this.host.cssVars["--qaid-positive"]),document.body.style.setProperty("--qaid-negative",this.host.cssVars["--qaid-negative"]),this.createTargetingOverlay(),this.crosshairH&&(this.crosshairH.style.display="none"),this.crosshairV&&(this.crosshairV.style.display="none"),this.scope&&(this.scope.style.display="none"),this.keyboardController=H({isExcluded:e=>m(e),onHighlight:e=>{const r=e.getBoundingClientRect(),o=this.highlightBox;o&&(o.style.transform=`translate(${r.left}px, ${r.top}px)`,o.style.width=`${r.width}px`,o.style.height=`${r.height}px`,o.style.display="block");const{text:a}=y(e);this.host.announceMsg(`Targeting ${a||e.tagName.toLowerCase()}`)},onSelect:e=>this.selectKeyboardTarget(e),onCancel:()=>this.cancel()})}selectKeyboardTarget(t){const e=k(t,8);Object.assign(this.host.selectedBounds,e,{clickX:e.x+e.width/2,clickY:e.y+e.height/2,visible:!0});const{selector:r,text:o}=y(t);this.host.feedbackData.elementSelector=r,this.host.feedbackData.elementText=o,this.removeTargetingOverlay(),document.body.classList.remove("qaid-targeting","qaid-type-up"),document.body.style.removeProperty("--qaid-positive"),document.body.style.removeProperty("--qaid-negative"),this.keyboardController=null,this.host.clearActiveThumb(),this.host.setState("SELECTED"),this.showSelectedMarker(),this.host.submitFeedback()}createTargetingOverlay(){const t=this.host.ensureOverlayHost();this.overlayContainer=document.createElement("div"),this.overlayContainer.className=`qaid-targeting-overlay qaid-type-${this.host.feedbackData.feedbackType}`,this.captureLayer=document.createElement("div"),this.captureLayer.className="qaid-capture-layer";const e=document.createElement("div");e.className="qaid-vignette",this.crosshairH=document.createElement("div"),this.crosshairH.className="qaid-crosshair-h",this.crosshairV=document.createElement("div"),this.crosshairV.className="qaid-crosshair-v",this.scope=document.createElement("div"),this.scope.className="qaid-scope";for(const r of["qaid-scope-ring","qaid-scope-ring-inner","qaid-scope-dot"]){const o=document.createElement("div");o.className=r,this.scope.appendChild(o)}this.highlightBox=document.createElement("div"),this.highlightBox.className="qaid-highlight-box",this.overlayContainer.appendChild(this.captureLayer),this.overlayContainer.appendChild(e),this.overlayContainer.appendChild(this.highlightBox),this.overlayContainer.appendChild(this.crosshairH),this.overlayContainer.appendChild(this.crosshairV),this.overlayContainer.appendChild(this.scope),this.crosshairH.style.top=`${this.mousePos.y}px`,this.crosshairV.style.left=`${this.mousePos.x}px`,this.scope.style.left=`${this.mousePos.x}px`,this.scope.style.top=`${this.mousePos.y}px`,this.host.applyVars(this.overlayContainer),t.appendChild(this.overlayContainer)}handleMouseMove(t){this.updateReticleAt(t.clientX,t.clientY)}updateReticleAt(t,e){if(this.mousePos.x=t,this.mousePos.y=e,this.crosshairH&&(this.crosshairH.style.top=`${e}px`),this.crosshairV&&(this.crosshairV.style.left=`${t}px`),this.scope&&(this.scope.style.left=`${t}px`,this.scope.style.top=`${e}px`),this.captureLayer&&this.host.shadowHost){const r=[this.host.shadowHost,this.host.overlayShadowHost].filter(Boolean),o=q(t,e,r);if(o&&!m(o)){if(this.highlightBox){const a=o.getBoundingClientRect();this.highlightBox.style.transform=`translate(${a.left}px, ${a.top}px)`,this.highlightBox.style.width=`${a.width}px`,this.highlightBox.style.height=`${a.height}px`,this.highlightBox.style.display="block"}}else this.highlightBox&&(this.highlightBox.style.display="none")}}handleClick(t){t.preventDefault(),t.stopPropagation(),this.selectAt(t.clientX,t.clientY)}handleTouchStart(t){const e=t.touches[0];e&&(this.touchStartPos={x:e.clientX,y:e.clientY},this.updateReticleAt(e.clientX,e.clientY))}handleTouchEnd(t){const e=t.changedTouches[0],r=this.touchStartPos;this.touchStartPos=null,!(!e||!r||Math.hypot(e.clientX-r.x,e.clientY-r.y)>N)&&(t.preventDefault(),this.selectAt(e.clientX,e.clientY))}selectAt(t,e){const r=[this.host.shadowHost,this.host.overlayShadowHost].filter(Boolean),o=q(t,e,r);if(!o||m(o))return;const a=k(o,8);Object.assign(this.host.selectedBounds,a,{clickX:t,clickY:e,visible:!0});const{selector:n,text:h}=y(o);this.host.feedbackData.elementSelector=n,this.host.feedbackData.elementText=h,this.stopTargetingListeners(),document.body.classList.remove("qaid-targeting","qaid-type-up"),document.body.style.removeProperty("--qaid-positive"),document.body.style.removeProperty("--qaid-negative"),this.host.setState("SELECTED"),this.host.clearActiveThumb(),this.showSelectedMarker(),this.host.submitFeedback()}stopTargetingListeners(){this.removeTargetingOverlay(),this.touchStartPos=null,document.removeEventListener("mousemove",this.boundMouseMove),document.removeEventListener("click",this.boundClick,!0),document.removeEventListener("touchstart",this.boundTouchStart),document.removeEventListener("touchend",this.boundTouchEnd),document.removeEventListener("keydown",this.host.boundKeyDown)}cancel(){this.keyboardController?.stop(),this.keyboardController=null,this.stopTargetingListeners(),document.body.classList.remove("qaid-targeting","qaid-type-up"),document.body.style.removeProperty("--qaid-positive"),document.body.style.removeProperty("--qaid-negative"),this.host.clearActiveThumb(),this.host.setState("IDLE"),this.host.feedbackData.feedbackType=null,this.host.feedbackData.elementSelector=null,this.host.feedbackData.elementText=null,this.host.selectedBounds.visible=!1}removeTargetingOverlay(){this.overlayContainer&&(this.overlayContainer.remove(),this.overlayContainer=null),this.captureLayer=null,this.crosshairH=null,this.crosshairV=null,this.scope=null}showSelectedMarker(){const t=this.host.ensureOverlayHost();this.marker=document.createElement("div"),this.marker.className="qaid-selected-marker",this.marker.style.left=`${this.host.selectedBounds.x}px`,this.marker.style.top=`${this.host.selectedBounds.y}px`,this.marker.style.width=`${this.host.selectedBounds.width}px`,this.marker.style.height=`${this.host.selectedBounds.height}px`,this.marker.style.zIndex=String(this.host.config.zIndex+1),this.host.applyVars(this.marker),t.appendChild(this.marker)}hideMarker(){this.marker&&(this.marker.remove(),this.marker=null)}destroy(){this.keyboardController?.stop(),this.keyboardController=null,this.stopTargetingListeners(),this.hideMarker()}}const R=M;export{O as TargetingController,R as styles};
2
+ //# sourceMappingURL=targeting-Bpbt68Pp.js.map