@aceshooting/lyra-ui 9.0.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 (110) hide show
  1. package/CHANGELOG.md +369 -0
  2. package/README.md +9 -2
  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.d.ts +1 -0
  9. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  10. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  11. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  12. package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
  13. package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
  14. package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
  15. package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
  16. package/dist/components/agent-tools/schema-viewer/schema-viewer.styles.js +2 -2
  17. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  18. package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
  19. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  20. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  21. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  22. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  23. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
  24. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  25. package/dist/components/charts/chart/bar-chart.class.js +1 -1
  26. package/dist/components/charts/chart/bubble-chart.class.js +1 -1
  27. package/dist/components/charts/chart/chart.class.js +1 -1
  28. package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
  29. package/dist/components/charts/chart/histogram.class.js +1 -1
  30. package/dist/components/charts/chart/line-chart.class.js +1 -1
  31. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  32. package/dist/components/charts/chart/pie-chart.class.js +1 -1
  33. package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
  34. package/dist/components/charts/chart/radar-chart.class.js +1 -1
  35. package/dist/components/charts/chart/scatter-chart.class.js +1 -1
  36. package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
  37. package/dist/components/conversation/chat-message/chat-message.styles.js +6 -0
  38. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  39. package/dist/components/conversation/generation-metrics/generation-metrics.class.js +2 -2
  40. package/dist/components/conversation/realtime-session/realtime-session.styles.js +1 -1
  41. package/dist/components/conversation/thread-list/thread-list.styles.js +9 -0
  42. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  43. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  44. package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
  45. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  46. package/dist/components/data/pagination/pagination.class.js +1 -1
  47. package/dist/components/data/table/table.class.js +1 -1
  48. package/dist/components/forms/button/button.styles.js +1 -1
  49. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  50. package/dist/components/forms/combobox/combobox.class.js +1 -1
  51. package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
  52. package/dist/components/forms/input/time-input.class.js +1 -1
  53. package/dist/components/forms/switch/switch.styles.js +3 -1
  54. package/dist/components/layout/card/card.styles.js +2 -2
  55. package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
  56. package/dist/components/layout/drilldown-panel/drilldown-panel.class.d.ts +1 -0
  57. package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
  58. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  59. package/dist/components/layout/multi-split/multi-split.styles.js +29 -9
  60. package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
  61. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
  62. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  63. package/dist/components/media/attachment-trigger/attachment-trigger.styles.js +2 -2
  64. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  65. package/dist/components/media/file-input/file-input.class.js +1 -1
  66. package/dist/components/media/flag/flag.class.js +1 -1
  67. package/dist/components/media/lightbox/lightbox.styles.js +2 -0
  68. package/dist/components/overlays/callout/callout.styles.js +2 -2
  69. package/dist/components/overlays/kbd/kbd.class.js +1 -1
  70. package/dist/components/overlays/overlay/popover.class.js +2 -2
  71. package/dist/components/overlays/overlay/tooltip.class.js +2 -2
  72. package/dist/components/overlays/popup/popup.class.js +2 -2
  73. package/dist/components/overlays/spinner/spinner.styles.js +2 -2
  74. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  75. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  76. package/dist/components/retrieval/entity-card/entity-card.class.d.ts +1 -0
  77. package/dist/components/retrieval/entity-dossier/entity-dossier.class.d.ts +1 -0
  78. package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
  79. package/dist/components/retrieval/graph/graph.class.d.ts +1 -0
  80. package/dist/components/retrieval/graph-legend/graph-legend.class.d.ts +1 -0
  81. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  82. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +1 -0
  83. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js +11 -0
  84. package/dist/components/retrieval/memory-panel/memory-panel.class.d.ts +1 -1
  85. package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
  86. package/dist/components/retrieval/provenance-panel/provenance-panel.class.d.ts +1 -1
  87. package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
  88. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  89. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  90. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  91. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  92. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  93. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  94. package/dist/internal/dev-mode-attribute-warning.d.ts +7 -0
  95. package/dist/internal/dev-mode-attribute-warning.js +1 -0
  96. package/dist/internal/lyra-element.js +1 -1
  97. package/dist/internal/package-metadata.d.ts +1 -1
  98. package/dist/internal/package-metadata.js +1 -1
  99. package/llms/components/lr-archive-viewer.md +5 -0
  100. package/llms/components/lr-attachment-trigger.md +2 -2
  101. package/llms/components/lr-ebook-viewer.md +3 -0
  102. package/llms/components/lr-heatmap.md +1 -1
  103. package/llms/index.md +1 -1
  104. package/llms/migration.md +3 -3
  105. package/llms/peers.md +1 -1
  106. package/llms/shared.md +13 -0
  107. package/llms-full.txt +24 -3
  108. package/package.json +5 -3
  109. package/vscode-html-data.json +1 -1
  110. package/web-types.json +2 -2
@@ -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{hostAriaLabel}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_sourcePickerSelection,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64;class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.showSelectAll=!0,this.searchable=!0,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-sources-change"])}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sources&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sources,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=source.children??[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sources,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedSourceIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>this.selectedSourceIds.includes(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}matchesQuery(entry){return entry.label.toLocaleLowerCase(this.effectiveLocale).includes(this.query.trim().toLocaleLowerCase(this.effectiveLocale))}isFiltering(){return this.searchable&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering)for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(this.matchesQuery(node.entry)||node.children.some(child=>matches.has(child)))&&matches.add(node)}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds();(normalized.length!==this.selectedSourceIds.length||normalized.some((id,index)=>id!==this.selectedSourceIds[index]))&&(this.selectedSourceIds=normalized)}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(activeElementIn(this.shadowRoot)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sources.length===0||!this.searchable?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const count=this.visibleRows().length,signature=`${this.query.trim().toLocaleLowerCase(this.effectiveLocale)}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,count===0&&this.announcementSink?.announce(this.localize("noMatches")))}commitSelection(next){this.selectedSourceIds=next,this.emit("lr-sources-change",{selectedSourceIds:next})}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),willSelect=this.checkedState(entry)!=="true",set=new Set(this.selectedSourceIds);for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}toggleSelectAll(){const all=this.allLeafIds(),allSelected=all.length>0&&all.every(id=>this.selectedSourceIds.includes(id));this.commitSelection(allSelected?[]:all)}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active){const state2=this.checkedState(row.entry),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());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{styleMap}from"lit/directives/style-map.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_sourcePickerSelection,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64;class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.showSelectAll=!0,this.searchable=!0,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-sources-change"])}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sources&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sources,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=source.children??[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sources,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedSourceIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>this.selectedSourceIds.includes(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}matchesQuery(entry){return entry.label.toLocaleLowerCase(this.effectiveLocale).includes(this.query.trim().toLocaleLowerCase(this.effectiveLocale))}isFiltering(){return this.searchable&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering)for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(this.matchesQuery(node.entry)||node.children.some(child=>matches.has(child)))&&matches.add(node)}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds();(normalized.length!==this.selectedSourceIds.length||normalized.some((id,index)=>id!==this.selectedSourceIds[index]))&&(this.selectedSourceIds=normalized)}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(activeElementIn(this.shadowRoot)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sources.length===0||!this.searchable?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const count=this.visibleRows().length,signature=`${this.query.trim().toLocaleLowerCase(this.effectiveLocale)}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,count===0&&this.announcementSink?.announce(this.localize("noMatches")))}commitSelection(next){this.selectedSourceIds=next,this.emit("lr-sources-change",{selectedSourceIds:next})}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),willSelect=this.checkedState(entry)!=="true",set=new Set(this.selectedSourceIds);for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}toggleSelectAll(){const all=this.allLeafIds(),allSelected=all.length>0&&all.every(id=>this.selectedSourceIds.includes(id));this.commitSelection(allSelected?[]:all)}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active){const state2=this.checkedState(row.entry),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());return html`
2
2
  <div
3
3
  part="item"
4
4
  role="treeitem"
@@ -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.0.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.0.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};
@@ -79,5 +79,10 @@ import. Opening a `.zip` through `<lr-document-viewer>` forwards `anchor`/`highl
79
79
  viewer, so a deep link into an entry name survives the registry hop. `.tar`, `.rar`, and other
80
80
  archive formats fall through to `<lr-document-preview>`'s generic download fallback.
81
81
 
82
+ A granular consumer (not importing the `all.js` compatibility bundle) must import
83
+ `@aceshooting/lyra-ui/components/viewers/archive-viewer/archive-viewer-register.js` once to install
84
+ this registration; without it `<lr-document-viewer>` never recognizes `.zip` files and falls
85
+ through to the generic download fallback described above.
86
+
82
87
  Remote resources are capped at 25 MB; exceeding it surfaces the localized
83
88
  `documentPreviewResourceTooLarge` message instead of the entry listing.
@@ -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
@@ -76,6 +76,9 @@ unambiguous beside other previous/next controls and are overridable through `.st
76
76
  matches `application/epub+zip` and `.epub` filenames, declaring `{ anchors: ['cfi', 'text-quote'],
77
77
  search: true, textSelect: true }` capabilities and forwarding `anchor`/`highlights` to the mounted
78
78
  viewer. The peer loader requires the callable EPUB factory; malformed module shapes fail closed.
79
+ A granular consumer (not importing the `all.js` compatibility bundle) must also import
80
+ `@aceshooting/lyra-ui/components/viewers/ebook-viewer/ebook-viewer-register.js` once to install
81
+ this registration; without it `<lr-document-viewer>` never recognizes `.epub` files.
79
82
 
80
83
  Remote resources are capped at 25 MB; exceeding it surfaces the localized
81
84
  `documentPreviewResourceTooLarge` message instead of the ebook.
@@ -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/migration.md CHANGED
@@ -150,9 +150,9 @@ The pinned Web Awesome manifest is authoritative for this inventory; only rows m
150
150
  | `<wa-spinner>` | `<lr-spinner>` | `exact` | Automatic: tag and supported side-effect registration import. Localized indeterminate busy indicator with reduced-motion support. |
151
151
  | `<wa-split-panel>` | `<lr-split-panel>` | `rewritten` | Automatic: tag/import plus events: wa-reposition → lr-reposition. |
152
152
  | `<wa-switch>` | `<lr-switch>` | `rewritten` | Automatic: tag/import plus events: wa-invalid → lr-invalid. Equivalent surface representation: name defaults null ≡ ; no source rewrite. |
153
- | `<wa-tab>` | `<lr-tab>` | `exact` | Automatic: tag and supported side-effect registration import. Tab strip with `placement` (logical `start`/`end` turn it vertical) and `activation="auto"`/`"manual"`; accepts the upstream `<lr-tab>`/`<lr-tab-panel>` child pairs or this library's own `slot`/`label` panel-attribute shape. |
153
+ | `<wa-tab>` | `<lr-tab>` | `exact` | Automatic: tag and supported side-effect registration import. Tab strip with `placement` (logical `start`/`end` turn it vertical) and `activation="auto"`/`"manual"`; composed from the upstream `<lr-tab>`/`<lr-tab-panel>` child pairs. |
154
154
  | `<wa-tab-group>` | `<lr-tab-group>` | `rewritten` | Automatic: tag/import plus events: wa-tab-hide → lr-tab-hide; events: wa-tab-show → lr-tab-show. |
155
- | `<wa-tab-panel>` | `<lr-tab-panel>` | `exact` | Automatic: tag and supported side-effect registration import. Tab strip with `placement` (logical `start`/`end` turn it vertical) and `activation="auto"`/`"manual"`; accepts the upstream `<lr-tab>`/`<lr-tab-panel>` child pairs or this library's own `slot`/`label` panel-attribute shape. |
155
+ | `<wa-tab-panel>` | `<lr-tab-panel>` | `exact` | Automatic: tag and supported side-effect registration import. Tab strip with `placement` (logical `start`/`end` turn it vertical) and `activation="auto"`/`"manual"`; composed from the upstream `<lr-tab>`/`<lr-tab-panel>` child pairs. |
156
156
  | `<wa-tag>` | `<lr-tag>` | `rewritten` | Automatic: tag/import plus events: wa-remove → lr-remove. |
157
157
  | `<wa-textarea>` | `<lr-textarea>` | `rewritten` | Automatic: tag/import plus events: wa-invalid → lr-invalid. Equivalent surface representation: name defaults null ≡ ; no source rewrite. |
158
158
  | `<wa-time-input>` | `<lr-time-input>` | `rewritten` | Automatic: tag/import plus events: wa-after-hide → lr-after-hide; events: wa-after-show → lr-after-show; events: wa-clear → lr-clear; events: wa-hide → lr-hide; events: wa-invalid → lr-invalid; events: wa-show → lr-show. |
@@ -222,7 +222,7 @@ Shoelace relationships are classified independently; a same-suffix tag is never
222
222
  | `<sl-switch>` | `<lr-switch>` | `rewritten` | Automatic: tag/import plus events: sl-blur → blur; events: sl-change → lr-change; events: sl-focus → focus; events: sl-input → lr-input; events: sl-invalid → lr-invalid. Equivalent surface representation: form defaults ≡ null; size defaults medium ≡ m; no source rewrite. |
223
223
  | `<sl-tab>` | `<lr-tab>` | `rewritten` | Automatic: tag/import plus events: sl-close → lr-close. |
224
224
  | `<sl-tab-group>` | `<lr-tab-group>` | `rewritten` | Automatic: tag/import plus events: sl-tab-hide → lr-tab-hide; events: sl-tab-show → lr-tab-show. |
225
- | `<sl-tab-panel>` | `<lr-tab-panel>` | `exact` | Automatic: tag and supported side-effect registration import. Tab strip with `placement` (logical `start`/`end` turn it vertical) and `activation="auto"`/`"manual"`; accepts the upstream `<lr-tab>`/`<lr-tab-panel>` child pairs or this library's own `slot`/`label` panel-attribute shape. |
225
+ | `<sl-tab-panel>` | `<lr-tab-panel>` | `exact` | Automatic: tag and supported side-effect registration import. Tab strip with `placement` (logical `start`/`end` turn it vertical) and `activation="auto"`/`"manual"`; composed from the upstream `<lr-tab>`/`<lr-tab-panel>` child pairs. |
226
226
  | `<sl-tag>` | `<lr-tag>` | `rewritten` | Automatic: tag/import plus events: sl-remove → lr-remove. Equivalent surface representation: size defaults medium ≡ m; no source rewrite. |
227
227
  | `<sl-textarea>` | `<lr-textarea>` | `rewritten` | Automatic: tag/import plus events: sl-blur → blur; events: sl-change → lr-change; events: sl-focus → focus; events: sl-input → lr-input; events: sl-invalid → lr-invalid. Equivalent surface representation: form defaults ≡ null; size defaults medium ≡ m; no source rewrite. |
228
228
  | `<sl-tooltip>` | `<lr-tooltip>` | `warning-required` | Manual: Pinned runtime evidence shows Shoelace emits non-cancelable state-change lifecycle notifications while Lyra provides synchronous pre-state veto events; automatic migration therefore requires review of listener timing and preventDefault() behavior. |