@aceshooting/lyra-ui 9.1.0 → 9.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +246 -0
  2. package/README.md +7 -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-eval-dashboard/agent-eval-dashboard.styles.js +2 -2
  7. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  8. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  9. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  10. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  11. package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
  12. package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
  13. package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
  14. package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
  15. package/dist/components/agent-tools/schema-viewer/schema-viewer.styles.js +2 -2
  16. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  17. package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
  18. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  19. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  20. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  21. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  22. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
  23. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  24. package/dist/components/charts/chart/bar-chart.class.js +1 -1
  25. package/dist/components/charts/chart/bubble-chart.class.js +1 -1
  26. package/dist/components/charts/chart/chart.class.js +1 -1
  27. package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
  28. package/dist/components/charts/chart/histogram.class.js +1 -1
  29. package/dist/components/charts/chart/line-chart.class.js +1 -1
  30. package/dist/components/charts/chart/pie-chart.class.js +1 -1
  31. package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
  32. package/dist/components/charts/chart/radar-chart.class.js +1 -1
  33. package/dist/components/charts/chart/scatter-chart.class.js +1 -1
  34. package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
  35. package/dist/components/conversation/chat-message/chat-message.styles.js +6 -0
  36. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  37. package/dist/components/conversation/generation-metrics/generation-metrics.class.js +2 -2
  38. package/dist/components/conversation/realtime-session/realtime-session.styles.js +1 -1
  39. package/dist/components/conversation/thread-list/thread-list.styles.js +9 -0
  40. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  41. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  42. package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
  43. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  44. package/dist/components/data/pagination/pagination.class.js +1 -1
  45. package/dist/components/data/table/table.class.js +1 -1
  46. package/dist/components/forms/button/button.styles.js +1 -1
  47. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  48. package/dist/components/forms/combobox/combobox.class.js +1 -1
  49. package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
  50. package/dist/components/forms/input/time-input.class.js +1 -1
  51. package/dist/components/forms/switch/switch.styles.js +3 -1
  52. package/dist/components/layout/card/card.styles.js +2 -2
  53. package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
  54. package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
  55. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  56. package/dist/components/layout/multi-split/multi-split.styles.js +29 -9
  57. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  58. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
  59. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  60. package/dist/components/media/attachment-trigger/attachment-trigger.styles.js +2 -2
  61. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  62. package/dist/components/media/file-input/file-input.class.js +1 -1
  63. package/dist/components/media/flag/flag.class.js +1 -1
  64. package/dist/components/media/lightbox/lightbox.styles.js +2 -0
  65. package/dist/components/overlays/callout/callout.styles.js +2 -2
  66. package/dist/components/overlays/kbd/kbd.class.js +1 -1
  67. package/dist/components/overlays/overlay/popover.class.js +2 -2
  68. package/dist/components/overlays/overlay/tooltip.class.js +2 -2
  69. package/dist/components/overlays/popup/popup.class.js +2 -2
  70. package/dist/components/overlays/spinner/spinner.styles.js +2 -2
  71. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  72. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  73. package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
  74. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  75. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js +11 -0
  76. package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
  77. package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
  78. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  79. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  80. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  81. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  82. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  83. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  84. package/dist/internal/dev-mode-attribute-warning.d.ts +7 -0
  85. package/dist/internal/dev-mode-attribute-warning.js +1 -0
  86. package/dist/internal/lyra-element.js +1 -1
  87. package/dist/internal/package-metadata.d.ts +1 -1
  88. package/dist/internal/package-metadata.js +1 -1
  89. package/llms/components/lr-attachment-trigger.md +2 -2
  90. package/llms/components/lr-heatmap.md +1 -1
  91. package/llms/index.md +1 -1
  92. package/llms/peers.md +1 -1
  93. package/llms/shared.md +13 -0
  94. package/llms-full.txt +16 -3
  95. package/package.json +3 -3
  96. package/vscode-html-data.json +1 -1
  97. 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_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,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-changed=${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_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-changed=${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_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,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_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(`
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_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,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_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`
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_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,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_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`
2
2
  <div
3
3
  part="base"
4
4
  aria-busy=${this.ebookState.kind==="loading"?"true":"false"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Dev-mode-only: warns once per (tag, attribute-name) when `host` carries an attribute that
3
+ * isn't in `observedAttributes` and isn't in the always-exempt global/data/aria set. No-op when
4
+ * Lit's own dev-mode signal isn't present (production, or a dev environment where Lit itself
5
+ * isn't in dev mode).
6
+ */
7
+ export declare function warnUnknownAttributes(host: Element, observedAttributes: readonly string[]): void;
@@ -0,0 +1 @@
1
+ const GLOBAL_ATTRIBUTE_EXEMPTIONS=new Set(["id","hidden","inert","tabindex","title","role","part","exportparts","is","popover","translate","spellcheck","autocapitalize","autofocus","contenteditable","draggable","enterkeyhint","inputmode","nonce","accesskey","itemid","itemprop","itemref","itemscope","itemtype"]);function isExemptAttribute(name){return name.startsWith("data-")||name.startsWith("aria-")||GLOBAL_ATTRIBUTE_EXEMPTIONS.has(name)}function levenshteinDistance(a,b){const rows=a.length+1,cols=b.length+1,distances=Array.from({length:rows},()=>new Array(cols).fill(0));for(let i=0;i<rows;i++)distances[i][0]=i;for(let j=0;j<cols;j++)distances[0][j]=j;for(let i=1;i<rows;i++)for(let j=1;j<cols;j++){const cost=a[i-1]===b[j-1]?0:1;distances[i][j]=Math.min(distances[i-1][j]+1,distances[i][j-1]+1,distances[i-1][j-1]+cost)}return distances[rows-1][cols-1]}const SUGGESTION_MAX_DISTANCE=3;function closestObservedAttribute(name,observed){let best,bestDistance=SUGGESTION_MAX_DISTANCE+1;for(const candidate of observed){const distance=levenshteinDistance(name,candidate);distance<bestDistance&&(bestDistance=distance,best=candidate)}return bestDistance<=SUGGESTION_MAX_DISTANCE?best:void 0}function litDevWarnings(){return globalThis.litIssuedWarnings}function warnUnknownAttributes(host,observedAttributes){const warnings=litDevWarnings();if(!warnings)return;const observedSet=new Set(observedAttributes);for(const name of host.getAttributeNames()){if(observedSet.has(name)||isExemptAttribute(name))continue;const key=`lyra-unknown-attribute:${host.localName}:${name}`;if(warnings.has(key))continue;warnings.add(key);const suggestion=closestObservedAttribute(name,observedAttributes);console.warn(suggestion?`<${host.localName}>: unknown attribute '${name}' \u2014 did you mean '${suggestion}'?`:`<${host.localName}>: unknown attribute '${name}'`)}}export{warnUnknownAttributes};
@@ -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{LitElement}from"lit";import{property}from"lit/decorators.js";import{captureFormInternals,ExternalLabelController}from"./form-control-labels.js";import{tokens}from"./tokens.styles.js";import{palette}from"./tokens/palette.styles.js";import{resolveIntlLocale}from"./intl-cache.js";import{observeInheritedContext,beginInheritedContextUpdate,finishInheritedContextUpdate,markInheritedContextUpdateRendered,queueInheritedDirectionChange,recordInheritedDirectionRead,recordInheritedLocaleRead}from"./inherited-context-observer.js";import{canonicalizeLyraLocale,enableLyraLocaleCache,invalidateLyraLocaleCache,lyraLocaleCatalogVersion,peekLyraLocale,recordLyraOwnerDocumentConnection,resolveLyraDirection,resolveLyraString,resolveLyraLocale,snapshotLyraLocaleStrings,subscribeLyraLocaleForHost}from"./localization-runtime.js";const PUBLIC_COLLECTION_ENTRY_LIMIT=1e4,PUBLIC_COLLECTION_NODE_LIMIT=5e4,PUBLIC_COLLECTION_DEPTH_LIMIT=256,OMIT_COLLECTION_VALUE=Symbol("omit-public-collection-value");function snapshotRealm(view){const candidate=view;return{Array:candidate?.Array??Array,Date:candidate?.Date??Date,Map:candidate?.Map??Map,Object:candidate?.Object??Object,Set:candidate?.Set??Set}}function isRealmNeutralPlainRecord(value){try{const prototype=Object.getPrototypeOf(value);if(prototype===null)return!0;const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor");return!!(constructor&&"value"in constructor&&typeof constructor.value=="function"&&constructor.value.name==="Object"&&Object.getPrototypeOf(prototype)===null)}catch{return!1}}function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isNativeArrayBufferView(value){try{return ArrayBuffer.isView(value)}catch{return!1}}function isImmutableBlob(value){if(typeof Blob>"u")return!1;const sizeGetter=Object.getOwnPropertyDescriptor(Blob.prototype,"size")?.get;if(!sizeGetter)return!1;try{return sizeGetter.call(value),!0}catch{return!1}}const MUTATING_DATE_METHODS=new Set(["setDate","setFullYear","setHours","setMilliseconds","setMinutes","setMonth","setSeconds","setTime","setUTCDate","setUTCFullYear","setUTCHours","setUTCMilliseconds","setUTCMinutes","setUTCMonth","setUTCSeconds","setYear"]);function nativeDateTime(value){try{return Date.prototype.getTime.call(value)}catch{return OMIT_COLLECTION_VALUE}}function snapshotReadonlyDate(source,time,budget){const target=new budget.realm.Date(time),boundMethods=new Map,rejectMutation=()=>{throw new TypeError("Cannot mutate a readonly Date snapshot")},snapshot=new Proxy(target,{get(date,key){if(MUTATING_DATE_METHODS.has(key))return rejectMutation;if(key==="constructor")return budget.realm.Date;const value=Reflect.get(date,key,date);if(typeof value!="function")return value;const cached=boundMethods.get(key);if(cached)return cached;const bound=value.bind(date);return boundMethods.set(key,bound),bound}});return rememberSnapshot(budget,source,snapshot),Object.freeze(snapshot)}function rememberSnapshot(budget,source,snapshot){budget.seen.set(source,snapshot),budget.additions.push(source)}function snapshotTransaction(budget,create){const remaining=budget.remaining,additions=budget.additions.length,result=create();if(result!==OMIT_COLLECTION_VALUE)return result;budget.remaining=remaining;for(let index=budget.additions.length-1;index>=additions;index-=1)budget.seen.delete(budget.additions[index]);return budget.additions.length=additions,OMIT_COLLECTION_VALUE}function emptyRealmArray(realm){return Object.freeze(new realm.Array)}function*ownEnumerableStringKeys(value){for(const key in value)Object.getOwnPropertyDescriptor(value,key)?.enumerable&&(yield key)}function snapshotDataRecord(value,keys,prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys){const output=budget.realm.Object.create(prototype);rememberSnapshot(budget,value,output);try{for(const key of keys){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor?.enumerable||!("value"in descriptor))continue;if(budget.remaining<=0)return OMIT_COLLECTION_VALUE;budget.remaining-=1;const entry=preserveRecordKeys?.has(key)?descriptor.value:preserveCollectionItemKeys?.has(key)?snapshotIdentityCollection(descriptor.value,budget.realm,budget):snapshotCollectionValue(descriptor.value,budget,depth+1);if(entry===OMIT_COLLECTION_VALUE)return OMIT_COLLECTION_VALUE;Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}}catch{return OMIT_COLLECTION_VALUE}return Object.freeze(output)}function snapshotCollectionValue(value,budget,depth,preserveRecordKeys,preserveCollectionItemKeys,allowArrayPrefixTruncation=!1){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(budget.seen.has(value))return budget.seen.get(value);if(depth>PUBLIC_COLLECTION_DEPTH_LIMIT||budget.remaining<=0)return OMIT_COLLECTION_VALUE;if(isArrayValue(value)){let lengthDescriptor;try{lengthDescriptor=Object.getOwnPropertyDescriptor(value,"length")}catch{return allowArrayPrefixTruncation?emptyRealmArray(budget.realm):OMIT_COLLECTION_VALUE}if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0)return allowArrayPrefixTruncation?emptyRealmArray(budget.realm):OMIT_COLLECTION_VALUE;const sourceLength=lengthDescriptor.value;if(!allowArrayPrefixTruncation&&sourceLength>PUBLIC_COLLECTION_ENTRY_LIMIT)return OMIT_COLLECTION_VALUE;const length=Math.min(sourceLength,PUBLIC_COLLECTION_ENTRY_LIMIT),output=new budget.realm.Array(length);rememberSnapshot(budget,value,output);for(let index=0;index<length;index+=1){if(budget.remaining<=0){if(!allowArrayPrefixTruncation)return OMIT_COLLECTION_VALUE;output.length=index;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{if(!allowArrayPrefixTruncation)return OMIT_COLLECTION_VALUE;output.length=index;break}if(!descriptor)continue;if(!("value"in descriptor)){if(!allowArrayPrefixTruncation)return OMIT_COLLECTION_VALUE;output.length=index;break}const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(descriptor.value,budget,depth+1)));if(entry===OMIT_COLLECTION_VALUE){if(!allowArrayPrefixTruncation)return OMIT_COLLECTION_VALUE;output.length=index;break}Object.defineProperty(output,index,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}if(isRealmNeutralPlainRecord(value)){let prototype;try{prototype=Object.getPrototypeOf(value)}catch{return OMIT_COLLECTION_VALUE}return snapshotDataRecord(value,ownEnumerableStringKeys(value),prototype===null?null:budget.realm.Object.prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys)}const dateTime=nativeDateTime(value);if(dateTime!==OMIT_COLLECTION_VALUE)return snapshotReadonlyDate(value,dateTime,budget);const entries=nativeMapEntries(value);if(entries)return snapshotDetachedMap(value,entries,budget,depth);const values=nativeSetValues(value);if(values)return snapshotDetachedSet(value,values,budget,depth);if(isNativeArrayBufferView(value))return OMIT_COLLECTION_VALUE;const rect=snapshotDOMRect(value,budget);return rect!==OMIT_COLLECTION_VALUE?rect:isImmutableBlob(value)?value:OMIT_COLLECTION_VALUE}function snapshotPublicCollection(value,view){if(value===null||typeof value!="object"&&typeof value!="function")return value;const realm=snapshotRealm(view),budget={remaining:PUBLIC_COLLECTION_NODE_LIMIT,seen:new WeakMap,additions:[],realm},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,void 0,void 0,!0));if(snapshot!==OMIT_COLLECTION_VALUE)return snapshot;if(isArrayValue(value)||isNativeArrayBufferView(value))return emptyRealmArray(realm);if(typeof value=="object"){if(nativeMapEntries(value))return readonlyMapFacade(new realm.Map,realm);if(nativeSetValues(value))return readonlySetFacade(new realm.Set,realm);if(isRealmNeutralPlainRecord(value)){const prototype=Object.getPrototypeOf(value);return Object.freeze(realm.Object.create(prototype===null?null:realm.Object.prototype))}}return emptyRealmArray(realm)}function nativeMapEntries(value){try{return Map.prototype.entries.call(value)}catch{return}}function nativeSetValues(value){try{return Set.prototype.values.call(value)}catch{return}}function snapshotDOMRect(value,budget){if(typeof DOMRectReadOnly>"u")return OMIT_COLLECTION_VALUE;const nativePrototype=DOMRectReadOnly.prototype,output=budget.realm.Object.create(budget.realm.Object.prototype);for(const key of["x","y","width","height","top","right","bottom","left"]){let coordinate;try{const getter=Object.getOwnPropertyDescriptor(nativePrototype,key)?.get;if(!getter)return OMIT_COLLECTION_VALUE;coordinate=getter.call(value)}catch{return OMIT_COLLECTION_VALUE}if(typeof coordinate!="number"||!Number.isFinite(coordinate))return OMIT_COLLECTION_VALUE;Object.defineProperty(output,key,{value:coordinate,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function readonlyMapFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},get:{value:key=>backing.get(key)},has:{value:key=>backing.has(key)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach((entry,key)=>callback.call(thisArg,entry,key,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),Object.freeze(facade)}function readonlySetFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},has:{value:entry=>backing.has(entry)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach(entry=>callback.call(thisArg,entry,entry,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),Object.freeze(facade)}function snapshotIdentityMap(entries,realm=snapshotRealm()){const backing=new realm.Map;for(let next=entries.next(),count=0;!next.done&&count<PUBLIC_COLLECTION_ENTRY_LIMIT;next=entries.next(),count+=1)backing.set(next.value[0],next.value[1]);return readonlyMapFacade(backing,realm)}function snapshotIdentitySet(values,realm=snapshotRealm()){const backing=new realm.Set;for(let next=values.next(),count=0;!next.done&&count<PUBLIC_COLLECTION_ENTRY_LIMIT;next=values.next(),count+=1)backing.add(next.value);return readonlySetFacade(backing,realm)}function snapshotDetachedMap(source,entries,budget,depth){const backing=new budget.realm.Map,facade=readonlyMapFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);for(let count=0;count<PUBLIC_COLLECTION_ENTRY_LIMIT;count+=1){let next;try{next=entries.next()}catch{break}if(next.done||budget.remaining<=0)break;const pair=snapshotTransaction(budget,()=>{budget.remaining-=1;const key=snapshotCollectionValue(next.value[0],budget,depth+1);if(key===OMIT_COLLECTION_VALUE)return OMIT_COLLECTION_VALUE;const entry=snapshotCollectionValue(next.value[1],budget,depth+1);return entry===OMIT_COLLECTION_VALUE?OMIT_COLLECTION_VALUE:[key,entry]});pair!==OMIT_COLLECTION_VALUE&&backing.set(pair[0],pair[1])}return facade}function snapshotDetachedSet(source,values,budget,depth){const backing=new budget.realm.Set,facade=readonlySetFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);for(let count=0;count<PUBLIC_COLLECTION_ENTRY_LIMIT;count+=1){let next;try{next=values.next()}catch{break}if(next.done||budget.remaining<=0)break;const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(next.value,budget,depth+1)));entry!==OMIT_COLLECTION_VALUE&&backing.add(entry)}return facade}function snapshotIdentityCollection(value,view,budget){const realm=snapshotRealm(view);if(budget&&value!==null&&(typeof value=="object"||typeof value=="function")&&budget.seen.has(value))return budget.seen.get(value);if(isArrayValue(value)){let lengthDescriptor;try{lengthDescriptor=Object.getOwnPropertyDescriptor(value,"length")}catch{return emptyRealmArray(realm)}const length=lengthDescriptor&&"value"in lengthDescriptor&&typeof lengthDescriptor.value=="number"&&Number.isSafeInteger(lengthDescriptor.value)&&lengthDescriptor.value>=0?Math.min(lengthDescriptor.value,PUBLIC_COLLECTION_ENTRY_LIMIT):0,output=new realm.Array(length);budget&&rememberSnapshot(budget,value,output);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}!descriptor||!("value"in descriptor)||Object.defineProperty(output,index,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}if(value===null||typeof value!="object")return value;const mapEntries=nativeMapEntries(value);if(mapEntries){const output=snapshotIdentityMap(mapEntries,realm);return budget&&rememberSnapshot(budget,value,output),output}const setValues=nativeSetValues(value);if(setValues){const output=snapshotIdentitySet(setValues,realm);return budget&&rememberSnapshot(budget,value,output),output}return emptyRealmArray(realm)}function snapshotEventDetail(value,view,preserveRootKeys,preserveCollectionItemKeys){if(value==null)return value;const budget={remaining:PUBLIC_COLLECTION_NODE_LIMIT,seen:new WeakMap,additions:[],realm:snapshotRealm(view)},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,preserveRootKeys,preserveCollectionItemKeys));return snapshot===OMIT_COLLECTION_VALUE?null:snapshot}const SEED_FIRST_RENDER_STATE=Symbol("lr-seed-first-render-state"),SLOT_PRESENCE_UNRESOLVED=Symbol("lr-slot-presence-unresolved"),REACTIVE_HOST_ATTRIBUTES=["aria-label","aria-describedby","lang","dir"],DIRECTION_HOST_ATTRIBUTES=["class","style","slot"];function trustedLyraConstructorChain(instance){const constructors=[];let prototype=Object.getPrototypeOf(instance);for(;prototype&&prototype!==LitElement.prototype;){const descriptor=Object.getOwnPropertyDescriptor(prototype,"constructor");typeof descriptor?.value=="function"&&constructors.push(descriptor.value),prototype=Object.getPrototypeOf(prototype)}return constructors}const collectionPolicyByPrototype=new WeakMap;function collectionPropertyPolicy(instance,name){const prototype=Object.getPrototypeOf(instance);let policies=collectionPolicyByPrototype.get(prototype);policies||(policies=new Map,collectionPolicyByPrototype.set(prototype,policies));const cached=policies.get(name);if(cached)return cached;let owns=!1,preservesItemIdentity=!1,preservesObjectIdentity=!1;for(const constructor of trustedLyraConstructorChain(instance)){const declared=constructor;Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties")&&declared.ownedCollectionProperties.includes(name)&&(owns=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionProperties")&&declared.identityCollectionProperties.includes(name)&&(preservesItemIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionObjectProperties")&&declared.identityCollectionObjectProperties.includes(name)&&(preservesObjectIdentity=!0)}const policy=Object.freeze({owns,preservesItemIdentity,preservesObjectIdentity});return policies.set(name,policy),policy}class LyraElement extends LitElement{static{this.styles=[palette,tokens]}static{this.ownedCollectionProperties=Object.freeze([])}static{this.identityCollectionProperties=Object.freeze([])}static{this.identityCollectionObjectProperties=Object.freeze([])}static{this.immutableEventDetails=Object.freeze([])}static{this.identityEventDetailProperties=Object.freeze({})}static{this.identityEventDetailCollectionItems=Object.freeze({})}static getPropertyDescriptor(name,key,options){const descriptor=super.getPropertyDescriptor(name,key,options);if(!descriptor?.set)return descriptor;const originalSet=descriptor.set;return{...descriptor,set(value){const policy=collectionPropertyPolicy(this,name);if(!policy.owns){originalSet.call(this,value);return}const ownerView=this.ownerDocument?.defaultView;originalSet.call(this,policy.preservesObjectIdentity&&value!==null&&typeof value=="object"&&!isArrayValue(value)?value:policy.preservesItemIdentity?snapshotIdentityCollection(value,ownerView):snapshotPublicCollection(value,ownerView))}}}static{this.defaultStrings=Object.freeze({})}static get observedAttributes(){return[...new Set([...super.observedAttributes,...REACTIVE_HOST_ATTRIBUTES,...DIRECTION_HOST_ATTRIBUTES])]}get strings(){return this.stringsValue}set strings(value){const previous=this.stringsValue;this.stringsValue=snapshotLyraLocaleStrings(value),this.requestUpdate("strings",previous)}constructor(){super(),this.locale="",this.stringsValue=snapshotLyraLocaleStrings({}),this.localeSubscriptionNeeded=!1,this.constructor.formAssociated&&this.addController(new ExternalLabelController(this))}attachInternals(){const internals=super.attachInternals();return captureFormInternals(this,internals),internals}connectedCallback(){this.hydratingServerShadow??=typeof Node>"u"||!this.hasUpdated&&this.shadowRoot!==null,super.connectedCallback(),recordLyraOwnerDocumentConnection(this),enableLyraLocaleCache(this),invalidateLyraLocaleCache(this),this.stopInheritedContextObservation?.(),this.stopInheritedContextObservation=observeInheritedContext(this),this.localeSubscriptionNeeded&&this.ensureLocaleSubscription(),this.lastLocalizedCatalogVersion!==void 0&&lyraLocaleCatalogVersion(resolveLyraLocale(this))!==this.lastLocalizedCatalogVersion&&this.requestUpdate();const deferred=this.deferredAfterUpdate;if(deferred){this.deferredAfterUpdate=void 0;for(const[key,callback]of deferred)this.scheduleAfterUpdate(callback,key)}}disconnectedCallback(){this.pendingLoadController?.abort(),this.pendingLoadController=void 0,this.stopLocaleSubscription?.(),this.stopLocaleSubscription=void 0,this.stopInheritedContextObservation?.(),this.stopInheritedContextObservation=void 0,invalidateLyraLocaleCache(this),super.disconnectedCallback()}adoptedCallback(){this.stopLocaleSubscription?.(),this.stopLocaleSubscription=void 0,invalidateLyraLocaleCache(this),this.isConnected&&this.localeSubscriptionNeeded&&this.ensureLocaleSubscription()}requestUpdate(name,oldValue,options){invalidateLyraLocaleCache(this),super.requestUpdate(name,oldValue,options)}performUpdate(){beginInheritedContextUpdate(this);try{super.performUpdate()}finally{finishInheritedContextUpdate(this)}}update(changedProperties){super.update(changedProperties),markInheritedContextUpdateRendered(this)}ensureLocaleSubscription(){this.localeSubscriptionNeeded=!0,!(!this.isConnected||this.stopLocaleSubscription)&&(this.stopLocaleSubscription=subscribeLyraLocaleForHost(this))}attributeChangedCallback(name,oldValue,value){const directionHostAttribute=oldValue!==value&&DIRECTION_HOST_ATTRIBUTES.includes(name);directionHostAttribute&&queueInheritedDirectionChange(this,name==="slot"),super.attributeChangedCallback(name,oldValue,value),oldValue!==value&&REACTIVE_HOST_ATTRIBUTES.includes(name)?this.requestUpdate():directionHostAttribute&&invalidateLyraLocaleCache(this)}seedFirstRenderState(seed){this.hasUpdated||this[SEED_FIRST_RENDER_STATE](seed)}[SEED_FIRST_RENDER_STATE](seed){if(!this.hydratingServerShadow){seed();return}const pending=this.deferredFirstRenderSeeds??=new Set;pending.add(seed),!(pending.size>1)&&this.updateComplete.then(()=>{setTimeout(()=>{this.hydratingServerShadow=!1;const seeds=this.deferredFirstRenderSeeds;this.deferredFirstRenderSeeds=void 0;for(const deferred of seeds??[])deferred();this.requestUpdate()},0)},()=>{this.hydratingServerShadow=!1,this.deferredFirstRenderSeeds=void 0})}updateBrowserDerivedState(update){this[SEED_FIRST_RENDER_STATE](update)}renderSlotPresence(present){return present||this[SLOT_PRESENCE_UNRESOLVED]()}[SLOT_PRESENCE_UNRESOLVED](){return typeof Node>"u"||this.hydratingServerShadow===!0}beginAbortableLoad(){this.pendingLoadController?.abort(),this.pendingLoadController=void 0;const AbortControllerCtor=this.ownerDocument?.defaultView?.AbortController;if(AbortControllerCtor)return this.pendingLoadController=new AbortControllerCtor,this.pendingLoadController.signal}scheduleAfterUpdate(callback,key="load"){const pending=this.afterUpdateCallbacks??=new Map;pending.has(key)||(pending.set(key,callback),!(pending.size>1)&&queueMicrotask(()=>{const due=this.afterUpdateCallbacks;if(this.afterUpdateCallbacks=void 0,!due)return;if(this.isConnected){for(const due_callback of due.values())due_callback();return}const held=this.deferredAfterUpdate??=new Map;for(const[heldKey,heldCallback]of due)held.has(heldKey)||held.set(heldKey,heldCallback)}))}localize(key,fallback,values){const message=resolveLyraString(this,key,this.strings,fallback,values,this.constructor.defaultStrings),locale=peekLyraLocale(this);return recordInheritedLocaleRead(this,locale),locale!==void 0&&(this.lastLocalizedCatalogVersion=lyraLocaleCatalogVersion(locale),this.ensureLocaleSubscription()),message}get effectiveMessageLocale(){if(this.locale)return canonicalizeLyraLocale(this.locale);const locale=resolveLyraLocale(this);return recordInheritedLocaleRead(this,locale),this.ensureLocaleSubscription(),locale}get effectiveLocale(){return resolveIntlLocale(this.effectiveMessageLocale)}get effectiveIntlLocale(){return this.effectiveLocale}get effectiveDirection(){const direction=resolveLyraDirection(this);return recordInheritedDirectionRead(this,direction),direction}addEventListener(type,listener,options){super.addEventListener(type,listener,options)}removeEventListener(type,listener,options){super.removeEventListener(type,listener,options)}emit(name,...args){const[detail,options]=args,ownerDocument=this.ownerDocument;let CustomEventCtor=ownerDocument?.defaultView?.CustomEvent;if(!CustomEventCtor&&ownerDocument)try{const candidate=ownerDocument.createEvent("CustomEvent").constructor;typeof candidate=="function"&&(CustomEventCtor=candidate)}catch{}CustomEventCtor??=globalThis.CustomEvent;let snapshotsDetail=!1;const identityDetailKeys=new Set,identityCollectionItemKeys=new Set;for(const constructor of trustedLyraConstructorChain(this)){if(Object.prototype.hasOwnProperty.call(constructor,"immutableEventDetails")&&constructor.immutableEventDetails.includes(name)&&(snapshotsDetail=!0),Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailProperties"))for(const key of constructor.identityEventDetailProperties[name]??[])identityDetailKeys.add(key);if(Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailCollectionItems"))for(const key of constructor.identityEventDetailCollectionItems[name]??[])identityCollectionItemKeys.add(key)}const event=new CustomEventCtor(name,{detail:detail===void 0?null:snapshotsDetail?snapshotEventDetail(detail,ownerDocument?.defaultView,identityDetailKeys,identityCollectionItemKeys):detail,bubbles:!0,composed:!0,cancelable:options?.cancelable??!1});return this.dispatchEvent(event),event}}__decorate([property({reflect:!0})],LyraElement.prototype,"locale",void 0),__decorate([property({attribute:!1})],LyraElement.prototype,"strings",null);export{LyraElement,SEED_FIRST_RENDER_STATE,SLOT_PRESENCE_UNRESOLVED};
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{LitElement}from"lit";import{property}from"lit/decorators.js";import{captureFormInternals,ExternalLabelController}from"./form-control-labels.js";import{tokens}from"./tokens.styles.js";import{palette}from"./tokens/palette.styles.js";import{resolveIntlLocale}from"./intl-cache.js";import{warnUnknownAttributes}from"./dev-mode-attribute-warning.js";import{observeInheritedContext,beginInheritedContextUpdate,finishInheritedContextUpdate,markInheritedContextUpdateRendered,queueInheritedDirectionChange,recordInheritedDirectionRead,recordInheritedLocaleRead}from"./inherited-context-observer.js";import{canonicalizeLyraLocale,enableLyraLocaleCache,invalidateLyraLocaleCache,lyraLocaleCatalogVersion,peekLyraLocale,recordLyraOwnerDocumentConnection,resolveLyraDirection,resolveLyraString,resolveLyraLocale,snapshotLyraLocaleStrings,subscribeLyraLocaleForHost}from"./localization-runtime.js";const PUBLIC_COLLECTION_ENTRY_LIMIT=1e4,PUBLIC_COLLECTION_NODE_LIMIT=5e4,PUBLIC_COLLECTION_DEPTH_LIMIT=256,OMIT_COLLECTION_VALUE=Symbol("omit-public-collection-value");function snapshotRealm(view){const candidate=view;return{Array:candidate?.Array??Array,Date:candidate?.Date??Date,Map:candidate?.Map??Map,Object:candidate?.Object??Object,Set:candidate?.Set??Set}}function isRealmNeutralPlainRecord(value){try{const prototype=Object.getPrototypeOf(value);if(prototype===null)return!0;const constructor=Object.getOwnPropertyDescriptor(prototype,"constructor");return!!(constructor&&"value"in constructor&&typeof constructor.value=="function"&&constructor.value.name==="Object"&&Object.getPrototypeOf(prototype)===null)}catch{return!1}}function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isNativeArrayBufferView(value){try{return ArrayBuffer.isView(value)}catch{return!1}}function isImmutableBlob(value){if(typeof Blob>"u")return!1;const sizeGetter=Object.getOwnPropertyDescriptor(Blob.prototype,"size")?.get;if(!sizeGetter)return!1;try{return sizeGetter.call(value),!0}catch{return!1}}const MUTATING_DATE_METHODS=new Set(["setDate","setFullYear","setHours","setMilliseconds","setMinutes","setMonth","setSeconds","setTime","setUTCDate","setUTCFullYear","setUTCHours","setUTCMilliseconds","setUTCMinutes","setUTCMonth","setUTCSeconds","setYear"]);function nativeDateTime(value){try{return Date.prototype.getTime.call(value)}catch{return OMIT_COLLECTION_VALUE}}function snapshotReadonlyDate(source,time,budget){const target=new budget.realm.Date(time),boundMethods=new Map,rejectMutation=()=>{throw new TypeError("Cannot mutate a readonly Date snapshot")},snapshot=new Proxy(target,{get(date,key){if(MUTATING_DATE_METHODS.has(key))return rejectMutation;if(key==="constructor")return budget.realm.Date;const value=Reflect.get(date,key,date);if(typeof value!="function")return value;const cached=boundMethods.get(key);if(cached)return cached;const bound=value.bind(date);return boundMethods.set(key,bound),bound}});return rememberSnapshot(budget,source,snapshot),Object.freeze(snapshot)}function rememberSnapshot(budget,source,snapshot){budget.seen.set(source,snapshot),budget.additions.push(source)}function snapshotTransaction(budget,create){const remaining=budget.remaining,additions=budget.additions.length,result=create();if(result!==OMIT_COLLECTION_VALUE)return result;budget.remaining=remaining;for(let index=budget.additions.length-1;index>=additions;index-=1)budget.seen.delete(budget.additions[index]);return budget.additions.length=additions,OMIT_COLLECTION_VALUE}function emptyRealmArray(realm){return Object.freeze(new realm.Array)}function*ownEnumerableStringKeys(value){for(const key in value)Object.getOwnPropertyDescriptor(value,key)?.enumerable&&(yield key)}function snapshotDataRecord(value,keys,prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys){const output=budget.realm.Object.create(prototype);rememberSnapshot(budget,value,output);try{for(const key of keys){const descriptor=Object.getOwnPropertyDescriptor(value,key);if(!descriptor?.enumerable||!("value"in descriptor))continue;if(budget.remaining<=0)return OMIT_COLLECTION_VALUE;budget.remaining-=1;const entry=preserveRecordKeys?.has(key)?descriptor.value:preserveCollectionItemKeys?.has(key)?snapshotIdentityCollection(descriptor.value,budget.realm,budget):snapshotCollectionValue(descriptor.value,budget,depth+1);if(entry===OMIT_COLLECTION_VALUE)return OMIT_COLLECTION_VALUE;Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}}catch{return OMIT_COLLECTION_VALUE}return Object.freeze(output)}function snapshotCollectionValue(value,budget,depth,preserveRecordKeys,preserveCollectionItemKeys,allowArrayPrefixTruncation=!1){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(budget.seen.has(value))return budget.seen.get(value);if(depth>PUBLIC_COLLECTION_DEPTH_LIMIT||budget.remaining<=0)return OMIT_COLLECTION_VALUE;if(isArrayValue(value)){let lengthDescriptor;try{lengthDescriptor=Object.getOwnPropertyDescriptor(value,"length")}catch{return allowArrayPrefixTruncation?emptyRealmArray(budget.realm):OMIT_COLLECTION_VALUE}if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0)return allowArrayPrefixTruncation?emptyRealmArray(budget.realm):OMIT_COLLECTION_VALUE;const sourceLength=lengthDescriptor.value;if(!allowArrayPrefixTruncation&&sourceLength>PUBLIC_COLLECTION_ENTRY_LIMIT)return OMIT_COLLECTION_VALUE;const length=Math.min(sourceLength,PUBLIC_COLLECTION_ENTRY_LIMIT),output=new budget.realm.Array(length);rememberSnapshot(budget,value,output);for(let index=0;index<length;index+=1){if(budget.remaining<=0){if(!allowArrayPrefixTruncation)return OMIT_COLLECTION_VALUE;output.length=index;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{if(!allowArrayPrefixTruncation)return OMIT_COLLECTION_VALUE;output.length=index;break}if(!descriptor)continue;if(!("value"in descriptor)){if(!allowArrayPrefixTruncation)return OMIT_COLLECTION_VALUE;output.length=index;break}const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(descriptor.value,budget,depth+1)));if(entry===OMIT_COLLECTION_VALUE){if(!allowArrayPrefixTruncation)return OMIT_COLLECTION_VALUE;output.length=index;break}Object.defineProperty(output,index,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}if(isRealmNeutralPlainRecord(value)){let prototype;try{prototype=Object.getPrototypeOf(value)}catch{return OMIT_COLLECTION_VALUE}return snapshotDataRecord(value,ownEnumerableStringKeys(value),prototype===null?null:budget.realm.Object.prototype,budget,depth,preserveRecordKeys,preserveCollectionItemKeys)}const dateTime=nativeDateTime(value);if(dateTime!==OMIT_COLLECTION_VALUE)return snapshotReadonlyDate(value,dateTime,budget);const entries=nativeMapEntries(value);if(entries)return snapshotDetachedMap(value,entries,budget,depth);const values=nativeSetValues(value);if(values)return snapshotDetachedSet(value,values,budget,depth);if(isNativeArrayBufferView(value))return OMIT_COLLECTION_VALUE;const rect=snapshotDOMRect(value,budget);return rect!==OMIT_COLLECTION_VALUE?rect:isImmutableBlob(value)?value:OMIT_COLLECTION_VALUE}function snapshotPublicCollection(value,view){if(value===null||typeof value!="object"&&typeof value!="function")return value;const realm=snapshotRealm(view),budget={remaining:PUBLIC_COLLECTION_NODE_LIMIT,seen:new WeakMap,additions:[],realm},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,void 0,void 0,!0));if(snapshot!==OMIT_COLLECTION_VALUE)return snapshot;if(isArrayValue(value)||isNativeArrayBufferView(value))return emptyRealmArray(realm);if(typeof value=="object"){if(nativeMapEntries(value))return readonlyMapFacade(new realm.Map,realm);if(nativeSetValues(value))return readonlySetFacade(new realm.Set,realm);if(isRealmNeutralPlainRecord(value)){const prototype=Object.getPrototypeOf(value);return Object.freeze(realm.Object.create(prototype===null?null:realm.Object.prototype))}}return emptyRealmArray(realm)}function nativeMapEntries(value){try{return Map.prototype.entries.call(value)}catch{return}}function nativeSetValues(value){try{return Set.prototype.values.call(value)}catch{return}}function snapshotDOMRect(value,budget){if(typeof DOMRectReadOnly>"u")return OMIT_COLLECTION_VALUE;const nativePrototype=DOMRectReadOnly.prototype,output=budget.realm.Object.create(budget.realm.Object.prototype);for(const key of["x","y","width","height","top","right","bottom","left"]){let coordinate;try{const getter=Object.getOwnPropertyDescriptor(nativePrototype,key)?.get;if(!getter)return OMIT_COLLECTION_VALUE;coordinate=getter.call(value)}catch{return OMIT_COLLECTION_VALUE}if(typeof coordinate!="number"||!Number.isFinite(coordinate))return OMIT_COLLECTION_VALUE;Object.defineProperty(output,key,{value:coordinate,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function readonlyMapFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},get:{value:key=>backing.get(key)},has:{value:key=>backing.has(key)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach((entry,key)=>callback.call(thisArg,entry,key,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),Object.freeze(facade)}function readonlySetFacade(backing,realm=snapshotRealm()){let facade;return facade=realm.Object.create(realm.Object.prototype),Object.defineProperties(facade,{size:{enumerable:!0,get:()=>backing.size},entries:{value:()=>backing.entries()},has:{value:entry=>backing.has(entry)},keys:{value:()=>backing.keys()},values:{value:()=>backing.values()},forEach:{value:(callback,thisArg)=>backing.forEach(entry=>callback.call(thisArg,entry,entry,facade))},[Symbol.iterator]:{value:()=>backing[Symbol.iterator]()}}),Object.freeze(facade)}function snapshotIdentityMap(entries,realm=snapshotRealm()){const backing=new realm.Map;for(let next=entries.next(),count=0;!next.done&&count<PUBLIC_COLLECTION_ENTRY_LIMIT;next=entries.next(),count+=1)backing.set(next.value[0],next.value[1]);return readonlyMapFacade(backing,realm)}function snapshotIdentitySet(values,realm=snapshotRealm()){const backing=new realm.Set;for(let next=values.next(),count=0;!next.done&&count<PUBLIC_COLLECTION_ENTRY_LIMIT;next=values.next(),count+=1)backing.add(next.value);return readonlySetFacade(backing,realm)}function snapshotDetachedMap(source,entries,budget,depth){const backing=new budget.realm.Map,facade=readonlyMapFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);for(let count=0;count<PUBLIC_COLLECTION_ENTRY_LIMIT;count+=1){let next;try{next=entries.next()}catch{break}if(next.done||budget.remaining<=0)break;const pair=snapshotTransaction(budget,()=>{budget.remaining-=1;const key=snapshotCollectionValue(next.value[0],budget,depth+1);if(key===OMIT_COLLECTION_VALUE)return OMIT_COLLECTION_VALUE;const entry=snapshotCollectionValue(next.value[1],budget,depth+1);return entry===OMIT_COLLECTION_VALUE?OMIT_COLLECTION_VALUE:[key,entry]});pair!==OMIT_COLLECTION_VALUE&&backing.set(pair[0],pair[1])}return facade}function snapshotDetachedSet(source,values,budget,depth){const backing=new budget.realm.Set,facade=readonlySetFacade(backing,budget.realm);rememberSnapshot(budget,source,facade);for(let count=0;count<PUBLIC_COLLECTION_ENTRY_LIMIT;count+=1){let next;try{next=values.next()}catch{break}if(next.done||budget.remaining<=0)break;const entry=snapshotTransaction(budget,()=>(budget.remaining-=1,snapshotCollectionValue(next.value,budget,depth+1)));entry!==OMIT_COLLECTION_VALUE&&backing.add(entry)}return facade}function snapshotIdentityCollection(value,view,budget){const realm=snapshotRealm(view);if(budget&&value!==null&&(typeof value=="object"||typeof value=="function")&&budget.seen.has(value))return budget.seen.get(value);if(isArrayValue(value)){let lengthDescriptor;try{lengthDescriptor=Object.getOwnPropertyDescriptor(value,"length")}catch{return emptyRealmArray(realm)}const length=lengthDescriptor&&"value"in lengthDescriptor&&typeof lengthDescriptor.value=="number"&&Number.isSafeInteger(lengthDescriptor.value)&&lengthDescriptor.value>=0?Math.min(lengthDescriptor.value,PUBLIC_COLLECTION_ENTRY_LIMIT):0,output=new realm.Array(length);budget&&rememberSnapshot(budget,value,output);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}!descriptor||!("value"in descriptor)||Object.defineProperty(output,index,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}if(value===null||typeof value!="object")return value;const mapEntries=nativeMapEntries(value);if(mapEntries){const output=snapshotIdentityMap(mapEntries,realm);return budget&&rememberSnapshot(budget,value,output),output}const setValues=nativeSetValues(value);if(setValues){const output=snapshotIdentitySet(setValues,realm);return budget&&rememberSnapshot(budget,value,output),output}return emptyRealmArray(realm)}function snapshotEventDetail(value,view,preserveRootKeys,preserveCollectionItemKeys){if(value==null)return value;const budget={remaining:PUBLIC_COLLECTION_NODE_LIMIT,seen:new WeakMap,additions:[],realm:snapshotRealm(view)},snapshot=snapshotTransaction(budget,()=>snapshotCollectionValue(value,budget,0,preserveRootKeys,preserveCollectionItemKeys));return snapshot===OMIT_COLLECTION_VALUE?null:snapshot}const SEED_FIRST_RENDER_STATE=Symbol("lr-seed-first-render-state"),SLOT_PRESENCE_UNRESOLVED=Symbol("lr-slot-presence-unresolved"),REACTIVE_HOST_ATTRIBUTES=["aria-label","aria-describedby","lang","dir"],DIRECTION_HOST_ATTRIBUTES=["class","style","slot"];function trustedLyraConstructorChain(instance){const constructors=[];let prototype=Object.getPrototypeOf(instance);for(;prototype&&prototype!==LitElement.prototype;){const descriptor=Object.getOwnPropertyDescriptor(prototype,"constructor");typeof descriptor?.value=="function"&&constructors.push(descriptor.value),prototype=Object.getPrototypeOf(prototype)}return constructors}const collectionPolicyByPrototype=new WeakMap;function collectionPropertyPolicy(instance,name){const prototype=Object.getPrototypeOf(instance);let policies=collectionPolicyByPrototype.get(prototype);policies||(policies=new Map,collectionPolicyByPrototype.set(prototype,policies));const cached=policies.get(name);if(cached)return cached;let owns=!1,preservesItemIdentity=!1,preservesObjectIdentity=!1;for(const constructor of trustedLyraConstructorChain(instance)){const declared=constructor;Object.prototype.hasOwnProperty.call(constructor,"ownedCollectionProperties")&&declared.ownedCollectionProperties.includes(name)&&(owns=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionProperties")&&declared.identityCollectionProperties.includes(name)&&(preservesItemIdentity=!0),Object.prototype.hasOwnProperty.call(constructor,"identityCollectionObjectProperties")&&declared.identityCollectionObjectProperties.includes(name)&&(preservesObjectIdentity=!0)}const policy=Object.freeze({owns,preservesItemIdentity,preservesObjectIdentity});return policies.set(name,policy),policy}class LyraElement extends LitElement{static{this.styles=[palette,tokens]}static{this.ownedCollectionProperties=Object.freeze([])}static{this.identityCollectionProperties=Object.freeze([])}static{this.identityCollectionObjectProperties=Object.freeze([])}static{this.immutableEventDetails=Object.freeze([])}static{this.identityEventDetailProperties=Object.freeze({})}static{this.identityEventDetailCollectionItems=Object.freeze({})}static getPropertyDescriptor(name,key,options){const descriptor=super.getPropertyDescriptor(name,key,options);if(!descriptor?.set)return descriptor;const originalSet=descriptor.set;return{...descriptor,set(value){const policy=collectionPropertyPolicy(this,name);if(!policy.owns){originalSet.call(this,value);return}const ownerView=this.ownerDocument?.defaultView;originalSet.call(this,policy.preservesObjectIdentity&&value!==null&&typeof value=="object"&&!isArrayValue(value)?value:policy.preservesItemIdentity?snapshotIdentityCollection(value,ownerView):snapshotPublicCollection(value,ownerView))}}}static{this.defaultStrings=Object.freeze({})}static get observedAttributes(){return[...new Set([...super.observedAttributes,...REACTIVE_HOST_ATTRIBUTES,...DIRECTION_HOST_ATTRIBUTES])]}get strings(){return this.stringsValue}set strings(value){const previous=this.stringsValue;this.stringsValue=snapshotLyraLocaleStrings(value),this.requestUpdate("strings",previous)}constructor(){super(),this.locale="",this.stringsValue=snapshotLyraLocaleStrings({}),this.localeSubscriptionNeeded=!1,this.constructor.formAssociated&&this.addController(new ExternalLabelController(this))}attachInternals(){const internals=super.attachInternals();return captureFormInternals(this,internals),internals}connectedCallback(){this.hydratingServerShadow??=typeof Node>"u"||!this.hasUpdated&&this.shadowRoot!==null,super.connectedCallback(),warnUnknownAttributes(this,this.constructor.observedAttributes),recordLyraOwnerDocumentConnection(this),enableLyraLocaleCache(this),invalidateLyraLocaleCache(this),this.stopInheritedContextObservation?.(),this.stopInheritedContextObservation=observeInheritedContext(this),this.localeSubscriptionNeeded&&this.ensureLocaleSubscription(),this.lastLocalizedCatalogVersion!==void 0&&lyraLocaleCatalogVersion(resolveLyraLocale(this))!==this.lastLocalizedCatalogVersion&&this.requestUpdate();const deferred=this.deferredAfterUpdate;if(deferred){this.deferredAfterUpdate=void 0;for(const[key,callback]of deferred)this.scheduleAfterUpdate(callback,key)}}disconnectedCallback(){this.pendingLoadController?.abort(),this.pendingLoadController=void 0,this.stopLocaleSubscription?.(),this.stopLocaleSubscription=void 0,this.stopInheritedContextObservation?.(),this.stopInheritedContextObservation=void 0,invalidateLyraLocaleCache(this),super.disconnectedCallback()}adoptedCallback(){this.stopLocaleSubscription?.(),this.stopLocaleSubscription=void 0,invalidateLyraLocaleCache(this),this.isConnected&&this.localeSubscriptionNeeded&&this.ensureLocaleSubscription()}requestUpdate(name,oldValue,options){invalidateLyraLocaleCache(this),super.requestUpdate(name,oldValue,options)}performUpdate(){beginInheritedContextUpdate(this);try{super.performUpdate()}finally{finishInheritedContextUpdate(this)}}update(changedProperties){super.update(changedProperties),markInheritedContextUpdateRendered(this)}ensureLocaleSubscription(){this.localeSubscriptionNeeded=!0,!(!this.isConnected||this.stopLocaleSubscription)&&(this.stopLocaleSubscription=subscribeLyraLocaleForHost(this))}attributeChangedCallback(name,oldValue,value){const directionHostAttribute=oldValue!==value&&DIRECTION_HOST_ATTRIBUTES.includes(name);directionHostAttribute&&queueInheritedDirectionChange(this,name==="slot"),super.attributeChangedCallback(name,oldValue,value),oldValue!==value&&REACTIVE_HOST_ATTRIBUTES.includes(name)?this.requestUpdate():directionHostAttribute&&invalidateLyraLocaleCache(this)}seedFirstRenderState(seed){this.hasUpdated||this[SEED_FIRST_RENDER_STATE](seed)}[SEED_FIRST_RENDER_STATE](seed){if(!this.hydratingServerShadow){seed();return}const pending=this.deferredFirstRenderSeeds??=new Set;pending.add(seed),!(pending.size>1)&&this.updateComplete.then(()=>{setTimeout(()=>{this.hydratingServerShadow=!1;const seeds=this.deferredFirstRenderSeeds;this.deferredFirstRenderSeeds=void 0;for(const deferred of seeds??[])deferred();this.requestUpdate()},0)},()=>{this.hydratingServerShadow=!1,this.deferredFirstRenderSeeds=void 0})}updateBrowserDerivedState(update){this[SEED_FIRST_RENDER_STATE](update)}renderSlotPresence(present){return present||this[SLOT_PRESENCE_UNRESOLVED]()}[SLOT_PRESENCE_UNRESOLVED](){return typeof Node>"u"||this.hydratingServerShadow===!0}beginAbortableLoad(){this.pendingLoadController?.abort(),this.pendingLoadController=void 0;const AbortControllerCtor=this.ownerDocument?.defaultView?.AbortController;if(AbortControllerCtor)return this.pendingLoadController=new AbortControllerCtor,this.pendingLoadController.signal}scheduleAfterUpdate(callback,key="load"){const pending=this.afterUpdateCallbacks??=new Map;pending.has(key)||(pending.set(key,callback),!(pending.size>1)&&queueMicrotask(()=>{const due=this.afterUpdateCallbacks;if(this.afterUpdateCallbacks=void 0,!due)return;if(this.isConnected){for(const due_callback of due.values())due_callback();return}const held=this.deferredAfterUpdate??=new Map;for(const[heldKey,heldCallback]of due)held.has(heldKey)||held.set(heldKey,heldCallback)}))}localize(key,fallback,values){const message=resolveLyraString(this,key,this.strings,fallback,values,this.constructor.defaultStrings),locale=peekLyraLocale(this);return recordInheritedLocaleRead(this,locale),locale!==void 0&&(this.lastLocalizedCatalogVersion=lyraLocaleCatalogVersion(locale),this.ensureLocaleSubscription()),message}get effectiveMessageLocale(){if(this.locale)return canonicalizeLyraLocale(this.locale);const locale=resolveLyraLocale(this);return recordInheritedLocaleRead(this,locale),this.ensureLocaleSubscription(),locale}get effectiveLocale(){return resolveIntlLocale(this.effectiveMessageLocale)}get effectiveIntlLocale(){return this.effectiveLocale}get effectiveDirection(){const direction=resolveLyraDirection(this);return recordInheritedDirectionRead(this,direction),direction}addEventListener(type,listener,options){super.addEventListener(type,listener,options)}removeEventListener(type,listener,options){super.removeEventListener(type,listener,options)}emit(name,...args){const[detail,options]=args,ownerDocument=this.ownerDocument;let CustomEventCtor=ownerDocument?.defaultView?.CustomEvent;if(!CustomEventCtor&&ownerDocument)try{const candidate=ownerDocument.createEvent("CustomEvent").constructor;typeof candidate=="function"&&(CustomEventCtor=candidate)}catch{}CustomEventCtor??=globalThis.CustomEvent;let snapshotsDetail=!1;const identityDetailKeys=new Set,identityCollectionItemKeys=new Set;for(const constructor of trustedLyraConstructorChain(this)){if(Object.prototype.hasOwnProperty.call(constructor,"immutableEventDetails")&&constructor.immutableEventDetails.includes(name)&&(snapshotsDetail=!0),Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailProperties"))for(const key of constructor.identityEventDetailProperties[name]??[])identityDetailKeys.add(key);if(Object.prototype.hasOwnProperty.call(constructor,"identityEventDetailCollectionItems"))for(const key of constructor.identityEventDetailCollectionItems[name]??[])identityCollectionItemKeys.add(key)}const event=new CustomEventCtor(name,{detail:detail===void 0?null:snapshotsDetail?snapshotEventDetail(detail,ownerDocument?.defaultView,identityDetailKeys,identityCollectionItemKeys):detail,bubbles:!0,composed:!0,cancelable:options?.cancelable??!1});return this.dispatchEvent(event),event}}__decorate([property({reflect:!0})],LyraElement.prototype,"locale",void 0),__decorate([property({attribute:!1})],LyraElement.prototype,"strings",null);export{LyraElement,SEED_FIRST_RENDER_STATE,SLOT_PRESENCE_UNRESOLVED};
@@ -3,4 +3,4 @@
3
3
  * Run `pnpm package-metadata` after changing package identity or version.
4
4
  */
5
5
  export declare const LYRA_PACKAGE_NAME: '@aceshooting/lyra-ui';
6
- export declare const LYRA_PACKAGE_VERSION: '9.1.0';
6
+ export declare const LYRA_PACKAGE_VERSION: '9.1.1';
@@ -1 +1 @@
1
- const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="9.1.0";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
1
+ const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="9.1.1";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
@@ -15,8 +15,8 @@
15
15
 
16
16
  ## `lr-attachment-trigger`
17
17
 
18
- A compact attach affordance designed for a chat composer's leading slot (see `lr-chat-composer`'s
19
- own `leading` slot, which this drops straight into, though it has no code dependency on it). First-
18
+ A compact attach affordance designed for a chat composer's start slot (see `lr-chat-composer`'s
19
+ own `start` slot, which this drops straight into, though it has no code dependency on it). First-
20
20
  party invention (no Web Awesome equivalent). Its shape adapts to how many attachment `capabilities`
21
21
  are configured: exactly one renders a single plain icon button; more than one renders a small
22
22
  anchored menu (composed from `lr-dropdown`/`lr-menu`/`lr-menu-item`) listing each
@@ -99,7 +99,7 @@ row?: number; col?: number; date?: string }`, matched the same way as `annotatio
99
99
  persistent ring (independent of keyboard focus) over the matching cell, appends a "Selected: ..."
100
100
  description to the host's own `aria-label`, and adds localized selected wording to the keyboard
101
101
  announcement when the focused cell is the selection. Purely a controlled property — mirrors
102
- `<lr-lite-chart>`'s `selectedIndex`, this component never mutates it itself. Unset (the default,
102
+ `<lr-lite-chart>`'s `selectedIndices`, this component never mutates it itself. Unset (the default,
103
103
  `null`) reproduces today's exact output.
104
104
  - `accessibleCells: boolean = false` (attribute `accessible-cells`) — renders `[part="cells"]` with
105
105
  at most 400 `[part="cell"]` native buttons around the active cell. The semantic grid exposes the
package/llms/index.md CHANGED
@@ -175,7 +175,7 @@ Optional peers: `llms/peers.md`. Safe `wa-*`/`sl-*` migration: `llms/migration.m
175
175
  - `lr-attachment-chip` · lr-attachment-chip.js · `stable` since `4.0.0` — a compact chip representing one file queued for (or already part of) a chat message: a composer's pre-send attachment tray, or a sent mes...
176
176
  - `lr-file-icon` · lr-file-icon.js · `stable` since `4.0.0` — Displays a localized, tokenized file-type badge from a MIME type.
177
177
  - `lr-media-card` · lr-media-card.js · `stable` since `4.0.0` — a lightweight inline preview for one already-sent, already-available attachment inside a rendered chat message body (e.g.
178
- - `lr-attachment-trigger` · lr-attachment-trigger.js · `stable` since `4.0.0` — a compact attach affordance designed for a chat composer's leading slot (see `<lr-chat-composer>`'s own `leading` slot, which this drops...
178
+ - `lr-attachment-trigger` · lr-attachment-trigger.js · `stable` since `4.0.0` — a compact attach affordance designed for a chat composer's start slot (see `<lr-chat-composer>`'s own `start` slot, which this drops stra...
179
179
  - `lr-avatar` · lr-avatar.js · `stable` since `4.0.0` — a small, fixed-size identity marker: an image, an `icon`-slotted fallback glyph, or an initials fallback, in that priority order.
180
180
  - `lr-animated-image` · lr-animated-image.js · `stable` since `4.0.0` — - displays an animated GIF/APNG/WebP with a play/pause control, defaulting to a frozen first frame both at rest and automatically under `...
181
181
  - `lr-animation` · lr-animation.js · `stable` since `4.0.0` — `<lr-animation>` declaratively animates its single slotted child through the native Web Animations API: a small curated preset catalog (`...
package/llms/peers.md CHANGED
@@ -46,7 +46,7 @@ changes the component library version without installing a supported SheetJS rel
46
46
  | `libphonenumber-js` | `>=1.11.0 <2` | `lr-phone-input` |
47
47
  | `mammoth` | `^1.12.1` | `lr-docx-viewer` |
48
48
  | `maplibre-gl` | `>=5 <7` | `lr-geojson-view`, `lr-geojson-viewer`, `lr-map` |
49
- | `marked` | `^18.0.9` | `lr-agent-workspace`, `lr-dashboard-grid`, `lr-eval-run`, `lr-markdown`, `lr-markdown-core`, `lr-message-parts`, `lr-notebook-viewer`, `lr-rag-answer`, `lr-streaming-text`, `lr-widget-renderer` |
49
+ | `marked` | `^18.0.10` | `lr-agent-workspace`, `lr-dashboard-grid`, `lr-eval-run`, `lr-markdown`, `lr-markdown-core`, `lr-message-parts`, `lr-notebook-viewer`, `lr-rag-answer`, `lr-streaming-text`, `lr-widget-renderer` |
50
50
  | `papaparse` | `^5.6.0` | `lr-csv-viewer`, `lr-dataset-viewer` |
51
51
  | `pdfjs-dist` | `^6.2.108` | `lr-pdf-viewer` |
52
52
  | `postal-mime` | `^3.0.0` | `lr-email-viewer` |
package/llms/shared.md CHANGED
@@ -1620,6 +1620,19 @@ files matter when scaffolding a project's editor configuration. Build tools can
1620
1620
  through the explicit `@aceshooting/lyra-ui/custom-elements.json` package export; native Node ESM
1621
1621
  uses `with { type: 'json' }` on that import.
1622
1622
 
1623
+ **Inherited members in `custom-elements.json`.** A subclass declaration's `cssParts` array is
1624
+ always the complete flattened set, including everything inherited from a superclass — `::part()`
1625
+ has no type-level inheritance chain a consumer could otherwise walk. `attributes`, `members`,
1626
+ `events`, `slots`, and `cssProperties` are the opposite: a subclass declaration lists only its own
1627
+ entries plus any inherited entry it explicitly overrides, pruning an inherited-and-unmodified entry
1628
+ of those four kinds. This is intentional, not a gap — a TypeScript/JS consumer already gets the
1629
+ full set for free from the generated `.d.ts` `extends` chain, the same resolution `web-types.json`
1630
+ and `vscode-html-data.json` perform ahead of time. A consumer reading `custom-elements.json`
1631
+ directly and needing the complete `attributes`/`members`/`events`/`slots`/`cssProperties` set for
1632
+ those four kinds must walk the declaration's own `superclass.name`/`superclass.module` across
1633
+ `modules[].declarations[]` itself, or read `web-types.json`/`vscode-html-data.json` instead, which
1634
+ are already fully resolved.
1635
+
1623
1636
  ## Independence and migration
1624
1637
 
1625
1638
  Lyra has no runtime, theme, or design-token dependency on Shoelace or Web Awesome. Documented `wa-*`
package/llms-full.txt CHANGED
@@ -1672,6 +1672,19 @@ files matter when scaffolding a project's editor configuration. Build tools can
1672
1672
  through the explicit `@aceshooting/lyra-ui/custom-elements.json` package export; native Node ESM
1673
1673
  uses `with { type: 'json' }` on that import.
1674
1674
 
1675
+ **Inherited members in `custom-elements.json`.** A subclass declaration's `cssParts` array is
1676
+ always the complete flattened set, including everything inherited from a superclass — `::part()`
1677
+ has no type-level inheritance chain a consumer could otherwise walk. `attributes`, `members`,
1678
+ `events`, `slots`, and `cssProperties` are the opposite: a subclass declaration lists only its own
1679
+ entries plus any inherited entry it explicitly overrides, pruning an inherited-and-unmodified entry
1680
+ of those four kinds. This is intentional, not a gap — a TypeScript/JS consumer already gets the
1681
+ full set for free from the generated `.d.ts` `extends` chain, the same resolution `web-types.json`
1682
+ and `vscode-html-data.json` perform ahead of time. A consumer reading `custom-elements.json`
1683
+ directly and needing the complete `attributes`/`members`/`events`/`slots`/`cssProperties` set for
1684
+ those four kinds must walk the declaration's own `superclass.name`/`superclass.module` across
1685
+ `modules[].declarations[]` itself, or read `web-types.json`/`vscode-html-data.json` instead, which
1686
+ are already fully resolved.
1687
+
1675
1688
  ## Independence and migration
1676
1689
 
1677
1690
  Lyra has no runtime, theme, or design-token dependency on Shoelace or Web Awesome. Documented `wa-*`
@@ -10597,7 +10610,7 @@ row?: number; col?: number; date?: string }`, matched the same way as `annotatio
10597
10610
  persistent ring (independent of keyboard focus) over the matching cell, appends a "Selected: ..."
10598
10611
  description to the host's own `aria-label`, and adds localized selected wording to the keyboard
10599
10612
  announcement when the focused cell is the selection. Purely a controlled property — mirrors
10600
- `<lr-lite-chart>`'s `selectedIndex`, this component never mutates it itself. Unset (the default,
10613
+ `<lr-lite-chart>`'s `selectedIndices`, this component never mutates it itself. Unset (the default,
10601
10614
  `null`) reproduces today's exact output.
10602
10615
  - `accessibleCells: boolean = false` (attribute `accessible-cells`) — renders `[part="cells"]` with
10603
10616
  at most 400 `[part="cell"]` native buttons around the active cell. The semantic grid exposes the
@@ -22394,8 +22407,8 @@ true}))` still invokes the anchor's native activation behavior if nothing calls
22394
22407
 
22395
22408
  ## `lr-attachment-trigger`
22396
22409
 
22397
- A compact attach affordance designed for a chat composer's leading slot (see `lr-chat-composer`'s
22398
- own `leading` slot, which this drops straight into, though it has no code dependency on it). First-
22410
+ A compact attach affordance designed for a chat composer's start slot (see `lr-chat-composer`'s
22411
+ own `start` slot, which this drops straight into, though it has no code dependency on it). First-
22399
22412
  party invention (no Web Awesome equivalent). Its shape adapts to how many attachment `capabilities`
22400
22413
  are configured: exactly one renders a single plain icon button; more than one renders a small
22401
22414
  anchored menu (composed from `lr-dropdown`/`lr-menu`/`lr-menu-item`) listing each
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aceshooting/lyra-ui",
3
- "version": "9.1.0",
3
+ "version": "9.1.1",
4
4
  "description": "Free, independent Lit web components: an open-source alternative to Shoelace and Web Awesome with accessible forms, dashboards, charts, and agent UI.",
5
5
  "keywords": [
6
6
  "web-components",
@@ -2266,7 +2266,7 @@
2266
2266
  "libphonenumber-js": ">=1.11.0 <2",
2267
2267
  "mammoth": "^1.12.1",
2268
2268
  "maplibre-gl": ">=5 <7",
2269
- "marked": "^18.0.9",
2269
+ "marked": "^18.0.10",
2270
2270
  "papaparse": "^5.6.0",
2271
2271
  "pdfjs-dist": "^6.2.108",
2272
2272
  "postal-mime": "^3.0.0",
@@ -2405,7 +2405,7 @@
2405
2405
  "libphonenumber-js": "^1.13.11",
2406
2406
  "mammoth": "^1.12.1",
2407
2407
  "maplibre-gl": "^6.4.0",
2408
- "marked": "^18.0.9",
2408
+ "marked": "^18.0.10",
2409
2409
  "oxc-parser": "^0.144.0",
2410
2410
  "papaparse": "^5.6.0",
2411
2411
  "pdfjs-dist": "^6.2.108",
@@ -1329,7 +1329,7 @@
1329
1329
  "name": "lr-attachment-trigger",
1330
1330
  "description": {
1331
1331
  "kind": "markdown",
1332
- "value": "`<lr-attachment-trigger>` — a compact attach affordance designed for a\nchat composer's leading slot (see `<lr-chat-composer>`'s own `leading`\nslot, which this drops straight into, though this component has no code\ndependency on it). Its shape adapts to how many attachment `capabilities`\nare configured:\n - Exactly one capability: a single plain icon button ([part='trigger']).\n Activating it performs that capability's action directly.\n - More than one: a small anchored menu ([part='menu'], composed from\n `<lr-dropdown>`/`<lr-menu>`/`<lr-menu-item>`) listing each capability as a row.\n\nTwo of the four capabilities (`files`, `image`) are file-picker-backed:\nactivating them opens a hidden native `<input type=\"file\">` via a\nsynthetic `.click()`, and the resulting selection is re-emitted as\n`lr-files`. `accept` is shared across both — `image` defaults it to\n`'image/*'` unless the `accept` prop overrides it, `files` always uses\n`accept` as-is (empty means \"any file type\", matching a bare native\n`<input type=\"file\">` with no `accept` attribute).\n\n**`camera`/`audio` are scope-limited by design.** This component does not\nimplement any camera or microphone capture UI itself — no `getUserMedia`,\nno `<input capture>` — because that's entirely a host/browser concern with\nno single right answer (a desktop web app, a mobile PWA, and a native\nwrapper all want different things here). Activating `camera` fires\n`lr-camera-request`; activating `audio` fires `lr-audio-request`. The\nhost owns everything from that point on — typically opening\n`<lr-push-to-talk>` in a `<lr-overlay>`/popover for `audio`, then\nhanding the resulting blob to something like `<lr-attachment-chip>`.\n\n---\n\n**Component metadata**\n\n- Status: `stable`\n- Since: `4.0.0`\n- Rationale: This exact lr-* tag appears in a published Lyra release manifest and remains a supported public contract under semver.\n- Graduation: Already stable; it retains that status while its documented behavior, accessibility, compatibility, and cross-browser support remain part of the public contract.\n\n---\n\n**CSS Shadow Parts**\n\n| Name | Description |\n| --- | --- |\n| `expand-icon` | The disclosure chevron inside the multi-capability trigger button. Only rendered when `capabilities.length > 1`. |\n| `hidden-input` | The internal native `<input type=\"file\">` that actually opens the OS file picker. Hidden (`display: none`) by default; exposed as a part only so a consumer can override that with `::part(hidden-input)` in the unlikely case their integration needs to. `accessibleLabel` supplies an accessible-name override for either trigger shape. A host `aria-label`, including an explicit empty value, wins over it. |\n| `menu` | The `<lr-dropdown>` shell. Only rendered when `capabilities.length > 1`. |\n| `menu-trigger` | The multi-capability button slotted into `<lr-dropdown>`'s `trigger` slot. Only rendered when `capabilities.length > 1`. |\n| `trigger` | The single-capability icon button. Only rendered when `capabilities.length === 1`. |"
1332
+ "value": "`<lr-attachment-trigger>` — a compact attach affordance designed for a\nchat composer's start slot (see `<lr-chat-composer>`'s own `start`\nslot, which this drops straight into, though this component has no code\ndependency on it). Its shape adapts to how many attachment `capabilities`\nare configured:\n - Exactly one capability: a single plain icon button ([part='trigger']).\n Activating it performs that capability's action directly.\n - More than one: a small anchored menu ([part='menu'], composed from\n `<lr-dropdown>`/`<lr-menu>`/`<lr-menu-item>`) listing each capability as a row.\n\nTwo of the four capabilities (`files`, `image`) are file-picker-backed:\nactivating them opens a hidden native `<input type=\"file\">` via a\nsynthetic `.click()`, and the resulting selection is re-emitted as\n`lr-files`. `accept` is shared across both — `image` defaults it to\n`'image/*'` unless the `accept` prop overrides it, `files` always uses\n`accept` as-is (empty means \"any file type\", matching a bare native\n`<input type=\"file\">` with no `accept` attribute).\n\n**`camera`/`audio` are scope-limited by design.** This component does not\nimplement any camera or microphone capture UI itself — no `getUserMedia`,\nno `<input capture>` — because that's entirely a host/browser concern with\nno single right answer (a desktop web app, a mobile PWA, and a native\nwrapper all want different things here). Activating `camera` fires\n`lr-camera-request`; activating `audio` fires `lr-audio-request`. The\nhost owns everything from that point on — typically opening\n`<lr-push-to-talk>` in a `<lr-overlay>`/popover for `audio`, then\nhanding the resulting blob to something like `<lr-attachment-chip>`.\n\n---\n\n**Component metadata**\n\n- Status: `stable`\n- Since: `4.0.0`\n- Rationale: This exact lr-* tag appears in a published Lyra release manifest and remains a supported public contract under semver.\n- Graduation: Already stable; it retains that status while its documented behavior, accessibility, compatibility, and cross-browser support remain part of the public contract.\n\n---\n\n**CSS Shadow Parts**\n\n| Name | Description |\n| --- | --- |\n| `expand-icon` | The disclosure chevron inside the multi-capability trigger button. Only rendered when `capabilities.length > 1`. |\n| `hidden-input` | The internal native `<input type=\"file\">` that actually opens the OS file picker. Hidden (`display: none`) by default; exposed as a part only so a consumer can override that with `::part(hidden-input)` in the unlikely case their integration needs to. `accessibleLabel` supplies an accessible-name override for either trigger shape. A host `aria-label`, including an explicit empty value, wins over it. |\n| `menu` | The `<lr-dropdown>` shell. Only rendered when `capabilities.length > 1`. |\n| `menu-trigger` | The multi-capability button slotted into `<lr-dropdown>`'s `trigger` slot. Only rendered when `capabilities.length > 1`. |\n| `trigger` | The single-capability icon button. Only rendered when `capabilities.length === 1`. |"
1333
1333
  },
1334
1334
  "attributes": [
1335
1335
  {