@aceshooting/lyra-ui 11.1.0 → 11.2.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 (101) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +8 -0
  3. package/custom-elements.json +1 -1
  4. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  5. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  6. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  7. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  8. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  9. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  10. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  11. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  12. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  13. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  14. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  15. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +1 -0
  16. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  17. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
  18. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  19. package/dist/components/charts/chart/bar-chart.class.js +1 -1
  20. package/dist/components/charts/chart/bubble-chart.class.js +1 -1
  21. package/dist/components/charts/chart/chart.class.js +1 -1
  22. package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
  23. package/dist/components/charts/chart/histogram.class.js +1 -1
  24. package/dist/components/charts/chart/line-chart.class.js +1 -1
  25. package/dist/components/charts/chart/pie-chart.class.js +1 -1
  26. package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
  27. package/dist/components/charts/chart/radar-chart.class.js +1 -1
  28. package/dist/components/charts/chart/scatter-chart.class.js +1 -1
  29. package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
  30. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  31. package/dist/components/conversation/model-select/model-select.class.d.ts +1 -0
  32. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  33. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  34. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +1 -0
  35. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  36. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +1 -0
  37. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  38. package/dist/components/data/heatmap/heatmap.class.d.ts +36 -1
  39. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  40. package/dist/components/data/table/table.class.js +1 -1
  41. package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -0
  42. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  43. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +1 -0
  44. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  45. package/dist/components/forms/combobox/combobox.class.d.ts +1 -0
  46. package/dist/components/forms/combobox/combobox.class.js +1 -1
  47. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +1 -0
  48. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  49. package/dist/components/forms/radio/radio-group.class.d.ts +1 -0
  50. package/dist/components/forms/radio/radio-group.class.js +1 -1
  51. package/dist/components/forms/radio/radio.class.d.ts +1 -0
  52. package/dist/components/forms/radio/radio.class.js +1 -1
  53. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -0
  54. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  55. package/dist/components/forms/select/select.class.d.ts +1 -0
  56. package/dist/components/forms/select/select.class.js +1 -1
  57. package/dist/components/forms/slider/slider.class.d.ts +1 -0
  58. package/dist/components/forms/slider/slider.class.js +1 -1
  59. package/dist/components/forms/switch/switch.class.d.ts +1 -0
  60. package/dist/components/forms/switch/switch.class.js +1 -1
  61. package/dist/components/forms/time-range/time-range.class.d.ts +1 -0
  62. package/dist/components/forms/time-range/time-range.class.js +1 -1
  63. package/dist/components/forms/token-input/token-input.class.d.ts +1 -0
  64. package/dist/components/forms/token-input/token-input.class.js +1 -1
  65. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  66. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  67. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  68. package/dist/components/media/file-input/file-input.class.d.ts +1 -0
  69. package/dist/components/media/file-input/file-input.class.js +1 -1
  70. package/dist/components/media/flag/flag-peer-bulk.d.ts +12 -0
  71. package/dist/components/media/flag/flag-peer-bulk.js +1 -0
  72. package/dist/components/media/flag/flag.class.d.ts +28 -0
  73. package/dist/components/media/flag/flag.class.js +2 -2
  74. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  75. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  76. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  77. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  78. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  79. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  80. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  81. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  82. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  83. package/dist/custom-elements-jsx.d.ts +1 -1
  84. package/dist/events.d.ts +7 -0
  85. package/dist/internal/form-associated.d.ts +1 -0
  86. package/dist/internal/form-associated.js +1 -1
  87. package/dist/internal/form-control-labels.js +1 -1
  88. package/dist/internal/lyra-element.js +1 -1
  89. package/dist/internal/package-metadata.d.ts +1 -1
  90. package/dist/internal/package-metadata.js +1 -1
  91. package/dist/lyra.d.ts +1 -1
  92. package/dist/svelte.d.ts +1 -1
  93. package/dist/vue.d.ts +1 -1
  94. package/llms/components/lr-flag.md +24 -1
  95. package/llms/components/lr-heatmap.md +16 -4
  96. package/llms/peers.md +2 -2
  97. package/llms/shared.md +19 -0
  98. package/llms-full.txt +61 -5
  99. package/package.json +6 -6
  100. package/vscode-html-data.json +1 -1
  101. package/web-types.json +2 -2
@@ -1 +1 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{boundedSelectionRects,boundedSelectionText,buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/attachment-chip.class.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=100*1024*1024;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);function archiveSelectionRange(viewer,contentRoot){const document=viewer.ownerDocument,view=document.defaultView,nestedRoot=contentRoot.getRootNode(),outerRoot=viewer.shadowRoot,ShadowRootCtor=view?.ShadowRoot,shadowRoots=[outerRoot,nestedRoot].filter((root,index,roots)=>ShadowRootCtor!==void 0&&root instanceof ShadowRootCtor&&roots.indexOf(root)===index),globalSelection=view?.getSelection();if(globalSelection?.getComposedRanges){const[composed]=globalSelection.getComposedRanges({shadowRoots});if(composed&&(composed.startContainer!==composed.endContainer||composed.startOffset!==composed.endOffset)){const range=document.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}}const selection=nestedRoot.getSelection?.()??globalSelection??null;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)}class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.archiveSearchMatches=[],this.archiveSearchActiveIndex=-1,this.archiveSearchMatchCountExact=!0,this.generation=0,this.archiveSearchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.archiveSelectionRoot=null,this.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=item=>item.name,this.announcements=new ViewerAnnouncementController(this),this.renderEntry=item=>{const entry=item,kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){return this.archiveSearchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.recomputeArchiveSearch(),await this.updateComplete,this.scrollActiveArchiveMatch(),this.archiveSearchMatches.length}async searchNext(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}async searchPrevious(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}clearSearch(){this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.emitArchiveSearchChange()}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.archiveSearchQuery!==""||this.archiveSearchMatches.length>0||!this.archiveSearchMatchCountExact||this.archiveSearchActiveIndex!==-1,this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.fetchState=this.src?{kind:"loading"}:{kind:"idle"})}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),this.syncArchiveNestedRoot(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitArchiveSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.archiveSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.archiveSearchQuery)},"search")}}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return!1;const loadGeneration=this.generation;let index=-1,resolvedName;if(anchor.kind==="fragment")index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id),resolvedName=this.fetchState.entries[index]?.name;else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span"),workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(let candidateIndex=0;candidateIndex<this.fetchState.entries.length;candidateIndex++){const entry=this.fetchState.entries[candidateIndex],buildCost=Math.max(1,entry.name.length);if(buildCost>workBudget.remainingCodeUnits)break;if(workBudget.remainingCodeUnits-=buildCost,probe.textContent=entry.name,createTextQuoteIndex(scopeFromElement(probe),this.effectiveLocale).resolve(anchor,workBudget)){index=candidateIndex;break}}}if(index<0)return!1;const list=this.archiveVirtualList();if(!list||(list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.waitForArchiveRow(list,index))||(this.requestUpdate(),await this.updateComplete,loadGeneration!==this.generation||this.fetchState.kind!=="loaded"))return!1;if(anchor.kind==="fragment"){const root=this.textContentRoot(),target=root?Array.from(root.querySelectorAll('[part~="entry-name"]')).find(el=>el.textContent===resolvedName):null;return target?.scrollIntoView?.({block:"nearest",behavior:"auto"}),target!=null}return ArchiveTextViewerTargetBase.prototype.applyAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;return(node.nodeType===elementNode?node:node.parentElement)?.closest('[part~="entry-name"]')??null},start=entryName(range.startContainer),end=entryName(range.endContainer);return!start||start!==end?null:buildQuoteAnchor(range,scopeFromElement(start))}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(!this.isConnected||generation!==this.generation)return;const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const metadata=assertZipArchiveMetadataWithinLimits(buffer,{description:"ZIP",maxEntries:MAX_ARCHIVE_ENTRIES,maxUncompressedBytes:MAX_ARCHIVE_UNCOMPRESSED_BYTES,signal});if(!this.isConnected||generation!==this.generation)return;const entries=metadata.entries.map(({name,dir,uncompressedBytes})=>({name,dir,size:uncompressedBytes}));this.fetchState={kind:"loaded",entries},this.archiveSearchQuery&&this.recomputeArchiveSearch()}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation(),!this.archiveNestedUpdatePending&&(this.archiveNestedUpdatePending=!0,queueMicrotask(()=>{this.archiveNestedUpdatePending=!1,this.isConnected&&this.requestUpdate()}))}archiveVirtualList(){return this.renderRoot.querySelector("lr-virtual-list")}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){if(await list.updateComplete,list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return!0;if(!view)return!1;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return!1}syncArchiveNestedRoot(){const root=this.textContentRoot();if(root!==this.archiveSelectionRoot&&(this.unbindTextSelection(),this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=root,root)){const emitSelection=()=>{const range=archiveSelectionRange(this,root);if(!range||!root.contains(range.startContainer)||!root.contains(range.endContainer))return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};root.addEventListener("pointerup",emitSelection),root.addEventListener("keyup",emitSelection),this.archiveSelectionCleanup=()=>{root.removeEventListener("pointerup",emitSelection),root.removeEventListener("keyup",emitSelection)}}const listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot)if(listRoot.querySelector("style[data-lr-archive-highlight-styles]"))this.styledVirtualListRoot=listRoot;else{const style=this.ownerDocument.createElement("style");style.dataset.lrArchiveHighlightStyles="",style.textContent=virtualListHighlightStyles.cssText,listRoot.append(style),this.styledVirtualListRoot=listRoot}if(root)for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]"))mark.hasAttribute("part")||mark.setAttribute("part","highlight")}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[],boundedQuery=boundedViewerSearchQuery(this.archiveSearchQuery,this.effectiveLocale),query=boundedQuery.needle,matches=[],budget=new ViewerSearchWorkBudget;if(boundedQuery.accepted&&query){for(const entry of entries)if(budget.includes(entry.name,query,this.effectiveLocale)&&matches.push(entry),!budget.complete)break}this.archiveSearchMatches=matches,this.archiveSearchMatchCountExact=boundedQuery.accepted&&budget.complete,this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1,this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,matchCountExact:this.archiveSearchMatchCountExact,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match),list=this.renderRoot.querySelector("lr-virtual-list");index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeItemId=${this.archiveSearchMatches[this.archiveSearchActiveIndex]?.name??""} @lr-visible-range-change=${this.stopVirtualListEvent} @lr-virtual-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;case"loading":return renderViewerLoading(this.localize("loadingDocument"));case"error":return html`<div part="error">${this.fetchState.message}</div>`;default:return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`}}render(){const label=viewerSemanticLabel(this,this.name||null),role=label===null?null:viewerSemanticRole(this,"region"),maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${role??nothing} aria-label=${label??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-archive-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0),__decorate([property()],LyraArchiveViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraArchiveViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{boundedSelectionRects,boundedSelectionText,buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/attachment-chip.class.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=100*1024*1024;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);function archiveSelectionRange(viewer,contentRoot){const document=viewer.ownerDocument,view=document.defaultView,nestedRoot=contentRoot.getRootNode(),outerRoot=viewer.shadowRoot,ShadowRootCtor=view?.ShadowRoot,shadowRoots=[outerRoot,nestedRoot].filter((root,index,roots)=>ShadowRootCtor!==void 0&&root instanceof ShadowRootCtor&&roots.indexOf(root)===index),globalSelection=view?.getSelection();if(globalSelection?.getComposedRanges){const[composed]=globalSelection.getComposedRanges({shadowRoots});if(composed&&(composed.startContainer!==composed.endContainer||composed.startOffset!==composed.endOffset)){const range=document.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}}const selection=nestedRoot.getSelection?.()??globalSelection??null;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)}class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.archiveSearchMatches=[],this.archiveSearchActiveIndex=-1,this.archiveSearchMatchCountExact=!0,this.generation=0,this.archiveSearchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.archiveSelectionRoot=null,this.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=item=>item.name,this.announcements=new ViewerAnnouncementController(this),this.renderEntry=item=>{const entry=item,kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){return this.archiveSearchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.recomputeArchiveSearch(),await this.updateComplete,this.scrollActiveArchiveMatch(),this.archiveSearchMatches.length}async searchNext(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}async searchPrevious(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}clearSearch(){this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.emitArchiveSearchChange()}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.archiveSearchQuery!==""||this.archiveSearchMatches.length>0||!this.archiveSearchMatchCountExact||this.archiveSearchActiveIndex!==-1,this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.fetchState=this.src?{kind:"loading"}:{kind:"idle"})}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),this.syncArchiveNestedRoot(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitArchiveSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.archiveSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.archiveSearchQuery)},"search")}}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return!1;const loadGeneration=this.generation;let index=-1,resolvedName;if(anchor.kind==="fragment")index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id),resolvedName=this.fetchState.entries[index]?.name;else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span"),workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(let candidateIndex=0;candidateIndex<this.fetchState.entries.length;candidateIndex++){const entry=this.fetchState.entries[candidateIndex],buildCost=Math.max(1,entry.name.length);if(buildCost>workBudget.remainingCodeUnits)break;if(workBudget.remainingCodeUnits-=buildCost,probe.textContent=entry.name,createTextQuoteIndex(scopeFromElement(probe),this.effectiveLocale).resolve(anchor,workBudget)){index=candidateIndex;break}}}if(index<0)return!1;const list=this.archiveVirtualList();if(!list||(list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.waitForArchiveRow(list,index))||(this.requestUpdate(),await this.updateComplete,loadGeneration!==this.generation||this.fetchState.kind!=="loaded"))return!1;if(anchor.kind==="fragment"){const root=this.textContentRoot(),target=root?Array.from(root.querySelectorAll('[part~="entry-name"]')).find(el=>el.textContent===resolvedName):null;return target?.scrollIntoView?.({block:"nearest",behavior:"auto"}),target!=null}return ArchiveTextViewerTargetBase.prototype.applyAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;return(node.nodeType===elementNode?node:node.parentElement)?.closest('[part~="entry-name"]')??null},start=entryName(range.startContainer),end=entryName(range.endContainer);return!start||start!==end?null:buildQuoteAnchor(range,scopeFromElement(start))}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(!this.isConnected||generation!==this.generation)return;const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const metadata=assertZipArchiveMetadataWithinLimits(buffer,{description:"ZIP",maxEntries:MAX_ARCHIVE_ENTRIES,maxUncompressedBytes:MAX_ARCHIVE_UNCOMPRESSED_BYTES,signal});if(!this.isConnected||generation!==this.generation)return;const entries=metadata.entries.map(({name,dir,uncompressedBytes})=>({name,dir,size:uncompressedBytes}));this.fetchState={kind:"loaded",entries},this.archiveSearchQuery&&this.recomputeArchiveSearch()}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation(),!this.archiveNestedUpdatePending&&(this.archiveNestedUpdatePending=!0,queueMicrotask(()=>{this.archiveNestedUpdatePending=!1,this.isConnected&&this.requestUpdate()}))}archiveVirtualList(){return this.renderRoot.querySelector("lr-virtual-list")}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){if(await list.updateComplete,list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return!0;if(!view)return!1;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return!1}syncArchiveNestedRoot(){const root=this.textContentRoot();if(root!==this.archiveSelectionRoot&&(this.unbindTextSelection(),this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=root,root)){const emitSelection=()=>{const range=archiveSelectionRange(this,root);if(!range||!root.contains(range.startContainer)||!root.contains(range.endContainer))return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};root.addEventListener("pointerup",emitSelection),root.addEventListener("keyup",emitSelection),this.archiveSelectionCleanup=()=>{root.removeEventListener("pointerup",emitSelection),root.removeEventListener("keyup",emitSelection)}}const listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot)if(listRoot.querySelector("style[data-lr-archive-highlight-styles]"))this.styledVirtualListRoot=listRoot;else{const style=this.ownerDocument.createElement("style");style.dataset.lrArchiveHighlightStyles="",style.textContent=virtualListHighlightStyles.cssText,listRoot.append(style),this.styledVirtualListRoot=listRoot}if(root)for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]"))mark.hasAttribute("part")||mark.setAttribute("part","highlight")}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[],boundedQuery=boundedViewerSearchQuery(this.archiveSearchQuery,this.effectiveLocale),query=boundedQuery.needle,matches=[],budget=new ViewerSearchWorkBudget;if(boundedQuery.accepted&&query){for(const entry of entries)if(budget.includes(entry.name,query,this.effectiveLocale)&&matches.push(entry),!budget.complete)break}this.archiveSearchMatches=matches,this.archiveSearchMatchCountExact=boundedQuery.accepted&&budget.complete,this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1,this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,matchCountExact:this.archiveSearchMatchCountExact,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match),list=this.renderRoot.querySelector("lr-virtual-list");index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeItemId=${this.archiveSearchMatches[this.archiveSearchActiveIndex]?.name??""} @lr-visible-range-change=${this.stopVirtualListEvent} @lr-virtual-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;case"loading":return renderViewerLoading(this.localize("loadingDocument"));case"error":return html`<div part="error">${this.fetchState.message}</div>`;default:return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`}}render(){const label=viewerSemanticLabel(this,this.name||null),role=label===null?null:viewerSemanticRole(this,"region"),maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${role??nothing} aria-label=${label??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-archive-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0),__decorate([property()],LyraArchiveViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraArchiveViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{getListFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{parseVCards}from"./vcard.js";import{styles}from"./contact-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_contactViewerAddressFormat,LYRA_DEFAULT_contactViewerAddressLabel,LYRA_DEFAULT_contactViewerEmailLabel,LYRA_DEFAULT_contactViewerLabel,LYRA_DEFAULT_contactViewerNoContacts,LYRA_DEFAULT_contactViewerOrganization,LYRA_DEFAULT_contactViewerPhoneLabel,LYRA_DEFAULT_contactViewerTypeCell,LYRA_DEFAULT_contactViewerTypeFax,LYRA_DEFAULT_contactViewerTypeHome,LYRA_DEFAULT_contactViewerTypeInternet,LYRA_DEFAULT_contactViewerTypePreferred,LYRA_DEFAULT_contactViewerTypeVoice,LYRA_DEFAULT_contactViewerTypeWork,LYRA_DEFAULT_contactViewerTypedValue,LYRA_DEFAULT_contactViewerUnnamedContact,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeContact,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraContactViewerBase extends LyraElement{}class LyraContactViewer extends TextViewerTarget(LyraContactViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.headingLevel="3",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this)}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,contactViewerAddressFormat:LYRA_DEFAULT_contactViewerAddressFormat,contactViewerAddressLabel:LYRA_DEFAULT_contactViewerAddressLabel,contactViewerEmailLabel:LYRA_DEFAULT_contactViewerEmailLabel,contactViewerLabel:LYRA_DEFAULT_contactViewerLabel,contactViewerNoContacts:LYRA_DEFAULT_contactViewerNoContacts,contactViewerOrganization:LYRA_DEFAULT_contactViewerOrganization,contactViewerPhoneLabel:LYRA_DEFAULT_contactViewerPhoneLabel,contactViewerTypeCell:LYRA_DEFAULT_contactViewerTypeCell,contactViewerTypeFax:LYRA_DEFAULT_contactViewerTypeFax,contactViewerTypeHome:LYRA_DEFAULT_contactViewerTypeHome,contactViewerTypeInternet:LYRA_DEFAULT_contactViewerTypeInternet,contactViewerTypePreferred:LYRA_DEFAULT_contactViewerTypePreferred,contactViewerTypeVoice:LYRA_DEFAULT_contactViewerTypeVoice,contactViewerTypeWork:LYRA_DEFAULT_contactViewerTypeWork,contactViewerTypedValue:LYRA_DEFAULT_contactViewerTypedValue,contactViewerUnnamedContact:LYRA_DEFAULT_contactViewerUnnamedContact,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeContact:LYRA_DEFAULT_documentPreviewTypeContact,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){this.lastLoadSrc=this.src;const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const contacts=parseVCards(source);generation===this.generation&&(this.fetchState=contacts.length?{kind:"loaded",contacts}:{kind:"empty"})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}formatList(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(values)}formatAddress(address){return this.localize("contactViewerAddressFormat",void 0,{poBox:address.poBox,extendedAddress:address.extendedAddress,streetAddress:address.streetAddress,locality:address.locality,region:address.region,postalCode:address.postalCode,country:address.country}).split(/\r\n|\r|\n/).map(line=>line.replace(/\s+/g," ").trim()).filter(Boolean).join(`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{getListFormat}from"../../../internal/intl-cache.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{parseVCards}from"./vcard.js";import{styles}from"./contact-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_contactViewerAddressFormat,LYRA_DEFAULT_contactViewerAddressLabel,LYRA_DEFAULT_contactViewerEmailLabel,LYRA_DEFAULT_contactViewerLabel,LYRA_DEFAULT_contactViewerNoContacts,LYRA_DEFAULT_contactViewerOrganization,LYRA_DEFAULT_contactViewerPhoneLabel,LYRA_DEFAULT_contactViewerTypeCell,LYRA_DEFAULT_contactViewerTypeFax,LYRA_DEFAULT_contactViewerTypeHome,LYRA_DEFAULT_contactViewerTypeInternet,LYRA_DEFAULT_contactViewerTypePreferred,LYRA_DEFAULT_contactViewerTypeVoice,LYRA_DEFAULT_contactViewerTypeWork,LYRA_DEFAULT_contactViewerTypedValue,LYRA_DEFAULT_contactViewerUnnamedContact,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeContact,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";class LyraContactViewerBase extends LyraElement{}class LyraContactViewer extends TextViewerTarget(LyraContactViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.headingLevel="3",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this)}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,contactViewerAddressFormat:LYRA_DEFAULT_contactViewerAddressFormat,contactViewerAddressLabel:LYRA_DEFAULT_contactViewerAddressLabel,contactViewerEmailLabel:LYRA_DEFAULT_contactViewerEmailLabel,contactViewerLabel:LYRA_DEFAULT_contactViewerLabel,contactViewerNoContacts:LYRA_DEFAULT_contactViewerNoContacts,contactViewerOrganization:LYRA_DEFAULT_contactViewerOrganization,contactViewerPhoneLabel:LYRA_DEFAULT_contactViewerPhoneLabel,contactViewerTypeCell:LYRA_DEFAULT_contactViewerTypeCell,contactViewerTypeFax:LYRA_DEFAULT_contactViewerTypeFax,contactViewerTypeHome:LYRA_DEFAULT_contactViewerTypeHome,contactViewerTypeInternet:LYRA_DEFAULT_contactViewerTypeInternet,contactViewerTypePreferred:LYRA_DEFAULT_contactViewerTypePreferred,contactViewerTypeVoice:LYRA_DEFAULT_contactViewerTypeVoice,contactViewerTypeWork:LYRA_DEFAULT_contactViewerTypeWork,contactViewerTypedValue:LYRA_DEFAULT_contactViewerTypedValue,contactViewerUnnamedContact:LYRA_DEFAULT_contactViewerUnnamedContact,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeContact:LYRA_DEFAULT_documentPreviewTypeContact,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){this.lastLoadSrc=this.src;const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const contacts=parseVCards(source);generation===this.generation&&(this.fetchState=contacts.length?{kind:"loaded",contacts}:{kind:"empty"})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}formatList(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(values)}formatAddress(address){return this.localize("contactViewerAddressFormat",void 0,{poBox:address.poBox,extendedAddress:address.extendedAddress,streetAddress:address.streetAddress,locality:address.locality,region:address.region,postalCode:address.postalCode,country:address.country}).split(/\r\n|\r|\n/).map(line=>line.replace(/\s+/g," ").trim()).filter(Boolean).join(`
2
2
  `)}formatType(type){const key={home:"contactViewerTypeHome",work:"contactViewerTypeWork",cell:"contactViewerTypeCell",voice:"contactViewerTypeVoice",fax:"contactViewerTypeFax",internet:"contactViewerTypeInternet",pref:"contactViewerTypePreferred",preferred:"contactViewerTypePreferred"}[type.toLowerCase()];return key?this.localize(key):type}formatTypedValue(value,types){return types.length?this.localize("contactViewerTypedValue",void 0,{value,types:this.formatList(types.map(type=>this.formatType(type)))}):value}renderContact(contact){const headingLevel=resolveHeadingLevel(this.headingLevel);return html`<article part="contact">
3
3
  <div
4
4
  part="contact-name"
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{styles}from"./document-compare.styles.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentCompareLabel,LYRA_DEFAULT_documentCompareNewVersion,LYRA_DEFAULT_documentCompareNoVersion,LYRA_DEFAULT_documentCompareOldVersion,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const DOCUMENT_COMPARE_VIEW=literalSetConverter(["diff","side-by-side"],"diff"),DOCUMENT_COMPARE_DIFF_LAYOUT=literalSetConverter(["unified","split"],"unified");function versionSourceIdentity(version){return version?JSON.stringify([version.id??"",version.uri??"",version.version??"",version.mimeType??"",version.name??""]):""}class LyraDocumentCompare extends LyraElement{constructor(){super(...arguments),this._view="diff",this._diffLayout="unified",this.copyable=!1,this.language="",this.syncScroll=!0,this.anchor=null,this.suppressSync=!1,this.onPaneScroll=source=>()=>{if(!this.syncScroll||this.suppressSync)return;const from=source==="old"?this.paneOldEl:this.paneNewEl,to=source==="old"?this.paneNewEl:this.paneOldEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const fraction=from.scrollTop/fromMax;this.suppressSync=!0,to.scrollTop=fraction*toMax,this.scheduleSyncRelease()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentCompareLabel:LYRA_DEFAULT_documentCompareLabel,documentCompareNewVersion:LYRA_DEFAULT_documentCompareNewVersion,documentCompareNoVersion:LYRA_DEFAULT_documentCompareNoVersion,documentCompareOldVersion:LYRA_DEFAULT_documentCompareOldVersion,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get view(){return this._view}set view(next){const normalized=DOCUMENT_COMPARE_VIEW.normalizeReflected(this,"view",next),old=this._view;old!==normalized&&(this._view=normalized,this.requestUpdate("view",old))}get diffLayout(){return this._diffLayout}set diffLayout(next){const normalized=DOCUMENT_COMPARE_DIFF_LAYOUT.normalizeReflected(this,"diff-layout",next),old=this._diffLayout;old!==normalized&&(this._diffLayout=normalized,this.requestUpdate("diffLayout",old))}disconnectedCallback(){this.cancelSyncRelease(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelSyncRelease()}cancelSyncRelease(){this.syncReleaseFrame!==void 0&&this.syncReleaseView?.cancelAnimationFrame(this.syncReleaseFrame),this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1}scheduleSyncRelease(){const view=this.ownerDocument.defaultView;if(!view){this.suppressSync=!1;return}const frame=view.requestAnimationFrame(()=>{this.syncReleaseView!==view||this.syncReleaseFrame!==frame||(this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1)});this.syncReleaseView=view,this.syncReleaseFrame=frame}updated(changed){super.updated(changed);const anchor=this.anchor,sourceChanged=property2=>changed.has(property2)&&versionSourceIdentity(changed.get(property2))!==versionSourceIdentity(this[property2]),oldSourceChanged=sourceChanged("oldVersion"),newSourceChanged=sourceChanged("newVersion");if(anchor!=null){(changed.has("anchor")||this.view==="side-by-side"&&(changed.has("view")||changed.has("oldVersion")||changed.has("newVersion")))&&(this.previewOldEl?.scrollToAnchor(anchor),this.previewNewEl?.scrollToAnchor(anchor));return}this.view!=="side-by-side"||!oldSourceChanged&&!newSourceChanged||(this.cancelSyncRelease(),(this.syncScroll||oldSourceChanged)&&this.paneOldEl&&(this.paneOldEl.scrollTop=0),(this.syncScroll||newSourceChanged)&&this.paneNewEl&&(this.paneNewEl.scrollTop=0))}onHighlightActivate(side,event){const{highlightId}=event.detail,otherPreview=side==="old"?this.previewNewEl:this.previewOldEl;otherPreview?.highlights.some(highlight=>highlight.id===highlightId)&&otherPreview?.scrollToAnchor(highlightId)}versionLabel(version,fallbackKey){return version?.name||version?.version||this.localize(fallbackKey)}renderDiff(){return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{literalSetConverter,trueDefaultBooleanConverter}from"../../../internal/converters.js";import{styles}from"./document-compare.styles.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentCompareLabel,LYRA_DEFAULT_documentCompareNewVersion,LYRA_DEFAULT_documentCompareNoVersion,LYRA_DEFAULT_documentCompareOldVersion,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const DOCUMENT_COMPARE_VIEW=literalSetConverter(["diff","side-by-side"],"diff"),DOCUMENT_COMPARE_DIFF_LAYOUT=literalSetConverter(["unified","split"],"unified");function versionSourceIdentity(version){return version?JSON.stringify([version.id??"",version.uri??"",version.version??"",version.mimeType??"",version.name??""]):""}class LyraDocumentCompare extends LyraElement{constructor(){super(...arguments),this._view="diff",this._diffLayout="unified",this.copyable=!1,this.language="",this.syncScroll=!0,this.anchor=null,this.suppressSync=!1,this.onPaneScroll=source=>()=>{if(!this.syncScroll||this.suppressSync)return;const from=source==="old"?this.paneOldEl:this.paneNewEl,to=source==="old"?this.paneNewEl:this.paneOldEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const fraction=from.scrollTop/fromMax;this.suppressSync=!0,to.scrollTop=fraction*toMax,this.scheduleSyncRelease()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentCompareLabel:LYRA_DEFAULT_documentCompareLabel,documentCompareNewVersion:LYRA_DEFAULT_documentCompareNewVersion,documentCompareNoVersion:LYRA_DEFAULT_documentCompareNoVersion,documentCompareOldVersion:LYRA_DEFAULT_documentCompareOldVersion,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get view(){return this._view}set view(next){const normalized=DOCUMENT_COMPARE_VIEW.normalizeReflected(this,"view",next),old=this._view;old!==normalized&&(this._view=normalized,this.requestUpdate("view",old))}get diffLayout(){return this._diffLayout}set diffLayout(next){const normalized=DOCUMENT_COMPARE_DIFF_LAYOUT.normalizeReflected(this,"diff-layout",next),old=this._diffLayout;old!==normalized&&(this._diffLayout=normalized,this.requestUpdate("diffLayout",old))}disconnectedCallback(){this.cancelSyncRelease(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelSyncRelease()}cancelSyncRelease(){this.syncReleaseFrame!==void 0&&this.syncReleaseView?.cancelAnimationFrame(this.syncReleaseFrame),this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1}scheduleSyncRelease(){const view=this.ownerDocument.defaultView;if(!view){this.suppressSync=!1;return}const frame=view.requestAnimationFrame(()=>{this.syncReleaseView!==view||this.syncReleaseFrame!==frame||(this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1)});this.syncReleaseView=view,this.syncReleaseFrame=frame}updated(changed){super.updated(changed);const anchor=this.anchor,sourceChanged=property2=>changed.has(property2)&&versionSourceIdentity(changed.get(property2))!==versionSourceIdentity(this[property2]),oldSourceChanged=sourceChanged("oldVersion"),newSourceChanged=sourceChanged("newVersion");if(anchor!=null){(changed.has("anchor")||this.view==="side-by-side"&&(changed.has("view")||changed.has("oldVersion")||changed.has("newVersion")))&&(this.previewOldEl?.scrollToAnchor(anchor),this.previewNewEl?.scrollToAnchor(anchor));return}this.view!=="side-by-side"||!oldSourceChanged&&!newSourceChanged||(this.cancelSyncRelease(),(this.syncScroll||oldSourceChanged)&&this.paneOldEl&&(this.paneOldEl.scrollTop=0),(this.syncScroll||newSourceChanged)&&this.paneNewEl&&(this.paneNewEl.scrollTop=0))}onHighlightActivate(side,event){const{highlightId}=event.detail,otherPreview=side==="old"?this.previewNewEl:this.previewOldEl;otherPreview?.highlights.some(highlight=>highlight.id===highlightId)&&otherPreview?.scrollToAnchor(highlightId)}versionLabel(version,fallbackKey){return version?.name||version?.version||this.localize(fallbackKey)}renderDiff(){return html`
2
2
  <lr-diff-view
3
3
  part="diff"
4
4
  .oldText=${this.oldVersion?.text??""}
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{createRef,ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{Announcer}from"../../../internal/announcer.js";import{announceSearchResult}from"../../../internal/viewer-search.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{getEpubJs}from"./ebook-loader.js";import{assertEpubArchiveWithinLimits}from"./epub-resource-guard.js";import{styles}from"./ebook-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget,VIEWER_SEARCH_QUERY_LIMIT}from"../viewer-search-limits.js";import{boundedSelectionRects,boundedSelectionText}from"../../../internal/text-quote.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_ebookViewerLoadError,LYRA_DEFAULT_ebookViewerNextChapter,LYRA_DEFAULT_ebookViewerPreviousChapter,LYRA_DEFAULT_ebookViewerRegionLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_previous,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";const MAX_TOC_ITEMS=1e4,MAX_TOC_DEPTH=100,MAX_SEARCH_MATCHES=1e4,MAX_SEARCH_SPINE_ITEMS=1e3,MAX_PAINTED_HIGHLIGHTS=100,TONE_FILL_TOKEN={accent:{token:"--lr-color-brand-quiet",fallback:"#ddf4ff"},success:{token:"--lr-color-success-quiet",fallback:"#dafbe1"},warning:{token:"--lr-color-warning-quiet",fallback:"#fff8c5"},danger:{token:"--lr-color-danger-quiet",fallback:"#ffebe9"},neutral:{token:"--lr-color-surface-raised",fallback:"#f6f8fa"}},SEARCH_MATCH_FILL_TOKEN={token:"--lr-color-warning",fallback:"#9a6700"},ACTIVE_HIGHLIGHT_STROKE_TOKEN={token:"--lr-focus-ring-color",fallback:"#0969da"};class LyraEbookViewerBase extends LyraElement{}class LyraEbookViewer extends DocumentAnchorTarget(LyraEbookViewerBase){static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,ebookViewerLoadError:LYRA_DEFAULT_ebookViewerLoadError,ebookViewerNextChapter:LYRA_DEFAULT_ebookViewerNextChapter,ebookViewerPreviousChapter:LYRA_DEFAULT_ebookViewerPreviousChapter,ebookViewerRegionLabel:LYRA_DEFAULT_ebookViewerRegionLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,previous:LYRA_DEFAULT_previous,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}constructor(){super(),this.src="",this.name="",this.accessibleLabel=null,this.maxHeight="",this.location="",this.anchorKinds=["cfi","text-quote"],this.ebookState={kind:"idle"},this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.mountRef=createRef(),this.generation=0,this.searchQuery="",this.lastSearchLocale="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.paintedHighlightCfis=[],this.announcements=new ViewerAnnouncementController(this),this.announcer=new Announcer({onFlush:text=>this.announcements.announcePolite(text)}),this.previous=()=>{this.runRenditionNavigation("previous")},this.next=()=>{this.runRenditionNavigation("next")},new ThemeWatcher(this,()=>this.repaintAnnotations())}updated(changed){if(super.updated(changed),this.announcements.transition("load",this.ebookState.kind,this.ebookState.kind==="error"?this.ebookState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange()),changed.has("location")){const fromRelocated=this.relocatedLocation===this.location;this.relocatedLocation=void 0,!fromRelocated&&this.rendition&&this.location&&this.displayLocation(this.location)}(changed.has("highlights")||changed.has("activeHighlightId"))&&this.rendition&&this.repaintAnnotations();const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.searchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.hasSearchState(),this.resetSearchState())}connectedCallback(){super.connectedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.anchorOperationGeneration++,this.announcer.cancel(),this.announcements.disconnect(),this.teardown(),this.ebookState={kind:"idle"},super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcements.adopted()}teardown(){const shouldEmitSearchReset=this.hasSearchState();this.book?.destroy(),this.book=void 0,this.rendition=void 0,this.resetSearchState(),this.paintedHighlightCfis=[],shouldEmitSearchReset&&this.isConnected&&this.emitSearchChange()}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}resetSearchState(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchAnnotationCfi=void 0}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.teardown(),!this.src.trim()){this.ebookState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.ebookState={kind:"loading"};let data,factory;try{if([data,factory]=await Promise.all([fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0).then(response=>{if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);return readResponseArrayBuffer(response)}),getEpubJs()]),!this.isConnected||generation!==this.generation||(await assertEpubArchiveWithinLimits(data,void 0,void 0,{signal}),!this.isConnected||generation!==this.generation))return}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.ebookState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"ebookViewerLoadError")},this.emit("lr-render-error",{error});return}if(!factory){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}const mount=this.mountRef.value;if(!mount){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}let candidateBook;try{const book=factory(data);candidateBook=book;const rendition=book.renderTo(mount,{width:"100%",height:"100%"});if(await book.ready,!this.isConnected||generation!==this.generation){book.destroy();return}if(await rendition.display(this.location||void 0),!this.isConnected||generation!==this.generation){book.destroy();return}rendition.on("relocated",loc=>{const cfi=loc?.start?.cfi??"",href=loc?.start?.href??"";!cfi||cfi===this.location||(this.relocatedLocation=cfi,this.location=cfi,this.emit("lr-location-change",{cfi,href}))}),rendition.on("selected",(cfiRange,contents)=>{const selection=contents?.window?.getSelection?.(),range=selection&&selection.rangeCount>0?selection.getRangeAt(0):null;if(!range)return;const text=boundedSelectionText(range);if(!text)return;const rects=this.translateSelectionRects(boundedSelectionRects(range),contents.window);this.emit("lr-text-select",{text,anchor:{kind:"cfi",cfi:cfiRange},rects})}),this.book=book,this.rendition=rendition,candidateBook=void 0,this.ebookState={kind:"ready"},this.repaintAnnotations()}catch(error){if(candidateBook?.destroy(),isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.ebookState={kind:"error",message:this.localize("ebookViewerLoadError")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.ebookState={kind:"error",message},this.emit("lr-render-error",{error})}reportRenditionFailure(error,rendition,generation){!this.isConnected||generation!==this.generation||rendition!==this.rendition||(this.ebookState={kind:"error",message:this.localize("ebookViewerLoadError")},this.emit("lr-render-error",{error}))}translateSelectionRects(rects,sourceWindow){const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow||!sourceWindow)return[];const translated=[];for(const rect of rects){let x=Number(rect.x??rect.left),y=Number(rect.y??rect.top),width=Number(rect.width),height=Number(rect.height);if(![x,y,width,height].every(Number.isFinite))continue;let current=sourceWindow,valid=!0;for(;current&&current!==ownerWindow;){if(!("frameElement"in current)){current=ownerWindow;break}let frameElement;try{frameElement=current.frameElement}catch{valid=!1;break}const frameWindow=frameElement?.ownerDocument.defaultView;if(!frameElement||!frameWindow||!(frameElement instanceof frameWindow.HTMLElement)){valid=!1;break}const frame=frameElement,frameRect=frame.getBoundingClientRect(),borderBoxWidth=frame.offsetWidth||frame.clientWidth,borderBoxHeight=frame.offsetHeight||frame.clientHeight,viewportWidth=current.innerWidth||frame.clientWidth,viewportHeight=current.innerHeight||frame.clientHeight;if(borderBoxWidth<=0||borderBoxHeight<=0||viewportWidth<=0||viewportHeight<=0){valid=!1;break}const borderScaleX=frameRect.width/borderBoxWidth,borderScaleY=frameRect.height/borderBoxHeight,contentScaleX=frame.clientWidth*borderScaleX/viewportWidth,contentScaleY=frame.clientHeight*borderScaleY/viewportHeight;x=frameRect.left+frame.clientLeft*borderScaleX+x*contentScaleX,y=frameRect.top+frame.clientTop*borderScaleY+y*contentScaleY,width*=contentScaleX,height*=contentScaleY,current=frame.ownerDocument.defaultView}!valid||current!==ownerWindow||translated.push(Object.freeze({x,y,width,height,top:y,right:x+width,bottom:y+height,left:x}))}return translated}displayLocation(location){const rendition=this.rendition;if(!rendition)return;const generation=this.generation;try{Promise.resolve(rendition.display(location)).catch(error=>{this.reportRenditionFailure(error,rendition,generation)})}catch(error){this.reportRenditionFailure(error,rendition,generation)}}runRenditionNavigation(action){const rendition=this.rendition;if(!rendition)return;const generation=this.generation;try{const task=action==="previous"?rendition.prev():rendition.next();Promise.resolve(task).catch(error=>{this.reportRenditionFailure(error,rendition,generation)})}catch(error){this.reportRenditionFailure(error,rendition,generation)}}async getToc(){const book=this.book;if(!book)return[];if(await book.ready,this.book!==book)return[];const items=[],seen=new WeakSet,stack=(book.navigation?.toc??[]).map(entry=>({entry,level:1})).reverse();for(;stack.length>0&&items.length<MAX_TOC_ITEMS;){const current=stack.pop(),{entry,level}=current;if(!(!entry||typeof entry!="object"||seen.has(entry))&&(seen.add(entry),items.push({id:entry.id||entry.href,label:String(entry.label??"").trim(),href:entry.href,level}),!(level>=MAX_TOC_DEPTH||!Array.isArray(entry.subitems))))for(let index=entry.subitems.length-1;index>=0;index--)stack.push({entry:entry.subitems[index],level:level+1})}return items}async scrollToAnchor(target){const operation=++this.anchorOperationGeneration;try{return await Object.getPrototypeOf(LyraEbookViewer.prototype).performScrollToAnchor.call(this,target)}catch(error){if(operation!==this.anchorOperationGeneration)return!1;const rendition=this.rendition;return rendition&&this.reportRenditionFailure(error,rendition,this.generation),this.emit("lr-anchor-result",{found:!1}),!1}}async applyAnchor(anchor){const rendition=this.rendition,operation=this.anchorOperationGeneration;if(!rendition)return!1;if(anchor.kind==="cfi")return operation!==this.anchorOperationGeneration||rendition!==this.rendition?!1:(await rendition.display(anchor.cfi),operation===this.anchorOperationGeneration&&rendition===this.rendition);if(anchor.kind==="text-quote"){const cfi=await this.findTextQuoteCfi(anchor.quote);return!cfi||operation!==this.anchorOperationGeneration||rendition!==this.rendition?!1:(await rendition.display(cfi),operation===this.anchorOperationGeneration&&rendition===this.rendition)}return!1}async findTextQuoteCfi(quote){const book=this.book,generation=this.generation,boundedQuery=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!book||!boundedQuery.accepted||!boundedQuery.needle)return null;const work=new ViewerSearchWorkBudget,spineItems=book.spine?.spineItems??[],itemCount=Math.min(spineItems.length,MAX_SEARCH_SPINE_ITEMS);for(let itemIndex=0;itemIndex<itemCount;itemIndex++){const item=spineItems[itemIndex];if(!work.consume(""))return null;let loaded=!1;try{if(await item.load(book.load?.bind(book)),loaded=!0,!this.isConnected||generation!==this.generation||this.book!==book)return null;const results=await item.find(quote)??[];if(!this.isConnected||generation!==this.generation||this.book!==book)return null;for(const result of results){if(!work.consume(""))return null;if(!(!result||typeof result.cfi!="string"))return work.consume(result.cfi)?result.cfi:null}}catch{continue}finally{loaded&&item.unload()}}return null}repaintHighlights(){if(!this.rendition)return;const work=new ViewerSearchWorkBudget;for(const cfi of this.paintedHighlightCfis){if(!work.consume(cfi))break;this.rendition.annotations.remove(cfi,"highlight")}this.paintedHighlightCfis=[];let painted=0;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(highlight.anchor.kind!=="cfi")continue;if(painted>=MAX_PAINTED_HIGHLIGHTS)break;const cfi=highlight.anchor.cfi.trim();if(!cfi||cfi.length>VIEWER_SEARCH_QUERY_LIMIT||!work.consume(cfi))continue;const tone=highlight.tone??"accent",active=highlight.id===this.activeHighlightId,styles2=this.resolveHighlightFill(TONE_FILL_TOKEN[tone]);if(active){const forcedColors=this.ownerDocument.defaultView?.matchMedia?.("(forced-colors: active)").matches??!1;styles2.stroke=forcedColors?"CanvasText":this.resolveHighlightFill(ACTIVE_HIGHLIGHT_STROKE_TOKEN).fill,styles2["stroke-width"]="3",styles2["stroke-dasharray"]="2 1"}this.rendition.annotations.highlight(cfi,{id:highlight.id},()=>this.emit("lr-highlight-activate",{highlightId:highlight.id}),active?`lr-hl-${tone} lr-ebook-highlight-active`:`lr-hl-${tone}`,styles2),this.paintedHighlightCfis.push(cfi),painted++}}repaintSearchAnnotation(){const rendition=this.rendition,cfi=this.searchAnnotationCfi;!rendition||!cfi||(rendition.annotations.remove(cfi,"highlight"),rendition.annotations.highlight(cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN)))}repaintAnnotations(){const rendition=this.rendition;if(rendition)try{this.repaintHighlights(),this.repaintSearchAnnotation()}catch(error){this.reportRenditionFailure(error,rendition,this.generation)}}async search(query){const generation=++this.searchGeneration,boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale);if(this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.clearSearchAnnotation(),!boundedQuery.accepted)return this.searchMatches=[],this.searchMatchCountExact=!1,this.searchActiveIndex=-1,this.emitSearchChange(),0;if(!this.book||!boundedQuery.needle)return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),0;const matches=[];let matchCountExact=!0,matchCeilingExceeded=!1;const book=this.book,work=new ViewerSearchWorkBudget,spineItems=book.spine?.spineItems??[],itemCount=Math.min(spineItems.length,MAX_SEARCH_SPINE_ITEMS);spineItems.length>itemCount&&(matchCountExact=!1);for(let itemIndex=0;itemIndex<itemCount;itemIndex++){const item=spineItems[itemIndex];if(generation!==this.searchGeneration)return this.searchMatches.length;if(!work.consume("")){matchCountExact=!1;break}let loaded=!1;try{if(await item.load(book.load?.bind(book)),loaded=!0,generation!==this.searchGeneration||this.book!==book)return this.searchMatches.length;const results=await item.find(query.trim())??[];if(generation!==this.searchGeneration||this.book!==book)return this.searchMatches.length;for(const r of results){if(!work.consume("")){matchCountExact=!1,matchCeilingExceeded=!0;break}if(!r||typeof r.cfi!="string")continue;const excerpt=typeof r.excerpt=="string"?r.excerpt:"";if(!work.consume(r.cfi)||!work.consume(excerpt)){matchCountExact=!1,matchCeilingExceeded=!0;break}if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1,matchCeilingExceeded=!0;break}matches.push({cfi:r.cfi,excerpt})}}catch{matchCountExact=!1;continue}finally{loaded&&item.unload()}if(matchCeilingExceeded)break}return generation!==this.searchGeneration?this.searchMatches.length:(this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.showSearchMatch(this.searchActiveIndex,generation),matches.length)}async searchNext(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}async searchPrevious(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}clearSearch(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.clearSearchAnnotation(),this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}clearSearchAnnotation(){this.searchAnnotationCfi&&this.rendition?.annotations.remove(this.searchAnnotationCfi,"highlight"),this.searchAnnotationCfi=void 0}async showSearchMatch(index,generation=this.searchGeneration){const match=this.searchMatches[index],rendition=this.rendition;if(!match||!rendition||generation!==this.searchGeneration)return!1;this.clearSearchAnnotation();try{await rendition.display(match.cfi)}catch(error){return generation===this.searchGeneration&&rendition===this.rendition&&this.reportRenditionFailure(error,rendition,this.generation),!1}if(generation!==this.searchGeneration||rendition!==this.rendition||this.searchMatches[index]!==match)return!1;try{rendition.annotations.highlight(match.cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN))}catch(error){return this.reportRenditionFailure(error,rendition,this.generation),!1}return this.searchAnnotationCfi=match.cfi,!0}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex});const numberFormat=getNumberFormat(this.effectiveLocale);announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values?Object.fromEntries(Object.entries(values).map(([name,value])=>[name,typeof value=="number"?numberFormat.format(value):value])):void 0),this.announcer,this.searchMatches.length,this.searchActiveIndex)}resolveHighlightFill({token,fallback}){return{fill:(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(token).trim()??"")||fallback}}renderStatus(){return this.ebookState.kind==="loading"?html`<p class="status-note">${this.localize("loadingDocument")}</p>`:this.ebookState.kind==="error"?html`<div part="error">${this.ebookState.message}</div>`:this.ebookState.kind==="idle"?html`<p class="status-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`:nothing}render(){const disabled=this.ebookState.kind!=="ready";return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{createRef,ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{chevronIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{Announcer}from"../../../internal/announcer.js";import{announceSearchResult}from"../../../internal/viewer-search.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{getEpubJs}from"./ebook-loader.js";import{assertEpubArchiveWithinLimits}from"./epub-resource-guard.js";import{styles}from"./ebook-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget,VIEWER_SEARCH_QUERY_LIMIT}from"../viewer-search-limits.js";import{boundedSelectionRects,boundedSelectionText}from"../../../internal/text-quote.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_ebookViewerLoadError,LYRA_DEFAULT_ebookViewerNextChapter,LYRA_DEFAULT_ebookViewerPreviousChapter,LYRA_DEFAULT_ebookViewerRegionLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_next,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_previous,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";const MAX_TOC_ITEMS=1e4,MAX_TOC_DEPTH=100,MAX_SEARCH_MATCHES=1e4,MAX_SEARCH_SPINE_ITEMS=1e3,MAX_PAINTED_HIGHLIGHTS=100,TONE_FILL_TOKEN={accent:{token:"--lr-color-brand-quiet",fallback:"#ddf4ff"},success:{token:"--lr-color-success-quiet",fallback:"#dafbe1"},warning:{token:"--lr-color-warning-quiet",fallback:"#fff8c5"},danger:{token:"--lr-color-danger-quiet",fallback:"#ffebe9"},neutral:{token:"--lr-color-surface-raised",fallback:"#f6f8fa"}},SEARCH_MATCH_FILL_TOKEN={token:"--lr-color-warning",fallback:"#9a6700"},ACTIVE_HIGHLIGHT_STROKE_TOKEN={token:"--lr-focus-ring-color",fallback:"#0969da"};class LyraEbookViewerBase extends LyraElement{}class LyraEbookViewer extends DocumentAnchorTarget(LyraEbookViewerBase){static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,ebookViewerLoadError:LYRA_DEFAULT_ebookViewerLoadError,ebookViewerNextChapter:LYRA_DEFAULT_ebookViewerNextChapter,ebookViewerPreviousChapter:LYRA_DEFAULT_ebookViewerPreviousChapter,ebookViewerRegionLabel:LYRA_DEFAULT_ebookViewerRegionLabel,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,next:LYRA_DEFAULT_next,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,previous:LYRA_DEFAULT_previous,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}constructor(){super(),this.src="",this.name="",this.accessibleLabel=null,this.maxHeight="",this.location="",this.anchorKinds=["cfi","text-quote"],this.ebookState={kind:"idle"},this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.mountRef=createRef(),this.generation=0,this.searchQuery="",this.lastSearchLocale="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.paintedHighlightCfis=[],this.announcements=new ViewerAnnouncementController(this),this.announcer=new Announcer({onFlush:text=>this.announcements.announcePolite(text)}),this.previous=()=>{this.runRenditionNavigation("previous")},this.next=()=>{this.runRenditionNavigation("next")},new ThemeWatcher(this,()=>this.repaintAnnotations())}updated(changed){if(super.updated(changed),this.announcements.transition("load",this.ebookState.kind,this.ebookState.kind==="error"?this.ebookState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange()),changed.has("location")){const fromRelocated=this.relocatedLocation===this.location;this.relocatedLocation=void 0,!fromRelocated&&this.rendition&&this.location&&this.displayLocation(this.location)}(changed.has("highlights")||changed.has("activeHighlightId"))&&this.rendition&&this.repaintAnnotations();const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.searchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.hasSearchState(),this.resetSearchState())}connectedCallback(){super.connectedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.anchorOperationGeneration++,this.announcer.cancel(),this.announcements.disconnect(),this.teardown(),this.ebookState={kind:"idle"},super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcements.adopted()}teardown(){const shouldEmitSearchReset=this.hasSearchState();this.book?.destroy(),this.book=void 0,this.rendition=void 0,this.resetSearchState(),this.paintedHighlightCfis=[],shouldEmitSearchReset&&this.isConnected&&this.emitSearchChange()}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}resetSearchState(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchAnnotationCfi=void 0}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.teardown(),!this.src.trim()){this.ebookState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.ebookState={kind:"loading"};let data,factory;try{if([data,factory]=await Promise.all([fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0).then(response=>{if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);return readResponseArrayBuffer(response)}),getEpubJs()]),!this.isConnected||generation!==this.generation||(await assertEpubArchiveWithinLimits(data,void 0,void 0,{signal}),!this.isConnected||generation!==this.generation))return}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.ebookState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"ebookViewerLoadError")},this.emit("lr-render-error",{error});return}if(!factory){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}const mount=this.mountRef.value;if(!mount){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}let candidateBook;try{const book=factory(data);candidateBook=book;const rendition=book.renderTo(mount,{width:"100%",height:"100%"});if(await book.ready,!this.isConnected||generation!==this.generation){book.destroy();return}if(await rendition.display(this.location||void 0),!this.isConnected||generation!==this.generation){book.destroy();return}rendition.on("relocated",loc=>{const cfi=loc?.start?.cfi??"",href=loc?.start?.href??"";!cfi||cfi===this.location||(this.relocatedLocation=cfi,this.location=cfi,this.emit("lr-location-change",{cfi,href}))}),rendition.on("selected",(cfiRange,contents)=>{const selection=contents?.window?.getSelection?.(),range=selection&&selection.rangeCount>0?selection.getRangeAt(0):null;if(!range)return;const text=boundedSelectionText(range);if(!text)return;const rects=this.translateSelectionRects(boundedSelectionRects(range),contents.window);this.emit("lr-text-select",{text,anchor:{kind:"cfi",cfi:cfiRange},rects})}),this.book=book,this.rendition=rendition,candidateBook=void 0,this.ebookState={kind:"ready"},this.repaintAnnotations()}catch(error){if(candidateBook?.destroy(),isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.ebookState={kind:"error",message:this.localize("ebookViewerLoadError")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.ebookState={kind:"error",message},this.emit("lr-render-error",{error})}reportRenditionFailure(error,rendition,generation){!this.isConnected||generation!==this.generation||rendition!==this.rendition||(this.ebookState={kind:"error",message:this.localize("ebookViewerLoadError")},this.emit("lr-render-error",{error}))}translateSelectionRects(rects,sourceWindow){const ownerWindow=this.ownerDocument.defaultView;if(!ownerWindow||!sourceWindow)return[];const translated=[];for(const rect of rects){let x=Number(rect.x??rect.left),y=Number(rect.y??rect.top),width=Number(rect.width),height=Number(rect.height);if(![x,y,width,height].every(Number.isFinite))continue;let current=sourceWindow,valid=!0;for(;current&&current!==ownerWindow;){if(!("frameElement"in current)){current=ownerWindow;break}let frameElement;try{frameElement=current.frameElement}catch{valid=!1;break}const frameWindow=frameElement?.ownerDocument.defaultView;if(!frameElement||!frameWindow||!(frameElement instanceof frameWindow.HTMLElement)){valid=!1;break}const frame=frameElement,frameRect=frame.getBoundingClientRect(),borderBoxWidth=frame.offsetWidth||frame.clientWidth,borderBoxHeight=frame.offsetHeight||frame.clientHeight,viewportWidth=current.innerWidth||frame.clientWidth,viewportHeight=current.innerHeight||frame.clientHeight;if(borderBoxWidth<=0||borderBoxHeight<=0||viewportWidth<=0||viewportHeight<=0){valid=!1;break}const borderScaleX=frameRect.width/borderBoxWidth,borderScaleY=frameRect.height/borderBoxHeight,contentScaleX=frame.clientWidth*borderScaleX/viewportWidth,contentScaleY=frame.clientHeight*borderScaleY/viewportHeight;x=frameRect.left+frame.clientLeft*borderScaleX+x*contentScaleX,y=frameRect.top+frame.clientTop*borderScaleY+y*contentScaleY,width*=contentScaleX,height*=contentScaleY,current=frame.ownerDocument.defaultView}!valid||current!==ownerWindow||translated.push(Object.freeze({x,y,width,height,top:y,right:x+width,bottom:y+height,left:x}))}return translated}displayLocation(location){const rendition=this.rendition;if(!rendition)return;const generation=this.generation;try{Promise.resolve(rendition.display(location)).catch(error=>{this.reportRenditionFailure(error,rendition,generation)})}catch(error){this.reportRenditionFailure(error,rendition,generation)}}runRenditionNavigation(action){const rendition=this.rendition;if(!rendition)return;const generation=this.generation;try{const task=action==="previous"?rendition.prev():rendition.next();Promise.resolve(task).catch(error=>{this.reportRenditionFailure(error,rendition,generation)})}catch(error){this.reportRenditionFailure(error,rendition,generation)}}async getToc(){const book=this.book;if(!book)return[];if(await book.ready,this.book!==book)return[];const items=[],seen=new WeakSet,stack=(book.navigation?.toc??[]).map(entry=>({entry,level:1})).reverse();for(;stack.length>0&&items.length<MAX_TOC_ITEMS;){const current=stack.pop(),{entry,level}=current;if(!(!entry||typeof entry!="object"||seen.has(entry))&&(seen.add(entry),items.push({id:entry.id||entry.href,label:String(entry.label??"").trim(),href:entry.href,level}),!(level>=MAX_TOC_DEPTH||!Array.isArray(entry.subitems))))for(let index=entry.subitems.length-1;index>=0;index--)stack.push({entry:entry.subitems[index],level:level+1})}return items}async scrollToAnchor(target){const operation=++this.anchorOperationGeneration;try{return await Object.getPrototypeOf(LyraEbookViewer.prototype).performScrollToAnchor.call(this,target)}catch(error){if(operation!==this.anchorOperationGeneration)return!1;const rendition=this.rendition;return rendition&&this.reportRenditionFailure(error,rendition,this.generation),this.emit("lr-anchor-result",{found:!1}),!1}}async applyAnchor(anchor){const rendition=this.rendition,operation=this.anchorOperationGeneration;if(!rendition)return!1;if(anchor.kind==="cfi")return operation!==this.anchorOperationGeneration||rendition!==this.rendition?!1:(await rendition.display(anchor.cfi),operation===this.anchorOperationGeneration&&rendition===this.rendition);if(anchor.kind==="text-quote"){const cfi=await this.findTextQuoteCfi(anchor.quote);return!cfi||operation!==this.anchorOperationGeneration||rendition!==this.rendition?!1:(await rendition.display(cfi),operation===this.anchorOperationGeneration&&rendition===this.rendition)}return!1}async findTextQuoteCfi(quote){const book=this.book,generation=this.generation,boundedQuery=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!book||!boundedQuery.accepted||!boundedQuery.needle)return null;const work=new ViewerSearchWorkBudget,spineItems=book.spine?.spineItems??[],itemCount=Math.min(spineItems.length,MAX_SEARCH_SPINE_ITEMS);for(let itemIndex=0;itemIndex<itemCount;itemIndex++){const item=spineItems[itemIndex];if(!work.consume(""))return null;let loaded=!1;try{if(await item.load(book.load?.bind(book)),loaded=!0,!this.isConnected||generation!==this.generation||this.book!==book)return null;const results=await item.find(quote)??[];if(!this.isConnected||generation!==this.generation||this.book!==book)return null;for(const result of results){if(!work.consume(""))return null;if(!(!result||typeof result.cfi!="string"))return work.consume(result.cfi)?result.cfi:null}}catch{continue}finally{loaded&&item.unload()}}return null}repaintHighlights(){if(!this.rendition)return;const work=new ViewerSearchWorkBudget;for(const cfi of this.paintedHighlightCfis){if(!work.consume(cfi))break;this.rendition.annotations.remove(cfi,"highlight")}this.paintedHighlightCfis=[];let painted=0;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(highlight.anchor.kind!=="cfi")continue;if(painted>=MAX_PAINTED_HIGHLIGHTS)break;const cfi=highlight.anchor.cfi.trim();if(!cfi||cfi.length>VIEWER_SEARCH_QUERY_LIMIT||!work.consume(cfi))continue;const tone=highlight.tone??"accent",active=highlight.id===this.activeHighlightId,styles2=this.resolveHighlightFill(TONE_FILL_TOKEN[tone]);if(active){const forcedColors=this.ownerDocument.defaultView?.matchMedia?.("(forced-colors: active)").matches??!1;styles2.stroke=forcedColors?"CanvasText":this.resolveHighlightFill(ACTIVE_HIGHLIGHT_STROKE_TOKEN).fill,styles2["stroke-width"]="3",styles2["stroke-dasharray"]="2 1"}this.rendition.annotations.highlight(cfi,{id:highlight.id},()=>this.emit("lr-highlight-activate",{highlightId:highlight.id}),active?`lr-hl-${tone} lr-ebook-highlight-active`:`lr-hl-${tone}`,styles2),this.paintedHighlightCfis.push(cfi),painted++}}repaintSearchAnnotation(){const rendition=this.rendition,cfi=this.searchAnnotationCfi;!rendition||!cfi||(rendition.annotations.remove(cfi,"highlight"),rendition.annotations.highlight(cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN)))}repaintAnnotations(){const rendition=this.rendition;if(rendition)try{this.repaintHighlights(),this.repaintSearchAnnotation()}catch(error){this.reportRenditionFailure(error,rendition,this.generation)}}async search(query){const generation=++this.searchGeneration,boundedQuery=boundedViewerSearchQuery(query,this.effectiveLocale);if(this.searchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.clearSearchAnnotation(),!boundedQuery.accepted)return this.searchMatches=[],this.searchMatchCountExact=!1,this.searchActiveIndex=-1,this.emitSearchChange(),0;if(!this.book||!boundedQuery.needle)return this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange(),0;const matches=[];let matchCountExact=!0,matchCeilingExceeded=!1;const book=this.book,work=new ViewerSearchWorkBudget,spineItems=book.spine?.spineItems??[],itemCount=Math.min(spineItems.length,MAX_SEARCH_SPINE_ITEMS);spineItems.length>itemCount&&(matchCountExact=!1);for(let itemIndex=0;itemIndex<itemCount;itemIndex++){const item=spineItems[itemIndex];if(generation!==this.searchGeneration)return this.searchMatches.length;if(!work.consume("")){matchCountExact=!1;break}let loaded=!1;try{if(await item.load(book.load?.bind(book)),loaded=!0,generation!==this.searchGeneration||this.book!==book)return this.searchMatches.length;const results=await item.find(query.trim())??[];if(generation!==this.searchGeneration||this.book!==book)return this.searchMatches.length;for(const r of results){if(!work.consume("")){matchCountExact=!1,matchCeilingExceeded=!0;break}if(!r||typeof r.cfi!="string")continue;const excerpt=typeof r.excerpt=="string"?r.excerpt:"";if(!work.consume(r.cfi)||!work.consume(excerpt)){matchCountExact=!1,matchCeilingExceeded=!0;break}if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1,matchCeilingExceeded=!0;break}matches.push({cfi:r.cfi,excerpt})}}catch{matchCountExact=!1;continue}finally{loaded&&item.unload()}if(matchCeilingExceeded)break}return generation!==this.searchGeneration?this.searchMatches.length:(this.searchMatches=matches,this.searchMatchCountExact=matchCountExact,this.searchActiveIndex=matches.length>0?0:-1,this.emitSearchChange(),this.searchActiveIndex>=0&&await this.showSearchMatch(this.searchActiveIndex,generation),matches.length)}async searchNext(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex+1)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}async searchPrevious(){if(!this.searchMatches.length)return!1;const generation=++this.searchGeneration;return this.searchActiveIndex=(this.searchActiveIndex-1+this.searchMatches.length)%this.searchMatches.length,this.emitSearchChange(),this.showSearchMatch(this.searchActiveIndex,generation)}clearSearch(){this.searchGeneration++,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.clearSearchAnnotation(),this.emit("lr-search-change",{query:"",matchCount:0,matchCountExact:!0,activeIndex:-1})}clearSearchAnnotation(){this.searchAnnotationCfi&&this.rendition?.annotations.remove(this.searchAnnotationCfi,"highlight"),this.searchAnnotationCfi=void 0}async showSearchMatch(index,generation=this.searchGeneration){const match=this.searchMatches[index],rendition=this.rendition;if(!match||!rendition||generation!==this.searchGeneration)return!1;this.clearSearchAnnotation();try{await rendition.display(match.cfi)}catch(error){return generation===this.searchGeneration&&rendition===this.rendition&&this.reportRenditionFailure(error,rendition,this.generation),!1}if(generation!==this.searchGeneration||rendition!==this.rendition||this.searchMatches[index]!==match)return!1;try{rendition.annotations.highlight(match.cfi,{},void 0,"lr-ebook-search",this.resolveHighlightFill(SEARCH_MATCH_FILL_TOKEN))}catch(error){return this.reportRenditionFailure(error,rendition,this.generation),!1}return this.searchAnnotationCfi=match.cfi,!0}emitSearchChange(){this.emit("lr-search-change",{query:this.searchQuery,matchCount:this.searchMatches.length,matchCountExact:this.searchMatchCountExact,activeIndex:this.searchActiveIndex});const numberFormat=getNumberFormat(this.effectiveLocale);announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values?Object.fromEntries(Object.entries(values).map(([name,value])=>[name,typeof value=="number"?numberFormat.format(value):value])):void 0),this.announcer,this.searchMatches.length,this.searchActiveIndex)}resolveHighlightFill({token,fallback}){return{fill:(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(token).trim()??"")||fallback}}renderStatus(){return this.ebookState.kind==="loading"?html`<p class="status-note">${this.localize("loadingDocument")}</p>`:this.ebookState.kind==="error"?html`<div part="error">${this.ebookState.message}</div>`:this.ebookState.kind==="idle"?html`<p class="status-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`:nothing}render(){const disabled=this.ebookState.kind!=="ready";return html`
2
2
  <div
3
3
  part="base"
4
4
  aria-busy=${this.ebookState.kind==="loading"?"true":"false"}
@@ -1,6 +1,6 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getDateTimeFormat,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../../media/attachment-chip/attachment-chip.class.js";import{loadEmailDeps}from"./email-loader.js";import{styles}from"./email-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewGenericFile,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeEmail,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_download,LYRA_DEFAULT_emailViewerAttachments,LYRA_DEFAULT_emailViewerDate,LYRA_DEFAULT_emailViewerFrom,LYRA_DEFAULT_emailViewerGroupAddress,LYRA_DEFAULT_emailViewerHideQuoted,LYRA_DEFAULT_emailViewerLabel,LYRA_DEFAULT_emailViewerMissingParser,LYRA_DEFAULT_emailViewerNoSubject,LYRA_DEFAULT_emailViewerOpenAttachment,LYRA_DEFAULT_emailViewerShowQuoted,LYRA_DEFAULT_emailViewerSubject,LYRA_DEFAULT_emailViewerTo,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";function normalizeAttachmentContent(content){return content instanceof Uint8Array?content:content instanceof ArrayBuffer?new Uint8Array(content):new TextEncoder().encode(content)}function immutableAttachmentBlob(content,mimeType){const copied=new Uint8Array(content.byteLength);return copied.set(content),new Blob([copied],{type:mimeType})}class LyraEmailViewerBase extends LyraElement{static{this.immutableEventDetails=Object.freeze(["lr-attachment-open","lr-text-select"])}}function splitTrailingQuoteBlock(text){const lines=text.split(/\r\n|\r|\n/);let start=lines.length,quotedLineCount=0;for(let i=lines.length-1;i>=0;i--)if(lines[i].trimStart().startsWith(">"))start=i,quotedLineCount++;else if(lines[i].trim()==="")start=i;else break;return quotedLineCount<3?null:{visible:lines.slice(0,start).join(`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getDateTimeFormat,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../../media/attachment-chip/attachment-chip.class.js";import{loadEmailDeps}from"./email-loader.js";import{styles}from"./email-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewGenericFile,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeEmail,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_download,LYRA_DEFAULT_emailViewerAttachments,LYRA_DEFAULT_emailViewerDate,LYRA_DEFAULT_emailViewerFrom,LYRA_DEFAULT_emailViewerGroupAddress,LYRA_DEFAULT_emailViewerHideQuoted,LYRA_DEFAULT_emailViewerLabel,LYRA_DEFAULT_emailViewerMissingParser,LYRA_DEFAULT_emailViewerNoSubject,LYRA_DEFAULT_emailViewerOpenAttachment,LYRA_DEFAULT_emailViewerShowQuoted,LYRA_DEFAULT_emailViewerSubject,LYRA_DEFAULT_emailViewerTo,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";function normalizeAttachmentContent(content){return content instanceof Uint8Array?content:content instanceof ArrayBuffer?new Uint8Array(content):new TextEncoder().encode(content)}function immutableAttachmentBlob(content,mimeType){const copied=new Uint8Array(content.byteLength);return copied.set(content),new Blob([copied],{type:mimeType})}class LyraEmailViewerBase extends LyraElement{static{this.immutableEventDetails=Object.freeze(["lr-attachment-open","lr-text-select"])}}function splitTrailingQuoteBlock(text){const lines=text.split(/\r\n|\r|\n/);let start=lines.length,quotedLineCount=0;for(let i=lines.length-1;i>=0;i--)if(lines[i].trimStart().startsWith(">"))start=i,quotedLineCount++;else if(lines[i].trim()==="")start=i;else break;return quotedLineCount<3?null:{visible:lines.slice(0,start).join(`
2
2
  `),quoted:lines.slice(start).join(`
3
- `)}}const QUOTE_SELECTOR='blockquote[type="cite" i], div.gmail_quote, div.yahoo_quoted, div[id^="divRplyFwdMsg"]';function parseHtmlDocument(html2,ownerDocument){const DOMParserCtor=ownerDocument.defaultView?.DOMParser;return DOMParserCtor?new DOMParserCtor().parseFromString(html2,"text/html"):null}function foldHtmlQuotes(html2,localize,expandedIndices,ownerDocument){const doc=parseHtmlDocument(html2,ownerDocument);return doc?(doc.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{const expanded=expandedIndices.includes(index);block.setAttribute("part","quoted"),expanded||block.setAttribute("hidden",""),block.setAttribute("data-quote-index",String(index));const button=doc.createElement("button");button.type="button",button.setAttribute("part","quote-toggle"),button.setAttribute("aria-expanded",String(expanded)),button.setAttribute("data-quote-toggle",String(index)),button.textContent=localize(expanded?"emailViewerHideQuoted":"emailViewerShowQuoted"),block.before(button)}),doc.body.innerHTML):html2}function isQuoteToggleElement(target){const candidate=target;return candidate.nodeType===1&&typeof candidate.hasAttribute=="function"&&candidate.hasAttribute("data-quote-toggle")}class LyraEmailViewer extends TextViewerTarget(LyraEmailViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.foldQuotes=!1,this.fetchState={kind:"idle"},this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.foldedHtmlCache=null,this.onBodyClick=e=>{const target=e.composedPath().find(isQuoteToggleElement);if(!target)return;const index=target.getAttribute("data-quote-toggle"),block=this.renderRoot.querySelector(`[data-quote-index="${index}"]`),numericIndex=Number(index);if(!block||!Number.isInteger(numericIndex)||numericIndex<0)return;const restoreFocus=activeElementIn(this.shadowRoot)===target;this.expandedHtmlQuoteIndices=this.expandedHtmlQuoteIndices.includes(numericIndex)?this.expandedHtmlQuoteIndices.filter(value=>value!==numericIndex):[...this.expandedHtmlQuoteIndices,numericIndex],restoreFocus&&this.scheduleAfterUpdate(()=>{this.renderRoot.querySelector(`[data-quote-toggle="${numericIndex}"]`)?.focus()})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeEmail:LYRA_DEFAULT_documentPreviewTypeEmail,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,download:LYRA_DEFAULT_download,emailViewerAttachments:LYRA_DEFAULT_emailViewerAttachments,emailViewerDate:LYRA_DEFAULT_emailViewerDate,emailViewerFrom:LYRA_DEFAULT_emailViewerFrom,emailViewerGroupAddress:LYRA_DEFAULT_emailViewerGroupAddress,emailViewerHideQuoted:LYRA_DEFAULT_emailViewerHideQuoted,emailViewerLabel:LYRA_DEFAULT_emailViewerLabel,emailViewerMissingParser:LYRA_DEFAULT_emailViewerMissingParser,emailViewerNoSubject:LYRA_DEFAULT_emailViewerNoSubject,emailViewerOpenAttachment:LYRA_DEFAULT_emailViewerOpenAttachment,emailViewerShowQuoted:LYRA_DEFAULT_emailViewerShowQuoted,emailViewerSubject:LYRA_DEFAULT_emailViewerSubject,emailViewerTo:LYRA_DEFAULT_emailViewerTo,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){if(this.foldQuotes&&this.fetchState.kind==="loaded"&&query.trim()){const normalizedQuery=query.toLocaleLowerCase(this.effectiveLocale),{bodyHtml,bodyText}=this.fetchState.email;if(bodyHtml!==null){const doc=parseHtmlDocument(bodyHtml,this.ownerDocument),next=new Set(this.expandedHtmlQuoteIndices);doc?.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{(block.textContent??"").toLocaleLowerCase(this.effectiveLocale).includes(normalizedQuery)&&next.add(index)});const expanded=[...next];(expanded.length!==this.expandedHtmlQuoteIndices.length||expanded.some((value,index)=>value!==this.expandedHtmlQuoteIndices[index]))&&(this.expandedHtmlQuoteIndices=expanded,await this.updateComplete)}else if(bodyText!==null){const split=splitTrailingQuoteBlock(bodyText);split&&split.quoted.toLocaleLowerCase(this.effectiveLocale).includes(normalizedQuery)&&!this.textQuoteExpanded&&(this.textQuoteExpanded=!0,await this.updateComplete)}}return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this.renderRoot.querySelector("[data-email-text-content]")}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.foldedHtmlCache=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("foldQuotes"))&&(this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[])}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const result=await this.parse(buffer,generation);result&&this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",...result})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}async parse(buffer,generation){const{PostalMime,DOMPurify}=await loadEmailDeps();if(!this.isConnected||generation!==this.generation)return null;if(!PostalMime)throw new LyraUserFacingError(this.localize("emailViewerMissingParser"));const parsed=await PostalMime.parse(buffer);if(!this.isConnected||generation!==this.generation)return null;const bodyHtml=parsed.html&&DOMPurify?sanitizePassiveMarkup(DOMPurify,parsed.html,this.ownerDocument,"passive-document"):null;if(!this.isConnected||generation!==this.generation)return null;if(parsed.html&&!DOMPurify&&!parsed.text)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));const content=parsed.attachments??[];return{fromAddress:parsed.from,toAddresses:parsed.to,email:{from:this.formatAddress(parsed.from),to:this.formatAddresses(parsed.to),subject:parsed.subject??"",date:parsed.date??"",bodyHtml,bodyText:bodyHtml?null:parsed.text??null,attachments:content.map(attachment=>{const normalized=normalizeAttachmentContent(attachment.content);return{filename:attachment.filename||this.localize("documentPreviewGenericFile"),mimeType:attachment.mimeType??"",size:normalized.byteLength,content:normalized}})}}}formatAddress(value){if(!value)return"";if(value.group){const members=getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value.group.map(entry=>this.formatAddress(entry)).filter(Boolean));return value.name?this.localize("emailViewerGroupAddress",void 0,{name:value.name,members}):members}return value.name&&value.address?getListFormat(this.effectiveLocale,{style:"long",type:"unit"}).format([value.name,value.address]):value.address??value.name??""}formatAddresses(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format((values??[]).map(value=>this.formatAddress(value)).filter(Boolean))}formatDate(value){if(!value)return"";const date=new Date(value);return Number.isNaN(date.getTime())?value:getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium",timeStyle:"short"}).format(date)}renderHeaders(email,fromAddress,toAddresses){return html`<div part="headers">
3
+ `)}}const QUOTE_SELECTOR='blockquote[type="cite" i], div.gmail_quote, div.yahoo_quoted, div[id^="divRplyFwdMsg"]';function parseHtmlDocument(html2,ownerDocument){const DOMParserCtor=ownerDocument.defaultView?.DOMParser;return DOMParserCtor?new DOMParserCtor().parseFromString(html2,"text/html"):null}function foldHtmlQuotes(html2,localize,expandedIndices,ownerDocument){const doc=parseHtmlDocument(html2,ownerDocument);return doc?(doc.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{const expanded=expandedIndices.includes(index);block.setAttribute("part","quoted"),expanded||block.setAttribute("hidden",""),block.setAttribute("data-quote-index",String(index));const button=doc.createElement("button");button.type="button",button.setAttribute("part","quote-toggle"),button.setAttribute("aria-expanded",String(expanded)),button.setAttribute("data-quote-toggle",String(index)),button.textContent=localize(expanded?"emailViewerHideQuoted":"emailViewerShowQuoted"),block.before(button)}),doc.body.innerHTML):html2}function isQuoteToggleElement(target){const candidate=target;return candidate.nodeType===1&&typeof candidate.hasAttribute=="function"&&candidate.hasAttribute("data-quote-toggle")}class LyraEmailViewer extends TextViewerTarget(LyraEmailViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.foldQuotes=!1,this.fetchState={kind:"idle"},this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.foldedHtmlCache=null,this.onBodyClick=e=>{const target=e.composedPath().find(isQuoteToggleElement);if(!target)return;const index=target.getAttribute("data-quote-toggle"),block=this.renderRoot.querySelector(`[data-quote-index="${index}"]`),numericIndex=Number(index);if(!block||!Number.isInteger(numericIndex)||numericIndex<0)return;const restoreFocus=activeElementIn(this.shadowRoot)===target;this.expandedHtmlQuoteIndices=this.expandedHtmlQuoteIndices.includes(numericIndex)?this.expandedHtmlQuoteIndices.filter(value=>value!==numericIndex):[...this.expandedHtmlQuoteIndices,numericIndex],restoreFocus&&this.scheduleAfterUpdate(()=>{this.renderRoot.querySelector(`[data-quote-toggle="${numericIndex}"]`)?.focus()})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewGenericFile:LYRA_DEFAULT_documentPreviewGenericFile,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeEmail:LYRA_DEFAULT_documentPreviewTypeEmail,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,download:LYRA_DEFAULT_download,emailViewerAttachments:LYRA_DEFAULT_emailViewerAttachments,emailViewerDate:LYRA_DEFAULT_emailViewerDate,emailViewerFrom:LYRA_DEFAULT_emailViewerFrom,emailViewerGroupAddress:LYRA_DEFAULT_emailViewerGroupAddress,emailViewerHideQuoted:LYRA_DEFAULT_emailViewerHideQuoted,emailViewerLabel:LYRA_DEFAULT_emailViewerLabel,emailViewerMissingParser:LYRA_DEFAULT_emailViewerMissingParser,emailViewerNoSubject:LYRA_DEFAULT_emailViewerNoSubject,emailViewerOpenAttachment:LYRA_DEFAULT_emailViewerOpenAttachment,emailViewerShowQuoted:LYRA_DEFAULT_emailViewerShowQuoted,emailViewerSubject:LYRA_DEFAULT_emailViewerSubject,emailViewerTo:LYRA_DEFAULT_emailViewerTo,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){if(this.foldQuotes&&this.fetchState.kind==="loaded"&&query.trim()){const normalizedQuery=query.toLocaleLowerCase(this.effectiveLocale),{bodyHtml,bodyText}=this.fetchState.email;if(bodyHtml!==null){const doc=parseHtmlDocument(bodyHtml,this.ownerDocument),next=new Set(this.expandedHtmlQuoteIndices);doc?.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{(block.textContent??"").toLocaleLowerCase(this.effectiveLocale).includes(normalizedQuery)&&next.add(index)});const expanded=[...next];(expanded.length!==this.expandedHtmlQuoteIndices.length||expanded.some((value,index)=>value!==this.expandedHtmlQuoteIndices[index]))&&(this.expandedHtmlQuoteIndices=expanded,await this.updateComplete)}else if(bodyText!==null){const split=splitTrailingQuoteBlock(bodyText);split&&split.quoted.toLocaleLowerCase(this.effectiveLocale).includes(normalizedQuery)&&!this.textQuoteExpanded&&(this.textQuoteExpanded=!0,await this.updateComplete)}}return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this.renderRoot.querySelector("[data-email-text-content]")}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.foldedHtmlCache=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("foldQuotes"))&&(this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[])}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const result=await this.parse(buffer,generation);result&&this.isConnected&&generation===this.generation&&(this.fetchState={kind:"loaded",...result})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}async parse(buffer,generation){const{PostalMime,DOMPurify}=await loadEmailDeps();if(!this.isConnected||generation!==this.generation)return null;if(!PostalMime)throw new LyraUserFacingError(this.localize("emailViewerMissingParser"));const parsed=await PostalMime.parse(buffer);if(!this.isConnected||generation!==this.generation)return null;const bodyHtml=parsed.html&&DOMPurify?sanitizePassiveMarkup(DOMPurify,parsed.html,this.ownerDocument,"passive-document"):null;if(!this.isConnected||generation!==this.generation)return null;if(parsed.html&&!DOMPurify&&!parsed.text)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));const content=parsed.attachments??[];return{fromAddress:parsed.from,toAddresses:parsed.to,email:{from:this.formatAddress(parsed.from),to:this.formatAddresses(parsed.to),subject:parsed.subject??"",date:parsed.date??"",bodyHtml,bodyText:bodyHtml?null:parsed.text??null,attachments:content.map(attachment=>{const normalized=normalizeAttachmentContent(attachment.content);return{filename:attachment.filename||this.localize("documentPreviewGenericFile"),mimeType:attachment.mimeType??"",size:normalized.byteLength,content:normalized}})}}}formatAddress(value){if(!value)return"";if(value.group){const members=getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value.group.map(entry=>this.formatAddress(entry)).filter(Boolean));return value.name?this.localize("emailViewerGroupAddress",void 0,{name:value.name,members}):members}return value.name&&value.address?getListFormat(this.effectiveLocale,{style:"long",type:"unit"}).format([value.name,value.address]):value.address??value.name??""}formatAddresses(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format((values??[]).map(value=>this.formatAddress(value)).filter(Boolean))}formatDate(value){if(!value)return"";const date=new Date(value);return Number.isNaN(date.getTime())?value:getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium",timeStyle:"short"}).format(date)}renderHeaders(email,fromAddress,toAddresses){return html`<div part="headers">
4
4
  <span part="from-label">${this.localize("emailViewerFrom")}</span><span part="from">${fromAddress?this.formatAddress(fromAddress):email.from}</span>
5
5
  <span part="to-label">${this.localize("emailViewerTo")}</span><span part="to">${toAddresses?this.formatAddresses(toAddresses):email.to}</span>
6
6
  <span part="subject-label">${this.localize("emailViewerSubject")}</span><span part="subject">${email.subject||this.localize("emailViewerNoSubject")}</span>
@@ -1014,7 +1014,7 @@ export type LyraHandoffDividerReactProps = LyraReactElementProps<LyraHandoffDivi
1014
1014
  'from-agent'?: LyraHandoffDivider['fromAgent'];
1015
1015
  'to-agent'?: LyraHandoffDivider['toAgent'];
1016
1016
  }>;
1017
- export type LyraHeatmapReactProps = LyraReactElementProps<LyraHeatmap, 'accessibleCells' | 'annotations' | 'bucketCount' | 'cellColor' | 'cellInteractive' | 'cellSize' | 'cellText' | 'colLabelHeight' | 'colLabelRotation' | 'colorSteps' | 'data' | 'domain' | 'fitToWidth' | 'legendStops' | 'locale' | 'maxCellSize' | 'midpoint' | 'minCellSize' | 'rowLabelWidth' | 'scale' | 'selectedCell' | 'strings' | 'valueLabel', {}, LyraHeatmapEventMap, 'lr-cell-click', '--lr-heatmap-annotation-color' | '--lr-heatmap-color-steps-gradient' | '--lr-heatmap-focus-ring-color' | '--lr-heatmap-label-font' | '--lr-heatmap-no-data-fill' | '--lr-heatmap-scale-hi' | '--lr-heatmap-scale-lo' | '--lr-heatmap-selected-color' | '--lr-heatmap-tooltip-bg' | '--lr-heatmap-tooltip-text', {
1017
+ export type LyraHeatmapReactProps = LyraReactElementProps<LyraHeatmap, 'accessibleCells' | 'annotations' | 'bucketCount' | 'cellColor' | 'cellInteractive' | 'cellSize' | 'cellText' | 'colLabelHeight' | 'colLabelRotation' | 'colorSteps' | 'data' | 'domain' | 'fitToWidth' | 'legendStops' | 'locale' | 'maxCellSize' | 'midpoint' | 'minCellSize' | 'rowLabelWidth' | 'scale' | 'selectedCell' | 'strings' | 'valueLabel', {}, LyraHeatmapEventMap, 'lr-cell-click' | 'lr-matrix-geometry-change', '--lr-heatmap-annotation-color' | '--lr-heatmap-color-steps-gradient' | '--lr-heatmap-focus-ring-color' | '--lr-heatmap-label-font' | '--lr-heatmap-no-data-fill' | '--lr-heatmap-scale-hi' | '--lr-heatmap-scale-lo' | '--lr-heatmap-selected-color' | '--lr-heatmap-tooltip-bg' | '--lr-heatmap-tooltip-text', {
1018
1018
  'accessible-cells'?: LyraHeatmap['accessibleCells'];
1019
1019
  'bucket-count'?: LyraHeatmap['bucketCount'];
1020
1020
  'cell-size'?: LyraHeatmap['cellSize'];
package/dist/events.d.ts CHANGED
@@ -1303,6 +1303,12 @@ export type LyraMapClickEvent = LyraMapEventMap['lr-map-click'];
1303
1303
  * Detail type: `LyraMapEventMap['lr-map-load']`.
1304
1304
  */
1305
1305
  export type LyraMapLoadEvent = LyraMapEventMap['lr-map-load'];
1306
+ /**
1307
+ * `lr-matrix-geometry-change` — dispatched by `<lr-heatmap>`.
1308
+ *
1309
+ * Detail type: `LyraHeatmapEventMap['lr-matrix-geometry-change']`.
1310
+ */
1311
+ export type LyraMatrixGeometryChangeEvent = LyraHeatmapEventMap['lr-matrix-geometry-change'];
1306
1312
  /**
1307
1313
  * `lr-maximize-change` — dispatched by `<lr-tool-result-dialog>`.
1308
1314
  *
@@ -2727,6 +2733,7 @@ export interface LyraGlobalEventMap {
2727
2733
  'lr-location-change': LyraLocationChangeEvent;
2728
2734
  'lr-map-click': LyraMapClickEvent;
2729
2735
  'lr-map-load': LyraMapLoadEvent;
2736
+ 'lr-matrix-geometry-change': LyraMatrixGeometryChangeEvent;
2730
2737
  'lr-maximize-change': LyraMaximizeChangeEvent;
2731
2738
  'lr-mcp-log': LyraMcpLogEvent;
2732
2739
  'lr-mcp-open-link': LyraMcpOpenLinkEvent;
@@ -1,5 +1,6 @@
1
1
  import type { LitElement } from 'lit';
2
2
  import { attachInternalsSafely, createFallbackInternals } from './element-internals.js';
3
+ import './form-control-labels.js';
3
4
  export { attachInternalsSafely, createFallbackInternals };
4
5
  type Constructor<T> = new (...args: any[]) => T;
5
6
  /** A write to the public `form` IDL may name an owner by id while reads stay element-valued. */
@@ -1 +1 @@
1
- import{LYRA_DEFAULT_fieldRequired}from"./default-strings.generated.js";import{resolveLyraString}from"./localization-runtime.js";import{AnchoredValidityController,SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"./anchored-validity.js";import{syncValidityStates}from"./custom-states.js";import{installInvalidEventAlias}from"./invalid-event-alias.js";import{omittedEmptyStringConverter}from"./converters.js";import{attachInternalsSafely,createFallbackInternals}from"./element-internals.js";const FORM_ASSOCIATED_DEFAULT_STRINGS=Object.freeze({fieldRequired:LYRA_DEFAULT_fieldRequired});function setFormOwner(host,owner){const id=typeof owner=="string"?owner:owner?.id??"";id?host.setAttribute("form",id):host.removeAttribute("form")}function getFormOwner(internals){return internals.form}function createStringArrayFormDataState(name,values){const state=new FormData,key=name||"value";for(const value of values)state.append(key,value);return state}function readStringArrayFormDataState(state){if(typeof FormData!="function")return[];let entries;try{entries=[...FormData.prototype.values.call(state)]}catch{return[]}return entries.some(entry=>typeof entry!="string")?[]:entries}function isEmptyFormValue(value){if(value==null)return!0;if(typeof value=="string")return value==="";if(typeof value=="object")try{if(Array.isArray(value))return value.length===0;const prototype=Object.getPrototypeOf(value);if(prototype===null)return Object.keys(value).length===0;if(Object.getPrototypeOf(prototype)===null){const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor")?.value;if(typeof constructor=="function"&&constructor.name==="Object"&&constructor.prototype===prototype)return Object.keys(value).length===0}}catch{return!1}return!1}const stringFormValueAdapter={empty:"",toFormValue:value=>value,isEmpty:value=>value==="",fromAttribute:attribute=>attribute,toAttribute:value=>value,fromFormState:state=>typeof state=="string"?state:""};function resolveFormValueAdapter(adapter){return adapter===void 0?stringFormValueAdapter:{empty:adapter.empty,toFormValue:value=>adapter.toFormValue(value),...adapter.toFormState?{toFormState:value=>adapter.toFormState(value)}:{},isEmpty:adapter.isEmpty?value=>adapter.isEmpty(value):isEmptyFormValue,fromAttribute:adapter.fromAttribute?attribute=>adapter.fromAttribute(attribute):attribute=>attribute,toAttribute:adapter.toAttribute?value=>adapter.toAttribute(value):value=>value==null?null:String(value),fromFormState:adapter.fromFormState?state=>adapter.fromFormState(state):state=>typeof state=="string"?state:adapter.empty}}function isBarredFromValidation(host,internals){if((host.effectiveDisabled??host.disabled)||host.readonly)return!0;if(internals){const willValidate=readNativeWillValidate(internals);if(willValidate!==void 0)return!willValidate}return!1}function readNativeWillValidate(internals){if(typeof ElementInternals!="function")return;const getter=Object.getOwnPropertyDescriptor(ElementInternals.prototype,"willValidate")?.get;if(typeof getter=="function")try{const value=getter.call(internals);return typeof value=="boolean"?value:void 0}catch{return}}function installCustomErrorProperty(host,getCustomValidityMessage){if(Object.prototype.hasOwnProperty.call(host,"customError"))return;const setValidity=host.setCustomValidity.bind(host),resetValidity=host.resetValidity?.bind(host);let committing=!1,resetting=!1;const reflectMessage=message=>{message?host.getAttribute("custom-error")!==message&&host.setAttribute("custom-error",message):host.hasAttribute("custom-error")&&host.removeAttribute("custom-error")},commit=next=>{if(committing){resetting&&setValidity(next??"");return}const old=getCustomValidityMessage()||null,message=next??"";committing=!0;try{setValidity(message),reflectMessage(getCustomValidityMessage()||"")}finally{committing=!1}host.requestUpdate("customError",old)};Object.defineProperty(host,"customError",{configurable:!0,enumerable:!0,get:()=>getCustomValidityMessage()||null,set:commit}),Object.defineProperty(host,"setCustomValidity",{configurable:!0,writable:!0,value:commit}),resetValidity&&Object.defineProperty(host,"resetValidity",{configurable:!0,writable:!0,value:()=>{if(committing)return;const old=getCustomValidityMessage()||null;committing=!0,resetting=!0;try{resetValidity(),reflectMessage(getCustomValidityMessage()||"")}finally{resetting=!1,committing=!1}host.requestUpdate("customError",old)}})}function FormAssociated(Base,valueAdapter){const adapter=resolveFormValueAdapter(valueAdapter),defaultValueConverter={fromAttribute:attribute=>attribute===null?null:adapter.fromAttribute(attribute),toAttribute:value=>value==null?null:adapter.toAttribute(value)};class FormAssociatedElement extends Base{static{this.formAssociated=!0}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0,...valueAdapter?{converter:defaultValueConverter}:{}},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},form:{noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(...args){super(...args),this._fieldsetDisabled=!1,this._disabled=!1,this._reflectingDisabledAttribute=!1,this._name="",this._value=adapter.empty,this._defaultValue=adapter.empty,this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this.reflectingFormOwner=!1,this._required=!1,this._hasInteracted=!1,this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),this.commitFormValue(this._value),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init));const markInteracted=()=>{this._hasInteracted||(this._hasInteracted=!0,this.syncValidityStates())};this.addEventListener("input",markInteracted),this.addEventListener("change",markInteracted),this.addEventListener("focusout",()=>{this.effectiveDisabled||markInteracted()}),this.syncValidityStates()}get form(){return getFormOwner(this.internals)}set form(owner){if(!this.reflectingFormOwner){this.reflectingFormOwner=!0;try{setFormOwner(this,owner)}finally{this.reflectingFormOwner=!1}}}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector("input:not([type='hidden']), textarea, select, button, [tabindex]:not([tabindex='-1'])")??null}[SET_ANCHORED_VALIDITY](flags,message=""){this.validityController.setValidity(flags,message),this.syncValidityStates()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.syncValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity(),this.syncValidityStates()}syncValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this._hasInteracted,barred:this.isBarredFromValidation()})}isBarredFromValidation(){return isBarredFromValidation(this,this.internals)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}commitFormValue(value){const submitted=adapter.toFormValue(value);adapter.toFormState?this.internals.setFormValue(submitted,adapter.toFormState(value)):this.internals.setFormValue(submitted)}get value(){return this._value}set value(next){const old=this._value;this._value=next??adapter.empty,this.settingDefaultValue||(this._valueDirty=!0),this.commitFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}captureLiveValueCheckpoint(){return{value:this._value,dirty:this._valueDirty}}restoreLiveValueCheckpoint(checkpoint){const old=this._value;this._value=checkpoint.value,this._valueDirty=checkpoint.dirty,this.commitFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??adapter.empty,this.reflectingDefaultValue=!0;try{const attribute=next==null?null:adapter.toAttribute(this._defaultValue);attribute==null?this.removeAttribute("value"):this.setAttribute("value",attribute)}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.updateValidity(),this.syncValidityStates(),this.requestUpdate("disabled",old)}toggleAttribute(qualifiedName,force){if(qualifiedName!=="disabled")return super.toggleAttribute(qualifiedName,force);this._reflectingDisabledAttribute=!0;try{return super.toggleAttribute(qualifiedName,force)}finally{queueMicrotask(()=>{this._reflectingDisabledAttribute=!1})}}setAttribute(qualifiedName,value){if(qualifiedName!=="disabled"){super.setAttribute(qualifiedName,value);return}this._reflectingDisabledAttribute=!0;try{super.setAttribute(qualifiedName,value)}finally{queueMicrotask(()=>{this._reflectingDisabledAttribute=!1})}}removeAttribute(qualifiedName){if(qualifiedName!=="disabled"){super.removeAttribute(qualifiedName);return}this._reflectingDisabledAttribute=!0;try{super.removeAttribute(qualifiedName)}finally{queueMicrotask(()=>{this._reflectingDisabledAttribute=!1})}}get required(){return this._required}set required(next){const old=this._required;this._required=next,this.toggleAttribute("required",next),this.updateValidity(),this.syncValidityStates(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}setFormValue(next){this.value=next}updateValidity(){if(this.isBarredFromValidation()){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&adapter.isEmpty(this._value)){const overrides=this.strings,message=resolveLyraString(this,"fieldRequired",overrides,void 0,void 0,FORM_ASSOCIATED_DEFAULT_STRINGS);this[SET_ANCHORED_VALIDITY]({valueMissing:!0},message)}else this[SET_ANCHORED_VALIDITY]({})}syncConstraintsToNative(){const host=this;host.hasUpdated&&host.performUpdate()}checkValidity(){return this.syncConstraintsToNative(),this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.syncConstraintsToNative(),this.updateValidity(),this._hasInteracted=!0,this.syncValidityStates(),this.internals.reportValidity()}formResetCallback(){this._valueDirty=!1,this.restoreLiveValueFromDefault(),this._hasInteracted=!1,this.syncValidityStates()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state,reason){this.value=adapter.fromFormState(state)}formDisabledCallback(fieldsetDisabled){if(this._reflectingDisabledAttribute)return;const before=this.effectiveDisabled;this._fieldsetDisabled=fieldsetDisabled,this.effectiveDisabled!==before&&(this.updateValidity(),this.syncValidityStates(),this.requestUpdate())}updated(changed){super.updated(changed),!(!changed.has("readonly")&&!changed.has("disabled"))&&(this.updateValidity(),this.syncValidityStates())}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.syncValidityStates()}}return FormAssociatedElement}export{FormAssociated,attachInternalsSafely,createFallbackInternals,createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,isEmptyFormValue,readStringArrayFormDataState,setFormOwner,stringFormValueAdapter};
1
+ import{LYRA_DEFAULT_fieldRequired}from"./default-strings.generated.js";import{resolveLyraString}from"./localization-runtime.js";import{AnchoredValidityController,SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"./anchored-validity.js";import{syncValidityStates}from"./custom-states.js";import{installInvalidEventAlias}from"./invalid-event-alias.js";import{omittedEmptyStringConverter}from"./converters.js";import{attachInternalsSafely,createFallbackInternals}from"./element-internals.js";import"./form-control-labels.js";const FORM_ASSOCIATED_DEFAULT_STRINGS=Object.freeze({fieldRequired:LYRA_DEFAULT_fieldRequired});function setFormOwner(host,owner){const id=typeof owner=="string"?owner:owner?.id??"";id?host.setAttribute("form",id):host.removeAttribute("form")}function getFormOwner(internals){return internals.form}function createStringArrayFormDataState(name,values){const state=new FormData,key=name||"value";for(const value of values)state.append(key,value);return state}function readStringArrayFormDataState(state){if(typeof FormData!="function")return[];let entries;try{entries=[...FormData.prototype.values.call(state)]}catch{return[]}return entries.some(entry=>typeof entry!="string")?[]:entries}function isEmptyFormValue(value){if(value==null)return!0;if(typeof value=="string")return value==="";if(typeof value=="object")try{if(Array.isArray(value))return value.length===0;const prototype=Object.getPrototypeOf(value);if(prototype===null)return Object.keys(value).length===0;if(Object.getPrototypeOf(prototype)===null){const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor")?.value;if(typeof constructor=="function"&&constructor.name==="Object"&&constructor.prototype===prototype)return Object.keys(value).length===0}}catch{return!1}return!1}const stringFormValueAdapter={empty:"",toFormValue:value=>value,isEmpty:value=>value==="",fromAttribute:attribute=>attribute,toAttribute:value=>value,fromFormState:state=>typeof state=="string"?state:""};function resolveFormValueAdapter(adapter){return adapter===void 0?stringFormValueAdapter:{empty:adapter.empty,toFormValue:value=>adapter.toFormValue(value),...adapter.toFormState?{toFormState:value=>adapter.toFormState(value)}:{},isEmpty:adapter.isEmpty?value=>adapter.isEmpty(value):isEmptyFormValue,fromAttribute:adapter.fromAttribute?attribute=>adapter.fromAttribute(attribute):attribute=>attribute,toAttribute:adapter.toAttribute?value=>adapter.toAttribute(value):value=>value==null?null:String(value),fromFormState:adapter.fromFormState?state=>adapter.fromFormState(state):state=>typeof state=="string"?state:adapter.empty}}function isBarredFromValidation(host,internals){if((host.effectiveDisabled??host.disabled)||host.readonly)return!0;if(internals){const willValidate=readNativeWillValidate(internals);if(willValidate!==void 0)return!willValidate}return!1}function readNativeWillValidate(internals){if(typeof ElementInternals!="function")return;const getter=Object.getOwnPropertyDescriptor(ElementInternals.prototype,"willValidate")?.get;if(typeof getter=="function")try{const value=getter.call(internals);return typeof value=="boolean"?value:void 0}catch{return}}function installCustomErrorProperty(host,getCustomValidityMessage){if(Object.prototype.hasOwnProperty.call(host,"customError"))return;const setValidity=host.setCustomValidity.bind(host),resetValidity=host.resetValidity?.bind(host);let committing=!1,resetting=!1;const reflectMessage=message=>{message?host.getAttribute("custom-error")!==message&&host.setAttribute("custom-error",message):host.hasAttribute("custom-error")&&host.removeAttribute("custom-error")},commit=next=>{if(committing){resetting&&setValidity(next??"");return}const old=getCustomValidityMessage()||null,message=next??"";committing=!0;try{setValidity(message),reflectMessage(getCustomValidityMessage()||"")}finally{committing=!1}host.requestUpdate("customError",old)};Object.defineProperty(host,"customError",{configurable:!0,enumerable:!0,get:()=>getCustomValidityMessage()||null,set:commit}),Object.defineProperty(host,"setCustomValidity",{configurable:!0,writable:!0,value:commit}),resetValidity&&Object.defineProperty(host,"resetValidity",{configurable:!0,writable:!0,value:()=>{if(committing)return;const old=getCustomValidityMessage()||null;committing=!0,resetting=!0;try{resetValidity(),reflectMessage(getCustomValidityMessage()||"")}finally{resetting=!1,committing=!1}host.requestUpdate("customError",old)}})}function FormAssociated(Base,valueAdapter){const adapter=resolveFormValueAdapter(valueAdapter),defaultValueConverter={fromAttribute:attribute=>attribute===null?null:adapter.fromAttribute(attribute),toAttribute:value=>value==null?null:adapter.toAttribute(value)};class FormAssociatedElement extends Base{static{this.formAssociated=!0}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0,...valueAdapter?{converter:defaultValueConverter}:{}},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},form:{noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}constructor(...args){super(...args),this._fieldsetDisabled=!1,this._disabled=!1,this._reflectingDisabledAttribute=!1,this._name="",this._value=adapter.empty,this._defaultValue=adapter.empty,this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this.reflectingFormOwner=!1,this._required=!1,this._hasInteracted=!1,this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),this.commitFormValue(this._value),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init));const markInteracted=()=>{this._hasInteracted||(this._hasInteracted=!0,this.syncValidityStates())};this.addEventListener("input",markInteracted),this.addEventListener("change",markInteracted),this.addEventListener("focusout",()=>{this.effectiveDisabled||markInteracted()}),this.syncValidityStates()}get form(){return getFormOwner(this.internals)}set form(owner){if(!this.reflectingFormOwner){this.reflectingFormOwner=!0;try{setFormOwner(this,owner)}finally{this.reflectingFormOwner=!1}}}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector("input:not([type='hidden']), textarea, select, button, [tabindex]:not([tabindex='-1'])")??null}[SET_ANCHORED_VALIDITY](flags,message=""){this.validityController.setValidity(flags,message),this.syncValidityStates()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.syncValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity(),this.syncValidityStates()}syncValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this._hasInteracted,barred:this.isBarredFromValidation()})}isBarredFromValidation(){return isBarredFromValidation(this,this.internals)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}commitFormValue(value){const submitted=adapter.toFormValue(value);adapter.toFormState?this.internals.setFormValue(submitted,adapter.toFormState(value)):this.internals.setFormValue(submitted)}get value(){return this._value}set value(next){const old=this._value;this._value=next??adapter.empty,this.settingDefaultValue||(this._valueDirty=!0),this.commitFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}captureLiveValueCheckpoint(){return{value:this._value,dirty:this._valueDirty}}restoreLiveValueCheckpoint(checkpoint){const old=this._value;this._value=checkpoint.value,this._valueDirty=checkpoint.dirty,this.commitFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??adapter.empty,this.reflectingDefaultValue=!0;try{const attribute=next==null?null:adapter.toAttribute(this._defaultValue);attribute==null?this.removeAttribute("value"):this.setAttribute("value",attribute)}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.updateValidity(),this.syncValidityStates(),this.requestUpdate("disabled",old)}toggleAttribute(qualifiedName,force){if(qualifiedName!=="disabled")return super.toggleAttribute(qualifiedName,force);this._reflectingDisabledAttribute=!0;try{return super.toggleAttribute(qualifiedName,force)}finally{queueMicrotask(()=>{this._reflectingDisabledAttribute=!1})}}setAttribute(qualifiedName,value){if(qualifiedName!=="disabled"){super.setAttribute(qualifiedName,value);return}this._reflectingDisabledAttribute=!0;try{super.setAttribute(qualifiedName,value)}finally{queueMicrotask(()=>{this._reflectingDisabledAttribute=!1})}}removeAttribute(qualifiedName){if(qualifiedName!=="disabled"){super.removeAttribute(qualifiedName);return}this._reflectingDisabledAttribute=!0;try{super.removeAttribute(qualifiedName)}finally{queueMicrotask(()=>{this._reflectingDisabledAttribute=!1})}}get required(){return this._required}set required(next){const old=this._required;this._required=next,this.toggleAttribute("required",next),this.updateValidity(),this.syncValidityStates(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}setFormValue(next){this.value=next}updateValidity(){if(this.isBarredFromValidation()){this[SET_ANCHORED_VALIDITY]({});return}if(this.required&&adapter.isEmpty(this._value)){const overrides=this.strings,message=resolveLyraString(this,"fieldRequired",overrides,void 0,void 0,FORM_ASSOCIATED_DEFAULT_STRINGS);this[SET_ANCHORED_VALIDITY]({valueMissing:!0},message)}else this[SET_ANCHORED_VALIDITY]({})}syncConstraintsToNative(){const host=this;host.hasUpdated&&host.performUpdate()}checkValidity(){return this.syncConstraintsToNative(),this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.syncConstraintsToNative(),this.updateValidity(),this._hasInteracted=!0,this.syncValidityStates(),this.internals.reportValidity()}formResetCallback(){this._valueDirty=!1,this.restoreLiveValueFromDefault(),this._hasInteracted=!1,this.syncValidityStates()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state,reason){this.value=adapter.fromFormState(state)}formDisabledCallback(fieldsetDisabled){if(this._reflectingDisabledAttribute)return;const before=this.effectiveDisabled;this._fieldsetDisabled=fieldsetDisabled,this.effectiveDisabled!==before&&(this.updateValidity(),this.syncValidityStates(),this.requestUpdate())}updated(changed){super.updated(changed),!(!changed.has("readonly")&&!changed.has("disabled"))&&(this.updateValidity(),this.syncValidityStates())}connectedCallback(){super.connectedCallback(),this.updateValidity(),this.syncValidityStates()}}return FormAssociatedElement}export{FormAssociated,attachInternalsSafely,createFallbackInternals,createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,isEmptyFormValue,readStringArrayFormDataState,setFormOwner,stringFormValueAdapter};
@@ -1 +1 @@
1
- import{deepActiveElementIn}from"./active-element.js";import{collectFocusableElements}from"./overlay-manager.js";const EXTERNAL_LABEL_ACTIVATION=Symbol("lr-external-label-activation"),EXTERNAL_LABEL_HOST_SEMANTICS=Symbol("lr-external-label-host-semantics"),attachedInternals=new WeakMap;function captureFormInternals(host,internals){attachedInternals.set(host,internals)}const COMPOSITE_ROLE_SELECTOR='[role="radiogroup"],[role="group"],[role="grid"],[role="tree"]',SEMANTIC_TARGET_SELECTOR=['input:not([type="hidden"]):not([tabindex="-1"])','textarea:not([tabindex="-1"])','select:not([tabindex="-1"])','button:not([tabindex="-1"])','[role]:not([tabindex="-1"])'].join(","),ACTIVATING_ROLES=new Set(["checkbox","switch","radio","menuitemcheckbox","menuitemradio"]),MAX_ASSOCIATION_CANDIDATES_PER_MUTATION=2048,MAX_ASSOCIATION_REFRESHES_PER_TASK=256,associationRootObservations=new WeakMap;function isLabelElement(node){return node!==null&&"nodeType"in node&&node.nodeType===1&&"localName"in node&&node.localName==="label"}function isHtmlElement(node){return node.nodeType===1&&"focus"in node&&"style"in node}function isShadowRootNode(node){return node?.nodeType===11&&"host"in node}function isCurrentlyAssociatedLabel(label,host){const root=host.getRootNode();if(label.getRootNode()!==root)return!1;if(!label.hasAttribute("for")){const control="control"in label?label.control:void 0;return control==null?label.contains(host):control===host}const id=label.htmlFor;return id===""?!1:"getElementById"in root&&typeof root.getElementById=="function"?root.getElementById(id)===host:!("querySelectorAll"in root)||typeof root.querySelectorAll!="function"?!1:[...root.querySelectorAll("[id]")].find(candidate=>candidate.id===id)===host}function addSubscriptionById(observation,subscription){if(!subscription.id)return;const subscribers=observation.subscriptionsById.get(subscription.id)??new Set;subscribers.add(subscription),observation.subscriptionsById.set(subscription.id,subscribers)}function removeSubscriptionById(observation,subscription){if(!subscription.id)return;const subscribers=observation.subscriptionsById.get(subscription.id);subscribers?.delete(subscription),subscribers?.size===0&&observation.subscriptionsById.delete(subscription.id)}function updateSubscriptionId(observation,subscription){const id=subscription.host.id;id!==subscription.id&&(removeSubscriptionById(observation,subscription),subscription.id=id,addSubscriptionById(observation,subscription))}function addImplicitSubscription(observation,label,subscription){const subscriptions=observation.implicitSubscriptionsByLabel.get(label)??new Set;subscriptions.add(subscription),observation.implicitSubscriptionsByLabel.set(label,subscriptions)}function removeImplicitSubscription(observation,label,subscription){const subscriptions=observation.implicitSubscriptionsByLabel.get(label);subscriptions?.delete(subscription),subscriptions?.size===0&&observation.implicitSubscriptionsByLabel.delete(label)}function updateImplicitSubscriptions(observation,subscription,labels){const next=labels.filter(label=>!label.hasAttribute("for"));for(const label of subscription.implicitLabels)next.includes(label)||removeImplicitSubscription(observation,label,subscription);for(const label of next)subscription.implicitLabels.includes(label)||addImplicitSubscription(observation,label,subscription);subscription.implicitLabels=next}function hasAssociationRefreshes(observation){return observation.pending.size>0||observation.fallbackIterator!==void 0}function cancelAssociationContinuation(observation){observation.cancelContinuation?.(),observation.cancelContinuation=void 0}function scheduleAssociationContinuation(observation){if(!hasAssociationRefreshes(observation)||observation.cancelContinuation!==void 0)return;const callback=()=>{observation.cancelContinuation=void 0,drainAssociationRefreshes(observation)};if(observation.ownerWindow){const handle=observation.ownerWindow.setTimeout(callback,0);observation.cancelContinuation=()=>observation.ownerWindow?.clearTimeout(handle)}else{const handle=globalThis.setTimeout(callback,0);observation.cancelContinuation=()=>globalThis.clearTimeout(handle)}}function refreshAssociationSubscription(observation,subscription){subscription.active&&(subscription.listener(),observation.fallbackIterator&&(subscription.fallbackGeneration=observation.fallbackGeneration))}function drainTargetedAssociationRefreshes(observation){let remaining=MAX_ASSOCIATION_REFRESHES_PER_TASK;for(const subscription of observation.pending)if(observation.pending.delete(subscription),refreshAssociationSubscription(observation,subscription),--remaining===0)break;scheduleAssociationContinuation(observation)}function drainAssociationRefreshes(observation){let remaining=MAX_ASSOCIATION_REFRESHES_PER_TASK;for(const subscription of observation.pending)if(observation.pending.delete(subscription),refreshAssociationSubscription(observation,subscription),--remaining===0)break;for(;remaining>0&&observation.fallbackIterator;){const next=observation.fallbackIterator.next();if(next.done){observation.fallbackIterator=void 0;break}next.value.active&&next.value.fallbackGeneration!==observation.fallbackGeneration&&(next.value.listener(),next.value.fallbackGeneration=observation.fallbackGeneration),remaining--}scheduleAssociationContinuation(observation)}function notifyAssociationSubscriptions(observation,subscriptions,fallbackAll=!1){if(fallbackAll){const continuationPending=observation.cancelContinuation!==void 0;observation.pending.clear(),observation.fallbackGeneration++,observation.fallbackIterator=observation.subscriptions.values();for(const subscription of subscriptions)subscription.active&&observation.pending.add(subscription);continuationPending?drainTargetedAssociationRefreshes(observation):drainAssociationRefreshes(observation);return}for(const subscription of subscriptions)subscription.active&&observation.pending.add(subscription);drainTargetedAssociationRefreshes(observation)}function isLabelableElement(element){return element.localName==="input"?element.type!=="hidden":element.localName==="button"||element.localName==="meter"||element.localName==="output"||element.localName==="progress"||element.localName==="select"||element.localName==="textarea"?!0:element.localName.includes("-")&&element.constructor.formAssociated===!0}function collectAssociationElement(element,result){const id=element.getAttribute("id");return id&&result.ids.add(id),isLabelElement(element)&&element.hasAttribute("for")&&element.htmlFor&&result.ids.add(element.htmlFor),isLabelableElement(element)}function nextAssociationNode(root,current){if(current.firstChild)return current.firstChild;let cursor=current;for(;cursor&&cursor!==root;){if(cursor.nextSibling)return cursor.nextSibling;cursor=cursor.parentNode}return null}function collectAssociationCandidates(node,result){let containsLabelable=!1,current=node;for(;current;){if(result.work>=MAX_ASSOCIATION_CANDIDATES_PER_MUTATION){result.truncated=!0;break}result.work++,current.nodeType===1&&(containsLabelable=collectAssociationElement(current,result)||containsLabelable),current=nextAssociationNode(node,current)}return containsLabelable}function containingImplicitLabel(node){if(isLabelElement(node))return node.hasAttribute("for")?null:node;if(node.nodeType!==1||!("closest"in node))return null;const label=node.closest("label");return label&&!label.hasAttribute("for")?label:null}function collectFirstImplicitSubscription(observation,label,candidates,affected){let current=label.firstChild;for(;current;){if(candidates.work>=MAX_ASSOCIATION_CANDIDATES_PER_MUTATION){candidates.truncated=!0;return}if(candidates.work++,current.nodeType===1&&(isLabelableElement(current)||observation.subscriptionsByHost.has(current))){const subscription=observation.subscriptionsByHost.get(current);subscription&&affected.add(subscription);return}current=nextAssociationNode(label,current)}}function affectedAssociationSubscriptions(observation,mutations){const affected=new Set,candidates={ids:new Set,implicitLabels:new Set,truncated:!1,work:0},addIndexedCandidates=()=>{for(const id of candidates.ids)for(const subscription of observation.subscriptionsById.get(id)??[])affected.add(subscription);for(const label of candidates.implicitLabels)for(const subscription of observation.implicitSubscriptionsByLabel.get(label)??[])affected.add(subscription)};for(const mutation of mutations){if(candidates.work>=MAX_ASSOCIATION_CANDIDATES_PER_MUTATION){candidates.truncated=!0;break}if(candidates.work++,mutation.type==="attributes"){const target=mutation.target;if(mutation.attributeName==="id"){const oldId=mutation.oldValue??"",id=target.getAttribute("id")??"";oldId&&candidates.ids.add(oldId),id&&candidates.ids.add(id);const hostSubscription=observation.subscriptionsByHost.get(target);hostSubscription&&(affected.add(hostSubscription),updateSubscriptionId(observation,hostSubscription))}else if(mutation.attributeName==="for"&&isLabelElement(target)){const oldFor=mutation.oldValue;oldFor&&candidates.ids.add(oldFor),target.htmlFor&&candidates.ids.add(target.htmlFor);for(const subscription of observation.implicitSubscriptionsByLabel.get(target)??[])affected.add(subscription);target.hasAttribute("for")||candidates.implicitLabels.add(target)}else if(mutation.attributeName==="type"&&target.localName==="input"){const label=containingImplicitLabel(target);label&&candidates.implicitLabels.add(label)}continue}let changedLabelableShape=!1;for(const node of mutation.addedNodes)if(changedLabelableShape=collectAssociationCandidates(node,candidates)||changedLabelableShape,candidates.truncated)break;if(!candidates.truncated){for(const node of mutation.removedNodes)if(changedLabelableShape=collectAssociationCandidates(node,candidates)||changedLabelableShape,candidates.truncated)break}if(changedLabelableShape){const label=containingImplicitLabel(mutation.target);label&&candidates.implicitLabels.add(label)}if(candidates.truncated)break}if(addIndexedCandidates(),candidates.truncated)return{subscriptions:affected,fallbackAll:!0};for(const label of candidates.implicitLabels)if(collectFirstImplicitSubscription(observation,label,candidates,affected),candidates.truncated)return{subscriptions:affected,fallbackAll:!0};return{subscriptions:affected,fallbackAll:!1}}function observeAssociationRoot(host,listener){const root=host.getRootNode();let observation=associationRootObservations.get(root);if(!observation){const Observer=host.ownerDocument.defaultView?.MutationObserver,subscriptions=new Set,subscriptionsById=new Map,implicitSubscriptionsByLabel=new WeakMap,subscriptionsByHost=new WeakMap,pending=new Set,holder={},observer=Observer===void 0?void 0:new Observer(mutations=>{const current=holder.observation;if(!current)return;const affected=affectedAssociationSubscriptions(current,mutations);notifyAssociationSubscriptions(current,affected.subscriptions,affected.fallbackAll)});observer?.observe(root,{attributes:!0,attributeFilter:["for","id","type"],attributeOldValue:!0,childList:!0,subtree:!0}),observation={subscriptions,subscriptionsById,implicitSubscriptionsByLabel,subscriptionsByHost,pending,observer,ownerWindow:host.ownerDocument.defaultView,fallbackGeneration:0},holder.observation=observation,associationRootObservations.set(root,observation)}const subscription={host,listener,id:host.id,implicitLabels:[],fallbackGeneration:-1,active:!0};return observation.subscriptions.add(subscription),observation.subscriptionsByHost.set(host,subscription),addSubscriptionById(observation,subscription),{update(labels){subscription.active&&(updateSubscriptionId(observation,subscription),updateImplicitSubscriptions(observation,subscription,labels))},disconnect(){if(!subscription.active)return;subscription.active=!1,observation.pending.delete(subscription),observation.subscriptions.delete(subscription),observation.subscriptionsByHost.delete(host);for(const label of subscription.implicitLabels)removeImplicitSubscription(observation,label,subscription);subscription.implicitLabels=[],removeSubscriptionById(observation,subscription);const current=associationRootObservations.get(root);!current||current.subscriptions.size>0||(current.observer?.disconnect(),cancelAssociationContinuation(current),current.pending.clear(),current.fallbackIterator=void 0,associationRootObservations.delete(root))}}}function isComposedDescendant(host,candidate){let current=candidate;for(;current;){if(current===host)return!0;if(current.parentNode){current=current.parentNode;continue}current=isShadowRootNode(current)?current.host:null}return!1}function resolveExternalLabels(host){const native=attachedInternals.get(host)?.labels;if(native)return Array.from(native).filter(isLabelElement).filter(label=>isCurrentlyAssociatedLabel(label,host));const labels=[],ancestor=host.closest("label");ancestor&&isCurrentlyAssociatedLabel(ancestor,host)&&labels.push(ancestor);const root=host.getRootNode();if(host.id&&"querySelectorAll"in root)for(const found of root.querySelectorAll("label[for]"))isLabelElement(found)&&isCurrentlyAssociatedLabel(found,host)&&!labels.includes(found)&&labels.push(found);return labels}function labelText(node,exclude){if(node===exclude)return"";if(node.nodeType===Node.TEXT_NODE)return node.textContent??"";let text="";for(const child of node.childNodes)text+=labelText(child,exclude);return text}function resolveExternalLabelText(labels,host){return labels.map(label=>labelText(label,host).trim()).filter(text=>text!=="").join(" ")}class ExternalLabelController{constructor(host){this.host=host,this.labels=[],this.activating=!1,this.onLabelClick=event=>{if(this.activating||this.barred)return;const source=event.currentTarget;if(!source||!isLabelElement(source)||!isCurrentlyAssociatedLabel(source,this.host)){this.refresh();return}event.composedPath().includes(this.host)||queueMicrotask(()=>{if(event.defaultPrevented||!this.host.isConnected||this.barred)return;if(!isCurrentlyAssociatedLabel(source,this.host)){this.refresh();return}const focusTarget=this.resolveFocusTarget(),activation=this.resolveActivation(focusTarget);this.activating=!0;try{this.host.focus(),isComposedDescendant(this.host,deepActiveElementIn(this.host.ownerDocument))||focusTarget?.focus(),activation==="activate"&&focusTarget?.click()}finally{this.activating=!1}})}}hostConnected(){this.associationRootSubscription?.disconnect(),this.associationRootSubscription=observeAssociationRoot(this.host,()=>this.refresh()),this.refresh()}hostUpdated(){this.refresh()}hostDisconnected(){this.release(),this.stopObservingLabels(),this.associationRootSubscription?.disconnect(),this.associationRootSubscription=void 0;for(const label of this.labels)label.removeEventListener("click",this.onLabelClick);this.labels=[]}refresh(){const next=resolveExternalLabels(this.host);if(next.length!==this.labels.length||next.some((label,index)=>label!==this.labels[index])){for(const label of this.labels)label.removeEventListener("click",this.onLabelClick);this.labels=next;for(const label of this.labels)label.addEventListener("click",this.onLabelClick);this.observeLabels()}this.associationRootSubscription?.update(next),this.apply()}observeLabels(){this.stopObservingLabels();const Observer=this.host.ownerDocument.defaultView?.MutationObserver;if(this.labels.length===0||Observer===void 0)return;const observer=new Observer(()=>this.refresh());for(const label of this.labels)observer.observe(label,{characterData:!0,childList:!0,subtree:!0});this.labelObserver=observer}stopObservingLabels(){this.labelObserver?.disconnect(),this.labelObserver=void 0}get barred(){return typeof this.host.matches=="function"&&this.host.matches(":disabled")?!0:!!(this.host.effectiveDisabled??this.host.disabled)}resolveNameTarget(focusTarget){if(this.hostSemanticOwner)return this.host;const root=this.ownRoot;if(!root)return focusTarget;if(focusTarget){for(const composite of root.querySelectorAll(COMPOSITE_ROLE_SELECTOR))if(isHtmlElement(composite)&&isComposedDescendant(composite,focusTarget))return composite}if(focusTarget&&focusTarget.getRootNode()===root)return focusTarget;const owned=focusTarget?this.outermostOwnedAncestor(focusTarget):null;if(owned)return owned;const semantic=root.querySelector(SEMANTIC_TARGET_SELECTOR);return semantic&&isHtmlElement(semantic)?semantic:focusTarget}outermostOwnedAncestor(node){const root=this.ownRoot;let owned=null,current=node;for(;current&&current!==this.host;)isHtmlElement(current)&&(current.getRootNode()===root||current.parentNode===this.host)&&(owned=current),current.parentNode?current=current.parentNode:current=isShadowRootNode(current)?current.host:null;return owned}get ownRoot(){const root=this.host.renderRoot;return isShadowRootNode(root)?root:this.host.shadowRoot}resolveFocusTarget(){return this.hostSemanticOwner?this.host:collectFocusableElements(this.host)[0]??null}get hostSemanticOwner(){const candidate=this.host;return typeof candidate[EXTERNAL_LABEL_HOST_SEMANTICS]=="function"?candidate:null}hostHasAuthoredName(owner){return owner[EXTERNAL_LABEL_HOST_SEMANTICS]({type:"has-authored-name"})===!0}resolveActivation(focusTarget){const declared=this.host[EXTERNAL_LABEL_ACTIVATION];if(typeof declared=="function")return declared.call(this.host);if(!focusTarget||focusTarget.getRootNode()!==this.ownRoot)return"focus";const role=focusTarget.getAttribute("role");return role&&ACTIVATING_ROLES.has(role)?"activate":"focus"}apply(){const hostOwner=this.hostSemanticOwner;if(hostOwner&&this.hostHasAuthoredName(hostOwner)||!hostOwner&&this.host.hasAttribute("aria-label")){this.release();return}const name=resolveExternalLabelText(this.labels,this.host);if(name===""){this.release();return}const settled=this.applied;if(settled&&settled.name===name&&settled.target.isConnected&&settled.target.getAttribute("aria-label")===name)return;const target=this.resolveNameTarget(this.resolveFocusTarget());target&&(this.applied&&this.applied.target!==target&&this.release(),this.applied||(this.applied={target,name,had:target.hasAttribute("aria-label"),previous:target.getAttribute("aria-label")}),target===this.host&&hostOwner?hostOwner[EXTERNAL_LABEL_HOST_SEMANTICS]({type:"apply",name}):target.getAttribute("aria-label")!==name&&target.setAttribute("aria-label",name),this.applied.name=name)}release(){const applied=this.applied;if(this.applied=void 0,!applied)return;const{target,name,had,previous}=applied,hostOwner=target===this.host?this.hostSemanticOwner:null;if(hostOwner){hostOwner[EXTERNAL_LABEL_HOST_SEMANTICS]({type:"release",appliedName:name,hadPrevious:had,previous});return}target.getAttribute("aria-label")===name&&(had?target.setAttribute("aria-label",previous??""):target.removeAttribute("aria-label"))}}export{EXTERNAL_LABEL_ACTIVATION,EXTERNAL_LABEL_HOST_SEMANTICS,ExternalLabelController,captureFormInternals,resolveExternalLabelText,resolveExternalLabels};
1
+ import{deepActiveElementIn}from"./active-element.js";import{collectFocusableElements}from"./overlay-manager.js";import{registerFormControlLabelSupport}from"./lyra-element.js";const EXTERNAL_LABEL_ACTIVATION=Symbol("lr-external-label-activation"),EXTERNAL_LABEL_HOST_SEMANTICS=Symbol("lr-external-label-host-semantics"),attachedInternals=new WeakMap;function captureFormInternals(host,internals){attachedInternals.set(host,internals)}const COMPOSITE_ROLE_SELECTOR='[role="radiogroup"],[role="group"],[role="grid"],[role="tree"]',SEMANTIC_TARGET_SELECTOR=['input:not([type="hidden"]):not([tabindex="-1"])','textarea:not([tabindex="-1"])','select:not([tabindex="-1"])','button:not([tabindex="-1"])','[role]:not([tabindex="-1"])'].join(","),ACTIVATING_ROLES=new Set(["checkbox","switch","radio","menuitemcheckbox","menuitemradio"]),MAX_ASSOCIATION_CANDIDATES_PER_MUTATION=2048,MAX_ASSOCIATION_REFRESHES_PER_TASK=256,associationRootObservations=new WeakMap;function isLabelElement(node){return node!==null&&"nodeType"in node&&node.nodeType===1&&"localName"in node&&node.localName==="label"}function isHtmlElement(node){return node.nodeType===1&&"focus"in node&&"style"in node}function isShadowRootNode(node){return node?.nodeType===11&&"host"in node}function isCurrentlyAssociatedLabel(label,host){const root=host.getRootNode();if(label.getRootNode()!==root)return!1;if(!label.hasAttribute("for")){const control="control"in label?label.control:void 0;return control==null?label.contains(host):control===host}const id=label.htmlFor;return id===""?!1:"getElementById"in root&&typeof root.getElementById=="function"?root.getElementById(id)===host:!("querySelectorAll"in root)||typeof root.querySelectorAll!="function"?!1:[...root.querySelectorAll("[id]")].find(candidate=>candidate.id===id)===host}function addSubscriptionById(observation,subscription){if(!subscription.id)return;const subscribers=observation.subscriptionsById.get(subscription.id)??new Set;subscribers.add(subscription),observation.subscriptionsById.set(subscription.id,subscribers)}function removeSubscriptionById(observation,subscription){if(!subscription.id)return;const subscribers=observation.subscriptionsById.get(subscription.id);subscribers?.delete(subscription),subscribers?.size===0&&observation.subscriptionsById.delete(subscription.id)}function updateSubscriptionId(observation,subscription){const id=subscription.host.id;id!==subscription.id&&(removeSubscriptionById(observation,subscription),subscription.id=id,addSubscriptionById(observation,subscription))}function addImplicitSubscription(observation,label,subscription){const subscriptions=observation.implicitSubscriptionsByLabel.get(label)??new Set;subscriptions.add(subscription),observation.implicitSubscriptionsByLabel.set(label,subscriptions)}function removeImplicitSubscription(observation,label,subscription){const subscriptions=observation.implicitSubscriptionsByLabel.get(label);subscriptions?.delete(subscription),subscriptions?.size===0&&observation.implicitSubscriptionsByLabel.delete(label)}function updateImplicitSubscriptions(observation,subscription,labels){const next=labels.filter(label=>!label.hasAttribute("for"));for(const label of subscription.implicitLabels)next.includes(label)||removeImplicitSubscription(observation,label,subscription);for(const label of next)subscription.implicitLabels.includes(label)||addImplicitSubscription(observation,label,subscription);subscription.implicitLabels=next}function hasAssociationRefreshes(observation){return observation.pending.size>0||observation.fallbackIterator!==void 0}function cancelAssociationContinuation(observation){observation.cancelContinuation?.(),observation.cancelContinuation=void 0}function scheduleAssociationContinuation(observation){if(!hasAssociationRefreshes(observation)||observation.cancelContinuation!==void 0)return;const callback=()=>{observation.cancelContinuation=void 0,drainAssociationRefreshes(observation)};if(observation.ownerWindow){const handle=observation.ownerWindow.setTimeout(callback,0);observation.cancelContinuation=()=>observation.ownerWindow?.clearTimeout(handle)}else{const handle=globalThis.setTimeout(callback,0);observation.cancelContinuation=()=>globalThis.clearTimeout(handle)}}function refreshAssociationSubscription(observation,subscription){subscription.active&&(subscription.listener(),observation.fallbackIterator&&(subscription.fallbackGeneration=observation.fallbackGeneration))}function drainTargetedAssociationRefreshes(observation){let remaining=MAX_ASSOCIATION_REFRESHES_PER_TASK;for(const subscription of observation.pending)if(observation.pending.delete(subscription),refreshAssociationSubscription(observation,subscription),--remaining===0)break;scheduleAssociationContinuation(observation)}function drainAssociationRefreshes(observation){let remaining=MAX_ASSOCIATION_REFRESHES_PER_TASK;for(const subscription of observation.pending)if(observation.pending.delete(subscription),refreshAssociationSubscription(observation,subscription),--remaining===0)break;for(;remaining>0&&observation.fallbackIterator;){const next=observation.fallbackIterator.next();if(next.done){observation.fallbackIterator=void 0;break}next.value.active&&next.value.fallbackGeneration!==observation.fallbackGeneration&&(next.value.listener(),next.value.fallbackGeneration=observation.fallbackGeneration),remaining--}scheduleAssociationContinuation(observation)}function notifyAssociationSubscriptions(observation,subscriptions,fallbackAll=!1){if(fallbackAll){const continuationPending=observation.cancelContinuation!==void 0;observation.pending.clear(),observation.fallbackGeneration++,observation.fallbackIterator=observation.subscriptions.values();for(const subscription of subscriptions)subscription.active&&observation.pending.add(subscription);continuationPending?drainTargetedAssociationRefreshes(observation):drainAssociationRefreshes(observation);return}for(const subscription of subscriptions)subscription.active&&observation.pending.add(subscription);drainTargetedAssociationRefreshes(observation)}function isLabelableElement(element){return element.localName==="input"?element.type!=="hidden":element.localName==="button"||element.localName==="meter"||element.localName==="output"||element.localName==="progress"||element.localName==="select"||element.localName==="textarea"?!0:element.localName.includes("-")&&element.constructor.formAssociated===!0}function collectAssociationElement(element,result){const id=element.getAttribute("id");return id&&result.ids.add(id),isLabelElement(element)&&element.hasAttribute("for")&&element.htmlFor&&result.ids.add(element.htmlFor),isLabelableElement(element)}function nextAssociationNode(root,current){if(current.firstChild)return current.firstChild;let cursor=current;for(;cursor&&cursor!==root;){if(cursor.nextSibling)return cursor.nextSibling;cursor=cursor.parentNode}return null}function collectAssociationCandidates(node,result){let containsLabelable=!1,current=node;for(;current;){if(result.work>=MAX_ASSOCIATION_CANDIDATES_PER_MUTATION){result.truncated=!0;break}result.work++,current.nodeType===1&&(containsLabelable=collectAssociationElement(current,result)||containsLabelable),current=nextAssociationNode(node,current)}return containsLabelable}function containingImplicitLabel(node){if(isLabelElement(node))return node.hasAttribute("for")?null:node;if(node.nodeType!==1||!("closest"in node))return null;const label=node.closest("label");return label&&!label.hasAttribute("for")?label:null}function collectFirstImplicitSubscription(observation,label,candidates,affected){let current=label.firstChild;for(;current;){if(candidates.work>=MAX_ASSOCIATION_CANDIDATES_PER_MUTATION){candidates.truncated=!0;return}if(candidates.work++,current.nodeType===1&&(isLabelableElement(current)||observation.subscriptionsByHost.has(current))){const subscription=observation.subscriptionsByHost.get(current);subscription&&affected.add(subscription);return}current=nextAssociationNode(label,current)}}function affectedAssociationSubscriptions(observation,mutations){const affected=new Set,candidates={ids:new Set,implicitLabels:new Set,truncated:!1,work:0},addIndexedCandidates=()=>{for(const id of candidates.ids)for(const subscription of observation.subscriptionsById.get(id)??[])affected.add(subscription);for(const label of candidates.implicitLabels)for(const subscription of observation.implicitSubscriptionsByLabel.get(label)??[])affected.add(subscription)};for(const mutation of mutations){if(candidates.work>=MAX_ASSOCIATION_CANDIDATES_PER_MUTATION){candidates.truncated=!0;break}if(candidates.work++,mutation.type==="attributes"){const target=mutation.target;if(mutation.attributeName==="id"){const oldId=mutation.oldValue??"",id=target.getAttribute("id")??"";oldId&&candidates.ids.add(oldId),id&&candidates.ids.add(id);const hostSubscription=observation.subscriptionsByHost.get(target);hostSubscription&&(affected.add(hostSubscription),updateSubscriptionId(observation,hostSubscription))}else if(mutation.attributeName==="for"&&isLabelElement(target)){const oldFor=mutation.oldValue;oldFor&&candidates.ids.add(oldFor),target.htmlFor&&candidates.ids.add(target.htmlFor);for(const subscription of observation.implicitSubscriptionsByLabel.get(target)??[])affected.add(subscription);target.hasAttribute("for")||candidates.implicitLabels.add(target)}else if(mutation.attributeName==="type"&&target.localName==="input"){const label=containingImplicitLabel(target);label&&candidates.implicitLabels.add(label)}continue}let changedLabelableShape=!1;for(const node of mutation.addedNodes)if(changedLabelableShape=collectAssociationCandidates(node,candidates)||changedLabelableShape,candidates.truncated)break;if(!candidates.truncated){for(const node of mutation.removedNodes)if(changedLabelableShape=collectAssociationCandidates(node,candidates)||changedLabelableShape,candidates.truncated)break}if(changedLabelableShape){const label=containingImplicitLabel(mutation.target);label&&candidates.implicitLabels.add(label)}if(candidates.truncated)break}if(addIndexedCandidates(),candidates.truncated)return{subscriptions:affected,fallbackAll:!0};for(const label of candidates.implicitLabels)if(collectFirstImplicitSubscription(observation,label,candidates,affected),candidates.truncated)return{subscriptions:affected,fallbackAll:!0};return{subscriptions:affected,fallbackAll:!1}}function observeAssociationRoot(host,listener){const root=host.getRootNode();let observation=associationRootObservations.get(root);if(!observation){const Observer=host.ownerDocument.defaultView?.MutationObserver,subscriptions=new Set,subscriptionsById=new Map,implicitSubscriptionsByLabel=new WeakMap,subscriptionsByHost=new WeakMap,pending=new Set,holder={},observer=Observer===void 0?void 0:new Observer(mutations=>{const current=holder.observation;if(!current)return;const affected=affectedAssociationSubscriptions(current,mutations);notifyAssociationSubscriptions(current,affected.subscriptions,affected.fallbackAll)});observer?.observe(root,{attributes:!0,attributeFilter:["for","id","type"],attributeOldValue:!0,childList:!0,subtree:!0}),observation={subscriptions,subscriptionsById,implicitSubscriptionsByLabel,subscriptionsByHost,pending,observer,ownerWindow:host.ownerDocument.defaultView,fallbackGeneration:0},holder.observation=observation,associationRootObservations.set(root,observation)}const subscription={host,listener,id:host.id,implicitLabels:[],fallbackGeneration:-1,active:!0};return observation.subscriptions.add(subscription),observation.subscriptionsByHost.set(host,subscription),addSubscriptionById(observation,subscription),{update(labels){subscription.active&&(updateSubscriptionId(observation,subscription),updateImplicitSubscriptions(observation,subscription,labels))},disconnect(){if(!subscription.active)return;subscription.active=!1,observation.pending.delete(subscription),observation.subscriptions.delete(subscription),observation.subscriptionsByHost.delete(host);for(const label of subscription.implicitLabels)removeImplicitSubscription(observation,label,subscription);subscription.implicitLabels=[],removeSubscriptionById(observation,subscription);const current=associationRootObservations.get(root);!current||current.subscriptions.size>0||(current.observer?.disconnect(),cancelAssociationContinuation(current),current.pending.clear(),current.fallbackIterator=void 0,associationRootObservations.delete(root))}}}function isComposedDescendant(host,candidate){let current=candidate;for(;current;){if(current===host)return!0;if(current.parentNode){current=current.parentNode;continue}current=isShadowRootNode(current)?current.host:null}return!1}function resolveExternalLabels(host){const native=attachedInternals.get(host)?.labels;if(native)return Array.from(native).filter(isLabelElement).filter(label=>isCurrentlyAssociatedLabel(label,host));const labels=[],ancestor=host.closest("label");ancestor&&isCurrentlyAssociatedLabel(ancestor,host)&&labels.push(ancestor);const root=host.getRootNode();if(host.id&&"querySelectorAll"in root)for(const found of root.querySelectorAll("label[for]"))isLabelElement(found)&&isCurrentlyAssociatedLabel(found,host)&&!labels.includes(found)&&labels.push(found);return labels}function labelText(node,exclude){if(node===exclude)return"";if(node.nodeType===Node.TEXT_NODE)return node.textContent??"";let text="";for(const child of node.childNodes)text+=labelText(child,exclude);return text}function resolveExternalLabelText(labels,host){return labels.map(label=>labelText(label,host).trim()).filter(text=>text!=="").join(" ")}class ExternalLabelController{constructor(host){this.host=host,this.labels=[],this.activating=!1,this.onLabelClick=event=>{if(this.activating||this.barred)return;const source=event.currentTarget;if(!source||!isLabelElement(source)||!isCurrentlyAssociatedLabel(source,this.host)){this.refresh();return}event.composedPath().includes(this.host)||queueMicrotask(()=>{if(event.defaultPrevented||!this.host.isConnected||this.barred)return;if(!isCurrentlyAssociatedLabel(source,this.host)){this.refresh();return}const focusTarget=this.resolveFocusTarget(),activation=this.resolveActivation(focusTarget);this.activating=!0;try{this.host.focus(),isComposedDescendant(this.host,deepActiveElementIn(this.host.ownerDocument))||focusTarget?.focus(),activation==="activate"&&focusTarget?.click()}finally{this.activating=!1}})}}hostConnected(){this.associationRootSubscription?.disconnect(),this.associationRootSubscription=observeAssociationRoot(this.host,()=>this.refresh()),this.refresh()}hostUpdated(){this.refresh()}hostDisconnected(){this.release(),this.stopObservingLabels(),this.associationRootSubscription?.disconnect(),this.associationRootSubscription=void 0;for(const label of this.labels)label.removeEventListener("click",this.onLabelClick);this.labels=[]}refresh(){const next=resolveExternalLabels(this.host);if(next.length!==this.labels.length||next.some((label,index)=>label!==this.labels[index])){for(const label of this.labels)label.removeEventListener("click",this.onLabelClick);this.labels=next;for(const label of this.labels)label.addEventListener("click",this.onLabelClick);this.observeLabels()}this.associationRootSubscription?.update(next),this.apply()}observeLabels(){this.stopObservingLabels();const Observer=this.host.ownerDocument.defaultView?.MutationObserver;if(this.labels.length===0||Observer===void 0)return;const observer=new Observer(()=>this.refresh());for(const label of this.labels)observer.observe(label,{characterData:!0,childList:!0,subtree:!0});this.labelObserver=observer}stopObservingLabels(){this.labelObserver?.disconnect(),this.labelObserver=void 0}get barred(){return typeof this.host.matches=="function"&&this.host.matches(":disabled")?!0:!!(this.host.effectiveDisabled??this.host.disabled)}resolveNameTarget(focusTarget){if(this.hostSemanticOwner)return this.host;const root=this.ownRoot;if(!root)return focusTarget;if(focusTarget){for(const composite of root.querySelectorAll(COMPOSITE_ROLE_SELECTOR))if(isHtmlElement(composite)&&isComposedDescendant(composite,focusTarget))return composite}if(focusTarget&&focusTarget.getRootNode()===root)return focusTarget;const owned=focusTarget?this.outermostOwnedAncestor(focusTarget):null;if(owned)return owned;const semantic=root.querySelector(SEMANTIC_TARGET_SELECTOR);return semantic&&isHtmlElement(semantic)?semantic:focusTarget}outermostOwnedAncestor(node){const root=this.ownRoot;let owned=null,current=node;for(;current&&current!==this.host;)isHtmlElement(current)&&(current.getRootNode()===root||current.parentNode===this.host)&&(owned=current),current.parentNode?current=current.parentNode:current=isShadowRootNode(current)?current.host:null;return owned}get ownRoot(){const root=this.host.renderRoot;return isShadowRootNode(root)?root:this.host.shadowRoot}resolveFocusTarget(){return this.hostSemanticOwner?this.host:collectFocusableElements(this.host)[0]??null}get hostSemanticOwner(){const candidate=this.host;return typeof candidate[EXTERNAL_LABEL_HOST_SEMANTICS]=="function"?candidate:null}hostHasAuthoredName(owner){return owner[EXTERNAL_LABEL_HOST_SEMANTICS]({type:"has-authored-name"})===!0}resolveActivation(focusTarget){const declared=this.host[EXTERNAL_LABEL_ACTIVATION];if(typeof declared=="function")return declared.call(this.host);if(!focusTarget||focusTarget.getRootNode()!==this.ownRoot)return"focus";const role=focusTarget.getAttribute("role");return role&&ACTIVATING_ROLES.has(role)?"activate":"focus"}apply(){const hostOwner=this.hostSemanticOwner;if(hostOwner&&this.hostHasAuthoredName(hostOwner)||!hostOwner&&this.host.hasAttribute("aria-label")){this.release();return}const name=resolveExternalLabelText(this.labels,this.host);if(name===""){this.release();return}const settled=this.applied;if(settled&&settled.name===name&&settled.target.isConnected&&settled.target.getAttribute("aria-label")===name)return;const target=this.resolveNameTarget(this.resolveFocusTarget());target&&(this.applied&&this.applied.target!==target&&this.release(),this.applied||(this.applied={target,name,had:target.hasAttribute("aria-label"),previous:target.getAttribute("aria-label")}),target===this.host&&hostOwner?hostOwner[EXTERNAL_LABEL_HOST_SEMANTICS]({type:"apply",name}):target.getAttribute("aria-label")!==name&&target.setAttribute("aria-label",name),this.applied.name=name)}release(){const applied=this.applied;if(this.applied=void 0,!applied)return;const{target,name,had,previous}=applied,hostOwner=target===this.host?this.hostSemanticOwner:null;if(hostOwner){hostOwner[EXTERNAL_LABEL_HOST_SEMANTICS]({type:"release",appliedName:name,hadPrevious:had,previous});return}target.getAttribute("aria-label")===name&&(had?target.setAttribute("aria-label",previous??""):target.removeAttribute("aria-label"))}}registerFormControlLabelSupport(captureFormInternals,host=>new ExternalLabelController(host));export{EXTERNAL_LABEL_ACTIVATION,EXTERNAL_LABEL_HOST_SEMANTICS,ExternalLabelController,captureFormInternals,resolveExternalLabelText,resolveExternalLabels};