@aceshooting/lyra-ui 27.0.0 → 28.1.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 (397) hide show
  1. package/CHANGELOG.md +67 -63
  2. package/README.md +7 -3
  3. package/dist/cli/css-declarations.mjs +1 -0
  4. package/dist/cli/lyra-rename-ledger.mjs +1 -1
  5. package/dist/cli/migrate-wa.mjs +9 -4
  6. package/dist/cli/migration-contract.json +1 -1
  7. package/dist/cli/migration-renames.mjs +2 -2
  8. package/dist/cli/migration-theme-scopes.mjs +3 -0
  9. package/dist/cli/theme-scope-vocabulary.generated.mjs +1 -0
  10. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  11. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  12. package/dist/components/agent-tools/agent-question/agent-question.class.js +1 -1
  13. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  14. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  15. package/dist/components/agent-tools/approval-queue/approval-queue.class.js +1 -1
  16. package/dist/components/agent-tools/artifact-panel/artifact-panel.class.js +1 -1
  17. package/dist/components/agent-tools/background-runs/background-runs.class.js +1 -1
  18. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  19. package/dist/components/agent-tools/budget-meter/budget-meter.class.js +1 -1
  20. package/dist/components/agent-tools/change-review/change-review.class.js +1 -1
  21. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  22. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
  23. package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +1 -1
  24. package/dist/components/agent-tools/connector-manager/connector-manager.class.js +1 -1
  25. package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
  26. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  27. package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
  28. package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +1 -1
  29. package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
  30. package/dist/components/agent-tools/permission-grant/permission-grant.class.js +1 -1
  31. package/dist/components/agent-tools/permission-rules/permission-rules.class.js +1 -1
  32. package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
  33. package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +1 -1
  34. package/dist/components/agent-tools/result-card/result-field.class.js +1 -1
  35. package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
  36. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  37. package/dist/components/agent-tools/stack-trace/stack-trace.class.js +1 -1
  38. package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +2 -2
  39. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  40. package/dist/components/agent-tools/terminal/terminal.class.js +1 -1
  41. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  42. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  43. package/dist/components/agent-tools/tool-approval-dialog/tool-approval-dialog.class.js +1 -1
  44. package/dist/components/agent-tools/tool-call-block/tool-call-block.class.js +1 -1
  45. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +1 -1
  46. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  47. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
  48. package/dist/components/agent-tools/tool-result-view/tool-result-view.class.js +1 -1
  49. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
  50. package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +1 -1
  51. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  52. package/dist/components/charts/chart/box-plot.class.d.ts +4 -2
  53. package/dist/components/charts/chart/box-plot.class.js +6 -5
  54. package/dist/components/charts/chart/chart-token-cache.js +2 -2
  55. package/dist/components/charts/chart/chart.class.d.ts +6 -4
  56. package/dist/components/charts/chart/chart.class.js +8 -7
  57. package/dist/components/charts/chart/histogram.class.js +1 -1
  58. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  59. package/dist/components/conversation/agent-workspace/agent-workspace.class.js +1 -1
  60. package/dist/components/conversation/audio-visualizer/audio-visualizer.class.js +1 -1
  61. package/dist/components/conversation/branch-picker/branch-picker.class.js +1 -1
  62. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  63. package/dist/components/conversation/chat-message/chat-message.class.js +1 -1
  64. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  65. package/dist/components/conversation/checkpoint/checkpoint.class.js +1 -1
  66. package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
  67. package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
  68. package/dist/components/conversation/code-block/code-block.class.js +1 -1
  69. package/dist/components/conversation/conversation-item/conversation-item.class.js +1 -1
  70. package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
  71. package/dist/components/conversation/handoff-divider/handoff-divider.class.js +1 -1
  72. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  73. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  74. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  75. package/dist/components/conversation/message-actions/message-actions.class.js +1 -1
  76. package/dist/components/conversation/message-feedback/message-feedback.class.js +1 -1
  77. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  78. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  79. package/dist/components/conversation/model-settings-panel/model-settings-panel.class.js +1 -1
  80. package/dist/components/conversation/prompt-input/prompt-input.class.js +1 -1
  81. package/dist/components/conversation/prompt-queue/prompt-queue.class.js +1 -1
  82. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  83. package/dist/components/conversation/realtime-session/realtime-session.class.js +1 -1
  84. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  85. package/dist/components/conversation/stream-status/stream-status.class.js +1 -1
  86. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +1 -1
  87. package/dist/components/conversation/thread-list/thread-list.class.js +1 -1
  88. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  89. package/dist/components/conversation/typing-indicator/typing-indicator.class.js +1 -1
  90. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  91. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  92. package/dist/components/data/calendar/calendar.class.js +1 -1
  93. package/dist/components/data/condition-builder/condition-builder.class.js +1 -1
  94. package/dist/components/data/context-meter/context-meter.class.js +1 -1
  95. package/dist/components/data/data-grid/data-grid.class.d.ts +2 -2
  96. package/dist/components/data/data-grid/data-grid.class.js +3 -3
  97. package/dist/components/data/document-library/document-library.class.js +1 -1
  98. package/dist/components/data/env-list/env-list.class.js +1 -1
  99. package/dist/components/data/file-tree/file-tree.class.d.ts +2 -2
  100. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  101. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  102. package/dist/components/data/flow-controls/flow-controls.class.js +1 -1
  103. package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
  104. package/dist/components/data/flow-node/flow-node.class.js +1 -1
  105. package/dist/components/data/flow-run-status/flow-run-status.class.js +1 -1
  106. package/dist/components/data/funnel/funnel.class.js +1 -1
  107. package/dist/components/data/gauge/gauge.class.js +1 -1
  108. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  109. package/dist/components/data/heatmap/heatmap.class.d.ts +2 -1
  110. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  111. package/dist/components/data/heatmap/heatmap.styles.js +1 -1
  112. package/dist/components/data/pagination/pagination.class.d.ts +2 -0
  113. package/dist/components/data/pagination/pagination.class.js +1 -1
  114. package/dist/components/data/pagination/pagination.styles.js +1 -1
  115. package/dist/components/data/sequence-strip/sequence-strip.class.js +1 -1
  116. package/dist/components/data/sparkline/sparkline.class.js +1 -1
  117. package/dist/components/data/stat/stat.class.js +1 -1
  118. package/dist/components/data/table/table.class.d.ts +23 -2
  119. package/dist/components/data/table/table.class.js +5 -3
  120. package/dist/components/data/table/table.styles.js +1 -1
  121. package/dist/components/data/timeline/timeline.class.js +1 -1
  122. package/dist/components/data/tree/tree.class.js +1 -1
  123. package/dist/components/data/word-cloud/word-cloud.class.js +1 -1
  124. package/dist/components/forms/button/button.class.js +1 -1
  125. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  126. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  127. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  128. package/dist/components/forms/color-picker/color-picker.class.d.ts +8 -4
  129. package/dist/components/forms/color-picker/color-picker.class.js +2 -2
  130. package/dist/components/forms/combobox/combobox.class.js +1 -1
  131. package/dist/components/forms/country-picker/country-picker.class.js +1 -1
  132. package/dist/components/forms/currency-picker/currency-picker.class.js +1 -1
  133. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  134. package/dist/components/forms/date-picker/date-picker.class.js +1 -1
  135. package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
  136. package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +7 -4
  137. package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
  138. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -0
  139. package/dist/components/forms/icon-button/icon-button.class.js +1 -1
  140. package/dist/components/forms/icon-button/icon-button.styles.js +1 -1
  141. package/dist/components/forms/input/input-shared.js +1 -1
  142. package/dist/components/forms/input/input.class.js +1 -1
  143. package/dist/components/forms/input/native-time-input.class.js +1 -1
  144. package/dist/components/forms/input/number-input.class.js +1 -1
  145. package/dist/components/forms/input/time-input.class.js +1 -1
  146. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  147. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  148. package/dist/components/forms/phone-input/phone-input.class.js +1 -1
  149. package/dist/components/forms/radio/radio-group.class.js +1 -1
  150. package/dist/components/forms/radio/radio.class.js +1 -1
  151. package/dist/components/forms/rubric-form/rubric-form.class.js +4 -4
  152. package/dist/components/forms/select/select.class.js +1 -1
  153. package/dist/components/forms/signature-pad/signature-pad.class.js +1 -1
  154. package/dist/components/forms/slider/slider.class.js +1 -1
  155. package/dist/components/forms/switch/switch.class.js +1 -1
  156. package/dist/components/forms/textarea/textarea.class.js +1 -1
  157. package/dist/components/forms/time-range/time-range.class.js +1 -1
  158. package/dist/components/forms/time-zone-picker/time-zone-picker.class.js +1 -1
  159. package/dist/components/forms/token-input/token-input.class.js +1 -1
  160. package/dist/components/forms/unit-picker/unit-picker.class.js +1 -1
  161. package/dist/components/layout/app-rail/app-rail-item.class.js +1 -1
  162. package/dist/components/layout/app-rail/app-rail.class.d.ts +70 -7
  163. package/dist/components/layout/app-rail/app-rail.class.js +16 -4
  164. package/dist/components/layout/app-rail/app-rail.styles.js +1 -1
  165. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  166. package/dist/components/layout/breadcrumb/breadcrumb.class.js +1 -1
  167. package/dist/components/layout/card/card.class.js +1 -1
  168. package/dist/components/layout/carousel/carousel.class.js +1 -1
  169. package/dist/components/layout/command-palette/command-palette.class.js +1 -1
  170. package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
  171. package/dist/components/layout/details/accordion-item.class.js +1 -1
  172. package/dist/components/layout/details/details.class.js +1 -1
  173. package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
  174. package/dist/components/layout/drilldown-panel/drilldown-panel.class.js +1 -1
  175. package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
  176. package/dist/components/layout/menu/menu.class.js +1 -1
  177. package/dist/components/layout/menubar/menubar.class.js +1 -1
  178. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  179. package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
  180. package/dist/components/layout/page/page.class.js +1 -1
  181. package/dist/components/layout/reorder-list/reorder-item.class.js +1 -1
  182. package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
  183. package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
  184. package/dist/components/layout/scroller/scroller.class.js +1 -1
  185. package/dist/components/layout/segmented/segmented.class.d.ts +7 -4
  186. package/dist/components/layout/segmented/segmented.styles.js +1 -1
  187. package/dist/components/layout/split-panel/split-panel.class.js +1 -1
  188. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  189. package/dist/components/layout/tab-group/tab.class.js +1 -1
  190. package/dist/components/layout/virtual-list/virtual-list.styles.js +1 -1
  191. package/dist/components/layout/widget/widget.class.js +1 -1
  192. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  193. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  194. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  195. package/dist/components/media/av-player/av-player.class.js +1 -1
  196. package/dist/components/media/avatar-group/avatar-group.class.js +1 -1
  197. package/dist/components/media/drop-zone/drop-zone.class.js +1 -1
  198. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  199. package/dist/components/media/file-input/file-input.class.js +1 -1
  200. package/dist/components/media/flag/flag.class.js +1 -1
  201. package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
  202. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -1
  203. package/dist/components/media/image-viewer/image-viewer.class.js +4 -2
  204. package/dist/components/media/image-viewer/image-viewer.styles.js +1 -1
  205. package/dist/components/media/lightbox/lightbox.class.js +1 -1
  206. package/dist/components/media/map/map.class.js +1 -1
  207. package/dist/components/media/media-card/media-card.class.js +1 -1
  208. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  209. package/dist/components/media/qr-code/qr-code.class.d.ts +2 -2
  210. package/dist/components/media/qr-code/qr-code.class.js +1 -1
  211. package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
  212. package/dist/components/media/video/video.class.js +1 -1
  213. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  214. package/dist/components/media/zoomable-frame/zoomable-frame.class.js +1 -1
  215. package/dist/components/overlays/alert/alert.class.js +1 -1
  216. package/dist/components/overlays/badge/tag.class.js +1 -1
  217. package/dist/components/overlays/callout/callout.class.js +1 -1
  218. package/dist/components/overlays/chip/chip-group.class.js +1 -1
  219. package/dist/components/overlays/chip/chip.class.js +1 -1
  220. package/dist/components/overlays/context-menu/context-menu.class.js +1 -1
  221. package/dist/components/overlays/dialog/confirm.js +1 -1
  222. package/dist/components/overlays/dialog/dialog.class.js +1 -1
  223. package/dist/components/overlays/kbd/kbd.class.js +1 -1
  224. package/dist/components/overlays/overlay/popover.class.js +1 -1
  225. package/dist/components/overlays/overlay/tooltip.class.js +1 -1
  226. package/dist/components/overlays/progress/progress-bar.class.js +1 -1
  227. package/dist/components/overlays/progress/progress-ring.class.js +1 -1
  228. package/dist/components/overlays/rating/rating.class.js +1 -1
  229. package/dist/components/overlays/skeleton/skeleton.class.js +1 -1
  230. package/dist/components/overlays/spinner/spinner.class.js +1 -1
  231. package/dist/components/overlays/toast/toast-item.class.js +1 -1
  232. package/dist/components/overlays/toast/toast.class.js +1 -1
  233. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +1 -1
  234. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  235. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  236. package/dist/components/retrieval/community-card/community-card.class.js +1 -1
  237. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +1 -1
  238. package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
  239. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  240. package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
  241. package/dist/components/retrieval/graph/graph.class.js +1 -1
  242. package/dist/components/retrieval/graph-legend/graph-legend.class.js +1 -1
  243. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  244. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +1 -1
  245. package/dist/components/retrieval/knowledge-base/knowledge-base.class.js +1 -1
  246. package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +1 -1
  247. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
  248. package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
  249. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  250. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
  251. package/dist/components/retrieval/node-palette/node-palette.class.js +1 -1
  252. package/dist/components/retrieval/path-strip/path-strip.class.js +1 -1
  253. package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
  254. package/dist/components/retrieval/rag-answer/rag-answer.class.js +1 -1
  255. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
  256. package/dist/components/retrieval/research-progress/research-progress.class.js +1 -1
  257. package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.js +1 -1
  258. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  259. package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +1 -1
  260. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  261. package/dist/components/retrieval/source-card/source-card.class.js +1 -1
  262. package/dist/components/retrieval/source-list/source-list.class.js +1 -1
  263. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  264. package/dist/components/utility/copy-button/copy-button.class.js +1 -1
  265. package/dist/components/utility/diff-view/diff-view.class.js +1 -1
  266. package/dist/components/utility/export-button/export-button.class.js +1 -1
  267. package/dist/components/utility/icon/icon.class.js +1 -1
  268. package/dist/components/utility/json-viewer/json-viewer.class.js +1 -1
  269. package/dist/components/utility/known-date/known-date.class.js +1 -1
  270. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  271. package/dist/components/utility/poll-status/poll-status.class.js +1 -1
  272. package/dist/components/utility/random-content/random-content.class.js +1 -1
  273. package/dist/components/utility/tour/tour.class.js +1 -1
  274. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  275. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  276. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  277. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  278. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +2 -2
  279. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  280. package/dist/components/viewers/document-preview/document-preview.class.js +1 -1
  281. package/dist/components/viewers/document-viewer/document-viewer.class.js +1 -1
  282. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  283. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  284. package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
  285. package/dist/components/viewers/geojson-view/geojson-view.class.js +1 -1
  286. package/dist/components/viewers/geojson-view/geojson-viewer.class.js +1 -1
  287. package/dist/components/viewers/highlight-layer/highlight-layer.class.js +1 -1
  288. package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
  289. package/dist/components/viewers/include/include.class.js +1 -1
  290. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  291. package/dist/components/viewers/page-rail/page-rail.class.d.ts +1 -1
  292. package/dist/components/viewers/page-rail/page-rail.class.js +3 -3
  293. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  294. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  295. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
  296. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  297. package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
  298. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
  299. package/dist/events.d.ts +6 -1
  300. package/dist/framework-types.d.ts +1 -1
  301. package/dist/internal/accessibility-visibility.js +1 -1
  302. package/dist/internal/collection-snapshot.js +1 -1
  303. package/dist/internal/default-strings/agent-tools.generated.js +1 -0
  304. package/dist/internal/default-strings/charts.generated.js +1 -0
  305. package/dist/internal/default-strings/conversation.generated.js +1 -0
  306. package/dist/internal/default-strings/data.generated.js +1 -0
  307. package/dist/internal/default-strings/forms.generated.js +1 -0
  308. package/dist/internal/default-strings/layout.generated.js +1 -0
  309. package/dist/internal/default-strings/media.generated.js +1 -0
  310. package/dist/internal/default-strings/overlays.generated.js +1 -0
  311. package/dist/internal/default-strings/retrieval.generated.js +1 -0
  312. package/dist/internal/default-strings/shared.generated.js +1 -0
  313. package/dist/internal/default-strings/utility.generated.js +1 -0
  314. package/dist/internal/default-strings/viewers.generated.js +5 -0
  315. package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
  316. package/dist/internal/dev-mode-attribute-warning.production.js +1 -1
  317. package/dist/internal/document-tokens.d.ts +11 -0
  318. package/dist/internal/document-tokens.generated.js +15 -0
  319. package/dist/internal/document-tokens.js +3 -0
  320. package/dist/internal/form-associated.d.ts +1 -1
  321. package/dist/internal/form-associated.js +1 -1
  322. package/dist/internal/glass-surface.styles.js +1 -1
  323. package/dist/internal/host-tokens.styles.js +1 -0
  324. package/dist/internal/image-zoom.js +1 -0
  325. package/dist/internal/intl-cache.js +1 -1
  326. package/dist/internal/localization-types.d.ts +1 -1
  327. package/dist/internal/localization.js +2 -2
  328. package/dist/internal/lyra-element.d.ts +4 -2
  329. package/dist/internal/lyra-element.js +2 -2
  330. package/dist/internal/nonmodal-overlay-manager.js +1 -1
  331. package/dist/internal/opaque-content-border.styles.js +1 -1
  332. package/dist/internal/open-overlay-ancestors.js +1 -0
  333. package/dist/internal/open-overlay-raise.styles.js +1 -0
  334. package/dist/internal/optional-peer-failure.js +1 -0
  335. package/dist/internal/package-metadata.js +1 -1
  336. package/dist/internal/prefix.js +1 -1
  337. package/dist/internal/specialist-host-tokens.styles.js +1 -0
  338. package/dist/internal/specialist-tokens.generated.js +2 -0
  339. package/dist/internal/step-value.js +1 -1
  340. package/dist/internal/theme-observation.js +1 -1
  341. package/dist/internal/theme-scopes.d.ts +11 -0
  342. package/dist/internal/theme-scopes.js +1 -0
  343. package/dist/looks/shadcn.css +1 -1
  344. package/dist/lyra.d.ts +1 -1
  345. package/dist/lyra.js +1 -1
  346. package/dist/styles/design-tokens.css +1 -1
  347. package/dist/styles/tokens-root.css +1 -1
  348. package/dist/surfaces/glass.css +1 -1
  349. package/dist/testing/happy-dom-shims.d.ts +22 -1
  350. package/dist/testing/happy-dom-shims.js +1 -1
  351. package/dist/testing/index.d.ts +1 -1
  352. package/dist/testing/index.js +1 -1
  353. package/dist/testing/interaction-drivers.d.ts +66 -7
  354. package/dist/testing/interaction-drivers.js +1 -1
  355. package/dist/testing/jsdom-shims.d.ts +70 -0
  356. package/dist/testing/jsdom-shims.js +1 -0
  357. package/dist/theme/look-inputs.d.ts +1 -1
  358. package/dist/theme/look-inputs.js +37 -41
  359. package/dist/theme/theme.d.ts +13 -0
  360. package/dist/theme/theme.js +1 -1
  361. package/dist/theme.css +1 -1
  362. package/dist/utilities/index.d.ts +1 -1
  363. package/dist/utilities/index.js +1 -1
  364. package/dist/utilities/scoped-registry.d.ts +3 -0
  365. package/dist/utilities/scoped-registry.js +1 -1
  366. package/dist/utilities/theme-scopes.d.ts +1 -0
  367. package/dist/utilities/theme-scopes.js +1 -0
  368. package/dist/utilities/tokens.d.ts +1 -0
  369. package/dist/utilities/tokens.js +1 -0
  370. package/llms/components/lr-app-rail.md +51 -4
  371. package/llms/components/lr-box-plot.md +5 -0
  372. package/llms/components/lr-chart.md +6 -0
  373. package/llms/components/lr-emoji-picker.md +13 -8
  374. package/llms/components/lr-heatmap.md +10 -2
  375. package/llms/components/lr-icon-button.md +13 -1
  376. package/llms/components/lr-image-viewer.md +8 -0
  377. package/llms/components/lr-pagination.md +4 -2
  378. package/llms/components/lr-segmented.md +7 -3
  379. package/llms/components/lr-table.md +14 -12
  380. package/llms/components/lr-thread-list.md +4 -3
  381. package/llms/migration.md +9 -0
  382. package/llms/peers.md +1 -1
  383. package/llms/shared/events-and-types.md +41 -0
  384. package/llms/shared/frameworks-and-ssr.md +16 -0
  385. package/llms/shared/imports-and-registration.md +4 -3
  386. package/llms/shared/native-styles-and-utilities.md +38 -3
  387. package/llms/shared/styles-and-tokens.md +242 -102
  388. package/llms/shared/testing-and-utilities.md +104 -7
  389. package/llms/shared.md +445 -115
  390. package/llms/tokens.md +31 -49
  391. package/locales.json +138 -138
  392. package/package.json +16 -8
  393. package/registrations.json +1 -1
  394. package/dist/internal/default-strings.generated.js +0 -5
  395. package/dist/internal/specialist-tokens.styles.js +0 -1
  396. package/dist/internal/tokens/palette.styles.js +0 -1
  397. package/dist/internal/tokens.styles.js +0 -1
@@ -1,6 +1,6 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{parseCellRange}from"../../../internal/cell-range.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{styles}from"./dataset-viewer.styles.js";import{parseDelimitedRecords}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{TableViewerController}from"../table-viewer-shared.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{literalSetConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_datasetViewerCaption,LYRA_DEFAULT_datasetViewerCaptionNamed,LYRA_DEFAULT_datasetViewerEmpty,LYRA_DEFAULT_datasetViewerMissingParser,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDataset,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";const DATASET_VIEWER_SCROLL_MODE=literalSetConverter(["self","page"],"self");class LyraDatasetViewerBase extends LyraElement{}class LyraDatasetViewer extends DocumentAnchorTarget(LyraDatasetViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this._scrollMode="self",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.loadTask=new LatestTask,this.table=new TableViewerController(this,{emitSearch:detail=>this.emit("lr-search-change",detail),emitActivate:highlightId=>this.emit("lr-highlight-activate",{highlightId}),localize:(key,fallback,values)=>this.localize(key,fallback,values),locale:()=>this.effectiveLocale,schedule:(callback,key)=>this.scheduleAfterUpdate(callback,key),load:()=>this.load(),research:query=>this.search(query),jump:match=>this.jumpToCell(match.row,match.col),teardown:()=>this.loadTask.next()}),this.renderRow=(row,index,fields)=>{const rawRow=index+2,rowHighlights=this.table.highlightsForRow(rawRow);return html`<div part="data-row" role="presentation">
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{loadPapaParseCached}from"../../../internal/papaparse-loader.js";import{parseCellRange}from"../../../internal/cell-range.js";import{DocumentAnchorTarget}from"../../../internal/anchor-target.js";import{styles}from"./dataset-viewer.styles.js";import{parseDelimitedRecords}from"../../../internal/delimited-data.js";import{LatestTask}from"../../../internal/latest-task.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{TableViewerController}from"../table-viewer-shared.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{literalSetConverter}from"../../../internal/converters.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_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_cellHighlightWithLabel,LYRA_DEFAULT_datasetViewerCaption,LYRA_DEFAULT_datasetViewerCaptionNamed,LYRA_DEFAULT_datasetViewerEmpty,LYRA_DEFAULT_datasetViewerMissingParser,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDataset,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const DATASET_VIEWER_SCROLL_MODE=literalSetConverter(["self","page"],"self");class LyraDatasetViewerBase extends LyraElement{}class LyraDatasetViewer extends DocumentAnchorTarget(LyraDatasetViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this._scrollMode="self",this.anchorKinds=["cell-range"],this.fetchState={kind:"idle"},this.loadTask=new LatestTask,this.table=new TableViewerController(this,{emitSearch:detail=>this.emit("lr-search-change",detail),emitActivate:highlightId=>this.emit("lr-highlight-activate",{highlightId}),localize:(key,fallback,values)=>this.localize(key,fallback,values),locale:()=>this.effectiveLocale,schedule:(callback,key)=>this.scheduleAfterUpdate(callback,key),load:()=>this.load(),research:query=>this.search(query),jump:match=>this.jumpToCell(match.row,match.col),teardown:()=>this.loadTask.next()}),this.renderRow=(row,index,fields)=>{const rawRow=index+2,rowHighlights=this.table.highlightsForRow(rawRow);return html`<div part="data-row" role="presentation">
2
2
  ${fields.map((field,col)=>this.renderCell(row[field]??"",col,rowHighlights))}
3
- </div>`},this.stopInternalEvent=event=>{event.stopPropagation()},this.virtualListKeyFunction=(_item,index)=>index}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,datasetViewerCaption:LYRA_DEFAULT_datasetViewerCaption,datasetViewerCaptionNamed:LYRA_DEFAULT_datasetViewerCaptionNamed,datasetViewerEmpty:LYRA_DEFAULT_datasetViewerEmpty,datasetViewerMissingParser:LYRA_DEFAULT_datasetViewerMissingParser,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDataset:LYRA_DEFAULT_documentPreviewTypeDataset,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,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,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}get scrollMode(){return this._scrollMode}set scrollMode(next){const normalized=DATASET_VIEWER_SCROLL_MODE.normalizeReflected(this,"scroll-mode",next),previous=this._scrollMode;previous!==normalized&&(this._scrollMode=normalized,this.requestUpdate("scrollMode",previous))}connectedCallback(){super.connectedCallback(),this.table.connected()}disconnectedCallback(){this.table.disconnecting(),super.disconnectedCallback(),this.table.disconnected()}adoptedCallback(){super.adoptedCallback(),this.table.adopted()}willUpdate(changed){super.willUpdate(changed),this.table.willUpdate(changed,this.highlights,this.activeHighlightId,!1)}updated(changed){super.updated(changed),this.table.updated(changed,this.fetchState)}async load(){this.table.lastLoadSrc=this.src;const generation=this.loadTask.next(),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||!this.loadTask.isCurrent(generation))return;const parsed=await this.parse(source,generation);if(parsed===void 0)return;if(this.isConnected&&this.loadTask.isCurrent(generation)){const{table}=parsed;this.fetchState=table?{kind:"loaded",table}:{kind:"empty"},table&&this.table.search.query&&await this.search(this.table.search.query),parsed.errors.length&&this.isConnected&&this.loadTask.isCurrent(generation)&&this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code:"delimited-parse-diagnostic",severity:"warning",fatal:!1,source:"papaparse",cause:parsed.errors})})}}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(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(text,generation){const papa=await loadPapaParseCached();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!papa)throw new LyraUserFacingError(this.localize("datasetViewerMissingParser"));const result=parseDelimitedRecords(papa,text);return!result.fields.length||!result.rows.length?{table:null,errors:result.errors}:{table:{fields:result.fields,rows:result.rows},errors:result.errors}}renderCell(value,colIndex,rowHighlights,role="cell"){return this.table.renderCell(value,colIndex,rowHighlights,role,role==="columnheader"?"header-cell":"cell","--_lr-dataset-viewer-highlight-color",this.activeHighlightId)}async jumpToCell(rawRow,col){const loadedState=this.fetchState;if(loadedState.kind!=="loaded")return!1;const{fields,rows}=loadedState.table;if(rawRow<1||rawRow>rows.length+1||col<0||col>=fields.length)return!1;const bodyIndex=rawRow-2;return bodyIndex<0?this.table.revealCell(this.renderRoot.querySelector('[part="header-row"]')?.querySelectorAll('[part~="header-cell"]')[col]):(this.table.setActiveRow(bodyIndex),await this.updateComplete,await this.scrollColumnIntoView(col),this.fetchState===loadedState)}async scrollColumnIntoView(col){await this.table.scrollColumnIntoView(this.renderRoot,tag("virtual-list"),col)}async applyAnchor(anchor){if(anchor.kind!=="cell-range"||anchor.sheet)return!1;const parsed=parseCellRange(anchor.range);return parsed?this.jumpToCell(parsed.startRow+1,parsed.startCol):!1}async search(query){return this.table.runSearch(query,this.fetchState.kind==="loaded",visit=>{if(this.fetchState.kind!=="loaded")return;const{fields,rows}=this.fetchState.table;for(let c=0;c<fields.length;c++)if(!visit(fields[c],{row:1,col:c}))return;for(let r=0;r<rows.length;r++){const row=rows[r];for(let c=0;c<fields.length;c++)if(!visit(row[fields[c]]??"",{row:r+2,col:c}))return}})}async searchNext(){return this.table.step(1)}async searchPrevious(){return this.table.step(-1)}clearSearch(){this.table.clearSearch()}renderBody(){switch(this.fetchState.kind){case"loaded":{const{fields,rows}=this.fetchState.table,localizedCount=getNumberFormat(this.effectiveLocale).format(rows.length),label=this.name?this.localize("datasetViewerCaptionNamed",void 0,{name:this.name,count:localizedCount}):this.localize("datasetViewerCaption",void 0,{count:localizedCount}),headerHighlights=this.table.highlightsForRow(1);return html`
3
+ </div>`},this.stopInternalEvent=event=>{event.stopPropagation()},this.virtualListKeyFunction=(_item,index)=>index}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,cellHighlightWithLabel:LYRA_DEFAULT_cellHighlightWithLabel,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,datasetViewerCaption:LYRA_DEFAULT_datasetViewerCaption,datasetViewerCaptionNamed:LYRA_DEFAULT_datasetViewerCaptionNamed,datasetViewerEmpty:LYRA_DEFAULT_datasetViewerEmpty,datasetViewerMissingParser:LYRA_DEFAULT_datasetViewerMissingParser,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDataset:LYRA_DEFAULT_documentPreviewTypeDataset,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,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,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}get scrollMode(){return this._scrollMode}set scrollMode(next){const normalized=DATASET_VIEWER_SCROLL_MODE.normalizeReflected(this,"scroll-mode",next),previous=this._scrollMode;previous!==normalized&&(this._scrollMode=normalized,this.requestUpdate("scrollMode",previous))}connectedCallback(){super.connectedCallback(),this.table.connected()}disconnectedCallback(){this.table.disconnecting(),super.disconnectedCallback(),this.table.disconnected()}adoptedCallback(){super.adoptedCallback(),this.table.adopted()}willUpdate(changed){super.willUpdate(changed),this.table.willUpdate(changed,this.highlights,this.activeHighlightId,!1)}updated(changed){super.updated(changed),this.table.updated(changed,this.fetchState)}async load(){this.table.lastLoadSrc=this.src;const generation=this.loadTask.next(),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||!this.loadTask.isCurrent(generation))return;const parsed=await this.parse(source,generation);if(parsed===void 0)return;if(this.isConnected&&this.loadTask.isCurrent(generation)){const{table}=parsed;this.fetchState=table?{kind:"loaded",table}:{kind:"empty"},table&&this.table.search.query&&await this.search(this.table.search.query),parsed.errors.length&&this.isConnected&&this.loadTask.isCurrent(generation)&&this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code:"delimited-parse-diagnostic",severity:"warning",fatal:!1,source:"papaparse",cause:parsed.errors})})}}catch(error){if(isAbortError(error)||!this.isConnected||!this.loadTask.isCurrent(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(text,generation){const papa=await loadPapaParseCached();if(!this.isConnected||!this.loadTask.isCurrent(generation))return;if(!papa)throw new LyraUserFacingError(this.localize("datasetViewerMissingParser"));const result=parseDelimitedRecords(papa,text);return!result.fields.length||!result.rows.length?{table:null,errors:result.errors}:{table:{fields:result.fields,rows:result.rows},errors:result.errors}}renderCell(value,colIndex,rowHighlights,role="cell"){return this.table.renderCell(value,colIndex,rowHighlights,role,role==="columnheader"?"header-cell":"cell","--_lr-dataset-viewer-highlight-color",this.activeHighlightId)}async jumpToCell(rawRow,col){const loadedState=this.fetchState;if(loadedState.kind!=="loaded")return!1;const{fields,rows}=loadedState.table;if(rawRow<1||rawRow>rows.length+1||col<0||col>=fields.length)return!1;const bodyIndex=rawRow-2;return bodyIndex<0?this.table.revealCell(this.renderRoot.querySelector('[part="header-row"]')?.querySelectorAll('[part~="header-cell"]')[col]):(this.table.setActiveRow(bodyIndex),await this.updateComplete,await this.scrollColumnIntoView(col),this.fetchState===loadedState)}async scrollColumnIntoView(col){await this.table.scrollColumnIntoView(this.renderRoot,tag("virtual-list"),col)}async applyAnchor(anchor){if(anchor.kind!=="cell-range"||anchor.sheet)return!1;const parsed=parseCellRange(anchor.range);return parsed?this.jumpToCell(parsed.startRow+1,parsed.startCol):!1}async search(query){return this.table.runSearch(query,this.fetchState.kind==="loaded",visit=>{if(this.fetchState.kind!=="loaded")return;const{fields,rows}=this.fetchState.table;for(let c=0;c<fields.length;c++)if(!visit(fields[c],{row:1,col:c}))return;for(let r=0;r<rows.length;r++){const row=rows[r];for(let c=0;c<fields.length;c++)if(!visit(row[fields[c]]??"",{row:r+2,col:c}))return}})}async searchNext(){return this.table.step(1)}async searchPrevious(){return this.table.step(-1)}clearSearch(){this.table.clearSearch()}renderBody(){switch(this.fetchState.kind){case"loaded":{const{fields,rows}=this.fetchState.table,localizedCount=getNumberFormat(this.effectiveLocale).format(rows.length),label=this.name?this.localize("datasetViewerCaptionNamed",void 0,{name:this.name,count:localizedCount}):this.localize("datasetViewerCaption",void 0,{count:localizedCount}),headerHighlights=this.table.highlightsForRow(1);return html`
4
4
  <div
5
5
  part="table"
6
6
  role="table"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{literalSetConverter}from"../../../internal/converters.js";import{styles}from"./document-compare.styles.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentCompareLabel,LYRA_DEFAULT_documentCompareNewVersion,LYRA_DEFAULT_documentCompareNoVersion,LYRA_DEFAULT_documentCompareOldVersion,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const DOCUMENT_COMPARE_VIEW=literalSetConverter(["diff","side-by-side"],"diff"),DOCUMENT_COMPARE_DIFF_LAYOUT=literalSetConverter(["unified","split"],"unified"),DOCUMENT_COMPARE_VERSION_FIELDS=["id","name","mimeType","uri","version","text","highlights"];function projectDocumentCompareVersion(value){try{if(value===null||typeof value!="object"||Array.isArray(value))return;const descriptors=new Map;for(const field of DOCUMENT_COMPARE_VERSION_FIELDS)descriptors.set(field,getOwnDataDescriptor(value,field));const fieldValue=field=>{const descriptor=descriptors.get(field);if(!(descriptor===void 0||descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR))return descriptor.value},idDescriptor=descriptors.get("id"),nameDescriptor=descriptors.get("name");if(idDescriptor===void 0||idDescriptor===MISSING_OWN_DATA_DESCRIPTOR||idDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||nameDescriptor===void 0||nameDescriptor===MISSING_OWN_DATA_DESCRIPTOR||nameDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return;const id=fieldValue("id"),name=fieldValue("name");if(typeof id!="string"||typeof name!="string")return;const mimeType=fieldValue("mimeType"),uri=fieldValue("uri"),version=fieldValue("version"),text=fieldValue("text"),highlights=fieldValue("highlights");return Object.freeze({id,name,...typeof mimeType=="string"?{mimeType}:{},...typeof uri=="string"?{uri}:{},...typeof version=="string"?{version}:{},...typeof text=="string"?{text}:{},...highlights===void 0?{}:{highlights:snapshotLyraHighlights(highlights)}})}catch{return}}function versionSourceIdentity(version){return version?JSON.stringify([version.id??"",version.uri??"",version.version??"",version.mimeType??"",version.name??""]):""}class LyraDocumentCompare extends LyraElement{constructor(){super(...arguments),this._view="diff",this._diffLayout="unified",this.copyable=!1,this._language="",this.withoutSyncScroll=!1,this.maxHeight="",this.anchor=null,this.suppressSync=!1,this.onPaneScroll=source=>()=>{if(this.withoutSyncScroll||this.suppressSync)return;const from=source==="old"?this.paneOldEl:this.paneNewEl,to=source==="old"?this.paneNewEl:this.paneOldEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const fraction=from.scrollTop/fromMax;this.suppressSync=!0,to.scrollTop=fraction*toMax,this.scheduleSyncRelease()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentCompareLabel:LYRA_DEFAULT_documentCompareLabel,documentCompareNewVersion:LYRA_DEFAULT_documentCompareNewVersion,documentCompareNoVersion:LYRA_DEFAULT_documentCompareNoVersion,documentCompareOldVersion:LYRA_DEFAULT_documentCompareOldVersion,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get view(){return this._view}set view(next){const normalized=DOCUMENT_COMPARE_VIEW.normalizeReflected(this,"view",next),old=this._view;old!==normalized&&(this._view=normalized,this.requestUpdate("view",old))}get oldVersion(){return this._oldVersion}set oldVersion(value){if(value===this._oldVersionSource||value===this._oldVersion)return;const previous=this._oldVersion;this._oldVersionSource=value,this._oldVersion=projectDocumentCompareVersion(value),this.requestUpdate("oldVersion",previous)}get newVersion(){return this._newVersion}set newVersion(value){if(value===this._newVersionSource||value===this._newVersion)return;const previous=this._newVersion;this._newVersionSource=value,this._newVersion=projectDocumentCompareVersion(value),this.requestUpdate("newVersion",previous)}get diffLayout(){return this._diffLayout}set diffLayout(next){const normalized=DOCUMENT_COMPARE_DIFF_LAYOUT.normalizeReflected(this,"diff-layout",next),old=this._diffLayout;old!==normalized&&(this._diffLayout=normalized,this.requestUpdate("diffLayout",old))}get language(){return this._language}set language(value){const normalized=typeof value=="string"?value:"",previous=this._language;previous!==normalized&&(this._language=normalized,this.requestUpdate("language",previous))}disconnectedCallback(){this.cancelSyncRelease(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelSyncRelease()}cancelSyncRelease(){this.syncReleaseFrame!==void 0&&this.syncReleaseView?.cancelAnimationFrame(this.syncReleaseFrame),this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1}scheduleSyncRelease(){const view=this.ownerDocument.defaultView;if(!view){this.suppressSync=!1;return}const frame=view.requestAnimationFrame(()=>{this.syncReleaseView!==view||this.syncReleaseFrame!==frame||(this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1)});this.syncReleaseView=view,this.syncReleaseFrame=frame}updated(changed){super.updated(changed);const anchor=this.anchor,sourceChanged=property2=>changed.has(property2)&&versionSourceIdentity(changed.get(property2))!==versionSourceIdentity(this[property2]),oldSourceChanged=sourceChanged("oldVersion"),newSourceChanged=sourceChanged("newVersion");if(this.view==="side-by-side"){if(anchor!=null){(changed.has("anchor")||changed.has("view")||oldSourceChanged||newSourceChanged)&&(this.previewOldEl?.scrollToAnchor(anchor),this.previewNewEl?.scrollToAnchor(anchor));return}!oldSourceChanged&&!newSourceChanged||(this.cancelSyncRelease(),(!this.withoutSyncScroll||oldSourceChanged)&&this.paneOldEl&&(this.paneOldEl.scrollTop=0),(!this.withoutSyncScroll||newSourceChanged)&&this.paneNewEl&&(this.paneNewEl.scrollTop=0))}}onHighlightActivate(side,event){const{highlightId}=event.detail,otherPreview=side==="old"?this.previewNewEl:this.previewOldEl;otherPreview?.highlights.some(highlight=>highlight.id===highlightId)&&otherPreview?.scrollToAnchor(highlightId)}async scrollToAnchor(target){return await this.updateComplete,this.diffEl?this.diffEl.scrollToAnchor(target):(await Promise.all([this.previewOldEl?.scrollToAnchor(target),this.previewNewEl?.scrollToAnchor(target)])).includes(!0)}async search(query2){return await this.updateComplete,this.diffEl?.search(query2)??0}async searchNext(){return this.diffEl?.searchNext()??!1}async searchPrevious(){return this.diffEl?.searchPrevious()??!1}clearSearch(){this.diffEl?.clearSearch()}versionLabel(version,fallbackKey){return version?.name||version?.version||this.localize(fallbackKey)}renderDiff(){return html`
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{literalSetConverter}from"../../../internal/converters.js";import{styles}from"./document-compare.styles.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,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_documentCompareLabel,LYRA_DEFAULT_documentCompareNewVersion,LYRA_DEFAULT_documentCompareNoVersion,LYRA_DEFAULT_documentCompareOldVersion}from"../../../internal/default-strings/viewers.generated.js";const DOCUMENT_COMPARE_VIEW=literalSetConverter(["diff","side-by-side"],"diff"),DOCUMENT_COMPARE_DIFF_LAYOUT=literalSetConverter(["unified","split"],"unified"),DOCUMENT_COMPARE_VERSION_FIELDS=["id","name","mimeType","uri","version","text","highlights"];function projectDocumentCompareVersion(value){try{if(value===null||typeof value!="object"||Array.isArray(value))return;const descriptors=new Map;for(const field of DOCUMENT_COMPARE_VERSION_FIELDS)descriptors.set(field,getOwnDataDescriptor(value,field));const fieldValue=field=>{const descriptor=descriptors.get(field);if(!(descriptor===void 0||descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR))return descriptor.value},idDescriptor=descriptors.get("id"),nameDescriptor=descriptors.get("name");if(idDescriptor===void 0||idDescriptor===MISSING_OWN_DATA_DESCRIPTOR||idDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR||nameDescriptor===void 0||nameDescriptor===MISSING_OWN_DATA_DESCRIPTOR||nameDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return;const id=fieldValue("id"),name=fieldValue("name");if(typeof id!="string"||typeof name!="string")return;const mimeType=fieldValue("mimeType"),uri=fieldValue("uri"),version=fieldValue("version"),text=fieldValue("text"),highlights=fieldValue("highlights");return Object.freeze({id,name,...typeof mimeType=="string"?{mimeType}:{},...typeof uri=="string"?{uri}:{},...typeof version=="string"?{version}:{},...typeof text=="string"?{text}:{},...highlights===void 0?{}:{highlights:snapshotLyraHighlights(highlights)}})}catch{return}}function versionSourceIdentity(version){return version?JSON.stringify([version.id??"",version.uri??"",version.version??"",version.mimeType??"",version.name??""]):""}class LyraDocumentCompare extends LyraElement{constructor(){super(...arguments),this._view="diff",this._diffLayout="unified",this.copyable=!1,this._language="",this.withoutSyncScroll=!1,this.maxHeight="",this.anchor=null,this.suppressSync=!1,this.onPaneScroll=source=>()=>{if(this.withoutSyncScroll||this.suppressSync)return;const from=source==="old"?this.paneOldEl:this.paneNewEl,to=source==="old"?this.paneNewEl:this.paneOldEl;if(!from||!to)return;const fromMax=from.scrollHeight-from.clientHeight,toMax=to.scrollHeight-to.clientHeight;if(fromMax<=0)return;const fraction=from.scrollTop/fromMax;this.suppressSync=!0,to.scrollTop=fraction*toMax,this.scheduleSyncRelease()}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentCompareLabel:LYRA_DEFAULT_documentCompareLabel,documentCompareNewVersion:LYRA_DEFAULT_documentCompareNewVersion,documentCompareNoVersion:LYRA_DEFAULT_documentCompareNoVersion,documentCompareOldVersion:LYRA_DEFAULT_documentCompareOldVersion,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get view(){return this._view}set view(next){const normalized=DOCUMENT_COMPARE_VIEW.normalizeReflected(this,"view",next),old=this._view;old!==normalized&&(this._view=normalized,this.requestUpdate("view",old))}get oldVersion(){return this._oldVersion}set oldVersion(value){if(value===this._oldVersionSource||value===this._oldVersion)return;const previous=this._oldVersion;this._oldVersionSource=value,this._oldVersion=projectDocumentCompareVersion(value),this.requestUpdate("oldVersion",previous)}get newVersion(){return this._newVersion}set newVersion(value){if(value===this._newVersionSource||value===this._newVersion)return;const previous=this._newVersion;this._newVersionSource=value,this._newVersion=projectDocumentCompareVersion(value),this.requestUpdate("newVersion",previous)}get diffLayout(){return this._diffLayout}set diffLayout(next){const normalized=DOCUMENT_COMPARE_DIFF_LAYOUT.normalizeReflected(this,"diff-layout",next),old=this._diffLayout;old!==normalized&&(this._diffLayout=normalized,this.requestUpdate("diffLayout",old))}get language(){return this._language}set language(value){const normalized=typeof value=="string"?value:"",previous=this._language;previous!==normalized&&(this._language=normalized,this.requestUpdate("language",previous))}disconnectedCallback(){this.cancelSyncRelease(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cancelSyncRelease()}cancelSyncRelease(){this.syncReleaseFrame!==void 0&&this.syncReleaseView?.cancelAnimationFrame(this.syncReleaseFrame),this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1}scheduleSyncRelease(){const view=this.ownerDocument.defaultView;if(!view){this.suppressSync=!1;return}const frame=view.requestAnimationFrame(()=>{this.syncReleaseView!==view||this.syncReleaseFrame!==frame||(this.syncReleaseFrame=void 0,this.syncReleaseView=void 0,this.suppressSync=!1)});this.syncReleaseView=view,this.syncReleaseFrame=frame}updated(changed){super.updated(changed);const anchor=this.anchor,sourceChanged=property2=>changed.has(property2)&&versionSourceIdentity(changed.get(property2))!==versionSourceIdentity(this[property2]),oldSourceChanged=sourceChanged("oldVersion"),newSourceChanged=sourceChanged("newVersion");if(this.view==="side-by-side"){if(anchor!=null){(changed.has("anchor")||changed.has("view")||oldSourceChanged||newSourceChanged)&&(this.previewOldEl?.scrollToAnchor(anchor),this.previewNewEl?.scrollToAnchor(anchor));return}!oldSourceChanged&&!newSourceChanged||(this.cancelSyncRelease(),(!this.withoutSyncScroll||oldSourceChanged)&&this.paneOldEl&&(this.paneOldEl.scrollTop=0),(!this.withoutSyncScroll||newSourceChanged)&&this.paneNewEl&&(this.paneNewEl.scrollTop=0))}}onHighlightActivate(side,event){const{highlightId}=event.detail,otherPreview=side==="old"?this.previewNewEl:this.previewOldEl;otherPreview?.highlights.some(highlight=>highlight.id===highlightId)&&otherPreview?.scrollToAnchor(highlightId)}async scrollToAnchor(target){return await this.updateComplete,this.diffEl?this.diffEl.scrollToAnchor(target):(await Promise.all([this.previewOldEl?.scrollToAnchor(target),this.previewNewEl?.scrollToAnchor(target)])).includes(!0)}async search(query2){return await this.updateComplete,this.diffEl?.search(query2)??0}async searchNext(){return this.diffEl?.searchNext()??!1}async searchPrevious(){return this.diffEl?.searchPrevious()??!1}clearSearch(){this.diffEl?.clearSearch()}versionLabel(version,fallbackKey){return version?.name||version?.version||this.localize(fallbackKey)}renderDiff(){return html`
2
2
  <lr-diff-view
3
3
  part="diff"
4
4
  .oldText=${this.oldVersion?.text??""}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing,svg}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{fileIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{safeDownloadHref,safeFetchUrl,safeMediaSrc}from"../../../internal/safe-url.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./document-preview.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{regionHighlightLabel,renderRegionHighlightActions,renderRegionHighlightLayer,sameRegionRect}from"../region-highlight-layer.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{snapshotLyraHighlightAnchorKind,snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_convertingDocument,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewAlt,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewGenericError,LYRA_DEFAULT_documentPreviewGenericFile,LYRA_DEFAULT_documentPreviewNotAvailable,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewTypeImage,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_download,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const IDLE_TEXT_FETCH={kind:"idle"};function classifyFormat(mimeType){const mt=(mimeType??"").split(";",1)[0].trim().toLowerCase();return mt.startsWith("text/")||mt==="application/json"?"text":mt.startsWith("image/")?"image":"generic"}const EMPTY_REGION_HIGHLIGHTS=Object.freeze([]);function projectRegionAnchor(value,knownRegionKind=!1){try{if(value===null||typeof value!="object"||Array.isArray(value))return;if(!knownRegionKind){const kind=getOwnDataDescriptor(value,"kind");if(kind===MISSING_OWN_DATA_DESCRIPTOR||kind===UNSAFE_OWN_DATA_DESCRIPTOR||kind.value!=="region")return}const rectDescriptor=getOwnDataDescriptor(value,"rect");if(rectDescriptor===MISSING_OWN_DATA_DESCRIPTOR||rectDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return;const rect=sanitizePercentRect(rectDescriptor.value);if(!rect)return;const pageDescriptor=getOwnDataDescriptor(value,"page"),page=pageDescriptor===MISSING_OWN_DATA_DESCRIPTOR||pageDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:pageDescriptor.value;return Object.freeze({rect,...typeof page=="number"&&Number.isFinite(page)?{page}:{}})}catch{return}}const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function downloadIcon(){return icon(svg`
1
+ import{__decorate}from"tslib";import{html,nothing,svg}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{fileIcon}from"../../../internal/icons.js";import{srOnly}from"../../../internal/a11y.js";import{safeDownloadHref,safeFetchUrl,safeMediaSrc}from"../../../internal/safe-url.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseText,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./document-preview.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{regionHighlightLabel,renderRegionHighlightActions,renderRegionHighlightLayer,sameRegionRect}from"../region-highlight-layer.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{snapshotLyraHighlightAnchorKind,snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewTypeImage,LYRA_DEFAULT_download,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_convertingDocument,LYRA_DEFAULT_documentPreviewAlt,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewGenericError,LYRA_DEFAULT_documentPreviewGenericFile,LYRA_DEFAULT_documentPreviewNotAvailable,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const IDLE_TEXT_FETCH={kind:"idle"};function classifyFormat(mimeType){const mt=(mimeType??"").split(";",1)[0].trim().toLowerCase();return mt.startsWith("text/")||mt==="application/json"?"text":mt.startsWith("image/")?"image":"generic"}const EMPTY_REGION_HIGHLIGHTS=Object.freeze([]);function projectRegionAnchor(value,knownRegionKind=!1){try{if(value===null||typeof value!="object"||Array.isArray(value))return;if(!knownRegionKind){const kind=getOwnDataDescriptor(value,"kind");if(kind===MISSING_OWN_DATA_DESCRIPTOR||kind===UNSAFE_OWN_DATA_DESCRIPTOR||kind.value!=="region")return}const rectDescriptor=getOwnDataDescriptor(value,"rect");if(rectDescriptor===MISSING_OWN_DATA_DESCRIPTOR||rectDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR)return;const rect=sanitizePercentRect(rectDescriptor.value);if(!rect)return;const pageDescriptor=getOwnDataDescriptor(value,"page"),page=pageDescriptor===MISSING_OWN_DATA_DESCRIPTOR||pageDescriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:pageDescriptor.value;return Object.freeze({rect,...typeof page=="number"&&Number.isFinite(page)?{page}:{}})}catch{return}}const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function downloadIcon(){return icon(svg`
2
2
  <path d="M12 3v12"></path>
3
3
  <polyline points="7 11 12 16 17 11"></polyline>
4
4
  <path d="M4 18v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"></path>
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{documentRendererRegistrySource}from"./registry-ownership.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{adaptDocumentRenderer,createDocumentRendererRegistry,findDocumentRenderer,loadDocumentRenderer,snapshotLyraDocumentRendererPayload}from"./registry.js";import{styles}from"./document-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{LYRA_DEFAULT_documentPreviewGenericError,LYRA_DEFAULT_documentViewerLabel,LYRA_DEFAULT_download,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings.generated.js";class LyraDocumentViewer extends LyraElement{constructor(){super(...arguments),this.open=!1,this.name="",this.mimeType="",this.src="",this.anchor=null,this._highlights=snapshotLyraHighlights([]),this.renderState={kind:"fallback"},this.generation=0,this.builtInRegistry=createDocumentRendererRegistry(),this.announcements=new ViewerAnnouncementController(this),this.containShellEvent=event=>{event.target===event.currentTarget&&event.stopPropagation()},this.onDialogClose=event=>{event.target===event.currentTarget&&(event.stopPropagation(),this.open=!1,this.emit("lr-close",event.detail))},this.onDownload=()=>{const file=this.currentFile();this.emit("lr-download",{src:file.src,filename:file.name})}}static{this.defaultStrings={...super.defaultStrings,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentViewerLabel:LYRA_DEFAULT_documentViewerLabel,download:LYRA_DEFAULT_download,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["highlights","registry"])}static{this.styles=[LyraElement.styles,styles,viewerLoadingStyles]}get payload(){return this._payload}set payload(value){if(value===this.payloadSource||value===this._payload)return;const old=this._payload;this._payload=value===void 0?void 0:snapshotLyraDocumentRendererPayload(value),this.payloadSource=value,this.requestUpdate("payload",old)}static{Object.defineProperty(this.prototype,"registry",{configurable:!0,enumerable:!0,get(){return this._registry},set(value){if(value===this.registrySource||value===this._registry)return;const old=this._registry;this._registry=snapshotPublicCollection(documentRendererRegistrySource(value),this.ownerDocument?.defaultView),this.registrySource=value,this.requestUpdate("registry",old)}})}get highlights(){return this._highlights}set highlights(value){if(value===this.highlightsSource||value===this._highlights)return;const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this.highlightsSource=value,this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.open&&this.resolve()}disconnectedCallback(){this.generation++,this.renderState={kind:"fallback"},this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){if(super.willUpdate(changed),!this.open){changed.has("open")&&(this.generation++,this.renderState={kind:"fallback"});return}const legacyFileChanged=this.payload===void 0&&(changed.has("name")||changed.has("mimeType")||changed.has("src")||changed.has("anchor")||changed.has("highlights")||changed.has("alt"));(!this.hasUpdated||changed.has("open")||changed.has("payload")||changed.has("registry")||legacyFileChanged)&&this.resolve()}updated(changed){super.updated(changed),this.announcements.transition("renderer",this.renderState.kind,this.renderState.kind==="error"?this.localize("documentPreviewGenericError"):this.localize("loadingDocument"))}currentFile(){if(this.payload){const file=this.payload.file;return{name:file.name,mimeType:file.mimeType,src:file.src,...file.anchor!==void 0?{anchor:file.anchor}:{},...file.highlights?{highlights:[...file.highlights]}:{},...file.alt!==void 0?{alt:file.alt}:{}}}return{name:this.name,mimeType:this.mimeType,src:this.src,anchor:this.anchor??void 0,highlights:this.highlights,alt:this.alt}}async resolve(){if(!this.isConnected||!this.open)return;const generation=++this.generation;this.rendererCapabilities=void 0;const file=this.currentFile(),registry=this.registry??this.builtInRegistry;let def;try{def=findDocumentRenderer(file,registry)}catch(error){this.failResolution(file,generation,error);return}if(!def){this.resolvedLazy=void 0,this.renderState={kind:"fallback"},this.finishAnchorResult(void 0,file,generation,!0);return}if(this.resolvedLazy?.def===def){this.finishRender(def,this.renderWith(this.resolvedLazy.resolved,file),file,generation);return}if(!def.load){this.resolvedLazy={def,resolved:def},this.finishRender(def,this.renderWith(def,file),file,generation);return}this.renderState={kind:"loading"};let resolved;try{resolved=await loadDocumentRenderer(def)}catch(error){generation===this.generation&&this.isConnected&&this.open&&(this.renderState={kind:"error"},this.emit("lr-render-error",{error}),this.finishAnchorResult(void 0,file,generation));return}generation!==this.generation||!this.isConnected||!this.open||(this.resolvedLazy={def,resolved},this.finishRender(def,this.renderWith(resolved,file),file,generation))}finishRender(def,rendered,file,generation){if("error"in rendered){this.failResolution(file,generation,rendered.error);return}const capabilities=rendered.capabilities??def.capabilities;this.rendererCapabilities=capabilities,this.finishAnchorResult(capabilities,file,generation)}failResolution(file,generation,error){generation!==this.generation||!this.isConnected||!this.open||(this.renderState={kind:"error"},this.emit("lr-render-error",{error}),file.anchor!=null&&this.scheduleAfterUpdate(()=>{generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found:!1})}))}finishAnchorResult(capabilities,file,generation,fallback=!1){if(file.anchor!=null&&!(generation!==this.generation||!this.isConnected||!this.open)){if(fallback){this.scheduleAfterUpdate(()=>{(async()=>{const found=await this.fallbackPreviewEl?.scrollToAnchor(file.anchor)??!1;generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found})})()});return}this.isAnchorCapable(capabilities,file.anchor)||this.scheduleAfterUpdate(()=>{generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found:!1})})}}isAnchorCapable(capabilities,anchor){const anchors=capabilities?.anchors;return!anchors||anchors.length===0?!1:typeof anchor=="string"?!0:anchors.includes(anchor.kind)}renderWith(definition,file){try{const adapted=adaptDocumentRenderer(definition,file,this.payload);return this.renderState={kind:"rendered",template:adapted.render()},{capabilities:adapted.capabilities}}catch(error){return{error}}}renderedElement(){if(!(!this.open||this.renderState.kind!=="rendered"))return this.renderRoot.querySelector('[part="body"]')?.firstElementChild??void 0}currentSearchTarget(){if(this.rendererCapabilities?.search!==!0)return;const element=this.renderedElement();return typeof element?.search=="function"?element:void 0}async scrollToAnchor(target){if(await this.updateComplete,!this.open)return!1;if(this.renderState.kind==="fallback"){const found=await this.fallbackPreviewEl?.scrollToAnchor(target)??!1;return this.emit("lr-anchor-result",{found}),found}const element=this.renderedElement();return this.isAnchorCapable(this.rendererCapabilities,target)&&typeof element?.scrollToAnchor=="function"?element.scrollToAnchor(target):(this.emit("lr-anchor-result",{found:!1}),!1)}async searchTarget(){return await this.updateComplete,this.currentSearchTarget()}async search(query2){return await(await this.searchTarget())?.search(query2)??0}async searchNext(){return await(await this.searchTarget())?.searchNext()??!1}async searchPrevious(){return await(await this.searchTarget())?.searchPrevious()??!1}clearSearch(){this.currentSearchTarget()?.clearSearch()}renderBody(){const file=this.currentFile();switch(this.renderState.kind){case"rendered":return this.renderState.template;case"loading":return renderViewerLoading(this.localize("loadingDocument"));case"error":return html`<div part="error">${this.localize("documentPreviewGenericError")}</div>`;default:return html`
1
+ import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{documentRendererRegistrySource}from"./registry-ownership.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{safeDownloadHref}from"../../../internal/safe-url.js";import{adaptDocumentRenderer,createDocumentRendererRegistry,findDocumentRenderer,loadDocumentRenderer,snapshotLyraDocumentRendererPayload}from"./registry.js";import{styles}from"./document-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{snapshotLyraHighlights}from"../../../internal/highlight-collection.js";import{LYRA_DEFAULT_download}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewGenericError,LYRA_DEFAULT_documentViewerLabel,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";class LyraDocumentViewer extends LyraElement{constructor(){super(...arguments),this.open=!1,this.name="",this.mimeType="",this.src="",this.anchor=null,this._highlights=snapshotLyraHighlights([]),this.renderState={kind:"fallback"},this.generation=0,this.builtInRegistry=createDocumentRendererRegistry(),this.announcements=new ViewerAnnouncementController(this),this.containShellEvent=event=>{event.target===event.currentTarget&&event.stopPropagation()},this.onDialogClose=event=>{event.target===event.currentTarget&&(event.stopPropagation(),this.open=!1,this.emit("lr-close",event.detail))},this.onDownload=()=>{const file=this.currentFile();this.emit("lr-download",{src:file.src,filename:file.name})}}static{this.defaultStrings={...super.defaultStrings,documentPreviewGenericError:LYRA_DEFAULT_documentPreviewGenericError,documentViewerLabel:LYRA_DEFAULT_documentViewerLabel,download:LYRA_DEFAULT_download,loadingDocument:LYRA_DEFAULT_loadingDocument}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["highlights","registry"])}static{this.styles=[LyraElement.styles,styles,viewerLoadingStyles]}get payload(){return this._payload}set payload(value){if(value===this.payloadSource||value===this._payload)return;const old=this._payload;this._payload=value===void 0?void 0:snapshotLyraDocumentRendererPayload(value),this.payloadSource=value,this.requestUpdate("payload",old)}static{Object.defineProperty(this.prototype,"registry",{configurable:!0,enumerable:!0,get(){return this._registry},set(value){if(value===this.registrySource||value===this._registry)return;const old=this._registry;this._registry=snapshotPublicCollection(documentRendererRegistrySource(value),this.ownerDocument?.defaultView),this.registrySource=value,this.requestUpdate("registry",old)}})}get highlights(){return this._highlights}set highlights(value){if(value===this.highlightsSource||value===this._highlights)return;const previous=this._highlights;this._highlights=snapshotLyraHighlights(value),this.highlightsSource=value,this.requestUpdate("highlights",previous)}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.open&&this.resolve()}disconnectedCallback(){this.generation++,this.renderState={kind:"fallback"},this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}willUpdate(changed){if(super.willUpdate(changed),!this.open){changed.has("open")&&(this.generation++,this.renderState={kind:"fallback"});return}const legacyFileChanged=this.payload===void 0&&(changed.has("name")||changed.has("mimeType")||changed.has("src")||changed.has("anchor")||changed.has("highlights")||changed.has("alt"));(!this.hasUpdated||changed.has("open")||changed.has("payload")||changed.has("registry")||legacyFileChanged)&&this.resolve()}updated(changed){super.updated(changed),this.announcements.transition("renderer",this.renderState.kind,this.renderState.kind==="error"?this.localize("documentPreviewGenericError"):this.localize("loadingDocument"))}currentFile(){if(this.payload){const file=this.payload.file;return{name:file.name,mimeType:file.mimeType,src:file.src,...file.anchor!==void 0?{anchor:file.anchor}:{},...file.highlights?{highlights:[...file.highlights]}:{},...file.alt!==void 0?{alt:file.alt}:{}}}return{name:this.name,mimeType:this.mimeType,src:this.src,anchor:this.anchor??void 0,highlights:this.highlights,alt:this.alt}}async resolve(){if(!this.isConnected||!this.open)return;const generation=++this.generation;this.rendererCapabilities=void 0;const file=this.currentFile(),registry=this.registry??this.builtInRegistry;let def;try{def=findDocumentRenderer(file,registry)}catch(error){this.failResolution(file,generation,error);return}if(!def){this.resolvedLazy=void 0,this.renderState={kind:"fallback"},this.finishAnchorResult(void 0,file,generation,!0);return}if(this.resolvedLazy?.def===def){this.finishRender(def,this.renderWith(this.resolvedLazy.resolved,file),file,generation);return}if(!def.load){this.resolvedLazy={def,resolved:def},this.finishRender(def,this.renderWith(def,file),file,generation);return}this.renderState={kind:"loading"};let resolved;try{resolved=await loadDocumentRenderer(def)}catch(error){generation===this.generation&&this.isConnected&&this.open&&(this.renderState={kind:"error"},this.emit("lr-render-error",{error}),this.finishAnchorResult(void 0,file,generation));return}generation!==this.generation||!this.isConnected||!this.open||(this.resolvedLazy={def,resolved},this.finishRender(def,this.renderWith(resolved,file),file,generation))}finishRender(def,rendered,file,generation){if("error"in rendered){this.failResolution(file,generation,rendered.error);return}const capabilities=rendered.capabilities??def.capabilities;this.rendererCapabilities=capabilities,this.finishAnchorResult(capabilities,file,generation)}failResolution(file,generation,error){generation!==this.generation||!this.isConnected||!this.open||(this.renderState={kind:"error"},this.emit("lr-render-error",{error}),file.anchor!=null&&this.scheduleAfterUpdate(()=>{generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found:!1})}))}finishAnchorResult(capabilities,file,generation,fallback=!1){if(file.anchor!=null&&!(generation!==this.generation||!this.isConnected||!this.open)){if(fallback){this.scheduleAfterUpdate(()=>{(async()=>{const found=await this.fallbackPreviewEl?.scrollToAnchor(file.anchor)??!1;generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found})})()});return}this.isAnchorCapable(capabilities,file.anchor)||this.scheduleAfterUpdate(()=>{generation!==this.generation||!this.isConnected||!this.open||this.emit("lr-anchor-result",{found:!1})})}}isAnchorCapable(capabilities,anchor){const anchors=capabilities?.anchors;return!anchors||anchors.length===0?!1:typeof anchor=="string"?!0:anchors.includes(anchor.kind)}renderWith(definition,file){try{const adapted=adaptDocumentRenderer(definition,file,this.payload);return this.renderState={kind:"rendered",template:adapted.render()},{capabilities:adapted.capabilities}}catch(error){return{error}}}renderedElement(){if(!(!this.open||this.renderState.kind!=="rendered"))return this.renderRoot.querySelector('[part="body"]')?.firstElementChild??void 0}currentSearchTarget(){if(this.rendererCapabilities?.search!==!0)return;const element=this.renderedElement();return typeof element?.search=="function"?element:void 0}async scrollToAnchor(target){if(await this.updateComplete,!this.open)return!1;if(this.renderState.kind==="fallback"){const found=await this.fallbackPreviewEl?.scrollToAnchor(target)??!1;return this.emit("lr-anchor-result",{found}),found}const element=this.renderedElement();return this.isAnchorCapable(this.rendererCapabilities,target)&&typeof element?.scrollToAnchor=="function"?element.scrollToAnchor(target):(this.emit("lr-anchor-result",{found:!1}),!1)}async searchTarget(){return await this.updateComplete,this.currentSearchTarget()}async search(query2){return await(await this.searchTarget())?.search(query2)??0}async searchNext(){return await(await this.searchTarget())?.searchNext()??!1}async searchPrevious(){return await(await this.searchTarget())?.searchPrevious()??!1}clearSearch(){this.currentSearchTarget()?.clearSearch()}renderBody(){const file=this.currentFile();switch(this.renderState.kind){case"rendered":return this.renderState.template;case"loading":return renderViewerLoading(this.localize("loadingDocument"));case"error":return html`<div part="error">${this.localize("documentPreviewGenericError")}</div>`;default:return html`
2
2
  <lr-document-preview
3
3
  src=${file.src}
4
4
  mime-type=${file.mimeType}
@@ -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{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{srOnly}from"../../../internal/a11y.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{Slugger}from"../../../internal/slugger.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{buildQuoteAnchor,createTextQuoteIndex,emptyTextQuoteMatches,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,scopeFromElement,TEXT_QUOTE_LIMITS,TEXT_SELECTION_RECT_LIMIT}from"../../../internal/text-quote.js";import{acquireHighlightHandle,supportsCustomHighlights,wrapTextRangeInMarks,unwrapTextMark}from"../../../internal/text-highlights.js";import{loadDocxDeps}from"./docx-loader.js";import{assertDocxArchiveWithinLimits}from"./docx-resource-guard.js";import{styles}from"./docx-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkupFragment}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{ViewerSearchState}from"../../../internal/viewer-search.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_docxViewerLabel,LYRA_DEFAULT_docxViewerMissingConverter,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";const HIGHLIGHT_TONES=["accent","success","warning","danger","neutral"],MAX_DOCX_SEARCH_MATCHES=1e3,MAX_DOCX_PAINTED_SEARCH_MATCHES=200,MAX_DOCX_PAINTED_HIGHLIGHTS=100,MAX_DOCX_CONVERSION_MESSAGES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function normalizeDocxConversion(value){if(value===null||typeof value!="object"&&typeof value!="function")return null;const markup=getOwnDataDescriptor(value,"value"),diagnostics=getOwnDataDescriptor(value,"messages");if(markup===MISSING_OWN_DATA_DESCRIPTOR||markup===UNSAFE_OWN_DATA_DESCRIPTOR||diagnostics===MISSING_OWN_DATA_DESCRIPTOR||diagnostics===UNSAFE_OWN_DATA_DESCRIPTOR||typeof markup.value!="string"||!isArrayValue(diagnostics.value))return null;const length=getOwnDataDescriptor(diagnostics.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 null;const messages=[],count=Math.min(length.value,MAX_DOCX_CONVERSION_MESSAGES);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(diagnostics.value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||messages.push(entry.value)}return Object.freeze({value:markup.value,messages:Object.freeze(messages)})}function wrapRangeInSearchMarks(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraDocxViewerBase extends LyraElement{}class LyraDocxViewer extends DocumentAnchorTarget(LyraDocxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.anchorKinds=["fragment","text-quote"],this.fetchState={kind:"idle"},this.searchState=new ViewerSearchState(emptyTextQuoteMatches,detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.resolvedHighlightActions=[],this.generation=0,this.lastLoadSrc="",this.loadLibrary=loadDocxDeps,this.announcements=new ViewerAnnouncementController(this),this.headingTree=[],this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActionSyncPending=!1,this.paintedSearchMarks=[],this.textIndexCache=null,this.textIndexMappingDirty=!1,this.detached=new DeferredTeardown(()=>this.releaseDetachedDocument()),this.onContentClick=e=>{const highlightId=this.hitTestHighlightAt(e.clientX,e.clientY);highlightId&&this.emit("lr-highlight-activate",{highlightId})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,docxViewerLabel:LYRA_DEFAULT_docxViewerLabel,docxViewerMissingConverter:LYRA_DEFAULT_docxViewerMissingConverter,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}connectedCallback(){if(super.connectedCallback(),this.announcements.connect(),this.detached.cancel()){const root=this.contentRoot();root&&this.bindTextSelection(root);return}this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedDocument(){this.generation++,this.resetResolvedHighlightActions(),this.highlightHandle?.release(),this.highlightHandle=void 0}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("highlights"))&&this.resetResolvedHighlightActions(),(changed.has("src")||changed.has("fetchState"))&&this.resetSearchForContentChange()}updated(changed){super.updated(changed);const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.textIndexCache=null),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("fetchState")){const root=this.contentRoot();root&&this.bindTextSelection(root),this.textIndexCache=null,this.textIndexMappingDirty=!1}(changed.has("fetchState")||changed.has("highlights")||changed.has("activeHighlightId")||localeChanged&&this.highlights.length>0)&&this.repaintHighlights(),localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)})}contentRoot(){return this.renderRoot.querySelector('[part="content"]')}resetSearchForContentChange(){const shouldEmit=this.searchState.dirty;this.searchState.reset(),this.clearSearchPaint(),shouldEmit&&this.searchState.emit()}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"},this.headingTree=[];return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const arrayBuffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view||(await assertDocxArchiveWithinLimits(arrayBuffer,void 0,void 0,{signal,strictAdmission:!0}),!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view))return;const{mammoth,DOMPurify}=await this.loadLibrary();if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!mammoth){this.failWithLocalizedMessage(this.localize("docxViewerMissingConverter"));return}if(!DOMPurify){this.failWithLocalizedMessage(this.localize("documentViewerMissingSanitizer"));return}const rawConverted=await mammoth.convertToHtml({arrayBuffer});if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const converted=normalizeDocxConversion(rawConverted);if(!converted)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const content=sanitizePassiveMarkupFragment(DOMPurify,converted.value,this.ownerDocument,"passive-document");if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"loaded",content:this.stampHeadings(content)};for(const cause of converted.messages)this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code:"docx-conversion-message",severity:"warning",fatal:!1,source:"mammoth",cause})})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}stampHeadings(content){const slugger=new Slugger,tree=[],walker=this.ownerDocument.createTreeWalker(content,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(!/^H[1-6]$/.test(heading.tagName))continue;const level=Number(heading.tagName.slice(1)),label=(heading.textContent??"").trim(),slug=slugger.slug(label);slug&&(heading.id=slug),tree.push({id:slug,label,level})}return this.headingTree=tree,content}getHeadingTree(){return[...this.headingTree]}async applyAnchor(anchor){const root=this.contentRoot();if(!root)return!1;switch(anchor.kind){case"fragment":return this.applyFragmentAnchor(root,anchor);case"text-quote":return this.applyTextQuoteAnchor(root,anchor);default:return!1}}applyFragmentAnchor(root,anchor){if(!anchor.id)return!1;let expectedIndex=-1;const headingLimit=Math.min(this.headingTree.length,TEXT_QUOTE_LIMITS.maxTraversalNodes);for(let index=0;index<headingLimit;index++)if(this.headingTree[index]?.id===anchor.id){expectedIndex=index;break}if(expectedIndex<0)return!1;const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,headingIndex=0,idMatch=null,positionalMatch=null,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(/^H[1-6]$/.test(heading.tagName)&&(heading.getAttribute("id")===anchor.id&&(idMatch??=heading),headingIndex===expectedIndex&&(positionalMatch=heading),headingIndex++,idMatch&&positionalMatch))break}const el=idMatch??positionalMatch;return el?(el.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"start"}),!0):!1}applyTextQuoteAnchor(root,anchor){const{scope,index}=this.currentTextIndex(root),match=index.resolve(anchor),range=match?rangeFromTextQuoteMatch(scope,match):null;return range?(((range.startContainer.nodeType===Node.ELEMENT_NODE?range.startContainer:range.startContainer.parentElement)??root).scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"}),!0):!1}computeSelectionAnchor(range){const root=this.contentRoot();return root?buildQuoteAnchor(range,this.currentTextIndex(root).scope):null}ensureHighlightHandle(){return this.highlightHandle||(this.highlightHandle=acquireHighlightHandle(this,this.ownerDocument)),this.highlightHandle}repaintHighlights(){this.resolvedHighlightRanges=[];const root=this.contentRoot(),handle=this.ensureHighlightHandle();if(!root){this.syncResolvedHighlightActions([]);for(const tone of HIGHLIGHT_TONES)handle.setRanges(tone,[]);handle.setActive(null);return}const{scope,index}=this.currentTextIndex(root),workBudget=index.createWorkBudget(),rangesByTone=new Map(HIGHLIGHT_TONES.map(tone=>[tone,[]]));let activeRange=null;const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),resolved=[];for(const highlight of candidates){if(resolved.length>=MAX_DOCX_PAINTED_HIGHLIGHTS)break;if(highlight.anchor.kind!=="text-quote")continue;const match=index.resolve(highlight.anchor,workBudget);match&&resolved.push({highlight,match})}const resolvedRanges=rangesFromTextQuoteMatches(scope,resolved.map(({match})=>match));for(let position=0;position<resolved.length;position++){const{highlight}=resolved[position],range=resolvedRanges[position]??null;range&&(rangesByTone.get(highlight.tone??"accent").push(range),this.resolvedHighlightRanges.push({highlight,range}),highlight.id===this.activeHighlightId&&(activeRange=range))}this.syncResolvedHighlightActions(this.resolvedHighlightRanges.map(({highlight})=>highlight));for(const[tone,ranges]of rangesByTone)handle.setRanges(tone,ranges);if(handle.setActive(activeRange),!supportsCustomHighlights(this.ownerDocument)){const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes+MAX_DOCX_PAINTED_HIGHLIGHTS&&(node=walker.nextNode());){inspected++;const mark=node;mark.localName==="mark"&&mark.hasAttribute("data-lr-highlight-tone")&&!mark.hasAttribute("part")&&mark.setAttribute("part","highlight")}this.textIndexMappingDirty=!0}}syncResolvedHighlightActions(highlights){this.pendingResolvedHighlightActions=[...new Set(highlights)],!this.resolvedHighlightActionSyncPending&&(this.resolvedHighlightActionSyncPending=!0,queueMicrotask(()=>{if(this.resolvedHighlightActionSyncPending=!1,!this.isConnected)return;const next=this.pendingResolvedHighlightActions;next.length===this.resolvedHighlightActions.length&&next.every((highlight,index)=>highlight===this.resolvedHighlightActions[index])||(this.resolvedHighlightActions=next)}))}resetResolvedHighlightActions(){this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActions=[]}hitTestHighlightAt(x,y){let remainingRects=TEXT_SELECTION_RECT_LIMIT;for(let i=this.resolvedHighlightRanges.length-1;i>=0;i--){const{highlight,range}=this.resolvedHighlightRanges[i];for(const rect of range.getClientRects()){if(remainingRects--<=0)return null;if(x>=rect.left&&x<=rect.right&&y>=rect.top&&y<=rect.bottom)return highlight.id}}return null}highlightActionLabel(highlight){return this.localize("highlightWithLabel",void 0,{label:highlight.label||(highlight.anchor.kind==="text-quote"?highlight.anchor.quote:highlight.id)})}activateHighlightAction(highlight){const resolved=this.resolvedHighlightRanges.find(entry=>entry.highlight===highlight);if(!resolved)return;const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;(resolved.range.commonAncestorContainer.nodeType===elementNode?resolved.range.commonAncestorContainer:resolved.range.commonAncestorContainer.parentElement)?.scrollIntoView?.({block:"nearest",behavior:"auto"}),this.activeHighlightId=highlight.id,this.emit("lr-highlight-activate",{highlightId:highlight.id})}renderHighlightActions(){const resolved=new Set(this.resolvedHighlightActions),highlights=this.highlights.filter(highlight=>highlight.anchor.kind==="text-quote"&&resolved.has(highlight));return highlights.length===0?nothing:html`
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{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{srOnly}from"../../../internal/a11y.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{Slugger}from"../../../internal/slugger.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{buildQuoteAnchor,createTextQuoteIndex,emptyTextQuoteMatches,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,scopeFromElement,TEXT_QUOTE_LIMITS,TEXT_SELECTION_RECT_LIMIT}from"../../../internal/text-quote.js";import{acquireHighlightHandle,supportsCustomHighlights,wrapTextRangeInMarks,unwrapTextMark}from"../../../internal/text-highlights.js";import{loadDocxDeps}from"./docx-loader.js";import{assertDocxArchiveWithinLimits}from"./docx-resource-guard.js";import{styles}from"./docx-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{DeferredTeardown}from"../document-viewer/deferred-teardown.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkupFragment}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{ViewerSearchState}from"../../../internal/viewer-search.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_docxViewerLabel,LYRA_DEFAULT_docxViewerMissingConverter,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const HIGHLIGHT_TONES=["accent","success","warning","danger","neutral"],MAX_DOCX_SEARCH_MATCHES=1e3,MAX_DOCX_PAINTED_SEARCH_MATCHES=200,MAX_DOCX_PAINTED_HIGHLIGHTS=100,MAX_DOCX_CONVERSION_MESSAGES=100;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function normalizeDocxConversion(value){if(value===null||typeof value!="object"&&typeof value!="function")return null;const markup=getOwnDataDescriptor(value,"value"),diagnostics=getOwnDataDescriptor(value,"messages");if(markup===MISSING_OWN_DATA_DESCRIPTOR||markup===UNSAFE_OWN_DATA_DESCRIPTOR||diagnostics===MISSING_OWN_DATA_DESCRIPTOR||diagnostics===UNSAFE_OWN_DATA_DESCRIPTOR||typeof markup.value!="string"||!isArrayValue(diagnostics.value))return null;const length=getOwnDataDescriptor(diagnostics.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 null;const messages=[],count=Math.min(length.value,MAX_DOCX_CONVERSION_MESSAGES);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(diagnostics.value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||messages.push(entry.value)}return Object.freeze({value:markup.value,messages:Object.freeze(messages)})}function wrapRangeInSearchMarks(range,part,budget){const doc=range.startContainer.ownerDocument;return doc?wrapTextRangeInMarks(range,doc,budget,mark=>mark.setAttribute("part",part)):[]}class LyraDocxViewerBase extends LyraElement{}class LyraDocxViewer extends DocumentAnchorTarget(LyraDocxViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.anchorKinds=["fragment","text-quote"],this.fetchState={kind:"idle"},this.searchState=new ViewerSearchState(emptyTextQuoteMatches,detail=>this.emit("lr-search-change",detail),()=>this.requestUpdate()),this.resolvedHighlightActions=[],this.generation=0,this.lastLoadSrc="",this.loadLibrary=loadDocxDeps,this.announcements=new ViewerAnnouncementController(this),this.headingTree=[],this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActionSyncPending=!1,this.paintedSearchMarks=[],this.textIndexCache=null,this.textIndexMappingDirty=!1,this.detached=new DeferredTeardown(()=>this.releaseDetachedDocument()),this.onContentClick=e=>{const highlightId=this.hitTestHighlightAt(e.clientX,e.clientY);highlightId&&this.emit("lr-highlight-activate",{highlightId})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,docxViewerLabel:LYRA_DEFAULT_docxViewerLabel,docxViewerMissingConverter:LYRA_DEFAULT_docxViewerMissingConverter,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loadingDocument:LYRA_DEFAULT_loadingDocument,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}connectedCallback(){if(super.connectedCallback(),this.announcements.connect(),this.detached.cancel()){const root=this.contentRoot();root&&this.bindTextSelection(root);return}this.hasUpdated&&this.src.trim()&&this.src===this.lastLoadSrc&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.announcements.disconnect(),super.disconnectedCallback(),this.detached.schedule()}releaseDetachedDocument(){this.generation++,this.resetResolvedHighlightActions(),this.highlightHandle?.release(),this.highlightHandle=void 0}adoptedCallback(){super.adoptedCallback(),this.detached.flush(),this.announcements.adopted()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("highlights"))&&this.resetResolvedHighlightActions(),(changed.has("src")||changed.has("fetchState"))&&this.resetSearchForContentChange()}updated(changed){super.updated(changed);const locale=this.effectiveLocale,localeChanged=this.textIndexLocale!==void 0&&this.textIndexLocale!==locale;if(this.textIndexLocale=locale,localeChanged&&(this.textIndexCache=null),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("fetchState")){const root=this.contentRoot();root&&this.bindTextSelection(root),this.textIndexCache=null,this.textIndexMappingDirty=!1}(changed.has("fetchState")||changed.has("highlights")||changed.has("activeHighlightId")||localeChanged&&this.highlights.length>0)&&this.repaintHighlights(),localeChanged&&this.searchState.query.trim()&&this.scheduleAfterUpdate(()=>{this.search(this.searchState.query)})}contentRoot(){return this.renderRoot.querySelector('[part="content"]')}resetSearchForContentChange(){const shouldEmit=this.searchState.dirty;this.searchState.reset(),this.clearSearchPaint(),shouldEmit&&this.searchState.emit()}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"},this.headingTree=[];return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const arrayBuffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view||(await assertDocxArchiveWithinLimits(arrayBuffer,void 0,void 0,{signal,strictAdmission:!0}),!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view))return;const{mammoth,DOMPurify}=await this.loadLibrary();if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;if(!mammoth){this.failWithLocalizedMessage(this.localize("docxViewerMissingConverter"));return}if(!DOMPurify){this.failWithLocalizedMessage(this.localize("documentViewerMissingSanitizer"));return}const rawConverted=await mammoth.convertToHtml({arrayBuffer});if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;const converted=normalizeDocxConversion(rawConverted);if(!converted)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const content=sanitizePassiveMarkupFragment(DOMPurify,converted.value,this.ownerDocument,"passive-document");if(!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"loaded",content:this.stampHeadings(content)};for(const cause of converted.messages)this.emit("lr-viewer-diagnostic",{diagnostic:Object.freeze({code:"docx-conversion-message",severity:"warning",fatal:!1,source:"mammoth",cause})})}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation||this.ownerDocument.defaultView!==fetchTarget.view)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}stampHeadings(content){const slugger=new Slugger,tree=[],walker=this.ownerDocument.createTreeWalker(content,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(!/^H[1-6]$/.test(heading.tagName))continue;const level=Number(heading.tagName.slice(1)),label=(heading.textContent??"").trim(),slug=slugger.slug(label);slug&&(heading.id=slug),tree.push({id:slug,label,level})}return this.headingTree=tree,content}getHeadingTree(){return[...this.headingTree]}async applyAnchor(anchor){const root=this.contentRoot();if(!root)return!1;switch(anchor.kind){case"fragment":return this.applyFragmentAnchor(root,anchor);case"text-quote":return this.applyTextQuoteAnchor(root,anchor);default:return!1}}applyFragmentAnchor(root,anchor){if(!anchor.id)return!1;let expectedIndex=-1;const headingLimit=Math.min(this.headingTree.length,TEXT_QUOTE_LIMITS.maxTraversalNodes);for(let index=0;index<headingLimit;index++)if(this.headingTree[index]?.id===anchor.id){expectedIndex=index;break}if(expectedIndex<0)return!1;const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,headingIndex=0,idMatch=null,positionalMatch=null,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes&&(node=walker.nextNode());){inspected++;const heading=node;if(/^H[1-6]$/.test(heading.tagName)&&(heading.getAttribute("id")===anchor.id&&(idMatch??=heading),headingIndex===expectedIndex&&(positionalMatch=heading),headingIndex++,idMatch&&positionalMatch))break}const el=idMatch??positionalMatch;return el?(el.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"start"}),!0):!1}applyTextQuoteAnchor(root,anchor){const{scope,index}=this.currentTextIndex(root),match=index.resolve(anchor),range=match?rangeFromTextQuoteMatch(scope,match):null;return range?(((range.startContainer.nodeType===Node.ELEMENT_NODE?range.startContainer:range.startContainer.parentElement)??root).scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"center"}),!0):!1}computeSelectionAnchor(range){const root=this.contentRoot();return root?buildQuoteAnchor(range,this.currentTextIndex(root).scope):null}ensureHighlightHandle(){return this.highlightHandle||(this.highlightHandle=acquireHighlightHandle(this,this.ownerDocument)),this.highlightHandle}repaintHighlights(){this.resolvedHighlightRanges=[];const root=this.contentRoot(),handle=this.ensureHighlightHandle();if(!root){this.syncResolvedHighlightActions([]);for(const tone of HIGHLIGHT_TONES)handle.setRanges(tone,[]);handle.setActive(null);return}const{scope,index}=this.currentTextIndex(root),workBudget=index.createWorkBudget(),rangesByTone=new Map(HIGHLIGHT_TONES.map(tone=>[tone,[]]));let activeRange=null;const candidates=prioritizedHighlightCandidates(this.highlights,this.activeHighlightId),resolved=[];for(const highlight of candidates){if(resolved.length>=MAX_DOCX_PAINTED_HIGHLIGHTS)break;if(highlight.anchor.kind!=="text-quote")continue;const match=index.resolve(highlight.anchor,workBudget);match&&resolved.push({highlight,match})}const resolvedRanges=rangesFromTextQuoteMatches(scope,resolved.map(({match})=>match));for(let position=0;position<resolved.length;position++){const{highlight}=resolved[position],range=resolvedRanges[position]??null;range&&(rangesByTone.get(highlight.tone??"accent").push(range),this.resolvedHighlightRanges.push({highlight,range}),highlight.id===this.activeHighlightId&&(activeRange=range))}this.syncResolvedHighlightActions(this.resolvedHighlightRanges.map(({highlight})=>highlight));for(const[tone,ranges]of rangesByTone)handle.setRanges(tone,ranges);if(handle.setActive(activeRange),!supportsCustomHighlights(this.ownerDocument)){const walker=root.ownerDocument.createTreeWalker(root,1);let inspected=0,node;for(;inspected<TEXT_QUOTE_LIMITS.maxTraversalNodes+MAX_DOCX_PAINTED_HIGHLIGHTS&&(node=walker.nextNode());){inspected++;const mark=node;mark.localName==="mark"&&mark.hasAttribute("data-lr-highlight-tone")&&!mark.hasAttribute("part")&&mark.setAttribute("part","highlight")}this.textIndexMappingDirty=!0}}syncResolvedHighlightActions(highlights){this.pendingResolvedHighlightActions=[...new Set(highlights)],!this.resolvedHighlightActionSyncPending&&(this.resolvedHighlightActionSyncPending=!0,queueMicrotask(()=>{if(this.resolvedHighlightActionSyncPending=!1,!this.isConnected)return;const next=this.pendingResolvedHighlightActions;next.length===this.resolvedHighlightActions.length&&next.every((highlight,index)=>highlight===this.resolvedHighlightActions[index])||(this.resolvedHighlightActions=next)}))}resetResolvedHighlightActions(){this.resolvedHighlightRanges=[],this.pendingResolvedHighlightActions=[],this.resolvedHighlightActions=[]}hitTestHighlightAt(x,y){let remainingRects=TEXT_SELECTION_RECT_LIMIT;for(let i=this.resolvedHighlightRanges.length-1;i>=0;i--){const{highlight,range}=this.resolvedHighlightRanges[i];for(const rect of range.getClientRects()){if(remainingRects--<=0)return null;if(x>=rect.left&&x<=rect.right&&y>=rect.top&&y<=rect.bottom)return highlight.id}}return null}highlightActionLabel(highlight){return this.localize("highlightWithLabel",void 0,{label:highlight.label||(highlight.anchor.kind==="text-quote"?highlight.anchor.quote:highlight.id)})}activateHighlightAction(highlight){const resolved=this.resolvedHighlightRanges.find(entry=>entry.highlight===highlight);if(!resolved)return;const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;(resolved.range.commonAncestorContainer.nodeType===elementNode?resolved.range.commonAncestorContainer:resolved.range.commonAncestorContainer.parentElement)?.scrollIntoView?.({block:"nearest",behavior:"auto"}),this.activeHighlightId=highlight.id,this.emit("lr-highlight-activate",{highlightId:highlight.id})}renderHighlightActions(){const resolved=new Set(this.resolvedHighlightActions),highlights=this.highlights.filter(highlight=>highlight.anchor.kind==="text-quote"&&resolved.has(highlight));return highlights.length===0?nothing:html`
2
2
  <div part="highlight-actions">
3
3
  ${highlights.map(highlight=>{const label=this.highlightActionLabel(highlight);return html`
4
4
  <button
@@ -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,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.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{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`
2
2
  <div
3
3
  part="base"
4
4
  aria-busy=${this.ebookState.kind==="loading"?"true":"false"}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getDateTimeFormat,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../../media/attachment-chip/file-size.js";import{loadEmailDeps}from"./email-loader.js";import{styles}from"./email-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{DeferredTeardown}from"../document-viewer/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_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeEmail,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_download,LYRA_DEFAULT_emailViewerAttachments,LYRA_DEFAULT_emailViewerDate,LYRA_DEFAULT_emailViewerFrom,LYRA_DEFAULT_emailViewerGroupAddress,LYRA_DEFAULT_emailViewerHideQuoted,LYRA_DEFAULT_emailViewerLabel,LYRA_DEFAULT_emailViewerMissingParser,LYRA_DEFAULT_emailViewerNoSubject,LYRA_DEFAULT_emailViewerOpenAttachment,LYRA_DEFAULT_emailViewerShowQuoted,LYRA_DEFAULT_emailViewerSubject,LYRA_DEFAULT_emailViewerTo,LYRA_DEFAULT_emailViewerUnnamedAttachment,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const MAX_EMAIL_RECIPIENT_POSITIONS=1e4,MAX_EMAIL_RECIPIENT_DEPTH=100,MAX_EMAIL_ATTACHMENT_POSITIONS=1e4;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isSafeRecord(value){if(value===null||typeof value!="object"||isArrayValue(value))return!1;try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function optionalOwnString(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor!==MISSING_OWN_DATA_DESCRIPTOR&&descriptor!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof descriptor.value=="string"?descriptor.value:void 0}function optionalOwnValue(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function projectAddressList(value,budget,depth){if(!isArrayValue(value)||budget.positions>=MAX_EMAIL_RECIPIENT_POSITIONS)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 addresses=[],count=Math.min(length.value,MAX_EMAIL_RECIPIENT_POSITIONS-budget.positions);for(let index=0;index<count;index+=1){budget.positions+=1;const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const address=projectAddress(descriptor.value,budget,depth);address&&addresses.push(address)}return addresses}function projectAddress(value,budget,depth){if(depth>MAX_EMAIL_RECIPIENT_DEPTH||budget.nodes>=MAX_EMAIL_RECIPIENT_POSITIONS||!isSafeRecord(value)||budget.seen.has(value))return;budget.seen.add(value),budget.nodes+=1;const name=optionalOwnString(value,"name"),address=optionalOwnString(value,"address"),groupValue=optionalOwnValue(value,"group"),group=groupValue===void 0?[]:projectAddressList(groupValue,budget,depth+1);if(!(name===void 0&&address===void 0&&group.length===0))return Object.freeze({...name===void 0?{}:{name},...address===void 0?{}:{address},...group.length===0?{}:{group:Object.freeze(group)}})}function normalizeAttachmentContent(content){try{if(typeof content=="string")return new TextEncoder().encode(content);if(content instanceof Uint8Array)return new Uint8Array(content);if(content instanceof ArrayBuffer)return new Uint8Array(content.slice(0))}catch{return}}function projectAttachments(value){if(!isArrayValue(value))return Object.freeze([]);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([]);const attachments=[],count=Math.min(length.value,MAX_EMAIL_ATTACHMENT_POSITIONS);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||!isSafeRecord(entry.value))continue;const content=normalizeAttachmentContent(optionalOwnValue(entry.value,"content"));if(!content)continue;const filename=optionalOwnString(entry.value,"filename")??"",mimeType=optionalOwnString(entry.value,"mimeType")??"";attachments.push(Object.freeze({filename,mimeType,size:content.byteLength,content}))}return Object.freeze(attachments)}function normalizeParsedEmail(value){if(!isSafeRecord(value))return null;const budget={positions:0,nodes:0,seen:new WeakSet},htmlValue=optionalOwnValue(value,"html"),textValue=optionalOwnValue(value,"text"),subjectValue=optionalOwnValue(value,"subject"),dateValue=optionalOwnValue(value,"date"),html2=typeof htmlValue=="string"?htmlValue:void 0,text=typeof textValue=="string"?textValue:void 0,subject=typeof subjectValue=="string"?subjectValue:void 0,date=typeof dateValue=="string"?dateValue:void 0,from=projectAddress(optionalOwnValue(value,"from"),budget,0),to=projectAddressList(optionalOwnValue(value,"to"),budget,0);return Object.freeze({...html2===void 0?{}:{html:html2},...text===void 0?{}:{text},...from===void 0?{}:{from},to:Object.freeze(to),...subject===void 0?{}:{subject},...date===void 0?{}:{date},attachments:projectAttachments(optionalOwnValue(value,"attachments"))})}function immutableAttachmentBlob(content,mimeType){const copied=new Uint8Array(content.byteLength);return copied.set(content),new Blob([copied],{type:mimeType})}class LyraEmailViewerBase extends LyraElement{static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-attachment-open","lr-text-select"])}}function splitTrailingQuoteBlock(text){const lines=text.split(/\r\n|\r|\n/);let start=lines.length,quotedLineCount=0;for(let i=lines.length-1;i>=0;i--)if(lines[i].trimStart().startsWith(">"))start=i,quotedLineCount++;else if(lines[i].trim()==="")start=i;else break;return quotedLineCount<3?null:{visible:lines.slice(0,start).join(`
1
+ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getDateTimeFormat,getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../../media/attachment-chip/file-size.js";import{loadEmailDeps}from"./email-loader.js";import{styles}from"./email-viewer.styles.js";import{viewerFrameStyles}from"../viewer-frame.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{sanitizePassiveMarkup}from"../passive-markup.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{DeferredTeardown}from"../document-viewer/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_download,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeEmail,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_documentViewerMissingSanitizer,LYRA_DEFAULT_emailViewerAttachments,LYRA_DEFAULT_emailViewerDate,LYRA_DEFAULT_emailViewerFrom,LYRA_DEFAULT_emailViewerGroupAddress,LYRA_DEFAULT_emailViewerHideQuoted,LYRA_DEFAULT_emailViewerLabel,LYRA_DEFAULT_emailViewerMissingParser,LYRA_DEFAULT_emailViewerNoSubject,LYRA_DEFAULT_emailViewerOpenAttachment,LYRA_DEFAULT_emailViewerShowQuoted,LYRA_DEFAULT_emailViewerSubject,LYRA_DEFAULT_emailViewerTo,LYRA_DEFAULT_emailViewerUnnamedAttachment,LYRA_DEFAULT_loadingDocument}from"../../../internal/default-strings/viewers.generated.js";const MAX_EMAIL_RECIPIENT_POSITIONS=1e4,MAX_EMAIL_RECIPIENT_DEPTH=100,MAX_EMAIL_ATTACHMENT_POSITIONS=1e4;function isArrayValue(value){try{return Array.isArray(value)}catch{return!1}}function isSafeRecord(value){if(value===null||typeof value!="object"||isArrayValue(value))return!1;try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function optionalOwnString(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor!==MISSING_OWN_DATA_DESCRIPTOR&&descriptor!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof descriptor.value=="string"?descriptor.value:void 0}function optionalOwnValue(value,key){const descriptor=getOwnDataDescriptor(value,key);return descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function projectAddressList(value,budget,depth){if(!isArrayValue(value)||budget.positions>=MAX_EMAIL_RECIPIENT_POSITIONS)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 addresses=[],count=Math.min(length.value,MAX_EMAIL_RECIPIENT_POSITIONS-budget.positions);for(let index=0;index<count;index+=1){budget.positions+=1;const descriptor=getOwnDataDescriptor(value,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const address=projectAddress(descriptor.value,budget,depth);address&&addresses.push(address)}return addresses}function projectAddress(value,budget,depth){if(depth>MAX_EMAIL_RECIPIENT_DEPTH||budget.nodes>=MAX_EMAIL_RECIPIENT_POSITIONS||!isSafeRecord(value)||budget.seen.has(value))return;budget.seen.add(value),budget.nodes+=1;const name=optionalOwnString(value,"name"),address=optionalOwnString(value,"address"),groupValue=optionalOwnValue(value,"group"),group=groupValue===void 0?[]:projectAddressList(groupValue,budget,depth+1);if(!(name===void 0&&address===void 0&&group.length===0))return Object.freeze({...name===void 0?{}:{name},...address===void 0?{}:{address},...group.length===0?{}:{group:Object.freeze(group)}})}function normalizeAttachmentContent(content){try{if(typeof content=="string")return new TextEncoder().encode(content);if(content instanceof Uint8Array)return new Uint8Array(content);if(content instanceof ArrayBuffer)return new Uint8Array(content.slice(0))}catch{return}}function projectAttachments(value){if(!isArrayValue(value))return Object.freeze([]);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([]);const attachments=[],count=Math.min(length.value,MAX_EMAIL_ATTACHMENT_POSITIONS);for(let index=0;index<count;index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||!isSafeRecord(entry.value))continue;const content=normalizeAttachmentContent(optionalOwnValue(entry.value,"content"));if(!content)continue;const filename=optionalOwnString(entry.value,"filename")??"",mimeType=optionalOwnString(entry.value,"mimeType")??"";attachments.push(Object.freeze({filename,mimeType,size:content.byteLength,content}))}return Object.freeze(attachments)}function normalizeParsedEmail(value){if(!isSafeRecord(value))return null;const budget={positions:0,nodes:0,seen:new WeakSet},htmlValue=optionalOwnValue(value,"html"),textValue=optionalOwnValue(value,"text"),subjectValue=optionalOwnValue(value,"subject"),dateValue=optionalOwnValue(value,"date"),html2=typeof htmlValue=="string"?htmlValue:void 0,text=typeof textValue=="string"?textValue:void 0,subject=typeof subjectValue=="string"?subjectValue:void 0,date=typeof dateValue=="string"?dateValue:void 0,from=projectAddress(optionalOwnValue(value,"from"),budget,0),to=projectAddressList(optionalOwnValue(value,"to"),budget,0);return Object.freeze({...html2===void 0?{}:{html:html2},...text===void 0?{}:{text},...from===void 0?{}:{from},to:Object.freeze(to),...subject===void 0?{}:{subject},...date===void 0?{}:{date},attachments:projectAttachments(optionalOwnValue(value,"attachments"))})}function immutableAttachmentBlob(content,mimeType){const copied=new Uint8Array(content.byteLength);return copied.set(content),new Blob([copied],{type:mimeType})}class LyraEmailViewerBase extends LyraElement{static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-attachment-open","lr-text-select"])}}function splitTrailingQuoteBlock(text){const lines=text.split(/\r\n|\r|\n/);let start=lines.length,quotedLineCount=0;for(let i=lines.length-1;i>=0;i--)if(lines[i].trimStart().startsWith(">"))start=i,quotedLineCount++;else if(lines[i].trim()==="")start=i;else break;return quotedLineCount<3?null:{visible:lines.slice(0,start).join(`
2
2
  `),quoted:lines.slice(start).join(`
3
3
  `)}}const QUOTE_SELECTOR='blockquote[type="cite" i], div.gmail_quote, div.yahoo_quoted, div[id^="divRplyFwdMsg"]';function parseHtmlDocument(html2,ownerDocument){const DOMParserCtor=ownerDocument.defaultView?.DOMParser;return DOMParserCtor?new DOMParserCtor().parseFromString(html2,"text/html"):null}function foldHtmlQuotes(html2,localize,expandedIndices,ownerDocument){const doc=parseHtmlDocument(html2,ownerDocument);if(!doc)return html2;for(const forged of doc.body.querySelectorAll("[data-quote-toggle], [data-quote-index], [data-email-chrome]"))forged.removeAttribute("data-quote-toggle"),forged.removeAttribute("data-quote-index"),forged.removeAttribute("data-email-chrome");return doc.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{const expanded=expandedIndices.includes(index);block.setAttribute("part","quoted"),expanded||block.setAttribute("hidden",""),block.setAttribute("data-quote-index",String(index));const button=doc.createElement("button");button.type="button",button.setAttribute("part","quote-toggle"),button.setAttribute("data-email-chrome","quote-toggle"),button.setAttribute("aria-expanded",String(expanded)),button.setAttribute("data-quote-toggle",String(index)),button.textContent=localize(expanded?"emailViewerHideQuoted":"emailViewerShowQuoted"),block.before(button)}),doc.body.innerHTML}function isQuoteToggleElement(target){const candidate=target;return candidate.nodeType===1&&candidate.localName==="button"&&candidate.hasAttribute("data-quote-toggle")}class LyraEmailViewer extends TextViewerTarget(LyraEmailViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.foldQuotes=!1,this.fetchState={kind:"idle"},this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.generation=0,this.lastLoadSrc="",this.announcements=new ViewerAnnouncementController(this),this.foldedHtmlCache=null,this.detached=new DeferredTeardown(()=>{this.generation++,this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[],this.foldedHtmlCache=null}),this.onBodyClick=e=>{const target=e.composedPath().find(isQuoteToggleElement);if(!target)return;const index=target.getAttribute("data-quote-toggle"),block=this.renderRoot.querySelector(`[data-quote-index="${index}"]`),numericIndex=Number(index);if(!block||!Number.isInteger(numericIndex)||numericIndex<0)return;const restoreFocus=shadowFocusTarget(this)===target;this.expandedHtmlQuoteIndices=this.expandedHtmlQuoteIndices.includes(numericIndex)?this.expandedHtmlQuoteIndices.filter(value=>value!==numericIndex):[...this.expandedHtmlQuoteIndices,numericIndex],restoreFocus&&this.scheduleAfterUpdate(()=>{this.renderRoot.querySelector(`[data-quote-toggle="${numericIndex}"]`)?.focus()})}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeEmail:LYRA_DEFAULT_documentPreviewTypeEmail,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,documentViewerMissingSanitizer:LYRA_DEFAULT_documentViewerMissingSanitizer,download:LYRA_DEFAULT_download,emailViewerAttachments:LYRA_DEFAULT_emailViewerAttachments,emailViewerDate:LYRA_DEFAULT_emailViewerDate,emailViewerFrom:LYRA_DEFAULT_emailViewerFrom,emailViewerGroupAddress:LYRA_DEFAULT_emailViewerGroupAddress,emailViewerHideQuoted:LYRA_DEFAULT_emailViewerHideQuoted,emailViewerLabel:LYRA_DEFAULT_emailViewerLabel,emailViewerMissingParser:LYRA_DEFAULT_emailViewerMissingParser,emailViewerNoSubject:LYRA_DEFAULT_emailViewerNoSubject,emailViewerOpenAttachment:LYRA_DEFAULT_emailViewerOpenAttachment,emailViewerShowQuoted:LYRA_DEFAULT_emailViewerShowQuoted,emailViewerSubject:LYRA_DEFAULT_emailViewerSubject,emailViewerTo:LYRA_DEFAULT_emailViewerTo,emailViewerUnnamedAttachment:LYRA_DEFAULT_emailViewerUnnamedAttachment,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,viewerFrameStyles,srOnly,viewerLoadingStyles]}async search(query){if(this.foldQuotes&&this.fetchState.kind==="loaded"&&query.trim()&&query.length<=TEXT_QUOTE_LIMITS.maxQueryCodeUnits){const budget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits},matchesQuote=block=>createTextQuoteIndex(scopeFromElement(block),this.effectiveLocale).search(query,budget).length>0,{bodyHtml,bodyText}=this.fetchState.email;if(bodyHtml!==null){this.searchDocument?.html!==bodyHtml&&(this.searchDocument={html:bodyHtml,doc:parseHtmlDocument(bodyHtml,this.ownerDocument)});const next=new Set(this.expandedHtmlQuoteIndices);this.searchDocument.doc?.body.querySelectorAll(QUOTE_SELECTOR).forEach((block,index)=>{!next.has(index)&&matchesQuote(block)&&next.add(index)});const expanded=[...next];(expanded.length!==this.expandedHtmlQuoteIndices.length||expanded.some((value,index)=>value!==this.expandedHtmlQuoteIndices[index]))&&(this.expandedHtmlQuoteIndices=expanded,await this.updateComplete)}else if(bodyText!==null){const split=splitTrailingQuoteBlock(bodyText),quote=this.ownerDocument.createElement("pre");quote.textContent=split?.quoted??"",split&&!this.textQuoteExpanded&&matchesQuote(quote)&&(this.textQuoteExpanded=!0,await this.updateComplete)}}return super.search(query)}async searchNext(){return super.searchNext()}async searchPrevious(){return super.searchPrevious()}clearSearch(){super.clearSearch()}textContentRoot(){return this.renderRoot.querySelector('[part="body"]')}buildTextScope(root){return scopeFromElement(root,void 0,element=>this.foldQuotes&&element.localName==="button"&&element.getAttribute("data-email-chrome")==="quote-toggle")}connectedCallback(){super.connectedCallback(),this.announcements.connect(),!this.detached.cancel()&&this.hasUpdated&&this.src.trim()&&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()}willUpdate(changed){super.willUpdate(changed),(changed.has("src")||changed.has("foldQuotes"))&&(this.textQuoteExpanded=!1,this.expandedHtmlQuoteIndices=[])}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()})}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(this.lastLoadSrc=this.src,!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){this.failWithLocalizedMessage(this.localize("documentPreviewUrlNotAllowed"));return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!this.isCurrentLoad(generation,fetchTarget.view))return;if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);const buffer=await readResponseArrayBuffer(response);if(!this.isCurrentLoad(generation,fetchTarget.view))return;const result=await this.parse(buffer,generation,fetchTarget.view);result&&this.isCurrentLoad(generation,fetchTarget.view)&&(this.fetchState={kind:"loaded",...result})}catch(error){if(isAbortError(error)||!this.isCurrentLoad(generation,fetchTarget.view))return;this.fetchState={kind:"error",message:error instanceof LyraUserFacingError?error.message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}failWithLocalizedMessage(message){const error=new LyraUserFacingError(message);this.fetchState={kind:"error",message},this.emit("lr-render-error",{error})}isCurrentLoad(generation,ownerView){return this.isConnected&&generation===this.generation&&this.ownerDocument.defaultView===ownerView}async parse(buffer,generation,ownerView){const{PostalMime,DOMPurify}=await loadEmailDeps();if(!this.isCurrentLoad(generation,ownerView))return null;if(!PostalMime)throw new LyraUserFacingError(this.localize("emailViewerMissingParser"));const rawParsed=await PostalMime.parse(buffer);if(!this.isCurrentLoad(generation,ownerView))return null;const parsed=normalizeParsedEmail(rawParsed);if(!parsed)throw new LyraUserFacingError(this.localize("documentPreviewFailedToLoad"));const sanitized=parsed.html!==void 0&&DOMPurify?sanitizePassiveMarkup(DOMPurify,parsed.html,this.ownerDocument,"passive-document"):"",bodyHtml=sanitized.trim()?sanitized:null;if(!this.isCurrentLoad(generation,ownerView))return null;if(parsed.html&&!DOMPurify&&!parsed.text)throw new LyraUserFacingError(this.localize("documentViewerMissingSanitizer"));return{...parsed.from===void 0?{}:{fromAddress:parsed.from},toAddresses:parsed.to,email:{from:this.formatAddress(parsed.from),to:this.formatAddresses(parsed.to),subject:parsed.subject??"",date:parsed.date??"",bodyHtml,bodyText:bodyHtml?null:parsed.text??null,attachments:[...parsed.attachments]}}}formatAddress(value){if(!value)return"";if(value.group){const members=getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value.group.map(entry=>this.formatAddress(entry)).filter(Boolean));return value.name?this.localize("emailViewerGroupAddress",void 0,{name:value.name,members}):members}return value.name&&value.address?getListFormat(this.effectiveLocale,{style:"long",type:"unit"}).format([value.name,value.address]):value.address??value.name??""}formatAddresses(values){return getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format((values??[]).map(value=>this.formatAddress(value)).filter(Boolean))}formatDate(value){if(!value)return"";const date=new Date(value);return Number.isNaN(date.getTime())?value:getDateTimeFormat(this.effectiveLocale,{dateStyle:"medium",timeStyle:"short"}).format(date)}renderHeaders(email,fromAddress,toAddresses){return html`<div part="headers">
4
4
  <span part="from-label">${this.localize("emailViewerFrom")}</span><span part="from">${fromAddress?this.formatAddress(fromAddress):email.from}</span>
@@ -1 +1 @@
1
- import{LyraGeoJsonViewer}from"./geojson-viewer.class.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound}from"../../../internal/default-strings.generated.js";class LyraGeojsonView extends LyraGeoJsonViewer{static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound}}}export{LyraGeojsonView};
1
+ import{LyraGeoJsonViewer}from"./geojson-viewer.class.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound}from"../../../internal/default-strings/shared.generated.js";class LyraGeojsonView extends LyraGeoJsonViewer{static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound}}}export{LyraGeojsonView};