@aceshooting/lyra-ui 30.9.0 → 31.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (201) hide show
  1. package/CHANGELOG.md +236 -339
  2. package/dist/ai/adapters/ag-ui.js +1 -1
  3. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  4. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
  5. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  6. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  7. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
  8. package/dist/components/charts/chart/box-plot.class.js +2 -2
  9. package/dist/components/charts/chart/chart-sync.js +1 -1
  10. package/dist/components/charts/chart/chart.class.d.ts +1 -1
  11. package/dist/components/charts/chart/chart.class.js +4 -4
  12. package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
  13. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  14. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
  15. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  16. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  17. package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
  18. package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
  19. package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
  20. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
  21. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
  22. package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
  23. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  24. package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
  25. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  26. package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
  27. package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
  28. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  29. package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
  30. package/dist/components/conversation/markdown/markdown-shared.js +3 -3
  31. package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
  32. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  33. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  34. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  35. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
  36. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
  37. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
  38. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
  39. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  40. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
  41. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  42. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
  43. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
  44. package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
  45. package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
  46. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  47. package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
  48. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  49. package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
  50. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  51. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  52. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  53. package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
  54. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  55. package/dist/components/data/pagination/pagination.class.js +1 -1
  56. package/dist/components/data/table/table.class.d.ts +31 -2
  57. package/dist/components/data/table/table.class.js +3 -3
  58. package/dist/components/data/table/table.styles.js +1 -1
  59. package/dist/components/data/timeline/timeline-cluster.js +1 -1
  60. package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
  61. package/dist/components/data/timeline/timeline-item.class.js +16 -12
  62. package/dist/components/data/timeline/timeline-item.styles.js +1 -1
  63. package/dist/components/data/timeline/timeline.class.d.ts +14 -2
  64. package/dist/components/data/timeline/timeline.class.js +9 -5
  65. package/dist/components/data/tree/tree-item.class.js +1 -1
  66. package/dist/components/data/tree/tree.class.d.ts +2 -0
  67. package/dist/components/data/tree/tree.class.js +1 -1
  68. package/dist/components/forms/button/button.class.d.ts +8 -6
  69. package/dist/components/forms/button/button.class.js +2 -2
  70. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  71. package/dist/components/forms/color-picker/color-core.js +1 -1
  72. package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
  73. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  74. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
  75. package/dist/components/forms/icon-button/icon-button.class.js +2 -2
  76. package/dist/components/forms/input/input-shared.js +2 -2
  77. package/dist/components/forms/input/number-input-locale.js +1 -0
  78. package/dist/components/forms/input/number-input.class.d.ts +19 -2
  79. package/dist/components/forms/input/number-input.class.js +2 -2
  80. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
  81. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  82. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  83. package/dist/components/layout/details/accordion-item.class.js +1 -1
  84. package/dist/components/layout/menu/menu.class.js +1 -1
  85. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  86. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  87. package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
  88. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  89. package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
  90. package/dist/components/layout/tab-group/tab.class.js +1 -1
  91. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
  92. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  93. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  94. package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
  95. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  96. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
  97. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
  98. package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
  99. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  100. package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
  101. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  102. package/dist/components/media/flag/flag-url-resolver.js +1 -1
  103. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
  104. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  105. package/dist/components/media/map/map-owned-features.js +1 -1
  106. package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
  107. package/dist/components/media/map/map-scene-render-controller.js +1 -1
  108. package/dist/components/media/map/map.class.d.ts +5 -5
  109. package/dist/components/media/map/map.class.js +3 -3
  110. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  111. package/dist/components/media/video/video.class.d.ts +3 -3
  112. package/dist/components/media/video/video.class.js +3 -1
  113. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  114. package/dist/components/overlays/chip/chip.class.js +1 -1
  115. package/dist/components/overlays/overlay/dropdown.class.js +1 -1
  116. package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
  117. package/dist/components/overlays/overlay/tooltip.class.js +3 -3
  118. package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
  119. package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
  120. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  121. package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
  122. package/dist/components/retrieval/graph/graph.class.js +1 -1
  123. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  124. package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
  125. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
  126. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  127. package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
  128. package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
  129. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  130. package/dist/components/utility/known-date/known-date.class.js +1 -1
  131. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  132. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  133. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  134. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  135. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
  136. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  137. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  138. package/dist/components/viewers/include/include.class.js +1 -1
  139. package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
  140. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  141. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  142. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  143. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  144. package/dist/components/viewers/table-viewer-shared.js +4 -4
  145. package/dist/framework-types.d.ts +1 -1
  146. package/dist/internal/anchored-overlay-runtime.js +1 -1
  147. package/dist/internal/catalog-picker.js +1 -1
  148. package/dist/internal/document-tokens.js +2 -2
  149. package/dist/internal/drop-session-controller.js +1 -1
  150. package/dist/internal/engine-3d.js +1 -1
  151. package/dist/internal/icon-only-content.js +1 -1
  152. package/dist/internal/layered-layout.js +1 -1
  153. package/dist/internal/map-custom-layer-controller.js +1 -1
  154. package/dist/internal/media-panorama.js +1 -1
  155. package/dist/internal/package-metadata.js +1 -1
  156. package/dist/internal/safe-url.js +1 -1
  157. package/dist/internal/scoped-definitions.generated.js +1 -1
  158. package/dist/internal/scroll-overflow.js +1 -1
  159. package/dist/internal/source-window-controller.js +1 -1
  160. package/dist/internal/text-quote.js +1 -1
  161. package/dist/internal/viewer-search.js +1 -1
  162. package/dist/lyra.d.ts +1 -1
  163. package/dist/sequence-time-binding.js +1 -1
  164. package/dist/simulation-clock.js +1 -1
  165. package/dist/styles/reservations.css +1 -1
  166. package/dist/styles/reservations.styles.js +1 -1
  167. package/dist/testing/happy-dom-shims.js +1 -1
  168. package/dist/theme/theme.js +1 -1
  169. package/llms/components/lr-attachment-chip.md +27 -12
  170. package/llms/components/lr-attachment-trigger.md +27 -7
  171. package/llms/components/lr-button.md +6 -4
  172. package/llms/components/lr-chat-composer.md +13 -7
  173. package/llms/components/lr-chat-message.md +44 -3
  174. package/llms/components/lr-chat-viewport.md +39 -2
  175. package/llms/components/lr-data-grid.md +2 -0
  176. package/llms/components/lr-dialog.md +10 -0
  177. package/llms/components/lr-drop-zone.md +26 -2
  178. package/llms/components/lr-icon-button.md +2 -1
  179. package/llms/components/lr-json-viewer.md +17 -0
  180. package/llms/components/lr-locale-picker.md +5 -0
  181. package/llms/components/lr-markdown-core.md +2 -1
  182. package/llms/components/lr-markdown.md +20 -4
  183. package/llms/components/lr-menu.md +3 -1
  184. package/llms/components/lr-number-input.md +28 -1
  185. package/llms/components/lr-prompt-input.md +1 -1
  186. package/llms/components/lr-streaming-text-core.md +3 -2
  187. package/llms/components/lr-streaming-text.md +4 -1
  188. package/llms/components/lr-suggestion-chips.md +28 -5
  189. package/llms/components/lr-tab-group.md +13 -1
  190. package/llms/components/lr-tab.md +5 -0
  191. package/llms/components/lr-table.md +25 -4
  192. package/llms/components/lr-timeline-item.md +1 -1
  193. package/llms/components/lr-timeline.md +38 -4
  194. package/llms/components/lr-tooltip.md +3 -1
  195. package/llms/components/lr-tree.md +4 -0
  196. package/llms/components/lr-virtual-list.md +1 -0
  197. package/llms/peers.md +2 -2
  198. package/llms/shared/forms-and-accessibility.md +21 -4
  199. package/llms/shared.md +21 -4
  200. package/package.json +21 -20
  201. package/registrations.json +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{waitForTransitionSettle}from"../../../internal/css-motion-time.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{styles}from"./mention-popover.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_noMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_mentionInputLimit,LYRA_DEFAULT_mentionMoreResults,LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions}from"../../../internal/default-strings/utility.generated.js";const MAX_VISIBLE_MENTION_ITEMS=50,MAX_MENTION_ITEMS=1e4;function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"],caretMirrors=new WeakMap;function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el);let cached=caretMirrors.get(el);if(!cached||cached.mirror.ownerDocument!==owner){const mirror2=owner.createElement("div"),prefix2=owner.createTextNode(""),marker2=owner.createElement("span"),suffix2=owner.createTextNode("");marker2.append(suffix2),mirror2.append(prefix2,marker2),cached={mirror:mirror2,prefix:prefix2,marker:marker2,suffix:suffix2},caretMirrors.set(el,cached)}const{mirror,prefix,marker,suffix}=cached;mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length,before=el.value.slice(0,index),after=el.value.slice(index)||"​";prefix.textContent!==before&&(prefix.textContent=before),suffix.textContent!==after&&(suffix.textContent=after),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{static{this.defaultStrings={...super.defaultStrings,mentionInputLimit:LYRA_DEFAULT_mentionInputLimit,mentionMoreResults:LYRA_DEFAULT_mentionMoreResults,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}constructor(){super(),this._textareaFocusSessionGeneration=0,this.itemPositions=new WeakMap,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this.listboxHidden=!0,this.listboxHideToken=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitMounted=!1,this.labelKeys=createHaystackMemo((item,locale)=>typeof item.label=="string"?item.label.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.descriptionKeys=createHaystackMemo((item,locale)=>typeof item.description=="string"?item.description.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.visibleItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()},this.inputLimited=!1,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open)}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),name===void 0&&(this.filteredMemo=void 0),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items;if(next===this.itemsSource||next===previous)return;this.itemsSource=next;const source=Array.isArray(next)?next:[];this.inputLimited=source.length>MAX_MENTION_ITEMS;const rows=new Array(Math.min(source.length,MAX_MENTION_ITEMS));this.itemPositions=new WeakMap;for(let index=0;index<Math.min(source.length,MAX_MENTION_ITEMS);index++){const descriptor=getOwnDataDescriptor(source,String(index));if(typeof descriptor=="symbol")continue;const item=descriptor.value,copy={};if(item&&typeof item=="object"){let keys=[];try{keys=Object.keys(item)}catch{}for(const key of keys){const field=getOwnDataDescriptor(item,key);typeof field!="symbol"&&Object.defineProperty(copy,key,{value:field.value,enumerable:!0})}}const snapshot=Object.freeze(copy);rows[index]=snapshot,this.itemPositions.set(snapshot,index)}this._items=Object.freeze(rows),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,changed.has("open")&&this.open&&(this.listboxHidden=!1),this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.visibleItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),this.limitMounted&&changed.has("inputLimited")&&this.inputLimited&&this.announcements.announcePolite(this.localize("mentionInputLimit")),this.limitMounted=!0,changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.settleListboxHidden();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]'),list=active?.parentElement;if(active&&list){const top=active.offsetTop,bottom=top+active.offsetHeight;top<list.scrollTop?list.scrollTop=top:bottom>list.scrollTop+list.clientHeight&&(list.scrollTop=bottom-list.clientHeight)}this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.listboxHideToken++,this.listboxHidden=!0,this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcements.adopted(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcements.announcePolite(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcements.announcePolite(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,{items,query,filter}=this,memo=this.filteredMemo;if(memo&&memo[0]===items&&memo[1]===query&&memo[2]===filter&&memo[3]===locale)return memo[4];const q=(query??"").trim().toLocaleLowerCase(locale),labels=filter?void 0:this.labelKeys(items,locale),descriptions=filter?void 0:this.descriptionKeys(items,locale),rows=items.filter((item,index)=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):labels[index].includes(q)||descriptions[index].includes(q):!0);return this.filteredMemo=[items,query,filter,locale,rows],rows}get visibleItems(){const filtered=this.filteredItems;if(this.visibleMemo?.[0]===filtered)return this.visibleMemo[1];const visible=filtered.length>MAX_VISIBLE_MENTION_ITEMS?filtered.slice(0,MAX_VISIBLE_MENTION_ITEMS):filtered;return this.visibleMemo=[filtered,visible],visible}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.visibleItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),shadowFocusTarget(this)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&shadowFocusTarget(this)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.visibleItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Home":case"End":return!this._ownsFocus||!rows.length?!1:(e.preventDefault(),this.activeIndex=e.key==="Home"?this.stepEnabledIndex(rows,-1,1):this.stepEnabledIndex(rows,rows.length,-1),!0);case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.itemPositions.get(item)??-1;if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}async settleListboxHidden(){const token=++this.listboxHideToken;await this.updateComplete,!(token!==this.listboxHideToken||this.open)&&(await waitForTransitionSettle(this.renderRoot.querySelector('[part="listbox"]'),this,{reducedMotion:prefersReducedMotion(this)}).finished,!(token!==this.listboxHideToken||this.open)&&(this.listboxHidden=!0))}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
1
+ import{__decorate}from"tslib";import{getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{createHaystackMemo}from"../../../internal/search-haystack.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{waitForTransitionSettle}from"../../../internal/css-motion-time.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{styles}from"./mention-popover.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_noMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_mentionInputLimit,LYRA_DEFAULT_mentionMoreResults,LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions}from"../../../internal/default-strings/utility.generated.js";const MAX_VISIBLE_MENTION_ITEMS=50,MAX_MENTION_ITEMS=1e4;function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"],caretMirrors=new WeakMap;function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el);let cached=caretMirrors.get(el);if(!cached||cached.mirror.ownerDocument!==owner){const mirror2=owner.createElement("div"),prefix2=owner.createTextNode(""),marker2=owner.createElement("span"),suffix2=owner.createTextNode("");marker2.append(suffix2),mirror2.append(prefix2,marker2),cached={mirror:mirror2,prefix:prefix2,marker:marker2,suffix:suffix2},caretMirrors.set(el,cached)}const{mirror,prefix,marker,suffix}=cached;mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length,before=el.value.slice(0,index),after=el.value.slice(index)||"​";prefix.textContent!==before&&(prefix.textContent=before),suffix.textContent!==after&&(suffix.textContent=after),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{static{this.defaultStrings={...super.defaultStrings,mentionInputLimit:LYRA_DEFAULT_mentionInputLimit,mentionMoreResults:LYRA_DEFAULT_mentionMoreResults,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}constructor(){super(),this._textareaFocusSessionGeneration=0,this.itemPositions=new WeakMap,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this.listboxHidden=!0,this.listboxHideToken=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.limitMounted=!1,this.labelKeys=createHaystackMemo((item,locale)=>typeof item.label=="string"?item.label.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.descriptionKeys=createHaystackMemo((item,locale)=>typeof item.description=="string"?item.description.toLocaleLowerCase(resolveIntlLocale(locale)):""),this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.visibleItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()},this.inputLimited=!1,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open)}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),name===void 0&&(this.filteredMemo=void 0),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items;if(next===this.itemsSource||next===previous)return;this.itemsSource=next;const source=Array.isArray(next)?next:[];this.inputLimited=source.length>MAX_MENTION_ITEMS;const rows=new Array(Math.min(source.length,MAX_MENTION_ITEMS));this.itemPositions=new WeakMap;for(let index=0;index<Math.min(source.length,MAX_MENTION_ITEMS);index++){const descriptor=getOwnDataDescriptor(source,String(index));if(typeof descriptor=="symbol")continue;const item=descriptor.value,copy={};if(item&&typeof item=="object"){let keys=[];try{keys=Object.keys(item)}catch{}for(const key of keys){const field=getOwnDataDescriptor(item,key);typeof field!="symbol"&&Object.defineProperty(copy,key,{value:field.value,enumerable:!0})}}const snapshot=Object.freeze(copy);rows[index]=snapshot,this.itemPositions.set(snapshot,index)}this._items=Object.freeze(rows),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,changed.has("open")&&this.open&&(this.listboxHidden=!1),this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.visibleItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),this.limitMounted&&changed.has("inputLimited")&&this.inputLimited&&this.announcements.announcePolite(this.localize("mentionInputLimit")),this.limitMounted=!0,changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.settleListboxHidden();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]'),list=active?.parentElement;if(active&&list){const top=active.offsetTop,bottom=top+active.offsetHeight;top<list.scrollTop?list.scrollTop=top:bottom>list.scrollTop+list.clientHeight&&(list.scrollTop=bottom-list.clientHeight)}this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.listboxHideToken++,this.listboxHidden=!0,this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcements.adopted(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcements.announcePolite(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcements.announcePolite(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,{items,query,filter}=this,memo=this.filteredMemo;if(memo&&memo[0]===items&&memo[1]===query&&memo[2]===filter&&memo[3]===locale)return memo[4];const q=(query??"").trim().toLocaleLowerCase(locale),labels=filter?void 0:this.labelKeys(items,locale),descriptions=filter?void 0:this.descriptionKeys(items,locale),rows=items.filter((item,index)=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):labels[index].includes(q)||descriptions[index].includes(q):!0);return this.filteredMemo=[items,query,filter,locale,rows],rows}get visibleItems(){const filtered=this.filteredItems;if(this.visibleMemo?.[0]===filtered)return this.visibleMemo[1];const visible=filtered.length>MAX_VISIBLE_MENTION_ITEMS?filtered.slice(0,MAX_VISIBLE_MENTION_ITEMS):filtered;return this.visibleMemo=[filtered,visible],visible}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.visibleItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),shadowFocusTarget(this)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&shadowFocusTarget(this)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.visibleItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Home":case"End":return!this._ownsFocus||!rows.length?!1:(e.preventDefault(),this.activeIndex=e.key==="Home"?this.stepEnabledIndex(rows,-1,1):this.stepEnabledIndex(rows,rows.length,-1),!0);case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.itemPositions.get(item)??-1;if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}async settleListboxHidden(){const token=++this.listboxHideToken;await this.updateComplete,!(token!==this.listboxHideToken||this.open)&&(await waitForTransitionSettle(this.renderRoot.querySelector('[part="listbox"]'),this,{reducedMotion:prefersReducedMotion(this)}).finished,!(token!==this.listboxHideToken||this.open)&&(this.listboxHidden=!0))}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText==null?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label==null?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
2
2
  <div
3
3
  part="option"
4
4
  id=${id}
@@ -1 +1 @@
1
- import{__decorate}from"tslib";import{utcDate}from"../../forms/date-picker/calendar-core.js";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{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{loadIcal}from"./calendar-loader.js";import{styles}from"./calendar-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{getDateTimeFormat}from"../../../internal/intl-cache.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{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_calendarViewerEmpty,LYRA_DEFAULT_calendarViewerLabel,LYRA_DEFAULT_calendarViewerMissingParser,LYRA_DEFAULT_calendarViewerNoSummary,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeCalendar,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_CALENDAR_EVENTS=250,MAX_CALENDAR_RENDERED_CHARS=2*1024*1024;function formatEventTime(event,locale){if(!event.start)return"";if(event.startKind==="date"){const formatter2=getDateTimeFormat(locale,{dateStyle:"medium",timeZone:"UTC"});if(!event.end||event.endKind!=="date")return formatter2.format(event.start);const inclusiveEnd=new Date(event.end.getTime());return inclusiveEnd.setUTCDate(inclusiveEnd.getUTCDate()-1),inclusiveEnd.getTime()<=event.start.getTime()?formatter2.format(event.start):formatter2.formatRange(event.start,inclusiveEnd)}const formatter=getDateTimeFormat(locale,{dateStyle:"medium",timeStyle:"short"});return event.end&&event.endKind==="date-time"?formatter.formatRange(event.start,event.end):formatter.format(event.start)}function parseCalendarTime(time){if(!time)return null;let value;if(time.isDate===!0&&Number.isInteger(time.year)&&Number.isInteger(time.month)&&Number.isInteger(time.day)){if(value=utcDate(time.year,time.month-1,time.day),value.getUTCFullYear()!==time.year||value.getUTCMonth()+1!==time.month||value.getUTCDate()!==time.day)throw new Error("Invalid all-day calendar date.")}else value=time.toJSDate();if(!Number.isFinite(value.getTime()))throw new Error("Invalid calendar date.");return{value,kind:time.isDate===!0?"date":"date-time"}}function eventTime(read){try{return parseCalendarTime(read())}catch{return null}}class LyraCalendarViewerBase extends LyraElement{}class LyraCalendarViewer extends TextViewerTarget(LyraCalendarViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,calendarViewerEmpty:LYRA_DEFAULT_calendarViewerEmpty,calendarViewerLabel:LYRA_DEFAULT_calendarViewerLabel,calendarViewerMissingParser:LYRA_DEFAULT_calendarViewerMissingParser,calendarViewerNoSummary:LYRA_DEFAULT_calendarViewerNoSummary,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeCalendar:LYRA_DEFAULT_documentPreviewTypeCalendar,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,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.detached.cancel()&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),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 events=await this.parse(source,generation);if(!this.isConnected||generation!==this.generation||!events)return;generation===this.generation&&(this.fetchState={kind:"loaded",events})}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})}}async parse(source,generation){const ical=await loadIcal();if(!this.isConnected||generation!==this.generation)return;if(!ical)throw new LyraUserFacingError(this.localize("calendarViewerMissingParser"));if((source.match(/^BEGIN:VEVENT\r?$/gim)?.length??0)>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");const subcomponents=new ical.Component(ical.parse(source)).getAllSubcomponents("vevent");if(subcomponents.length>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");let renderedChars=0;return subcomponents.map(subcomponent=>{const event=new ical.Event(subcomponent),parsedStart=eventTime(()=>event.startDate),parsedEnd=eventTime(()=>event.endDate),end=parsedStart&&parsedEnd&&(parsedStart.kind!==parsedEnd.kind||parsedEnd.value.getTime()<parsedStart.value.getTime())?null:parsedEnd,uid=event.uid??"",summary=event.summary??"",location=event.location??"",description=event.description??"";if(renderedChars+=uid.length+summary.length+location.length+description.length,renderedChars>MAX_CALENDAR_RENDERED_CHARS)throw new LyraResourceLimitError("The calendar contains too much rendered text.");return{uid,summary,start:parsedStart?.value??null,end:end?.value??null,startKind:parsedStart?.kind??null,endKind:end?.kind??null,location,description}})}renderEvent(event){return html`<li part="event"><span part="event-summary">${event.summary||this.localize("calendarViewerNoSummary")}</span><span part="event-time">${formatEventTime(event,this.effectiveLocale)}</span>${event.location?html`<span part="event-location">${event.location}</span>`:nothing}${event.description?html`<p part="event-description">${event.description}</p>`:nothing}</li>`}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.events.length?html`<ul part="event-list">${this.fetchState.events.map(event=>this.renderEvent(event))}</ul>`:html`<p class="empty-note">${this.localize("calendarViewerEmpty")}</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("documentPreviewTypeCalendar")})}</p>`}}textContentRoot(){return this.fetchState.kind==="loaded"&&this.fetchState.events.length>0?super.textContentRoot():null}render(){const maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${viewerSemanticRole(this,"region")??nothing} style=${maxHeight?styleMap({"--lr-calendar-viewer-max-height":maxHeight}):nothing} aria-label=${viewerSemanticLabel(this,this.name||this.localize("calendarViewerLabel"))??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraCalendarViewer.prototype,"src",void 0),__decorate([property()],LyraCalendarViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraCalendarViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraCalendarViewer.prototype,"fetchState",void 0);export{LyraCalendarViewer};
1
+ import{__decorate}from"tslib";import{utcDate}from"../../forms/date-picker/calendar-core.js";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{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,isResourceLimitError,LyraResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{loadIcal}from"./calendar-loader.js";import{styles}from"./calendar-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{getDateTimeFormat}from"../../../internal/intl-cache.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{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_calendarViewerEmpty,LYRA_DEFAULT_calendarViewerLabel,LYRA_DEFAULT_calendarViewerMissingParser,LYRA_DEFAULT_calendarViewerNoSummary,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeCalendar,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_CALENDAR_EVENTS=250,MAX_CALENDAR_RENDERED_CHARS=2*1024*1024;function formatEventTime(event,locale){if(!event.start)return"";if(event.startKind==="date"){const formatter2=getDateTimeFormat(locale,{dateStyle:"medium",timeZone:"UTC"});if(!event.end||event.endKind!=="date")return formatter2.format(event.start);const inclusiveEnd=new Date(event.end.getTime());return inclusiveEnd.setUTCDate(inclusiveEnd.getUTCDate()-1),inclusiveEnd.getTime()<=event.start.getTime()?formatter2.format(event.start):formatter2.formatRange(event.start,inclusiveEnd)}const formatter=getDateTimeFormat(locale,{dateStyle:"medium",timeStyle:"short"});return event.end&&event.endKind==="date-time"?formatter.formatRange(event.start,event.end):formatter.format(event.start)}function parseCalendarTime(time){if(!time)return null;let value;if(time.isDate===!0&&Number.isInteger(time.year)&&Number.isInteger(time.month)&&Number.isInteger(time.day)){if(value=utcDate(time.year,time.month-1,time.day),value.getUTCFullYear()!==time.year||value.getUTCMonth()+1!==time.month||value.getUTCDate()!==time.day)throw new Error("Invalid all-day calendar date.")}else value=time.toJSDate();if(!Number.isFinite(value.getTime()))throw new Error("Invalid calendar date.");return{value,kind:time.isDate===!0?"date":"date-time"}}function eventTime(read){try{return parseCalendarTime(read())}catch{return null}}class LyraCalendarViewerBase extends LyraElement{}class LyraCalendarViewer extends TextViewerTarget(LyraCalendarViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.detached=new DeferredTeardown(()=>{this.generation++})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,calendarViewerEmpty:LYRA_DEFAULT_calendarViewerEmpty,calendarViewerLabel:LYRA_DEFAULT_calendarViewerLabel,calendarViewerMissingParser:LYRA_DEFAULT_calendarViewerMissingParser,calendarViewerNoSummary:LYRA_DEFAULT_calendarViewerNoSummary,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeCalendar:LYRA_DEFAULT_documentPreviewTypeCalendar,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,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.detached.cancel()&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),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(!this.isConnected||generation!==this.generation)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const source=await readResponseText(response);if(!this.isConnected||generation!==this.generation)return;const events=await this.parse(source,generation);if(!this.isConnected||generation!==this.generation||!events)return;generation===this.generation&&(this.fetchState={kind:"loaded",events})}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})}}async parse(source,generation){const ical=await loadIcal();if(!this.isConnected||generation!==this.generation)return;if(!ical)throw new LyraUserFacingError(this.localize("calendarViewerMissingParser"));if((source.match(/^BEGIN:VEVENT\r?$/gim)?.length??0)>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");const subcomponents=new ical.Component(ical.parse(source)).getAllSubcomponents("vevent");if(subcomponents.length>MAX_CALENDAR_EVENTS)throw new LyraResourceLimitError("The calendar contains too many events.");let renderedChars=0;return subcomponents.map(subcomponent=>{const event=new ical.Event(subcomponent),parsedStart=eventTime(()=>event.startDate),parsedEnd=eventTime(()=>event.endDate),end=parsedStart&&parsedEnd&&(parsedStart.kind!==parsedEnd.kind||parsedEnd.value.getTime()<parsedStart.value.getTime())?null:parsedEnd,uid=event.uid??"",summary=event.summary??"",location=event.location??"",description=event.description??"";if(renderedChars+=uid.length+summary.length+location.length+description.length,renderedChars>MAX_CALENDAR_RENDERED_CHARS)throw new LyraResourceLimitError("The calendar contains too much rendered text.");return{uid,summary,start:parsedStart?.value??null,end:end?.value??null,startKind:parsedStart?.kind??null,endKind:end?.kind??null,location,description}})}renderEvent(event){return html`<li part="event"><span part="event-summary">${event.summary||this.localize("calendarViewerNoSummary")}</span><span part="event-time">${formatEventTime(event,this.effectiveLocale)}</span>${event.location?html`<span part="event-location">${event.location}</span>`:nothing}${event.description?html`<p part="event-description">${event.description}</p>`:nothing}</li>`}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.events.length?html`<ul part="event-list">${this.fetchState.events.map(event=>this.renderEvent(event))}</ul>`:html`<p class="empty-note">${this.localize("calendarViewerEmpty")}</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("documentPreviewTypeCalendar")})}</p>`}}textContentRoot(){return this.fetchState.kind==="loaded"&&this.fetchState.events.length>0?super.textContentRoot():null}render(){const maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${viewerSemanticRole(this,"region")??nothing} style=${maxHeight?styleMap({"--lr-calendar-viewer-max-height":maxHeight}):nothing} aria-label=${viewerSemanticLabel(this,this.name||this.localize("calendarViewerLabel"))??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraCalendarViewer.prototype,"src",void 0),__decorate([property()],LyraCalendarViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraCalendarViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraCalendarViewer.prototype,"fetchState",void 0);export{LyraCalendarViewer};
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";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{viewerFrameStyles}from"../viewer-frame.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{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{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_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeContact,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.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),this.detached=new DeferredTeardown(()=>{this.generation++})}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,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,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,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,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.detached.cancel()&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),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
+ import{__decorate}from"tslib";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{viewerFrameStyles}from"../viewer-frame.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{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{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_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeContact,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.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),this.detached=new DeferredTeardown(()=>{this.generation++})}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,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,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,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,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.detached.cancel()&&this.hasUpdated&&this.src&&(this.requestUpdate(),this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),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(!this.isConnected||generation!==this.generation)return;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"
@@ -19,7 +19,7 @@ import{__decorate}from"tslib";import{finiteCount}from"../../../internal/numbers.
19
19
  .items=${body.length<=1e4?body:nothing}
20
20
  .source=${this.table.indexedSource(body)}
21
21
  .renderItem=${renderItem}
22
- .keyFunction=${indexKeyFunction}
22
+ .keyFunction=${body.length<=1e4?indexKeyFunction:void 0}
23
23
  .activeItemId=${this.table.activeRowKey}
24
24
  item-role="row"
25
25
  row-index-offset=${hasHeaderRow?"1":"0"}
@@ -16,7 +16,7 @@ import{__decorate}from"tslib";import{finiteCount}from"../../../internal/numbers.
16
16
  .items=${guard([rows],()=>rows.length<=1e4?rows:nothing)}
17
17
  .source=${this.tableController.indexedSource(rows)}
18
18
  .renderItem=${this.tableController.rowRenderer(rows,[fields,window.columns,this.activeHighlightId,this.strings],(row,index)=>this.renderRow(row,index,fields))}
19
- .keyFunction=${this.virtualListKeyFunction}
19
+ .keyFunction=${rows.length<=1e4?this.virtualListKeyFunction:void 0}
20
20
  .activeItemId=${this.tableController.activeRowKey}
21
21
  .scrollElement=${this.scrollMode==="page"?this.ownerDocument.defaultView??void 0:void 0}
22
22
  item-role="row"
@@ -9,7 +9,7 @@ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,stat
9
9
  >${highlight.label||label}</button>
10
10
  `})}
11
11
  </div>
12
- `}getTextIndex(root){const locale=this.effectiveLocale;if(!this.textIndexCache||this.textIndexCache.locale!==locale){const scope=scopeFromElement(root);this.textIndexCache={scope,index:createTextQuoteIndex(scope,locale,{maxMatches:MAX_DOCX_SEARCH_MATCHES}),locale},this.textIndexMappingDirty=!1}return this.textIndexCache}currentTextIndex(root){const cached=this.getTextIndex(root);if(!this.textIndexMappingDirty)return cached;const scope=scopeFromElement(root);return cached.index.rebindScope(scope)?(cached.scope=scope,this.textIndexMappingDirty=!1,cached):(this.textIndexCache=null,this.textIndexMappingDirty=!1,this.getTextIndex(root))}async search(query){if(invalidateLyraLocaleCache(this),this.searchState.query=query,!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.clearSearchPaint(),this.searchState.publish(void 0,!1),0;const root=this.contentRoot(),trimmed=query.trim();if(!root||!trimmed)return this.clearSearchPaint(),this.searchState.publish(),0;const{index}=this.getTextIndex(root),matches=index.search(trimmed,index.createWorkBudget());return this.searchState.publish(matches,matches.matchCountExact),this.paintSearchMatches(),this.searchState.activeIndex>=0&&this.scrollToActiveSearchMatch(),matches.length}async searchNext(){return this.stepSearch(1)}async searchPrevious(){return this.stepSearch(-1)}stepSearch(direction){return this.searchState.step(direction)?(this.paintSearchMatches(),this.scrollToActiveSearchMatch(),!0):!1}clearSearch(){this.clearSearchPaint(),this.searchState.clear()}scrollToActiveSearchMatch(){this.renderRoot.querySelector('mark[part~="search-match-active"]')?.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"})}clearSearchPaint(){this.paintedSearchMarks.length>0&&(this.textIndexMappingDirty=!0);for(const mark of this.paintedSearchMarks)unwrapTextMark(mark);this.paintedSearchMarks=[]}paintSearchMatches(){this.clearSearchPaint();const root=this.contentRoot();if(!root||this.searchState.matches.length===0)return;const{scope}=this.currentTextIndex(root),marks=[],count=Math.min(this.searchState.matches.length,MAX_DOCX_PAINTED_SEARCH_MATCHES),half=MAX_DOCX_PAINTED_SEARCH_MATCHES>>1,centre=this.searchState.activeIndex<0?0:this.searchState.activeIndex,start=Math.max(0,Math.min(centre-half,this.searchState.matches.length-count)),budget={traversalNodes:TEXT_QUOTE_LIMITS.maxTraversalNodes,codeUnits:TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,marks:MAX_DOCX_PAINTED_SEARCH_MATCHES},window=[];for(let i=start+count-1;i>=start;i--){const match=this.searchState.matches.at(i);match&&window.push({index:i,match})}const resolvedRanges=rangesFromTextQuoteMatches(scope,window.map(({match})=>match)),ranges=[];for(let position=0;position<window.length;position++){const range=resolvedRanges[position];range&&ranges.push({index:window[position].index,range})}for(const{index,range}of ranges){const part=index===this.searchState.activeIndex?"search-match search-match-active":"search-match";marks.push(...wrapRangeInSearchMarks(range,part,budget))}this.paintedSearchMarks=marks,marks.length>0&&(this.textIndexMappingDirty=!0)}renderBody(){switch(this.fetchState.kind){case"loaded":return html`
12
+ `}getTextIndex(root){const locale=this.effectiveLocale;if(!this.textIndexCache||this.textIndexCache.locale!==locale){const scope=scopeFromElement(root);this.textIndexCache={scope,index:createTextQuoteIndex(scope,locale,{maxMatches:MAX_DOCX_SEARCH_MATCHES}),locale},this.textIndexMappingDirty=!1}return this.textIndexCache}currentTextIndex(root){const cached=this.getTextIndex(root);if(!this.textIndexMappingDirty)return cached;const scope=scopeFromElement(root);return cached.index.rebindScope(scope)?(cached.scope=scope,this.textIndexMappingDirty=!1,cached):(this.textIndexCache=null,this.textIndexMappingDirty=!1,this.getTextIndex(root))}async search(query){if(invalidateLyraLocaleCache(this),this.searchState.query=query,!boundedViewerSearchQuery(query,this.effectiveLocale).accepted)return this.clearSearchPaint(),this.searchState.publish(void 0,!1),0;const root=this.contentRoot(),trimmed=query.trim();if(!root||!trimmed)return this.clearSearchPaint(),this.searchState.publish(),0;const{index}=this.getTextIndex(root),matches=index.search(trimmed,index.createWorkBudget());return this.searchState.publish(matches,matches.matchCountExact)?(this.paintSearchMatches(),this.searchState.activeIndex>=0&&this.scrollToActiveSearchMatch(),matches.length):0}async searchNext(){return this.stepSearch(1)}async searchPrevious(){return this.stepSearch(-1)}stepSearch(direction){return this.searchState.step(direction)?(this.paintSearchMatches(),this.scrollToActiveSearchMatch(),!0):!1}clearSearch(){this.clearSearchPaint(),this.searchState.clear()}scrollToActiveSearchMatch(){this.renderRoot.querySelector('mark[part~="search-match-active"]')?.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"})}clearSearchPaint(){this.paintedSearchMarks.length>0&&(this.textIndexMappingDirty=!0);for(const mark of this.paintedSearchMarks)unwrapTextMark(mark);this.paintedSearchMarks=[]}paintSearchMatches(){this.clearSearchPaint();const root=this.contentRoot();if(!root||this.searchState.matches.length===0)return;const{scope}=this.currentTextIndex(root),marks=[],count=Math.min(this.searchState.matches.length,MAX_DOCX_PAINTED_SEARCH_MATCHES),half=MAX_DOCX_PAINTED_SEARCH_MATCHES>>1,centre=this.searchState.activeIndex<0?0:this.searchState.activeIndex,start=Math.max(0,Math.min(centre-half,this.searchState.matches.length-count)),budget={traversalNodes:TEXT_QUOTE_LIMITS.maxTraversalNodes,codeUnits:TEXT_QUOTE_LIMITS.maxCorpusCodeUnits,marks:MAX_DOCX_PAINTED_SEARCH_MATCHES},window=[];for(let i=start+count-1;i>=start;i--){const match=this.searchState.matches.at(i);match&&window.push({index:i,match})}const resolvedRanges=rangesFromTextQuoteMatches(scope,window.map(({match})=>match)),ranges=[];for(let position=0;position<window.length;position++){const range=resolvedRanges[position];range&&ranges.push({index:window[position].index,range})}for(const{index,range}of ranges){const part=index===this.searchState.activeIndex?"search-match search-match-active":"search-match";marks.push(...wrapRangeInSearchMarks(range,part,budget))}this.paintedSearchMarks=marks,marks.length>0&&(this.textIndexMappingDirty=!0)}renderBody(){switch(this.fetchState.kind){case"loaded":return html`
13
13
  <div
14
14
  part="content"
15
15
  role=${viewerSemanticRole(this,"document")??nothing}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";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{DEFAULT_CANVAS_COLOR}from"../../../internal/canvas-color.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,isObjectValue,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{textQuoteContextScore}from"../document-viewer/anchors.js";import{getEpubJs}from"./ebook-loader.js";import{assertEpubArchiveWithinLimits}from"./epub-resource-guard.js";import{guardEpubUnloadListener}from"./epub-unload-guard.js";import{styles}from"./ebook-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{renderViewerPagerButton,viewerPagerStyles}from"../viewer-pager.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_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_ebookViewerLoadError,LYRA_DEFAULT_ebookViewerMissingLibrary,LYRA_DEFAULT_ebookViewerNextChapter,LYRA_DEFAULT_ebookViewerPreviousChapter,LYRA_DEFAULT_ebookViewerRegionLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_TOC_ITEMS=1e4,MAX_TOC_DEPTH=100,MAX_SEARCH_MATCHES=1e4,MAX_SEARCH_SPINE_ITEMS=1e3,MAX_FIND_RESULTS=1e4,MAX_PAINTED_HIGHLIGHTS=100,MAX_PEER_PROTOTYPES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function inheritedDataDescriptor(value,key){let current=value;for(let depth=0;current&&depth<MAX_PEER_PROTOTYPES;depth+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(current,key)}catch{return}if(descriptor)return"value"in descriptor?descriptor:void 0;try{current=Object.getPrototypeOf(current)}catch{return}}}function inheritedDataValue(value,key){return isObjectValue(value)?inheritedDataDescriptor(value,key)?.value:void 0}function savedCallable(value,key){if(!isObjectValue(value))return;const candidate=inheritedDataDescriptor(value,key)?.value;if(typeof candidate=="function")return(...args)=>Reflect.apply(candidate,value,args)}function savedThenable(value){const then=savedCallable(value,"then");if(then)return new Promise((resolve,reject)=>{try{then(()=>resolve(),reject)}catch(error){reject(error)}})}function taskFrom(call,...args){try{return savedThenable(call(...args))??Promise.resolve()}catch(error){return Promise.reject(error)}}function awaitPeerResult(value){const then=savedCallable(value,"then"),wrap=resolved=>Object.freeze({value:resolved});return then?new Promise((resolve,reject)=>{try{then(resolved=>resolve(wrap(resolved)),reject)}catch(error){reject(error)}}):Promise.resolve(wrap(value))}function quoteContextScore(excerpt,quote,prefix,suffix){const text=excerpt.replace(/\s+/g," ").toLowerCase(),needle=quote.replace(/\s+/g," ").toLowerCase();let best=0;for(let at=text.indexOf(needle);at>=0;at=text.indexOf(needle,at+1))best=Math.max(best,textQuoteContextScore(text,at,at+needle.length,prefix,suffix));return best}const EPUB_CHAPTER_CONTENT_SECURITY_POLICY="default-src 'none'; img-src blob: data:; media-src blob: data:; font-src blob: data:; style-src blob: 'unsafe-inline'";function silenceChapterNetwork(chapter){const root=chapter.documentElement;if(!root)return;for(const node of[...chapter.childNodes])node.nodeType===Node.PROCESSING_INSTRUCTION_NODE&&chapter.removeChild(node);for(const element of[...chapter.querySelectorAll("link, meta")]){const rel=` ${(element.getAttribute("rel")??"").toLowerCase()} `;(/ (?:dns-prefetch|preconnect) /.test(rel)||(element.getAttribute("http-equiv")??"").trim().toLowerCase()==="refresh")&&element.remove()}const namespace=root.namespaceURI??"http://www.w3.org/1999/xhtml";let head=chapter.querySelector("head");head||(head=chapter.createElementNS(namespace,"head"),root.insertBefore(head,root.firstChild));const policy=chapter.createElementNS(namespace,"meta");policy.setAttribute("http-equiv","Content-Security-Policy"),policy.setAttribute("content",EPUB_CHAPTER_CONTENT_SECURITY_POLICY),head.insertBefore(policy,head.firstChild)}function registerNetworkSilentChapters(book){const contentHooks=inheritedDataValue(inheritedDataValue(book.spine,"hooks"),"content");savedCallable(contentHooks,"register")?.(silenceChapterNetwork)}function normalizeBook(value){if(!isObjectValue(value))return;const ready=savedThenable(inheritedDataValue(value,"ready")),renderTo=savedCallable(value,"renderTo"),destroy=savedCallable(value,"destroy");if(!ready||!renderTo||!destroy)return;let navigationCaptured=!1,navigation;const getNavigation=()=>(navigationCaptured||(navigationCaptured=!0,navigation=inheritedDataValue(value,"navigation")),navigation),spine=inheritedDataValue(value,"spine"),load=savedCallable(value,"load");return Object.freeze({ready,...spine===void 0?{}:{spine},...load===void 0?{}:{load},getNavigation,renderTo:(element,options)=>renderTo(element,options),destroy:()=>{destroy()}})}function normalizeRendition(value){if(!isObjectValue(value))return;const display=savedCallable(value,"display"),prev=savedCallable(value,"prev"),next=savedCallable(value,"next"),on=savedCallable(value,"on"),annotationsValue=inheritedDataValue(value,"annotations"),highlight=savedCallable(annotationsValue,"highlight"),remove=savedCallable(annotationsValue,"remove");if(!(!display||!prev||!next||!on||!highlight||!remove))return Object.freeze({display:target=>taskFrom(display,target),prev:()=>taskFrom(prev),next:()=>taskFrom(next),on:(type,callback)=>{on(type,callback)},annotations:Object.freeze({highlight:(cfi,data,callback,className,styles2)=>highlight(cfi,data,callback,className,styles2),remove:(cfi,type)=>{remove(cfi,type)}})})}function normalizeSpineItem(value){const load=savedCallable(value,"load"),find=savedCallable(value,"find"),unload=savedCallable(value,"unload");if(!(!load||!find||!unload))return Object.freeze({load:request=>load(request),find:query=>find(query),unload:()=>{unload()}})}function projectSpineItems(book){const spineItems=inheritedDataValue(book.spine,"spineItems");if(!isArrayValue(spineItems))return Object.freeze({items:Object.freeze([]),exact:spineItems===void 0});const length=getOwnDataDescriptor(spineItems,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze({items:Object.freeze([]),exact:!1});const items=[];let exact=length.value<=MAX_SEARCH_SPINE_ITEMS;const count=Math.min(length.value,MAX_SEARCH_SPINE_ITEMS);for(let index=0;index<count;index+=1){const descriptor=getOwnDataDescriptor(spineItems,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){exact=!1;continue}const item=normalizeSpineItem(descriptor.value);if(!item){exact=!1;continue}items.push(item)}return Object.freeze({items:Object.freeze(items),exact})}function projectFindResults(value,work){if(!isArrayValue(value))return Object.freeze({matches:Object.freeze([]),exact:!1});const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze({matches:Object.freeze([]),exact:!1});const matches=[];let exact=length.value<=MAX_FIND_RESULTS;const count=Math.min(length.value,MAX_FIND_RESULTS);for(let index=0;index<count;index+=1){const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!isObjectValue(descriptor.value)){exact=!1;continue}const cfi=getOwnDataDescriptor(descriptor.value,"cfi"),excerpt=getOwnDataDescriptor(descriptor.value,"excerpt");if(cfi===MISSING_OWN_DATA_DESCRIPTOR||cfi===UNSAFE_OWN_DATA_DESCRIPTOR||typeof cfi.value!="string"){exact=!1;continue}if(!work.canConsume(cfi.value)||!work.consume(cfi.value)||cfi.value.trim()===""){exact=!1;continue}let excerptValue="";excerpt!==MISSING_OWN_DATA_DESCRIPTOR&&(excerpt===UNSAFE_OWN_DATA_DESCRIPTOR||typeof excerpt.value!="string"||!work.canConsume(excerpt.value)||!work.consume(excerpt.value)?exact=!1:excerptValue=excerpt.value),matches.push({cfi:cfi.value,excerpt:excerptValue})}return Object.freeze({matches:Object.freeze(matches),exact})}function pushTocEntries(value,level,budget,stack){if(!isArrayValue(value)||budget.positions>=MAX_TOC_ITEMS)return;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return;const count=Math.min(length.value,MAX_TOC_ITEMS-budget.positions);for(let index=count-1;index>=0;index-=1){budget.positions+=1;const descriptor=getOwnDataDescriptor(value,String(index));descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||stack.push({value:descriptor.value,level})}}function projectToc(value){const budget={positions:0,nodes:0,seen:new WeakSet},stack=[];pushTocEntries(value,1,budget,stack);const items=[];for(;stack.length>0&&budget.nodes<MAX_TOC_ITEMS;){const current=stack.pop();if(!isObjectValue(current.value)||budget.seen.has(current.value))continue;budget.seen.add(current.value),budget.nodes+=1;const href=getOwnDataDescriptor(current.value,"href"),id=getOwnDataDescriptor(current.value,"id"),label=getOwnDataDescriptor(current.value,"label"),children=getOwnDataDescriptor(current.value,"subitems");if(href!==MISSING_OWN_DATA_DESCRIPTOR&&href!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof href.value=="string"){const idValue=id!==MISSING_OWN_DATA_DESCRIPTOR&&id!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof id.value=="string"&&id.value!==""?id.value:href.value,labelValue=label!==MISSING_OWN_DATA_DESCRIPTOR&&label!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof label.value=="string"?label.value.trim():"";items.push({id:idValue,label:labelValue,href:href.value,level:current.level})}current.level<MAX_TOC_DEPTH&&children!==MISSING_OWN_DATA_DESCRIPTOR&&children!==UNSAFE_OWN_DATA_DESCRIPTOR&&pushTocEntries(children.value,current.level+1,budget,stack)}return Object.freeze(items)}const 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:DEFAULT_CANVAS_COLOR};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,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,ebookViewerLoadError:LYRA_DEFAULT_ebookViewerLoadError,ebookViewerMissingLibrary:LYRA_DEFAULT_ebookViewerMissingLibrary,ebookViewerNextChapter:LYRA_DEFAULT_ebookViewerNextChapter,ebookViewerPreviousChapter:LYRA_DEFAULT_ebookViewerPreviousChapter,ebookViewerRegionLabel:LYRA_DEFAULT_ebookViewerRegionLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerPagerStyles,srOnly,viewerLoadingStyles]}constructor(){super(),this.src="",this.name="",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.failedGeneration=-1,this.searchQuery="",this.lastSearchLocale="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.paintedHighlightCfis=[],this.announcements=new ViewerAnnouncementController(this),this.chapterButtonFocused=!1,this.previous=()=>{this.runRenditionNavigation("previous")},this.next=()=>{this.runRenditionNavigation("next")},new ThemeWatcher(this,()=>this.repaintAnnotations())}updated(changed){if(super.updated(changed),this.chapterButtonFocused&&this.ebookState.kind!=="ready"&&this.shadowRoot?.querySelector('[part="mount"]')?.focus(),this.chapterButtonFocused=!1,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);const active=shadowFocusTarget(this);this.chapterButtonFocused=active?.localName==="button"&&!active.disabled&&active.getAttribute("part")?.endsWith("-button")===!0,changed.has("src")&&(this.pendingSearchResetEvent||=this.hasSearchState(),this.resetSearchState())}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src.trim()&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.anchorOperationGeneration++,this.announcements.disconnect(),this.teardown(),this.ebookState={kind:"idle"},super.disconnectedCallback()}connectedMoveCallback(){}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}teardown(){const shouldEmitSearchReset=this.hasSearchState();this.destroyBook(this.book),this.book=void 0,this.rendition=void 0,this.resetSearchState(),this.paintedHighlightCfis=[],shouldEmitSearchReset&&this.isConnected&&this.emitSearchChange()}destroyBook(book){try{book?.destroy()}catch{}}isCurrentLoad(generation,ownerView){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView}isCurrentBookRendition(generation,ownerView,book,rendition){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView&&this.book===book&&this.rendition===rendition}failCurrentLoad(error,message=this.localize("ebookViewerLoadError")){this.failedGeneration!==this.generation&&(this.failedGeneration=this.generation,this.ebookState={kind:"error",message},this.emit("lr-render-error",{error}))}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.isCurrentLoad(generation,fetchTarget.view)||(await assertEpubArchiveWithinLimits(data,void 0,void 0,{signal}),!this.isCurrentLoad(generation,fetchTarget.view)))return}catch(error){if(isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.failCurrentLoad(error,this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"ebookViewerLoadError"));return}if(!factory){this.failWithLocalizedMessage(this.localize("ebookViewerMissingLibrary"));return}const mount=this.mountRef.value;if(!mount){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}let candidateBook;try{const book=normalizeBook(factory(data));if(!book)throw new Error("EPUB peer returned an unusable book.");candidateBook=book,registerNetworkSilentChapters(book);const rawRendition=book.renderTo(mount,{width:"100%",height:"100%"});guardEpubUnloadListener({settings:inheritedDataValue(rawRendition,"settings"),requireManager:savedCallable(rawRendition,"requireManager")});const rendition=normalizeRendition(rawRendition);if(!rendition)throw new Error("EPUB peer returned an unusable rendition.");if(await book.ready,!this.isCurrentLoad(generation,fetchTarget.view)){this.destroyBook(book),candidateBook=void 0;return}if(book.getNavigation(),await rendition.display(this.location||void 0),!this.isCurrentLoad(generation,fetchTarget.view)){this.destroyBook(book),candidateBook=void 0;return}rendition.on("relocated",loc=>{if(!this.isCurrentBookRendition(generation,fetchTarget.view,book,rendition))return;const start=inheritedDataValue(loc,"start"),cfi=inheritedDataValue(start,"cfi"),href=inheritedDataValue(start,"href");typeof cfi!="string"||cfi.trim()===""||!cfi||cfi===this.location||(this.relocatedLocation=cfi,this.location=cfi,this.emit("lr-location-change",{cfi,href:typeof href=="string"?href:""}))}),rendition.on("selected",(cfiRange,contents)=>{if(!(!this.isCurrentBookRendition(generation,fetchTarget.view,book,rendition)||typeof cfiRange!="string"))try{const contentsWindow=inheritedDataValue(contents,"window"),selection=savedCallable(contentsWindow,"getSelection")?.(),range=this.selectedRange(selection);if(!range)return;const text=boundedSelectionText(range);if(!text)return;const rects=this.translateSelectionRects(boundedSelectionRects(range),contentsWindow);this.emit("lr-text-select",{text,anchor:{kind:"cfi",cfi:cfiRange},rects})}catch{}}),this.book=book,this.rendition=rendition,candidateBook=void 0,this.ebookState={kind:"ready"},this.repaintAnnotations()}catch(error){if(this.destroyBook(candidateBook),isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.failCurrentLoad(error)}}selectedRange(selection){const prototype=this.ownerDocument.defaultView?.Selection.prototype;if(prototype)try{const count2=Object.getOwnPropertyDescriptor(prototype,"rangeCount")?.get?.call(selection);if(typeof count2=="number")return count2>0?prototype.getRangeAt.call(selection,0):null}catch{}const count=inheritedDataValue(selection,"rangeCount"),getRangeAt=savedCallable(selection,"getRangeAt");return typeof count=="number"&&count>0&&getRangeAt?getRangeAt(0):null}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.failCurrentLoad(error,message)}reportRenditionFailure(error,rendition,generation,ownerView=this.ownerDocument.defaultView){!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==ownerView||rendition!==this.rendition||this.failCurrentLoad(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,ownerView=this.ownerDocument.defaultView;if(ownerView)try{Promise.resolve(rendition.display(location)).catch(error=>{this.reportRenditionFailure(error,rendition,generation,ownerView)})}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}runRenditionNavigation(action){const rendition=this.rendition;if(!rendition)return;const generation=this.generation,ownerView=this.ownerDocument.defaultView;if(ownerView)try{const task=action==="previous"?rendition.prev():rendition.next();Promise.resolve(task).catch(error=>{this.reportRenditionFailure(error,rendition,generation,ownerView)})}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}async getToc(){const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!book||!ownerView)return[];try{await book.ready}catch{return[]}return!this.isCurrentLoad(generation,ownerView)||this.book!==book?[]:[...projectToc(inheritedDataValue(book.getNavigation(),"toc"))]}async scrollToAnchor(target){const operation=++this.anchorOperationGeneration,generation=this.generation,ownerView=this.ownerDocument.defaultView,book=this.book,rendition=this.rendition;try{return await Object.getPrototypeOf(LyraEbookViewer.prototype).performScrollToAnchor.call(this,target)}catch(error){return operation!==this.anchorOperationGeneration||!ownerView||!this.isCurrentLoad(generation,ownerView)||this.book!==book||this.rendition!==rendition||(rendition&&this.reportRenditionFailure(error,rendition,generation,ownerView),this.emit("lr-anchor-result",{found:!1})),!1}}async applyAnchor(anchor){const rendition=this.rendition,operation=this.anchorOperationGeneration,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!rendition||!ownerView)return!1;if(anchor.kind==="cfi")return operation!==this.anchorOperationGeneration||!this.isCurrentLoad(generation,ownerView)||rendition!==this.rendition?!1:(await rendition.display(anchor.cfi),operation===this.anchorOperationGeneration&&this.isCurrentLoad(generation,ownerView)&&rendition===this.rendition);if(anchor.kind==="text-quote"){const cfi=await this.findTextQuoteCfi(anchor);return!cfi||operation!==this.anchorOperationGeneration||!this.isCurrentLoad(generation,ownerView)||rendition!==this.rendition?!1:(await rendition.display(cfi),operation===this.anchorOperationGeneration&&this.isCurrentLoad(generation,ownerView)&&rendition===this.rendition)}return!1}async findTextQuoteCfi(anchor){const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView,quote=anchor.quote.trim(),boundedQuery=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!book||!ownerView||!boundedQuery.accepted||!boundedQuery.needle)return null;const fullContextScore=(anchor.prefix?.trim()?1:0)+(anchor.suffix?.trim()?1:0);let bestMatch=null,bestScore=-1;const work=new ViewerSearchWorkBudget,spine=projectSpineItems(book);for(const item of spine.items){if(!work.consume(""))return bestMatch;let loaded=!1;try{if(await awaitPeerResult(item.load(book.load)),loaded=!0,!this.isCurrentLoad(generation,ownerView)||this.book!==book)return null;const{value:rawResults}=await awaitPeerResult(item.find(quote)),results=projectFindResults(rawResults,work);if(!this.isCurrentLoad(generation,ownerView)||this.book!==book)return null;for(const result of results.matches){if(!work.consume(""))return bestMatch;const score=fullContextScore===0?0:quoteContextScore(result.excerpt,quote,anchor.prefix,anchor.suffix);if(score===fullContextScore)return result.cfi;score>bestScore&&(bestMatch=result.cfi,bestScore=score)}}catch{continue}finally{if(loaded)try{item.unload()}catch{}}}return bestMatch}repaintHighlights(){const rendition=this.rendition;if(!rendition)return;const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView,work=new ViewerSearchWorkBudget;for(const cfi of this.paintedHighlightCfis){if(!work.consume(cfi))break;rendition.annotations.remove(cfi,"highlight")}this.paintedHighlightCfis=[];let painted=0;const fillCache=new Map,resolveFill=pair=>{let value=fillCache.get(pair.token);return value===void 0&&(value=this.resolveHighlightFill(pair).fill,fillCache.set(pair.token,value)),value};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={fill:resolveFill(TONE_FILL_TOKEN[tone])};if(active){const forcedColors=this.ownerDocument.defaultView?.matchMedia?.("(forced-colors: active)").matches??!1;styles2.stroke=forcedColors?"CanvasText":resolveFill(ACTIVE_HIGHLIGHT_STROKE_TOKEN),styles2["stroke-width"]="3",styles2["stroke-dasharray"]="2 1"}rendition.annotations.highlight(cfi,{id:highlight.id},()=>{!book||!ownerView||!this.isCurrentBookRendition(generation,ownerView,book,rendition)||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,ownerView=this.ownerDocument.defaultView,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||!ownerView||!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,spine=projectSpineItems(book);spine.exact||(matchCountExact=!1);for(const item of spine.items){if(generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected)return this.searchMatches.length;if(!work.consume("")){matchCountExact=!1;break}let loaded=!1;try{if(await awaitPeerResult(item.load(book.load)),loaded=!0,generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book)return this.searchMatches.length;const{value:rawResults}=await awaitPeerResult(item.find(query.trim())),results=projectFindResults(rawResults,work);if(generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book)return this.searchMatches.length;results.exact||(matchCountExact=!1);for(const r of results.matches){if(!work.consume("")){matchCountExact=!1,matchCeilingExceeded=!0;break}if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1,matchCeilingExceeded=!0;break}matches.push(r)}}catch{matchCountExact=!1;continue}finally{if(loaded)try{item.unload()}catch{matchCountExact=!1}}if(matchCeilingExceeded)break}return generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book?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,ownerView),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(){const cfi=this.searchAnnotationCfi;this.searchAnnotationCfi=void 0;const rendition=this.rendition,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!(!cfi||!rendition||!ownerView))try{rendition.annotations.remove(cfi,"highlight")}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}async showSearchMatch(index,generation=this.searchGeneration,ownerView=this.ownerDocument.defaultView){const match=this.searchMatches[index],rendition=this.rendition;if(!match||!rendition||generation!==this.searchGeneration||!ownerView||!this.isConnected||this.ownerDocument.defaultView!==ownerView)return!1;this.clearSearchAnnotation();try{await rendition.display(match.cfi)}catch(error){return generation===this.searchGeneration&&rendition===this.rendition&&this.ownerDocument.defaultView===ownerView&&this.reportRenditionFailure(error,rendition,this.generation,ownerView),!1}if(generation!==this.searchGeneration||rendition!==this.rendition||this.searchMatches[index]!==match||!this.isConnected||this.ownerDocument.defaultView!==ownerView)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,ownerView),!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})}resolveHighlightFill({token,fallback}){return{fill:(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(token).trim()??"")||fallback}}renderStatus(){return this.ebookState.kind==="loading"?renderViewerLoading(this.localize("loadingDocument")):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 maxHeight=sanitizeCssLength(this.maxHeight),disabled=this.ebookState.kind!=="ready";return html`
1
+ import{__decorate}from"tslib";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{DEFAULT_CANVAS_COLOR}from"../../../internal/canvas-color.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,isObjectValue,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{textQuoteContextScore}from"../document-viewer/anchors.js";import{getEpubJs}from"./ebook-loader.js";import{assertEpubArchiveWithinLimits}from"./epub-resource-guard.js";import{guardEpubUnloadListener}from"./epub-unload-guard.js";import{styles}from"./ebook-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{renderViewerPagerButton,viewerPagerStyles}from"../viewer-pager.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_documentPreviewEmpty}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_ebookViewerLoadError,LYRA_DEFAULT_ebookViewerMissingLibrary,LYRA_DEFAULT_ebookViewerNextChapter,LYRA_DEFAULT_ebookViewerPreviousChapter,LYRA_DEFAULT_ebookViewerRegionLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_TOC_ITEMS=1e4,MAX_TOC_DEPTH=100,MAX_SEARCH_MATCHES=1e4,MAX_SEARCH_SPINE_ITEMS=1e3,MAX_FIND_RESULTS=1e4,MAX_PAINTED_HIGHLIGHTS=100,MAX_PEER_PROTOTYPES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function inheritedDataDescriptor(value,key){let current=value;for(let depth=0;current&&depth<MAX_PEER_PROTOTYPES;depth+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(current,key)}catch{return}if(descriptor)return"value"in descriptor?descriptor:void 0;try{current=Object.getPrototypeOf(current)}catch{return}}}function inheritedDataValue(value,key){return isObjectValue(value)?inheritedDataDescriptor(value,key)?.value:void 0}function savedCallable(value,key){if(!isObjectValue(value))return;const candidate=inheritedDataDescriptor(value,key)?.value;if(typeof candidate=="function")return(...args)=>Reflect.apply(candidate,value,args)}function savedThenable(value){const then=savedCallable(value,"then");if(then)return new Promise((resolve,reject)=>{try{then(()=>resolve(),reject)}catch(error){reject(error)}})}function taskFrom(call,...args){try{return savedThenable(call(...args))??Promise.resolve()}catch(error){return Promise.reject(error)}}function awaitPeerResult(value){const then=savedCallable(value,"then"),wrap=resolved=>Object.freeze({value:resolved});return then?new Promise((resolve,reject)=>{try{then(resolved=>resolve(wrap(resolved)),reject)}catch(error){reject(error)}}):Promise.resolve(wrap(value))}function quoteContextScore(excerpt,quote,prefix,suffix){const text=excerpt.replace(/\s+/g," ").toLowerCase(),needle=quote.replace(/\s+/g," ").toLowerCase();let best=0;for(let at=text.indexOf(needle);at>=0;at=text.indexOf(needle,at+1))best=Math.max(best,textQuoteContextScore(text,at,at+needle.length,prefix,suffix));return best}const EPUB_CHAPTER_CONTENT_SECURITY_POLICY="default-src 'none'; img-src blob: data:; media-src blob: data:; font-src blob: data:; style-src blob: 'unsafe-inline'";function silenceChapterNetwork(chapter){const root=chapter.documentElement;if(!root)return;for(const node of[...chapter.childNodes])node.nodeType===Node.PROCESSING_INSTRUCTION_NODE&&chapter.removeChild(node);for(const element of[...chapter.querySelectorAll("link, meta")]){const rel=` ${(element.getAttribute("rel")??"").toLowerCase()} `;(/ (?:dns-prefetch|preconnect) /.test(rel)||(element.getAttribute("http-equiv")??"").trim().toLowerCase()==="refresh")&&element.remove()}const namespace=root.namespaceURI??"http://www.w3.org/1999/xhtml";let head=chapter.querySelector("head");head||(head=chapter.createElementNS(namespace,"head"),root.insertBefore(head,root.firstChild));const policy=chapter.createElementNS(namespace,"meta");policy.setAttribute("http-equiv","Content-Security-Policy"),policy.setAttribute("content",EPUB_CHAPTER_CONTENT_SECURITY_POLICY),head.insertBefore(policy,head.firstChild)}function registerNetworkSilentChapters(book){const contentHooks=inheritedDataValue(inheritedDataValue(book.spine,"hooks"),"content");savedCallable(contentHooks,"register")?.(silenceChapterNetwork)}function normalizeBook(value){if(!isObjectValue(value))return;const ready=savedThenable(inheritedDataValue(value,"ready")),renderTo=savedCallable(value,"renderTo"),destroy=savedCallable(value,"destroy");if(!ready||!renderTo||!destroy)return;let navigationCaptured=!1,navigation;const getNavigation=()=>(navigationCaptured||(navigationCaptured=!0,navigation=inheritedDataValue(value,"navigation")),navigation),spine=inheritedDataValue(value,"spine"),load=savedCallable(value,"load");return Object.freeze({ready,...spine===void 0?{}:{spine},...load===void 0?{}:{load},getNavigation,renderTo:(element,options)=>renderTo(element,options),destroy:()=>{destroy()}})}function normalizeRendition(value){if(!isObjectValue(value))return;const display=savedCallable(value,"display"),prev=savedCallable(value,"prev"),next=savedCallable(value,"next"),on=savedCallable(value,"on"),annotationsValue=inheritedDataValue(value,"annotations"),highlight=savedCallable(annotationsValue,"highlight"),remove=savedCallable(annotationsValue,"remove");if(!(!display||!prev||!next||!on||!highlight||!remove))return Object.freeze({display:target=>taskFrom(display,target),prev:()=>taskFrom(prev),next:()=>taskFrom(next),on:(type,callback)=>{on(type,callback)},annotations:Object.freeze({highlight:(cfi,data,callback,className,styles2)=>highlight(cfi,data,callback,className,styles2),remove:(cfi,type)=>{remove(cfi,type)}})})}function normalizeSpineItem(value){const load=savedCallable(value,"load"),find=savedCallable(value,"find"),unload=savedCallable(value,"unload");if(!(!load||!find||!unload))return Object.freeze({load:request=>load(request),find:query=>find(query),unload:()=>{unload()}})}function projectSpineItems(book){const spineItems=inheritedDataValue(book.spine,"spineItems");if(!isArrayValue(spineItems))return Object.freeze({items:Object.freeze([]),exact:spineItems===void 0});const length=getOwnDataDescriptor(spineItems,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze({items:Object.freeze([]),exact:!1});const items=[];let exact=length.value<=MAX_SEARCH_SPINE_ITEMS;const count=Math.min(length.value,MAX_SEARCH_SPINE_ITEMS);for(let index=0;index<count;index+=1){const descriptor=getOwnDataDescriptor(spineItems,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){exact=!1;continue}const item=normalizeSpineItem(descriptor.value);if(!item){exact=!1;continue}items.push(item)}return Object.freeze({items:Object.freeze(items),exact})}function projectFindResults(value,work){if(!isArrayValue(value))return Object.freeze({matches:Object.freeze([]),exact:!1});const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze({matches:Object.freeze([]),exact:!1});const matches=[];let exact=length.value<=MAX_FIND_RESULTS;const count=Math.min(length.value,MAX_FIND_RESULTS);for(let index=0;index<count;index+=1){const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!isObjectValue(descriptor.value)){exact=!1;continue}const cfi=getOwnDataDescriptor(descriptor.value,"cfi"),excerpt=getOwnDataDescriptor(descriptor.value,"excerpt");if(cfi===MISSING_OWN_DATA_DESCRIPTOR||cfi===UNSAFE_OWN_DATA_DESCRIPTOR||typeof cfi.value!="string"){exact=!1;continue}if(!work.canConsume(cfi.value)||!work.consume(cfi.value)||cfi.value.trim()===""){exact=!1;continue}let excerptValue="";excerpt!==MISSING_OWN_DATA_DESCRIPTOR&&(excerpt===UNSAFE_OWN_DATA_DESCRIPTOR||typeof excerpt.value!="string"||!work.canConsume(excerpt.value)||!work.consume(excerpt.value)?exact=!1:excerptValue=excerpt.value),matches.push({cfi:cfi.value,excerpt:excerptValue})}return Object.freeze({matches:Object.freeze(matches),exact})}function pushTocEntries(value,level,budget,stack){if(!isArrayValue(value)||budget.positions>=MAX_TOC_ITEMS)return;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return;const count=Math.min(length.value,MAX_TOC_ITEMS-budget.positions);for(let index=count-1;index>=0;index-=1){budget.positions+=1;const descriptor=getOwnDataDescriptor(value,String(index));descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||stack.push({value:descriptor.value,level})}}function projectToc(value){const budget={positions:0,nodes:0,seen:new WeakSet},stack=[];pushTocEntries(value,1,budget,stack);const items=[];for(;stack.length>0&&budget.nodes<MAX_TOC_ITEMS;){const current=stack.pop();if(!isObjectValue(current.value)||budget.seen.has(current.value))continue;budget.seen.add(current.value),budget.nodes+=1;const href=getOwnDataDescriptor(current.value,"href"),id=getOwnDataDescriptor(current.value,"id"),label=getOwnDataDescriptor(current.value,"label"),children=getOwnDataDescriptor(current.value,"subitems");if(href!==MISSING_OWN_DATA_DESCRIPTOR&&href!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof href.value=="string"){const idValue=id!==MISSING_OWN_DATA_DESCRIPTOR&&id!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof id.value=="string"&&id.value!==""?id.value:href.value,labelValue=label!==MISSING_OWN_DATA_DESCRIPTOR&&label!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof label.value=="string"?label.value.trim():"";items.push({id:idValue,label:labelValue,href:href.value,level:current.level})}current.level<MAX_TOC_DEPTH&&children!==MISSING_OWN_DATA_DESCRIPTOR&&children!==UNSAFE_OWN_DATA_DESCRIPTOR&&pushTocEntries(children.value,current.level+1,budget,stack)}return Object.freeze(items)}const 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:DEFAULT_CANVAS_COLOR};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,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,ebookViewerLoadError:LYRA_DEFAULT_ebookViewerLoadError,ebookViewerMissingLibrary:LYRA_DEFAULT_ebookViewerMissingLibrary,ebookViewerNextChapter:LYRA_DEFAULT_ebookViewerNextChapter,ebookViewerPreviousChapter:LYRA_DEFAULT_ebookViewerPreviousChapter,ebookViewerRegionLabel:LYRA_DEFAULT_ebookViewerRegionLabel,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.styles=[LyraElement.styles,styles,viewerPagerStyles,srOnly,viewerLoadingStyles]}constructor(){super(),this.src="",this.name="",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.failedGeneration=-1,this.searchQuery="",this.lastSearchLocale="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.paintedHighlightCfis=[],this.announcements=new ViewerAnnouncementController(this),this.chapterButtonFocused=!1,this.previous=()=>{this.runRenditionNavigation("previous")},this.next=()=>{this.runRenditionNavigation("next")},new ThemeWatcher(this,()=>this.repaintAnnotations())}updated(changed){if(super.updated(changed),this.chapterButtonFocused&&this.ebookState.kind!=="ready"&&this.shadowRoot?.querySelector('[part="mount"]')?.focus(),this.chapterButtonFocused=!1,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);const active=shadowFocusTarget(this);this.chapterButtonFocused=active?.localName==="button"&&!active.disabled&&active.getAttribute("part")?.endsWith("-button")===!0,changed.has("src")&&(this.pendingSearchResetEvent||=this.hasSearchState(),this.resetSearchState())}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src?.trim()&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.anchorOperationGeneration++,this.announcements.disconnect(),this.teardown(),this.ebookState={kind:"idle"},super.disconnectedCallback()}connectedMoveCallback(){}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}teardown(){const shouldEmitSearchReset=this.hasSearchState();this.destroyBook(this.book),this.book=void 0,this.rendition=void 0,this.resetSearchState(),this.paintedHighlightCfis=[],shouldEmitSearchReset&&this.isConnected&&this.emitSearchChange()}destroyBook(book){try{book?.destroy()}catch{}}isCurrentLoad(generation,ownerView){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView}isCurrentBookRendition(generation,ownerView,book,rendition){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView&&this.book===book&&this.rendition===rendition}failCurrentLoad(error,message=this.localize("ebookViewerLoadError")){this.failedGeneration!==this.generation&&(this.failedGeneration=this.generation,this.ebookState={kind:"error",message},this.emit("lr-render-error",{error}))}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.isCurrentLoad(generation,fetchTarget.view)||(await assertEpubArchiveWithinLimits(data,void 0,void 0,{signal}),!this.isCurrentLoad(generation,fetchTarget.view)))return}catch(error){if(isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.failCurrentLoad(error,this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"ebookViewerLoadError"));return}if(!factory){this.failWithLocalizedMessage(this.localize("ebookViewerMissingLibrary"));return}const mount=this.mountRef.value;if(!mount){this.failWithLocalizedMessage(this.localize("ebookViewerLoadError"));return}let candidateBook;try{const book=normalizeBook(factory(data));if(!book)throw new Error("EPUB peer returned an unusable book.");candidateBook=book,registerNetworkSilentChapters(book);const rawRendition=book.renderTo(mount,{width:"100%",height:"100%"});guardEpubUnloadListener({settings:inheritedDataValue(rawRendition,"settings"),requireManager:savedCallable(rawRendition,"requireManager")});const rendition=normalizeRendition(rawRendition);if(!rendition)throw new Error("EPUB peer returned an unusable rendition.");if(await book.ready,!this.isCurrentLoad(generation,fetchTarget.view)){this.destroyBook(book),candidateBook=void 0;return}if(book.getNavigation(),await rendition.display(this.location||void 0),!this.isCurrentLoad(generation,fetchTarget.view)){this.destroyBook(book),candidateBook=void 0;return}rendition.on("relocated",loc=>{if(!this.isCurrentBookRendition(generation,fetchTarget.view,book,rendition))return;const start=inheritedDataValue(loc,"start"),cfi=inheritedDataValue(start,"cfi"),href=inheritedDataValue(start,"href");typeof cfi!="string"||cfi.trim()===""||!cfi||cfi===this.location||(this.relocatedLocation=cfi,this.location=cfi,this.emit("lr-location-change",{cfi,href:typeof href=="string"?href:""}))}),rendition.on("selected",(cfiRange,contents)=>{if(!(!this.isCurrentBookRendition(generation,fetchTarget.view,book,rendition)||typeof cfiRange!="string"))try{const contentsWindow=inheritedDataValue(contents,"window"),selection=savedCallable(contentsWindow,"getSelection")?.(),range=this.selectedRange(selection);if(!range)return;const text=boundedSelectionText(range);if(!text)return;const rects=this.translateSelectionRects(boundedSelectionRects(range),contentsWindow);this.emit("lr-text-select",{text,anchor:{kind:"cfi",cfi:cfiRange},rects})}catch{}}),this.book=book,this.rendition=rendition,candidateBook=void 0,this.ebookState={kind:"ready"},this.repaintAnnotations()}catch(error){if(this.destroyBook(candidateBook),isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.failCurrentLoad(error)}}selectedRange(selection){const prototype=this.ownerDocument.defaultView?.Selection.prototype;if(prototype)try{const count2=Object.getOwnPropertyDescriptor(prototype,"rangeCount")?.get?.call(selection);if(typeof count2=="number")return count2>0?prototype.getRangeAt.call(selection,0):null}catch{}const count=inheritedDataValue(selection,"rangeCount"),getRangeAt=savedCallable(selection,"getRangeAt");return typeof count=="number"&&count>0&&getRangeAt?getRangeAt(0):null}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.failCurrentLoad(error,message)}reportRenditionFailure(error,rendition,generation,ownerView=this.ownerDocument.defaultView){!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==ownerView||rendition!==this.rendition||this.failCurrentLoad(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,ownerView=this.ownerDocument.defaultView;if(ownerView)try{Promise.resolve(rendition.display(location)).catch(error=>{this.reportRenditionFailure(error,rendition,generation,ownerView)})}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}runRenditionNavigation(action){const rendition=this.rendition;if(!rendition)return;const generation=this.generation,ownerView=this.ownerDocument.defaultView;if(ownerView)try{const task=action==="previous"?rendition.prev():rendition.next();Promise.resolve(task).catch(error=>{this.reportRenditionFailure(error,rendition,generation,ownerView)})}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}async getToc(){const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!book||!ownerView)return[];try{await book.ready}catch{return[]}return!this.isCurrentLoad(generation,ownerView)||this.book!==book?[]:[...projectToc(inheritedDataValue(book.getNavigation(),"toc"))]}async scrollToAnchor(target){const operation=++this.anchorOperationGeneration,generation=this.generation,ownerView=this.ownerDocument.defaultView,book=this.book,rendition=this.rendition;try{return await Object.getPrototypeOf(LyraEbookViewer.prototype).performScrollToAnchor.call(this,target)}catch(error){return operation!==this.anchorOperationGeneration||!ownerView||!this.isCurrentLoad(generation,ownerView)||this.book!==book||this.rendition!==rendition||(rendition&&this.reportRenditionFailure(error,rendition,generation,ownerView),this.emit("lr-anchor-result",{found:!1})),!1}}async applyAnchor(anchor){const rendition=this.rendition,operation=this.anchorOperationGeneration,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!rendition||!ownerView)return!1;if(anchor.kind==="cfi")return operation!==this.anchorOperationGeneration||!this.isCurrentLoad(generation,ownerView)||rendition!==this.rendition?!1:(await rendition.display(anchor.cfi),operation===this.anchorOperationGeneration&&this.isCurrentLoad(generation,ownerView)&&rendition===this.rendition);if(anchor.kind==="text-quote"){const cfi=await this.findTextQuoteCfi(anchor);return!cfi||operation!==this.anchorOperationGeneration||!this.isCurrentLoad(generation,ownerView)||rendition!==this.rendition?!1:(await rendition.display(cfi),operation===this.anchorOperationGeneration&&this.isCurrentLoad(generation,ownerView)&&rendition===this.rendition)}return!1}async findTextQuoteCfi(anchor){const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView,quote=anchor.quote.trim(),boundedQuery=boundedViewerSearchQuery(quote,this.effectiveLocale);if(!book||!ownerView||!boundedQuery.accepted||!boundedQuery.needle)return null;const fullContextScore=(anchor.prefix?.trim()?1:0)+(anchor.suffix?.trim()?1:0);let bestMatch=null,bestScore=-1;const work=new ViewerSearchWorkBudget,spine=projectSpineItems(book);for(const item of spine.items){if(!work.consume(""))return bestMatch;let loaded=!1;try{if(await awaitPeerResult(item.load(book.load)),loaded=!0,!this.isCurrentLoad(generation,ownerView)||this.book!==book)return null;const{value:rawResults}=await awaitPeerResult(item.find(quote)),results=projectFindResults(rawResults,work);if(!this.isCurrentLoad(generation,ownerView)||this.book!==book)return null;for(const result of results.matches){if(!work.consume(""))return bestMatch;const score=fullContextScore===0?0:quoteContextScore(result.excerpt,quote,anchor.prefix,anchor.suffix);if(score===fullContextScore)return result.cfi;score>bestScore&&(bestMatch=result.cfi,bestScore=score)}}catch{continue}finally{if(loaded)try{item.unload()}catch{}}}return bestMatch}repaintHighlights(){const rendition=this.rendition;if(!rendition)return;const book=this.book,generation=this.generation,ownerView=this.ownerDocument.defaultView,work=new ViewerSearchWorkBudget;for(const cfi of this.paintedHighlightCfis){if(!work.consume(cfi))break;rendition.annotations.remove(cfi,"highlight")}this.paintedHighlightCfis=[];let painted=0;const fillCache=new Map,resolveFill=pair=>{let value=fillCache.get(pair.token);return value===void 0&&(value=this.resolveHighlightFill(pair).fill,fillCache.set(pair.token,value)),value};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={fill:resolveFill(TONE_FILL_TOKEN[tone])};if(active){const forcedColors=this.ownerDocument.defaultView?.matchMedia?.("(forced-colors: active)").matches??!1;styles2.stroke=forcedColors?"CanvasText":resolveFill(ACTIVE_HIGHLIGHT_STROKE_TOKEN),styles2["stroke-width"]="3",styles2["stroke-dasharray"]="2 1"}rendition.annotations.highlight(cfi,{id:highlight.id},()=>{!book||!ownerView||!this.isCurrentBookRendition(generation,ownerView,book,rendition)||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,ownerView=this.ownerDocument.defaultView,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||!ownerView||!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,spine=projectSpineItems(book);spine.exact||(matchCountExact=!1);for(const item of spine.items){if(generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected)return this.searchMatches.length;if(!work.consume("")){matchCountExact=!1;break}let loaded=!1;try{if(await awaitPeerResult(item.load(book.load)),loaded=!0,generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book)return this.searchMatches.length;const{value:rawResults}=await awaitPeerResult(item.find(query.trim())),results=projectFindResults(rawResults,work);if(generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book)return this.searchMatches.length;results.exact||(matchCountExact=!1);for(const r of results.matches){if(!work.consume("")){matchCountExact=!1,matchCeilingExceeded=!0;break}if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1,matchCeilingExceeded=!0;break}matches.push(r)}}catch{matchCountExact=!1;continue}finally{if(loaded)try{item.unload()}catch{matchCountExact=!1}}if(matchCeilingExceeded)break}return generation!==this.searchGeneration||this.ownerDocument.defaultView!==ownerView||!this.isConnected||this.book!==book?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,ownerView),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(){const cfi=this.searchAnnotationCfi;this.searchAnnotationCfi=void 0;const rendition=this.rendition,generation=this.generation,ownerView=this.ownerDocument.defaultView;if(!(!cfi||!rendition||!ownerView))try{rendition.annotations.remove(cfi,"highlight")}catch(error){this.reportRenditionFailure(error,rendition,generation,ownerView)}}async showSearchMatch(index,generation=this.searchGeneration,ownerView=this.ownerDocument.defaultView){const match=this.searchMatches[index],rendition=this.rendition;if(!match||!rendition||generation!==this.searchGeneration||!ownerView||!this.isConnected||this.ownerDocument.defaultView!==ownerView)return!1;this.clearSearchAnnotation();try{await rendition.display(match.cfi)}catch(error){return generation===this.searchGeneration&&rendition===this.rendition&&this.ownerDocument.defaultView===ownerView&&this.reportRenditionFailure(error,rendition,this.generation,ownerView),!1}if(generation!==this.searchGeneration||rendition!==this.rendition||this.searchMatches[index]!==match||!this.isConnected||this.ownerDocument.defaultView!==ownerView)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,ownerView),!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})}resolveHighlightFill({token,fallback}){return{fill:(this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue(token).trim()??"")||fallback}}renderStatus(){return this.ebookState.kind==="loading"?renderViewerLoading(this.localize("loadingDocument")):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 maxHeight=sanitizeCssLength(this.maxHeight),disabled=this.ebookState.kind!=="ready";return html`
2
2
  <div
3
3
  part="base"
4
4
  aria-busy=${this.ebookState.kind==="loading"?"true":"false"}
@@ -1 +1 @@
1
- import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{literalSetConverter}from"../../../internal/converters.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{loadHtmlSanitizer}from"../html-viewer/dompurify-loader.js";import{acquireSanitizedIncludeResource,IncludeResourceError,invalidateIncludeResource,MAX_INCLUDE_BYTES}from"./include-resource.js";import{styles}from"./include.styles.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound}from"../../../internal/default-strings/shared.generated.js";const INCLUDE_MODE=literalSetConverter(["cors","no-cors","same-origin"],"same-origin");class LyraIncludeBase extends LyraElement{}const ID_REFERENCE_ATTRIBUTES=["aria-activedescendant","aria-controls","aria-describedby","aria-details","aria-errormessage","aria-flowto","aria-labelledby","aria-owns","for","form","headers","list"];let nextClonePrefix=0;function decodedFragment(hash){const encoded=hash.startsWith("#")?hash.slice(1):hash;try{return decodeURIComponent(encoded)}catch{return encoded}}function isTemplateElement(element){return element.localName==="template"&&"content"in element}function allElements(root){const elements=[...root.querySelectorAll("*")];for(const template of elements.filter(isTemplateElement))elements.push(...allElements(template.content));return elements}function elementWithId(root,id){for(const element of allElements(root))if(element.id===id)return element;return null}class LyraInclude extends TextViewerTarget(LyraIncludeBase){constructor(){super(...arguments),this.src="",this._mode="same-origin",this.withoutCache=!1,this.generation=0,this.clonePrefix=`include-fragment-${++nextClonePrefix}`,this.detached=new DeferredTeardown(()=>{this.generation++,this.releaseResourceLease(),this.setAttribute("aria-busy","false")})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound}}static{this.styles=[LyraElement.styles,styles,srOnly]}get mode(){return this._mode}set mode(next){const normalized=INCLUDE_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this}updated(changed){super.updated(changed),(changed.has("src")||changed.has("mode")||changed.has("withoutCache"))&&this.scheduleAfterUpdate(()=>{this.load()})}connectedCallback(){super.connectedCallback(),!this.detached.cancel()&&(this.setAttribute("aria-busy","false"),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush()}async reload(){const source=this.resolveSource();source?.kind==="remote"&&invalidateIncludeResource(source.url,this.effectiveMode,source.owner),await this.load()}get effectiveMode(){return this.mode}resolveSource(){const value=this.src.trim();if(!value)return null;if(value.startsWith("#"))return{kind:"same-page",fragment:decodedFragment(value)};const target=resolveOwnerFetchTarget(this,value);if(!target)return null;try{const parsed=new target.view.URL(target.url),fragment=decodedFragment(parsed.hash);return parsed.hash="",{kind:"remote",url:parsed.href,fragment,owner:target.view}}catch{return null}}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async sanitizeSamePage(source,generation){const markup=source.innerHTML;if(new TextEncoder().encode(markup).byteLength>MAX_INCLUDE_BYTES)return this.fail(0,"resource-too-large"),null;const sanitizer=await loadHtmlSanitizer();return!this.isConnected||generation!==this.generation?null:sanitizer?sanitizePassiveMarkup(sanitizer,markup,this.ownerDocument,"transclusion"):(this.fail(0,"missing-sanitizer"),null)}fragmentFromSanitized(markup,fragmentId){const template=this.ownerDocument.createElement("template");template.innerHTML=markup;const output=this.ownerDocument.createDocumentFragment();if(fragmentId){const target=elementWithId(template.content,fragmentId);if(!target)return null;const children=isTemplateElement(target)?target.content.childNodes:target.childNodes;for(const child of children)output.append(child.cloneNode(!0))}else output.append(template.content.cloneNode(!0));return this.rebaseFragmentIds(output),output}rebaseFragmentIds(fragment){const idMap=new Map;let index=0;const elements=allElements(fragment);for(const element of elements){if(element.removeAttribute("name"),!element.id)continue;const original=element.id,next=`${this.clonePrefix}-${++index}`;idMap.has(original)||idMap.set(original,next),element.id=next}for(const element of elements){for(const attribute of ID_REFERENCE_ATTRIBUTES){if(!element.hasAttribute(attribute))continue;const replacements=element.getAttribute(attribute).split(/\s+/).filter(Boolean).map(token=>idMap.get(token)).filter(token=>!!token);replacements.length>0?element.setAttribute(attribute,replacements.join(" ")):element.removeAttribute(attribute)}for(const attribute of["href","xlink:href"]){const value=element.getAttribute(attribute);if(!value)continue;if(!value.startsWith("#")){element.removeAttribute(attribute);continue}const replacement=idMap.get(decodedFragment(value));replacement?element.setAttribute(attribute,`#${replacement}`):element.removeAttribute(attribute)}for(const attribute of element.getAttributeNames()){const value=element.getAttribute(attribute)??"";if(!/url\s*\(/i.test(value))continue;const match=/^\s*url\(\s*(['"]?)#([A-Za-z_][\w:.-]*)\1\s*\)\s*$/i.exec(value),replacement=match?idMap.get(match[2]):void 0;replacement?element.setAttribute(attribute,`url(#${replacement})`):element.removeAttribute(attribute)}}}async load(){const generation=++this.generation;if(this.releaseResourceLease(),this.setAttribute("aria-busy","false"),!this.src.trim()||!this.isConnected)return;const source=this.resolveSource();if(!source){this.emitError({status:0,reason:"blocked-url"});return}this.setAttribute("aria-busy","true");let lease;try{let markup,fragmentId=source.fragment;if(source.kind==="same-page"){const target=this.ownerDocument.getElementById(source.fragment);if(!target){this.fail(0,"missing-fragment");return}markup=await this.sanitizeSamePage(target,generation),fragmentId=""}else lease=acquireSanitizedIncludeResource(source.url,this.effectiveMode,!this.withoutCache,source.owner),this.resourceLease=lease,markup=await lease.promise;if(markup==null||!this.isConnected||generation!==this.generation||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;const fragment=this.fragmentFromSanitized(markup,fragmentId);if(!fragment){this.fail(0,"missing-fragment");return}if(generation!==this.generation||!this.isConnected||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;this.replaceChildren(fragment),this.requestUpdate(),this.setAttribute("aria-busy","false"),this.emit("lr-load",{src:this.src})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;error instanceof IncludeResourceError?this.fail(error.status,error.reason,error.cause??error):this.fail(0,"network",error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}fail(status,reason,error){this.setAttribute("aria-busy","false"),this.emitError({status,reason,error})}emitError(detail){this.emit("lr-include-error",detail),this.emit("lr-error",detail)}render(){return html`<span part="base"><slot></slot></span>${this.renderAnchorLiveRegion()}`}}__decorate([property({reflect:!0})],LyraInclude.prototype,"src",void 0),__decorate([property({reflect:!0,converter:INCLUDE_MODE})],LyraInclude.prototype,"mode",null),__decorate([property({type:Boolean,attribute:"without-cache"})],LyraInclude.prototype,"withoutCache",void 0);export{LyraInclude};
1
+ import{__decorate}from"tslib";import{html}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{literalSetConverter}from"../../../internal/converters.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{loadHtmlSanitizer}from"../html-viewer/dompurify-loader.js";import{acquireSanitizedIncludeResource,IncludeResourceError,invalidateIncludeResource,MAX_INCLUDE_BYTES}from"./include-resource.js";import{styles}from"./include.styles.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{DeferredTeardown}from"../../../internal/deferred-teardown.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound}from"../../../internal/default-strings/shared.generated.js";const INCLUDE_MODE=literalSetConverter(["cors","no-cors","same-origin"],"same-origin");class LyraIncludeBase extends LyraElement{}const ID_REFERENCE_ATTRIBUTES=["aria-activedescendant","aria-controls","aria-describedby","aria-details","aria-errormessage","aria-flowto","aria-labelledby","aria-owns","for","form","headers","list"];let nextClonePrefix=0;function decodedFragment(hash){const encoded=hash.startsWith("#")?hash.slice(1):hash;try{return decodeURIComponent(encoded)}catch{return encoded}}function isTemplateElement(element){return element.localName==="template"&&"content"in element}function allElements(root){const elements=[...root.querySelectorAll("*")];for(const template of elements.filter(isTemplateElement))elements.push(...allElements(template.content));return elements}function elementWithId(root,id){for(const element of allElements(root))if(element.id===id)return element;return null}class LyraInclude extends TextViewerTarget(LyraIncludeBase){constructor(){super(...arguments),this.src="",this._mode="same-origin",this.withoutCache=!1,this.generation=0,this.clonePrefix=`include-fragment-${++nextClonePrefix}`,this.detached=new DeferredTeardown(()=>{this.generation++,this.releaseResourceLease(),this.setAttribute("aria-busy","false")})}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound}}static{this.styles=[LyraElement.styles,styles,srOnly]}get mode(){return this._mode}set mode(next){const normalized=INCLUDE_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}async search(query){return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this}updated(changed){super.updated(changed),(changed.has("src")||changed.has("mode")||changed.has("withoutCache"))&&this.scheduleAfterUpdate(()=>{this.load()})}connectedCallback(){super.connectedCallback(),!this.detached.cancel()&&(this.setAttribute("aria-busy","false"),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){super.disconnectedCallback(),this.detached.schedule()}adoptedCallback(){super.adoptedCallback(),this.detached.flush()}async reload(){const source=this.resolveSource();source?.kind==="remote"&&invalidateIncludeResource(source.url,this.effectiveMode,source.owner),await this.load()}get effectiveMode(){return this.mode}resolveSource(){const value=this.src.trim();if(!value)return null;if(value.startsWith("#"))return{kind:"same-page",fragment:decodedFragment(value)};const target=resolveOwnerFetchTarget(this,value);if(!target)return null;try{const parsed=new target.view.URL(target.url),fragment=decodedFragment(parsed.hash);return parsed.hash="",{kind:"remote",url:parsed.href,fragment,owner:target.view}}catch{return null}}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async sanitizeSamePage(source,generation){const markup=source.innerHTML;if(new TextEncoder().encode(markup).byteLength>MAX_INCLUDE_BYTES)return this.fail(0,"resource-too-large"),null;const sanitizer=await loadHtmlSanitizer();return!this.isConnected||generation!==this.generation?null:sanitizer?sanitizePassiveMarkup(sanitizer,markup,this.ownerDocument,"transclusion"):(this.fail(0,"missing-sanitizer"),null)}fragmentFromSanitized(markup,fragmentId){const template=this.ownerDocument.createElement("template");template.innerHTML=markup;const output=this.ownerDocument.createDocumentFragment();if(fragmentId){const target=elementWithId(template.content,fragmentId);if(!target)return null;const children=isTemplateElement(target)?target.content.childNodes:target.childNodes;for(const child of children)output.append(child.cloneNode(!0))}else output.append(template.content.cloneNode(!0));return this.rebaseFragmentIds(output),output}rebaseFragmentIds(fragment){const idMap=new Map;let index=0;const elements=allElements(fragment);for(const element of elements){if(element.removeAttribute("name"),!element.id)continue;const original=element.id,next=`${this.clonePrefix}-${++index}`;idMap.has(original)||idMap.set(original,next),element.id=next}for(const element of elements){for(const attribute of ID_REFERENCE_ATTRIBUTES){if(!element.hasAttribute(attribute))continue;const replacements=element.getAttribute(attribute).split(/\s+/).filter(Boolean).map(token=>idMap.get(token)).filter(token=>!!token);replacements.length>0?element.setAttribute(attribute,replacements.join(" ")):element.removeAttribute(attribute)}for(const attribute of["href","xlink:href"]){const value=element.getAttribute(attribute);if(!value)continue;if(!value.startsWith("#")){element.removeAttribute(attribute);continue}const replacement=idMap.get(decodedFragment(value));replacement?element.setAttribute(attribute,`#${replacement}`):element.removeAttribute(attribute)}for(const attribute of element.getAttributeNames()){const value=element.getAttribute(attribute)??"";if(!/url\s*\(/i.test(value))continue;const match=/^\s*url\(\s*(['"]?)#([A-Za-z_][\w:.-]*)\1\s*\)\s*$/i.exec(value),replacement=match?idMap.get(match[2]):void 0;replacement?element.setAttribute(attribute,`url(#${replacement})`):element.removeAttribute(attribute)}}}async load(){const generation=++this.generation;if(this.releaseResourceLease(),this.setAttribute("aria-busy","false"),!this.src?.trim()||!this.isConnected)return;const source=this.resolveSource();if(!source){this.emitError({status:0,reason:"blocked-url"});return}this.setAttribute("aria-busy","true");let lease;try{let markup,fragmentId=source.fragment;if(source.kind==="same-page"){const target=this.ownerDocument.getElementById(source.fragment);if(!target){this.fail(0,"missing-fragment");return}markup=await this.sanitizeSamePage(target,generation),fragmentId=""}else lease=acquireSanitizedIncludeResource(source.url,this.effectiveMode,!this.withoutCache,source.owner),this.resourceLease=lease,markup=await lease.promise;if(markup==null||!this.isConnected||generation!==this.generation||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;const fragment=this.fragmentFromSanitized(markup,fragmentId);if(!fragment){this.fail(0,"missing-fragment");return}if(generation!==this.generation||!this.isConnected||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;this.replaceChildren(fragment),this.requestUpdate(),this.setAttribute("aria-busy","false"),this.emit("lr-load",{src:this.src})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||source.kind==="remote"&&this.ownerDocument.defaultView!==source.owner)return;error instanceof IncludeResourceError?this.fail(error.status,error.reason,error.cause??error):this.fail(0,"network",error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}fail(status,reason,error){this.setAttribute("aria-busy","false"),this.emitError({status,reason,error})}emitError(detail){this.emit("lr-include-error",detail),this.emit("lr-error",detail)}render(){return html`<span part="base"><slot></slot></span>${this.renderAnchorLiveRegion()}`}}__decorate([property({reflect:!0})],LyraInclude.prototype,"src",void 0),__decorate([property({reflect:!0,converter:INCLUDE_MODE})],LyraInclude.prototype,"mode",null),__decorate([property({type:Boolean,attribute:"without-cache"})],LyraInclude.prototype,"withoutCache",void 0);export{LyraInclude};
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ifDefined}from"lit/directives/if-defined.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{isAbortError,isResourceLimitError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{engine3dFailureReason}from"../../../internal/engine-3d.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{modelEngineEnvironment,modelEngineLoader,supportsAsyncModelData}from"./model-viewer-loader.js";import{MODEL_SOURCE_MAX_BYTES,DEFAULT_MODEL_CAMERA,readModelSource,resolveModelFormat,snapshotModelCamera}from"./model-viewer-source.js";import{styles}from"./model-viewer.styles.js";import{LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_download,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_retry,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_modelViewerAlternative,LYRA_DEFAULT_modelViewerEmpty,LYRA_DEFAULT_modelViewerFit,LYRA_DEFAULT_modelViewerInstructions,LYRA_DEFAULT_modelViewerInvalid,LYRA_DEFAULT_modelViewerLabel,LYRA_DEFAULT_modelViewerProgress,LYRA_DEFAULT_modelViewerReady,LYRA_DEFAULT_modelViewerRotateDown,LYRA_DEFAULT_modelViewerRotateLeft,LYRA_DEFAULT_modelViewerRotateRight,LYRA_DEFAULT_modelViewerRotateUp,LYRA_DEFAULT_modelViewerUnsupportedFormat}from"../../../internal/default-strings/viewers.generated.js";const KEY_ACTIONS=Object.freeze({ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down","+":"in","=":"in","-":"out",Home:"fit"});class LyraModelViewer extends LyraElement{constructor(){super(...arguments),this._src="",this._name="",this._mimeType="",this._format="auto",this.authoredCamera=!1,this.alt="",this.target="_blank",this.rel="",this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null,this.generation=0,this.observers=[],this.mediaCleanup=[],this.announcements=new ViewerAnnouncementController(this),this.descriptions=new HostDescriptionController(this,()=>this.viewport,()=>{const instructions=this.renderRoot.querySelector('[part="instructions"]');return instructions?[instructions]:[]})}static{this.defaultStrings={...super.defaultStrings,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,loadingDocument:LYRA_DEFAULT_loadingDocument,modelViewerAlternative:LYRA_DEFAULT_modelViewerAlternative,modelViewerEmpty:LYRA_DEFAULT_modelViewerEmpty,modelViewerFit:LYRA_DEFAULT_modelViewerFit,modelViewerInstructions:LYRA_DEFAULT_modelViewerInstructions,modelViewerInvalid:LYRA_DEFAULT_modelViewerInvalid,modelViewerLabel:LYRA_DEFAULT_modelViewerLabel,modelViewerProgress:LYRA_DEFAULT_modelViewerProgress,modelViewerReady:LYRA_DEFAULT_modelViewerReady,modelViewerRotateDown:LYRA_DEFAULT_modelViewerRotateDown,modelViewerRotateLeft:LYRA_DEFAULT_modelViewerRotateLeft,modelViewerRotateRight:LYRA_DEFAULT_modelViewerRotateRight,modelViewerRotateUp:LYRA_DEFAULT_modelViewerRotateUp,modelViewerUnsupportedFormat:LYRA_DEFAULT_modelViewerUnsupportedFormat,retry:LYRA_DEFAULT_retry,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.styles=[LyraElement.styles,styles]}get src(){return this._src}set src(value){const next=typeof value=="string"?value:"",old=this._src;next!==old&&(this.retire(),this._src=next,this.requestUpdate("src",old))}get name(){return this._name}set name(value){const next=typeof value=="string"?value:"",old=this._name;next!==old&&(this.retire(),this._name=next,this.requestUpdate("name",old))}get mimeType(){return this._mimeType}set mimeType(value){const next=typeof value=="string"?value:"",old=this._mimeType;next!==old&&(this.retire(),this._mimeType=next,this.requestUpdate("mimeType",old))}get format(){return this._format}set format(value){const next=value??"auto",old=this._format;next!==old&&(this.retire(),this._format=next,this.requestUpdate("format",old))}get camera(){return this._camera}set camera(value){const next=value==null?void 0:snapshotModelCamera(value),old=this._camera;this._camera=next,this.authoredCamera=next!==void 0;try{next?this.engine?.setCamera(next):this.status==="ready"&&this.fit()}catch(error){this.fail("invalid","error",error)}this.requestUpdate("camera",old)}get viewport(){return this.renderRoot?.querySelector('[part="viewport"]')??null}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.retire(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.retire(),this.announcements.adopted(),this.descriptions.adopted(),this.isConnected&&this.scheduleAfterUpdate(()=>{this.load()})}updated(changed){super.updated(changed),this.announcements.transition("model",this.status,this.statusText(),this.status==="error"?"assertive":this.status==="ready"||this.status==="empty"||this.status==="loading"||this.status==="context-lost"?"polite":void 0),["src","name","mimeType","format"].some(key=>changed.has(key))&&this.scheduleAfterUpdate(()=>{this.load()})}retire(){this.generation++,this.controller?.abort(),this.controller=void 0;for(const observer of this.observers)observer.disconnect();this.observers=[];for(const cleanup of this.mediaCleanup)cleanup();this.mediaCleanup=[];const engine=this.engine;this.engine=void 0;try{engine?.dispose()}catch{}this.viewport?.replaceChildren(),this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null}fail(message,reason,error){this.retire(),this.status="error",this.message=message,this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason}),this.emit("lr-render-error",{error:error??new Error("Model engine unavailable")})}async load(){if(this.retire(),!this.src||!this.isConnected)return;const owner=this.ownerDocument,view=owner.defaultView,container=this.viewport;if(!view||!container)return;const generation=this.generation,controller=new view.AbortController;this.controller=controller;const current=()=>generation===this.generation&&!controller.signal.aborted&&this.isConnected&&this.ownerDocument===owner;if(this.src.length>MODEL_SOURCE_MAX_BYTES){this.fail("tooLarge","error");return}const format=resolveModelFormat(this.format,this.name,this.mimeType,this.src);if(!format){this.fail("unsupportedFormat","unsupported");return}if(!resolveOwnerFetchTarget(this,this.src)){this.fail("urlNotAllowed","error");return}if(!modelEngineEnvironment.available(owner)){this.fail("engineUnsupported","unsupported");return}this.status="loading";let candidate=null;try{const bytes=await readModelSource(this,this.src,controller.signal,current,(loaded,total)=>{current()&&(total!==this.total||loaded===total||loaded-this.loaded>=1048576)&&(this.loaded=loaded,this.total=total)});if(!current())return;if(candidate=await modelEngineLoader.create(),!current()){candidate?.dispose();return}if(!candidate){this.fail("engineUnavailable","unavailable");return}const engine=candidate;if(this.engine=engine,typeof engine.fit!="function"){this.fail("engineUnavailable","unavailable");return}engine.setStyle(this.engineStyle());let parsed=!1,contextLost=!1;const publishParsedView=()=>{!current()||contextLost||!parsed||(this.status=engine.positionOf?.(0)===null?"empty":"ready",this.message="",this.status==="ready"&&!this.authoredCamera&&this.fit())};if(await engine.mount(container,{hover:()=>{},pick:()=>{},camera:value=>{current()&&this.status==="ready"&&this.acceptCamera(value,!0)},progress:(loaded,total)=>{if(!(!current()||parsed||!Number.isFinite(loaded)||!Number.isFinite(total)||total<0||loaded<total))try{parsed=!0,publishParsedView(),current()&&this.emit("lr-load",{format})}catch(error){current()&&this.fail("invalid","error",error)}},lost:reason=>{if(current())if(reason==="context-lost"){if(contextLost)return;contextLost=!0,this.status="context-lost",this.message="contextLost",this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason})}else this.fail("invalid","error")},rendering:info=>{current()&&(this.software=info.software)},restored:()=>{if(!(!current()||!contextLost))try{contextLost=!1,this.message="",parsed?publishParsedView():this.status="loading",current()&&this.refreshEngine()}catch(error){current()&&this.fail("invalid","error",error)}}}),!current()){this.engine===engine&&(this.engine=void 0,engine.dispose());return}if(container.querySelectorAll("canvas").forEach(canvas=>{canvas.setAttribute("aria-hidden","true"),canvas.removeAttribute("tabindex")}),this.authoredCamera&&this.camera&&engine.setCamera(this.camera),this.watchEnvironment(current),this.refreshEngine(),!current())return;if(supportsAsyncModelData(engine)){if(await engine.setDataAsync({bytes,format},generation,{signal:controller.signal}),!current())return}else engine.setData({bytes,format},generation)}catch(error){if(!current()||isAbortError(error))return;const reason=engine3dFailureReason(error);this.fail(isResourceLimitError(error)?"tooLarge":reason==="unsupported"?"engineUnsupported":"invalid",reason,error)}}engineStyle(){const view=this.ownerDocument.defaultView,computed=view.getComputedStyle(this),canvas=this.ownerDocument.createElement("canvas");canvas.width=canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0}),color=token=>{const resolved=resolveCanvasColor(this,`var(${token})`,computed.color);if(!context)return resolved;context.clearRect(0,0,1,1),context.fillStyle=resolved,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:[color("--lr-color-brand")],fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:8,lineWidth:1,devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}refreshEngine(){if(!(!this.engine||!this.isConnected))try{this.engine.setStyle(this.engineStyle());const box=this.viewport?.getBoundingClientRect();box&&this.engine.resize(Math.max(1,box.width),Math.max(1,box.height))}catch(error){this.fail("invalid","error",error)}}watchEnvironment(current){const view=this.ownerDocument.defaultView,refresh=()=>{current()&&this.refreshEngine()},resize=new view.ResizeObserver(refresh);resize.observe(this.viewport),this.observers.push(resize);const mutation=new view.MutationObserver(refresh);let ancestor=this;for(;ancestor;){mutation.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}this.observers.push(mutation);for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const media=view.matchMedia(query);media.addEventListener("change",refresh),this.mediaCleanup.push(()=>media.removeEventListener("change",refresh))}}acceptCamera(value,emit){let next;try{next=snapshotModelCamera(value)}catch{return}const old=this._camera;this._camera=next,this.requestUpdate("camera",old),emit&&(this.authoredCamera=!0,this.emit("lr-camera-change",{camera:next}))}fit(){if(this.engine&&this.status==="ready")try{this.acceptCamera(this.engine.fit?.(),!1)}catch(error){this.fail("invalid","error",error)}}retry(){this.retire(),this.scheduleAfterUpdate(()=>{this.load()})}move(action){if(!this.engine||this.status!=="ready")return;if(action==="fit"){const generation=this.generation;this.fit(),generation===this.generation&&this.status==="ready"&&this.camera&&this.emit("lr-camera-change",{camera:this.camera});return}const current=this.camera??DEFAULT_MODEL_CAMERA,horizontal=this.effectiveDirection==="rtl"?-1:1,next=snapshotModelCamera({...current,yaw:current.yaw+(action==="left"?-.1*horizontal:action==="right"?.1*horizontal:0),pitch:current.pitch+(action==="up"?.1:action==="down"?-.1:0),distance:current.distance*(action==="in"?.8:action==="out"?1.25:1)});try{this.engine.setCamera(next),this.acceptCamera(next,!0)}catch(error){this.fail("invalid","error",error)}}keydown(event){if(event.altKey||event.ctrlKey||event.metaKey||event.isComposing||event.currentTarget!==event.target||this.closest("[inert]"))return;const action=Object.hasOwn(KEY_ACTIONS,event.key)?KEY_ACTIONS[event.key]:void 0;!action||this.status!=="ready"||(event.preventDefault(),this.move(action))}statusText(){switch(this.message){case"tooLarge":return this.localize("documentPreviewResourceTooLarge");case"urlNotAllowed":return this.localize("documentPreviewUrlNotAllowed");case"unsupportedFormat":return this.localize("modelViewerUnsupportedFormat");case"invalid":return this.localize("modelViewerInvalid");case"engineUnsupported":return this.localize("engine3dUnsupported");case"engineUnavailable":return this.localize("engine3dUnavailable");case"contextLost":return this.localize("engine3dContextLost");default:break}if(this.status==="ready")return this.localize("modelViewerReady");if(this.status==="empty")return this.localize("modelViewerEmpty");if(this.status==="loading"){if(this.total===null)return this.localize("loadingDocument");const number=getNumberFormat(this.effectiveLocale);return this.localize("modelViewerProgress",void 0,{loaded:number.format(this.loaded),total:number.format(this.total)})}return this.localize("documentPreviewEmpty",void 0,{type:this.localize("modelViewerLabel")})}render(){const label=hostAriaLabel(this)??(this.name||this.localize("modelViewerLabel")),ready=this.status==="ready",href=this.src.length<=MODEL_SOURCE_MAX_BYTES?safeDownloadHref(this.src,this.ownerDocument?.defaultView?.URL??URL):null,controls=[["left",this.localize("modelViewerRotateLeft")],["right",this.localize("modelViewerRotateRight")],["up",this.localize("modelViewerRotateUp")],["down",this.localize("modelViewerRotateDown")],["in",this.localize("zoomIn")],["out",this.localize("zoomOut")],["fit",this.localize("modelViewerFit")]];return html`<section part="base" role="region" aria-label=${label}>
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ifDefined}from"lit/directives/if-defined.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{isAbortError,isResourceLimitError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{engine3dFailureReason}from"../../../internal/engine-3d.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{modelEngineEnvironment,modelEngineLoader,supportsAsyncModelData}from"./model-viewer-loader.js";import{MODEL_SOURCE_MAX_BYTES,DEFAULT_MODEL_CAMERA,readModelSource,resolveModelFormat,snapshotModelCamera}from"./model-viewer-source.js";import{styles}from"./model-viewer.styles.js";import{LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_download,LYRA_DEFAULT_engine3dContextLost,LYRA_DEFAULT_engine3dSoftwareRendering,LYRA_DEFAULT_engine3dUnavailable,LYRA_DEFAULT_engine3dUnsupported,LYRA_DEFAULT_retry,LYRA_DEFAULT_zoomIn,LYRA_DEFAULT_zoomOut}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_modelViewerAlternative,LYRA_DEFAULT_modelViewerEmpty,LYRA_DEFAULT_modelViewerFit,LYRA_DEFAULT_modelViewerInstructions,LYRA_DEFAULT_modelViewerInvalid,LYRA_DEFAULT_modelViewerLabel,LYRA_DEFAULT_modelViewerProgress,LYRA_DEFAULT_modelViewerReady,LYRA_DEFAULT_modelViewerRotateDown,LYRA_DEFAULT_modelViewerRotateLeft,LYRA_DEFAULT_modelViewerRotateRight,LYRA_DEFAULT_modelViewerRotateUp,LYRA_DEFAULT_modelViewerUnsupportedFormat}from"../../../internal/default-strings/viewers.generated.js";const KEY_ACTIONS=Object.freeze({ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down","+":"in","=":"in","-":"out",Home:"fit"});class LyraModelViewer extends LyraElement{constructor(){super(...arguments),this._src="",this._name="",this._mimeType="",this._format="auto",this.authoredCamera=!1,this.alt="",this.target="_blank",this.rel="",this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null,this.generation=0,this.observers=[],this.mediaCleanup=[],this.announcements=new ViewerAnnouncementController(this),this.descriptions=new HostDescriptionController(this,()=>this.viewport,()=>{const instructions=this.renderRoot.querySelector('[part="instructions"]');return instructions?[instructions]:[]})}static{this.defaultStrings={...super.defaultStrings,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,download:LYRA_DEFAULT_download,engine3dContextLost:LYRA_DEFAULT_engine3dContextLost,engine3dSoftwareRendering:LYRA_DEFAULT_engine3dSoftwareRendering,engine3dUnavailable:LYRA_DEFAULT_engine3dUnavailable,engine3dUnsupported:LYRA_DEFAULT_engine3dUnsupported,loadingDocument:LYRA_DEFAULT_loadingDocument,modelViewerAlternative:LYRA_DEFAULT_modelViewerAlternative,modelViewerEmpty:LYRA_DEFAULT_modelViewerEmpty,modelViewerFit:LYRA_DEFAULT_modelViewerFit,modelViewerInstructions:LYRA_DEFAULT_modelViewerInstructions,modelViewerInvalid:LYRA_DEFAULT_modelViewerInvalid,modelViewerLabel:LYRA_DEFAULT_modelViewerLabel,modelViewerProgress:LYRA_DEFAULT_modelViewerProgress,modelViewerReady:LYRA_DEFAULT_modelViewerReady,modelViewerRotateDown:LYRA_DEFAULT_modelViewerRotateDown,modelViewerRotateLeft:LYRA_DEFAULT_modelViewerRotateLeft,modelViewerRotateRight:LYRA_DEFAULT_modelViewerRotateRight,modelViewerRotateUp:LYRA_DEFAULT_modelViewerRotateUp,modelViewerUnsupportedFormat:LYRA_DEFAULT_modelViewerUnsupportedFormat,retry:LYRA_DEFAULT_retry,zoomIn:LYRA_DEFAULT_zoomIn,zoomOut:LYRA_DEFAULT_zoomOut}}static{this.styles=[LyraElement.styles,styles]}get src(){return this._src}set src(value){const next=typeof value=="string"?value:"",old=this._src;next!==old&&(this.retire(),this._src=next,this.requestUpdate("src",old))}get name(){return this._name}set name(value){const next=typeof value=="string"?value:"",old=this._name;next!==old&&(this.retire(),this._name=next,this.requestUpdate("name",old))}get mimeType(){return this._mimeType}set mimeType(value){const next=typeof value=="string"?value:"",old=this._mimeType;next!==old&&(this.retire(),this._mimeType=next,this.requestUpdate("mimeType",old))}get format(){return this._format}set format(value){const next=value??"auto",old=this._format;next!==old&&(this.retire(),this._format=next,this.requestUpdate("format",old))}get camera(){return this._camera}set camera(value){const next=value==null?void 0:snapshotModelCamera(value),old=this._camera;this._camera=next,this.authoredCamera=next!==void 0;const generation=this.generation;try{next?this.engine?.setCamera(next):this.status==="ready"&&this.fit()}catch(error){generation===this.generation&&this.fail("invalid","error",error)}this.requestUpdate("camera",old)}get viewport(){return this.renderRoot?.querySelector('[part="viewport"]')??null}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.retire(),this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.retire(),this.announcements.adopted(),this.descriptions.adopted(),this.isConnected&&this.scheduleAfterUpdate(()=>{this.load()})}updated(changed){super.updated(changed),this.announcements.transition("model",this.status,this.statusText(),this.status==="error"?"assertive":this.status==="ready"||this.status==="empty"||this.status==="loading"||this.status==="context-lost"?"polite":void 0),["src","name","mimeType","format"].some(key=>changed.has(key))&&this.scheduleAfterUpdate(()=>{this.load()})}retire(){this.generation++,this.controller?.abort(),this.controller=void 0;for(const observer of this.observers)observer.disconnect();this.observers=[];for(const cleanup of this.mediaCleanup)cleanup();this.mediaCleanup=[];const engine=this.engine;this.engine=void 0;try{engine?.dispose()}catch{}this.viewport?.replaceChildren(),this.status="idle",this.message="",this.software=!1,this.loaded=0,this.total=null}fail(message,reason,error){this.retire(),this.status="error",this.message=message,this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason}),this.emit("lr-render-error",{error:error??new Error("Model engine unavailable")})}async load(){if(this.retire(),!this.src||!this.isConnected)return;const owner=this.ownerDocument,view=owner.defaultView,container=this.viewport;if(!view||!container)return;const generation=this.generation,controller=new view.AbortController;this.controller=controller;const current=()=>generation===this.generation&&!controller.signal.aborted&&this.isConnected&&this.ownerDocument===owner;if(this.src.length>MODEL_SOURCE_MAX_BYTES){this.fail("tooLarge","error");return}const format=resolveModelFormat(this.format,this.name,this.mimeType,this.src);if(!format){this.fail("unsupportedFormat","unsupported");return}if(!resolveOwnerFetchTarget(this,this.src)){this.fail("urlNotAllowed","error");return}if(!modelEngineEnvironment.available(owner)){this.fail("engineUnsupported","unsupported");return}this.status="loading";let candidate=null;try{const bytes=await readModelSource(this,this.src,controller.signal,current,(loaded,total)=>{current()&&(total!==this.total||loaded===total||loaded-this.loaded>=1048576)&&(this.loaded=loaded,this.total=total)});if(!current())return;if(candidate=await modelEngineLoader.create(),!current()){candidate?.dispose();return}if(!candidate){this.fail("engineUnavailable","unavailable");return}const engine=candidate;if(this.engine=engine,typeof engine.fit!="function"){this.fail("engineUnavailable","unavailable");return}if(engine.setStyle(this.engineStyle()),!current())return;let parsed=!1,contextLost=!1;const publishParsedView=()=>{if(!current()||contextLost||!parsed)return;const empty=engine.positionOf?.(0)===null;!current()||contextLost||(this.status=empty?"empty":"ready",this.message="",this.status==="ready"&&!this.authoredCamera&&this.fit())};if(await engine.mount(container,{hover:()=>{},pick:()=>{},camera:value=>{current()&&this.status==="ready"&&this.acceptCamera(value,!0)},progress:(loaded,total)=>{if(!(!current()||parsed||!Number.isFinite(loaded)||!Number.isFinite(total)||total<0||loaded<total))try{parsed=!0,publishParsedView(),current()&&this.emit("lr-load",{format})}catch(error){current()&&this.fail("invalid","error",error)}},lost:reason=>{if(current())if(reason==="context-lost"){if(contextLost)return;contextLost=!0,this.status="context-lost",this.message="contextLost",this.emit("lr-engine-fallback",{from:"webgl",to:"list",reason})}else this.fail("invalid","error")},rendering:info=>{current()&&(this.software=info.software)},restored:()=>{if(!(!current()||!contextLost))try{contextLost=!1,this.message="",parsed?publishParsedView():this.status="loading",current()&&this.refreshEngine()}catch(error){current()&&this.fail("invalid","error",error)}}}),!current()){this.engine===engine&&(this.engine=void 0,engine.dispose());return}if(container.querySelectorAll("canvas").forEach(canvas=>{canvas.setAttribute("aria-hidden","true"),canvas.removeAttribute("tabindex")}),this.authoredCamera&&this.camera&&engine.setCamera(this.camera),!current()||(this.watchEnvironment(current),this.refreshEngine(),!current()))return;if(supportsAsyncModelData(engine)){if(await engine.setDataAsync({bytes,format},generation,{signal:controller.signal}),!current())return}else engine.setData({bytes,format},generation)}catch(error){if(!current()||isAbortError(error))return;const reason=engine3dFailureReason(error);this.fail(isResourceLimitError(error)?"tooLarge":reason==="unsupported"?"engineUnsupported":"invalid",reason,error)}}engineStyle(){const view=this.ownerDocument.defaultView,computed=view.getComputedStyle(this),canvas=this.ownerDocument.createElement("canvas");canvas.width=canvas.height=1;const context=canvas.getContext("2d",{willReadFrequently:!0}),color=token=>{const resolved=resolveCanvasColor(this,`var(${token})`,computed.color);if(!context)return resolved;context.clearRect(0,0,1,1),context.fillStyle=resolved,context.fillRect(0,0,1,1);const rgba=context.getImageData(0,0,1,1).data;return`rgba(${rgba[0]}, ${rgba[1]}, ${rgba[2]}, ${rgba[3]/255})`};return{background:color("--lr-color-surface"),foreground:color("--lr-color-text"),muted:color("--lr-color-text-quiet"),accent:color("--lr-color-brand"),focus:color("--lr-focus-ring-color"),palette:[color("--lr-color-brand")],fontFamily:computed.fontFamily,fontSize:finiteRange(Number.parseFloat(computed.fontSize),14,1,128),pointSize:8,lineWidth:1,devicePixelRatio:finiteRange(view.devicePixelRatio,1,.25,4),reducedMotion:view.matchMedia("(prefers-reduced-motion: reduce)").matches,forcedColors:view.matchMedia("(forced-colors: active)").matches}}refreshEngine(){const engine=this.engine,generation=this.generation;if(!(!engine||!this.isConnected))try{if(engine.setStyle(this.engineStyle()),generation!==this.generation)return;const box=this.viewport?.getBoundingClientRect();box&&engine.resize(Math.max(1,box.width),Math.max(1,box.height))}catch(error){generation===this.generation&&this.fail("invalid","error",error)}}watchEnvironment(current){const view=this.ownerDocument.defaultView,refresh=()=>{current()&&this.refreshEngine()},resize=new view.ResizeObserver(refresh);resize.observe(this.viewport),this.observers.push(resize);const mutation=new view.MutationObserver(refresh);let ancestor=this;for(;ancestor;){mutation.observe(ancestor,{attributes:!0});const root=ancestor.getRootNode();ancestor=ancestor.parentElement??(root instanceof view.ShadowRoot?root.host:null)}this.observers.push(mutation);for(const query of["(prefers-reduced-motion: reduce)","(forced-colors: active)","(prefers-color-scheme: dark)"]){const media=view.matchMedia(query);media.addEventListener("change",refresh),this.mediaCleanup.push(()=>media.removeEventListener("change",refresh))}}acceptCamera(value,emit){let next;try{next=snapshotModelCamera(value)}catch{return}const old=this._camera;this._camera=next,this.requestUpdate("camera",old),emit&&(this.authoredCamera=!0,this.emit("lr-camera-change",{camera:next}))}fit(){if(this.engine&&this.status==="ready"){const generation=this.generation;try{const camera=this.engine.fit?.();generation===this.generation&&this.status==="ready"&&this.acceptCamera(camera,!1)}catch(error){generation===this.generation&&this.fail("invalid","error",error)}}}retry(){this.retire(),this.scheduleAfterUpdate(()=>{this.load()})}move(action){if(!this.engine||this.status!=="ready")return;if(action==="fit"){const generation2=this.generation;this.fit(),generation2===this.generation&&this.status==="ready"&&this.camera&&this.emit("lr-camera-change",{camera:this.camera});return}const current=this.camera??DEFAULT_MODEL_CAMERA,horizontal=this.effectiveDirection==="rtl"?-1:1,next=snapshotModelCamera({...current,yaw:current.yaw+(action==="left"?-.1*horizontal:action==="right"?.1*horizontal:0),pitch:current.pitch+(action==="up"?.1:action==="down"?-.1:0),distance:current.distance*(action==="in"?.8:action==="out"?1.25:1)}),generation=this.generation;try{this.engine.setCamera(next),generation===this.generation&&this.status==="ready"&&this.acceptCamera(next,!0)}catch(error){generation===this.generation&&this.fail("invalid","error",error)}}keydown(event){if(event.altKey||event.ctrlKey||event.metaKey||event.isComposing||event.currentTarget!==event.target||this.closest("[inert]"))return;const action=Object.hasOwn(KEY_ACTIONS,event.key)?KEY_ACTIONS[event.key]:void 0;!action||this.status!=="ready"||(event.preventDefault(),this.move(action))}statusText(){switch(this.message){case"tooLarge":return this.localize("documentPreviewResourceTooLarge");case"urlNotAllowed":return this.localize("documentPreviewUrlNotAllowed");case"unsupportedFormat":return this.localize("modelViewerUnsupportedFormat");case"invalid":return this.localize("modelViewerInvalid");case"engineUnsupported":return this.localize("engine3dUnsupported");case"engineUnavailable":return this.localize("engine3dUnavailable");case"contextLost":return this.localize("engine3dContextLost");default:break}if(this.status==="ready")return this.localize("modelViewerReady");if(this.status==="empty")return this.localize("modelViewerEmpty");if(this.status==="loading"){if(this.total===null)return this.localize("loadingDocument");const number=getNumberFormat(this.effectiveLocale);return this.localize("modelViewerProgress",void 0,{loaded:number.format(this.loaded),total:number.format(this.total)})}return this.localize("documentPreviewEmpty",void 0,{type:this.localize("modelViewerLabel")})}render(){const label=hostAriaLabel(this)??(this.name||this.localize("modelViewerLabel")),ready=this.status==="ready",href=this.src.length<=MODEL_SOURCE_MAX_BYTES?safeDownloadHref(this.src,this.ownerDocument?.defaultView?.URL??URL):null,controls=[["left",this.localize("modelViewerRotateLeft")],["right",this.localize("modelViewerRotateRight")],["up",this.localize("modelViewerRotateUp")],["down",this.localize("modelViewerRotateDown")],["in",this.localize("zoomIn")],["out",this.localize("zoomOut")],["fit",this.localize("modelViewerFit")]];return html`<section part="base" role="region" aria-label=${label}>
2
2
  <div part="viewport" role="group" aria-label=${label} aria-busy=${String(this.status==="loading")} tabindex=${ready?"0":"-1"} ?data-ready=${ready} ?hidden=${this.status==="idle"||this.status==="empty"||this.status==="error"} @keydown=${this.keydown}></div>
3
3
  <div part="toolbar">${controls.map(([action,label2])=>html`<button part="control" type="button" ?disabled=${!ready} @click=${()=>this.move(action)}>${label2}</button>`)}</div>
4
4
  <p part="instructions">${this.localize("modelViewerInstructions")}</p>