@aceshooting/lyra-ui 30.8.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 (241) hide show
  1. package/CHANGELOG.md +239 -329
  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-loader.js +1 -1
  9. package/dist/components/charts/chart/box-plot.class.js +2 -2
  10. package/dist/components/charts/chart/chart-core-loader.js +1 -1
  11. package/dist/components/charts/chart/chart-feature-loader.js +1 -1
  12. package/dist/components/charts/chart/chart-sync.js +1 -1
  13. package/dist/components/charts/chart/chart.class.d.ts +1 -1
  14. package/dist/components/charts/chart/chart.class.js +4 -4
  15. package/dist/components/charts/chart/lite-chart-axis-layout.js +1 -1
  16. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  17. package/dist/components/charts/chart-3d/chart-3d-engine.js +1 -1
  18. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +9 -4
  19. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  20. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  21. package/dist/components/conversation/chat-message/chat-message.class.d.ts +27 -3
  22. package/dist/components/conversation/chat-message/chat-message.class.js +14 -12
  23. package/dist/components/conversation/chat-message/chat-message.styles.js +1 -1
  24. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +29 -2
  25. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +2 -2
  26. package/dist/components/conversation/chat-viewport/chat-viewport.styles.js +1 -1
  27. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  28. package/dist/components/conversation/code-block/code-loader.js +1 -1
  29. package/dist/components/conversation/code-block/shiki-oniguruma.js +1 -1
  30. package/dist/components/conversation/code-block/shiki-types.js +1 -1
  31. package/dist/components/conversation/markdown/katex-loader.js +1 -1
  32. package/dist/components/conversation/markdown/markdown-base.class.d.ts +1 -1
  33. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  34. package/dist/components/conversation/markdown/markdown-code-header.js +1 -1
  35. package/dist/components/conversation/markdown/markdown-core.class.d.ts +10 -0
  36. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  37. package/dist/components/conversation/markdown/markdown-loader.js +1 -1
  38. package/dist/components/conversation/markdown/markdown-shared.d.ts +7 -2
  39. package/dist/components/conversation/markdown/markdown-shared.js +3 -3
  40. package/dist/components/conversation/markdown/markdown.class.d.ts +10 -0
  41. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  42. package/dist/components/conversation/message-feedback/message-feedback.class.js +2 -2
  43. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  44. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +2 -1
  45. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +4 -0
  46. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +1 -1
  47. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +1 -1
  48. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  49. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +1 -1
  50. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  51. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +17 -3
  52. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +3 -3
  53. package/dist/components/conversation/suggestion-chips/suggestion-chips.d.ts +1 -1
  54. package/dist/components/conversation/suggestion-chips/suggestion-chips.js +1 -1
  55. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  56. package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
  57. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  58. package/dist/components/data/data-grid/data-grid.class.d.ts +10 -10
  59. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  60. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  61. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  62. package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
  63. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  64. package/dist/components/data/pagination/pagination.class.js +1 -1
  65. package/dist/components/data/table/table.class.d.ts +31 -2
  66. package/dist/components/data/table/table.class.js +3 -3
  67. package/dist/components/data/table/table.styles.js +1 -1
  68. package/dist/components/data/timeline/timeline-cluster.js +1 -1
  69. package/dist/components/data/timeline/timeline-item.class.d.ts +10 -3
  70. package/dist/components/data/timeline/timeline-item.class.js +16 -12
  71. package/dist/components/data/timeline/timeline-item.styles.js +1 -1
  72. package/dist/components/data/timeline/timeline.class.d.ts +14 -2
  73. package/dist/components/data/timeline/timeline.class.js +9 -5
  74. package/dist/components/data/tree/tree-item.class.js +1 -1
  75. package/dist/components/data/tree/tree.class.d.ts +2 -0
  76. package/dist/components/data/tree/tree.class.js +1 -1
  77. package/dist/components/forms/button/button.class.d.ts +8 -6
  78. package/dist/components/forms/button/button.class.js +2 -2
  79. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  80. package/dist/components/forms/color-picker/color-core.js +1 -1
  81. package/dist/components/forms/date-picker/date-input.class.d.ts +1 -1
  82. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  83. package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
  84. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -2
  85. package/dist/components/forms/icon-button/icon-button.class.js +2 -2
  86. package/dist/components/forms/input/input-shared.js +2 -2
  87. package/dist/components/forms/input/number-input-locale.js +1 -0
  88. package/dist/components/forms/input/number-input.class.d.ts +19 -2
  89. package/dist/components/forms/input/number-input.class.js +2 -2
  90. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +3 -3
  91. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  92. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  93. package/dist/components/layout/details/accordion-item.class.js +1 -1
  94. package/dist/components/layout/menu/menu.class.js +1 -1
  95. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  96. package/dist/components/layout/navigation-menu-item/navigation-menu-item.class.js +1 -1
  97. package/dist/components/layout/tab-group/tab-group.class.d.ts +8 -1
  98. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  99. package/dist/components/layout/tab-group/tab.class.d.ts +7 -1
  100. package/dist/components/layout/tab-group/tab.class.js +1 -1
  101. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +2 -2
  102. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  103. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  104. package/dist/components/media/attachment-chip/attachment-chip.class.d.ts +21 -14
  105. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  106. package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +36 -12
  107. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
  108. package/dist/components/media/drop-zone/drop-zone.class.d.ts +23 -5
  109. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  110. package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
  111. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  112. package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -1
  113. package/dist/components/media/flag/flag-peer-bulk.js +1 -1
  114. package/dist/components/media/flag/flag-peer.js +1 -1
  115. package/dist/components/media/flag/flag-url-resolver.js +1 -1
  116. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -2
  117. package/dist/components/media/image-viewer/image-viewer.class.js +1 -1
  118. package/dist/components/media/map/map-feature-loader.js +1 -1
  119. package/dist/components/media/map/map-loader.js +1 -1
  120. package/dist/components/media/map/map-owned-features.js +1 -1
  121. package/dist/components/media/map/map-scene-elevated-lines.js +2 -2
  122. package/dist/components/media/map/map-scene-render-controller.js +1 -1
  123. package/dist/components/media/map/map.class.d.ts +5 -5
  124. package/dist/components/media/map/map.class.js +3 -3
  125. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  126. package/dist/components/media/qr-code/qr-code-loader.js +1 -1
  127. package/dist/components/media/video/video.class.d.ts +3 -3
  128. package/dist/components/media/video/video.class.js +3 -1
  129. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  130. package/dist/components/overlays/chip/chip.class.js +1 -1
  131. package/dist/components/overlays/overlay/dropdown.class.js +1 -1
  132. package/dist/components/overlays/overlay/tooltip.class.d.ts +5 -1
  133. package/dist/components/overlays/overlay/tooltip.class.js +3 -3
  134. package/dist/components/retrieval/embedding-explorer/embedding-explorer-engine.js +1 -1
  135. package/dist/components/retrieval/graph/graph-engine-adapter.js +1 -1
  136. package/dist/components/retrieval/graph/graph-loader.js +1 -1
  137. package/dist/components/retrieval/graph/graph-node-renderer.js +1 -1
  138. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  139. package/dist/components/retrieval/graph/graph.class.d.ts +1 -1
  140. package/dist/components/retrieval/graph/graph.class.js +1 -1
  141. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  142. package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +1 -1
  143. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
  144. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  145. package/dist/components/utility/icon/dompurify-loader.js +1 -1
  146. package/dist/components/utility/json-viewer/json-viewer.class.d.ts +16 -1
  147. package/dist/components/utility/json-viewer/json-viewer.class.js +4 -4
  148. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  149. package/dist/components/utility/known-date/known-date.class.js +1 -1
  150. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  151. package/dist/components/viewers/calendar-viewer/calendar-loader.js +1 -1
  152. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  153. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  154. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  155. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +1 -1
  156. package/dist/components/viewers/docx-viewer/docx-loader.js +1 -1
  157. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  158. package/dist/components/viewers/ebook-viewer/ebook-loader.js +1 -1
  159. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  160. package/dist/components/viewers/ebook-viewer/epub-unload-guard.js +1 -0
  161. package/dist/components/viewers/email-viewer/email-loader.js +1 -1
  162. package/dist/components/viewers/html-viewer/dompurify-loader.js +1 -1
  163. package/dist/components/viewers/include/include.class.js +1 -1
  164. package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -1
  165. package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
  166. package/dist/components/viewers/notebook-viewer/dompurify-loader.js +1 -1
  167. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  168. package/dist/components/viewers/pdf-viewer/pdf-loader.js +1 -1
  169. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  170. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  171. package/dist/components/viewers/pptx-viewer/pptx-loader.js +1 -1
  172. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-loader.js +1 -1
  173. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  174. package/dist/components/viewers/svg-viewer/dompurify-loader.js +1 -1
  175. package/dist/components/viewers/table-viewer-shared.js +4 -4
  176. package/dist/framework-types.d.ts +1 -1
  177. package/dist/internal/anchored-overlay-runtime.js +1 -1
  178. package/dist/internal/catalog-picker.js +1 -1
  179. package/dist/internal/document-tokens.js +2 -2
  180. package/dist/internal/dompurify-loader.js +1 -1
  181. package/dist/internal/drop-session-controller.js +1 -1
  182. package/dist/internal/engine-3d.js +1 -1
  183. package/dist/internal/icon-only-content.js +1 -1
  184. package/dist/internal/layered-layout.js +1 -1
  185. package/dist/internal/locale-loaders.generated.js +1 -1
  186. package/dist/internal/map-custom-layer-controller.js +1 -1
  187. package/dist/internal/map-scene-layer-runtime.js +1 -1
  188. package/dist/internal/media-panorama.js +1 -1
  189. package/dist/internal/package-metadata.js +1 -1
  190. package/dist/internal/papaparse-loader.js +1 -1
  191. package/dist/internal/safe-url.js +1 -1
  192. package/dist/internal/scoped-definitions.generated.js +1 -1
  193. package/dist/internal/scroll-overflow.js +1 -1
  194. package/dist/internal/source-window-controller.js +1 -1
  195. package/dist/internal/text-quote.js +1 -1
  196. package/dist/internal/viewer-search.js +1 -1
  197. package/dist/lyra.d.ts +1 -1
  198. package/dist/sequence-time-binding.js +1 -1
  199. package/dist/simulation-clock.js +1 -1
  200. package/dist/styles/reservations.css +1 -1
  201. package/dist/styles/reservations.styles.js +1 -1
  202. package/dist/testing/happy-dom-shims.js +1 -1
  203. package/dist/theme/theme.js +1 -1
  204. package/dist/theme-core.css +1 -0
  205. package/dist/utilities/scoped-registry.js +1 -1
  206. package/llms/components/lr-attachment-chip.md +27 -12
  207. package/llms/components/lr-attachment-trigger.md +27 -7
  208. package/llms/components/lr-button.md +6 -4
  209. package/llms/components/lr-chat-composer.md +13 -7
  210. package/llms/components/lr-chat-message.md +44 -3
  211. package/llms/components/lr-chat-viewport.md +39 -2
  212. package/llms/components/lr-data-grid.md +2 -0
  213. package/llms/components/lr-dialog.md +10 -0
  214. package/llms/components/lr-drop-zone.md +26 -2
  215. package/llms/components/lr-icon-button.md +2 -1
  216. package/llms/components/lr-json-viewer.md +17 -0
  217. package/llms/components/lr-locale-picker.md +5 -0
  218. package/llms/components/lr-markdown-core.md +2 -1
  219. package/llms/components/lr-markdown.md +20 -4
  220. package/llms/components/lr-menu.md +3 -1
  221. package/llms/components/lr-number-input.md +28 -1
  222. package/llms/components/lr-prompt-input.md +1 -1
  223. package/llms/components/lr-streaming-text-core.md +3 -2
  224. package/llms/components/lr-streaming-text.md +4 -1
  225. package/llms/components/lr-suggestion-chips.md +28 -5
  226. package/llms/components/lr-tab-group.md +13 -1
  227. package/llms/components/lr-tab.md +5 -0
  228. package/llms/components/lr-table.md +25 -4
  229. package/llms/components/lr-timeline-item.md +1 -1
  230. package/llms/components/lr-timeline.md +38 -4
  231. package/llms/components/lr-tooltip.md +3 -1
  232. package/llms/components/lr-tree.md +4 -0
  233. package/llms/components/lr-virtual-list.md +1 -0
  234. package/llms/peers.md +2 -2
  235. package/llms/shared/ai-and-peers.md +34 -0
  236. package/llms/shared/forms-and-accessibility.md +21 -4
  237. package/llms/shared/imports-and-registration.md +2 -0
  238. package/llms/shared/styles-and-tokens.md +47 -1
  239. package/llms/shared.md +104 -5
  240. package/package.json +25 -21
  241. 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{createOptionalPeerLoader}from"../../../internal/optional-peer-capabilities.js";const CALENDAR_ICAL_WARNING_KEY="lyra-calendar-viewer-ical-unavailable",CALENDAR_ICAL_WARNING="<lr-calendar-viewer> could not load its optional ical.js peer.";function isIcalApi(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"parse"in value&&typeof value.parse=="function"&&"Component"in value&&typeof value.Component=="function"&&"Event"in value&&typeof value.Event=="function"}const ical=createOptionalPeerLoader({load:()=>import("ical.js"),isCapability:isIcalApi,warningKey:CALENDAR_ICAL_WARNING_KEY,warning:CALENDAR_ICAL_WARNING});function loadIcalDeps(importIcal){return ical.loadWith(importIcal)}function loadIcal(){return ical.get()}function clearIcalCache(){ical.clear()}export{clearIcalCache,loadIcal,loadIcalDeps};
1
+ import{createOptionalPeerLoader}from"../../../internal/optional-peer-capabilities.js";const CALENDAR_ICAL_WARNING_KEY="lyra-calendar-viewer-ical-unavailable",CALENDAR_ICAL_WARNING="<lr-calendar-viewer> could not load its optional ical.js peer.";function isIcalApi(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"parse"in value&&typeof value.parse=="function"&&"Component"in value&&typeof value.Component=="function"&&"Event"in value&&typeof value.Event=="function"}const ical=createOptionalPeerLoader({load:()=>(async()=>{try{return await import("ical.js")}catch(e){throw e}})(),isCapability:isIcalApi,warningKey:CALENDAR_ICAL_WARNING_KEY,warning:CALENDAR_ICAL_WARNING});function loadIcalDeps(importIcal){return ical.loadWith(importIcal)}function loadIcal(){return ical.get()}function clearIcalCache(){ical.clear()}export{clearIcalCache,loadIcal,loadIcalDeps};
@@ -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"
@@ -1 +1 @@
1
- import{loadDompurify}from"../../../internal/dompurify-loader.js";import{createOptionalPeerLoader}from"../../../internal/optional-peer-capabilities.js";let depsPromise,resolvedDeps;function isMammothApi(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"convertToHtml"in value&&typeof value.convertToHtml=="function"}const mammothLoader=createOptionalPeerLoader({load:()=>import("mammoth/mammoth.browser.js"),isCapability:isMammothApi,warningKey:"lyra-docx-viewer-mammoth-unavailable",warning:"<lr-docx-viewer> could not load its optional mammoth peer."});async function loadMammothAndSanitizer(importMammoth,importDompurify){const[mammoth,DOMPurify]=await Promise.all([importMammoth?mammothLoader.loadWith(importMammoth):mammothLoader.get(),loadDompurify(importDompurify)]);return{mammoth:mammoth??void 0,DOMPurify:DOMPurify??void 0}}function loadDocxDeps(){return depsPromise||(depsPromise=loadMammothAndSanitizer().then(resolved=>(resolvedDeps=resolved,resolved))),depsPromise}function getDocxDepsIfLoaded(){return resolvedDeps}function clearDocxDepsCache(){depsPromise=void 0,resolvedDeps=void 0,mammothLoader.clear()}export{clearDocxDepsCache,getDocxDepsIfLoaded,loadDocxDeps,loadMammothAndSanitizer};
1
+ import{loadDompurify}from"../../../internal/dompurify-loader.js";import{createOptionalPeerLoader}from"../../../internal/optional-peer-capabilities.js";let depsPromise,resolvedDeps;function isMammothApi(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"convertToHtml"in value&&typeof value.convertToHtml=="function"}const mammothLoader=createOptionalPeerLoader({load:()=>(async()=>{try{return await import("mammoth/mammoth.browser.js")}catch(e){throw e}})(),isCapability:isMammothApi,warningKey:"lyra-docx-viewer-mammoth-unavailable",warning:"<lr-docx-viewer> could not load its optional mammoth peer."});async function loadMammothAndSanitizer(importMammoth,importDompurify){const[mammoth,DOMPurify]=await Promise.all([importMammoth?mammothLoader.loadWith(importMammoth):mammothLoader.get(),loadDompurify(importDompurify)]);return{mammoth:mammoth??void 0,DOMPurify:DOMPurify??void 0}}function loadDocxDeps(){return depsPromise||(depsPromise=loadMammothAndSanitizer().then(resolved=>(resolvedDeps=resolved,resolved))),depsPromise}function getDocxDepsIfLoaded(){return resolvedDeps}function clearDocxDepsCache(){depsPromise=void 0,resolvedDeps=void 0,mammothLoader.clear()}export{clearDocxDepsCache,getDocxDepsIfLoaded,loadDocxDeps,loadMammothAndSanitizer};
@@ -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 +1 @@
1
- import{createOptionalPeerLoader}from"../../../internal/optional-peer-capabilities.js";function isEpubFactory(value){return typeof value=="function"}let override;const epub=createOptionalPeerLoader({load:()=>import("epubjs"),isCapability:isEpubFactory,warningKey:"lyra-ebook-viewer-epubjs-unavailable",warning:"<lr-ebook-viewer> could not load its optional epubjs peer."});function loadEpubJs(importEpub){return epub.loadWith(importEpub)}function getEpubJs(){return override??epub.get()}function __setEpubJsForTesting(factory){override=factory===void 0?void 0:Promise.resolve(factory),epub.clear()}export{__setEpubJsForTesting,getEpubJs,loadEpubJs};
1
+ import{createOptionalPeerLoader}from"../../../internal/optional-peer-capabilities.js";function isEpubFactory(value){return typeof value=="function"}let override;const epub=createOptionalPeerLoader({load:()=>(async()=>{try{return await import("epubjs")}catch(e){throw e}})(),isCapability:isEpubFactory,warningKey:"lyra-ebook-viewer-epubjs-unavailable",warning:"<lr-ebook-viewer> could not load its optional epubjs peer."});function loadEpubJs(importEpub){return epub.loadWith(importEpub)}function getEpubJs(){return override??epub.get()}function __setEpubJsForTesting(factory){override=factory===void 0?void 0:Promise.resolve(factory),epub.clear()}export{__setEpubJsForTesting,getEpubJs,loadEpubJs};
@@ -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{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 rendition=normalizeRendition(book.renderTo(mount,{width:"100%",height:"100%"}));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"}
@@ -0,0 +1 @@
1
+ function isManagerClass(value){if(typeof value!="function")return!1;const prototype=Object.getOwnPropertyDescriptor(value,"prototype")?.value;if(typeof prototype!="object"||prototype===null)return!1;let current=prototype;for(let depth=0;current&&depth<8;depth+=1){const descriptor=Object.getOwnPropertyDescriptor(current,"addEventListeners");if(descriptor)return typeof descriptor.value=="function";current=Object.getPrototypeOf(current)}return!1}function guardEpubUnloadListener({settings,requireManager}){if(typeof settings!="object"||settings===null||!requireManager)return;const descriptor=Object.getOwnPropertyDescriptor(settings,"manager");if(!descriptor||!("value"in descriptor)||!descriptor.writable)return;const Manager=requireManager(descriptor.value);if(!isManagerClass(Manager))return;class UnloadFreeManager extends Manager{addEventListeners(...args){const ownListener=Object.hasOwn(window,"addEventListener"),previous=window.addEventListener;window.addEventListener=function(type,...rest){if(type!=="unload")return previous.call(this,type,...rest)};try{return super.addEventListeners(...args)}finally{ownListener?window.addEventListener=previous:delete window.addEventListener}}}Object.defineProperty(settings,"manager",{...descriptor,value:UnloadFreeManager})}export{guardEpubUnloadListener};
@@ -1 +1 @@
1
- import{loadDompurify}from"../../../internal/dompurify-loader.js";import{createOptionalPeerLoader}from"../../../internal/optional-peer-capabilities.js";function isPostalMimeApi(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"parse"in value&&typeof value.parse=="function"}const postalMime=createOptionalPeerLoader({load:()=>import("postal-mime"),isCapability:isPostalMimeApi,warningKey:"lyra-email-viewer-postal-mime-unavailable",warning:"<lr-email-viewer> could not load its optional postal-mime peer."});let depsPromise,resolvedDeps;async function loadEmailAndSanitizer(importPostalMime,importDompurify){const[PostalMime,DOMPurify]=await Promise.all([importPostalMime?postalMime.loadWith(importPostalMime):postalMime.get(),loadDompurify(importDompurify)]);return{PostalMime:PostalMime??void 0,DOMPurify:DOMPurify??void 0}}function loadEmailDeps(){return depsPromise??=loadEmailAndSanitizer().then(result=>((!result.PostalMime||!result.DOMPurify)&&(depsPromise=void 0),resolvedDeps=result,result)),depsPromise}function getEmailDepsIfLoaded(){return resolvedDeps}function clearEmailDepsCache(){depsPromise=void 0,resolvedDeps=void 0,postalMime.clear()}function __setEmailDepsForTesting(deps){depsPromise=deps===void 0?void 0:Promise.resolve(deps),resolvedDeps=deps}export{__setEmailDepsForTesting,clearEmailDepsCache,getEmailDepsIfLoaded,loadEmailAndSanitizer,loadEmailDeps};
1
+ import{loadDompurify}from"../../../internal/dompurify-loader.js";import{createOptionalPeerLoader}from"../../../internal/optional-peer-capabilities.js";function isPostalMimeApi(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"parse"in value&&typeof value.parse=="function"}const postalMime=createOptionalPeerLoader({load:()=>(async()=>{try{return await import("postal-mime")}catch(e){throw e}})(),isCapability:isPostalMimeApi,warningKey:"lyra-email-viewer-postal-mime-unavailable",warning:"<lr-email-viewer> could not load its optional postal-mime peer."});let depsPromise,resolvedDeps;async function loadEmailAndSanitizer(importPostalMime,importDompurify){const[PostalMime,DOMPurify]=await Promise.all([importPostalMime?postalMime.loadWith(importPostalMime):postalMime.get(),loadDompurify(importDompurify)]);return{PostalMime:PostalMime??void 0,DOMPurify:DOMPurify??void 0}}function loadEmailDeps(){return depsPromise??=loadEmailAndSanitizer().then(result=>((!result.PostalMime||!result.DOMPurify)&&(depsPromise=void 0),resolvedDeps=result,result)),depsPromise}function getEmailDepsIfLoaded(){return resolvedDeps}function clearEmailDepsCache(){depsPromise=void 0,resolvedDeps=void 0,postalMime.clear()}function __setEmailDepsForTesting(deps){depsPromise=deps===void 0?void 0:Promise.resolve(deps),resolvedDeps=deps}export{__setEmailDepsForTesting,clearEmailDepsCache,getEmailDepsIfLoaded,loadEmailAndSanitizer,loadEmailDeps};
@@ -1 +1 @@
1
- import{clearDompurifyCache,loadDompurify}from"../../../internal/dompurify-loader.js";let override;function loadHtmlSanitizerDeps(importDompurify=()=>import("dompurify")){return loadDompurify(importDompurify)}function loadHtmlSanitizer(){return override??loadDompurify()}function clearHtmlSanitizerCache(){override=void 0,clearDompurifyCache()}function __setHtmlSanitizerForTesting(value){override=value===void 0?void 0:Promise.resolve(value)}export{__setHtmlSanitizerForTesting,clearHtmlSanitizerCache,loadHtmlSanitizer,loadHtmlSanitizerDeps};
1
+ import{clearDompurifyCache,loadDompurify}from"../../../internal/dompurify-loader.js";let override;function loadHtmlSanitizerDeps(importDompurify=()=>(async()=>{try{return await import("dompurify")}catch(e){throw e}})()){return loadDompurify(importDompurify)}function loadHtmlSanitizer(){return override??loadDompurify()}function clearHtmlSanitizerCache(){override=void 0,clearDompurifyCache()}function __setHtmlSanitizerForTesting(value){override=value===void 0?void 0:Promise.resolve(value)}export{__setHtmlSanitizerForTesting,clearHtmlSanitizerCache,loadHtmlSanitizer,loadHtmlSanitizerDeps};
@@ -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 +1 @@
1
- import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{webgl2Available}from"../../../internal/engine-3d.js";import{tag}from"../../../internal/prefix.js";const modelEngineLoader=createEngine3dLoader({entry:"model",tag:tag("model-viewer"),load:()=>import("@aceshooting/lyra-3d/model")}),modelEngineEnvironment={available:document=>webgl2Available(()=>document.createElement("canvas"))};function supportsAsyncModelData(engine){return"setDataAsync"in engine&&typeof engine.setDataAsync=="function"}export{modelEngineEnvironment,modelEngineLoader,supportsAsyncModelData};
1
+ import{createEngine3dLoader}from"../../../internal/engine-3d-loader.js";import{webgl2Available}from"../../../internal/engine-3d.js";import{tag}from"../../../internal/prefix.js";const modelEngineLoader=createEngine3dLoader({entry:"model",tag:tag("model-viewer"),load:()=>(async()=>{try{return await import("@aceshooting/lyra-3d/model")}catch(e){throw e}})()}),modelEngineEnvironment={available:document=>webgl2Available(()=>document.createElement("canvas"))};function supportsAsyncModelData(engine){return"setDataAsync"in engine&&typeof engine.setDataAsync=="function"}export{modelEngineEnvironment,modelEngineLoader,supportsAsyncModelData};