@aceshooting/lyra-ui 19.0.1 → 20.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (418) hide show
  1. package/CHANGELOG.md +159 -0
  2. package/custom-elements.json +1 -1
  3. package/dist/cli/migration-contract.json +1 -1
  4. package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +14 -4
  5. package/dist/components/agent-tools/activity-feed/activity-feed.styles.js +1 -1
  6. package/dist/components/agent-tools/approval-queue/approval-queue.class.d.ts +1 -0
  7. package/dist/components/agent-tools/approval-queue/approval-queue.class.js +4 -3
  8. package/dist/components/agent-tools/approval-queue/approval-queue.styles.js +1 -1
  9. package/dist/components/agent-tools/artifact-panel/artifact-panel.class.d.ts +3 -1
  10. package/dist/components/agent-tools/context-inspector/context-inspector.class.d.ts +1 -0
  11. package/dist/components/agent-tools/context-inspector/context-inspector.class.js +4 -3
  12. package/dist/components/agent-tools/context-inspector/context-inspector.styles.js +1 -1
  13. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  14. package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
  15. package/dist/components/agent-tools/evaluation-run/evaluation-run.class.d.ts +1 -0
  16. package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +4 -3
  17. package/dist/components/agent-tools/evaluation-run/evaluation-run.styles.js +1 -1
  18. package/dist/components/agent-tools/policy-summary/policy-summary.class.d.ts +1 -0
  19. package/dist/components/agent-tools/policy-summary/policy-summary.class.js +4 -3
  20. package/dist/components/agent-tools/policy-summary/policy-summary.styles.js +1 -1
  21. package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +1 -1
  22. package/dist/components/agent-tools/schema-viewer/schema-viewer.class.d.ts +10 -1
  23. package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +3 -3
  24. package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +1 -1
  25. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.d.ts +6 -3
  26. package/dist/components/agent-tools/thinking-panel/thinking-panel.styles.js +1 -1
  27. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +14 -3
  28. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  29. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +12 -2
  30. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +3 -1
  31. package/dist/components/charts/chart/box-plot.class.d.ts +15 -3
  32. package/dist/components/charts/chart/box-plot.class.js +3 -3
  33. package/dist/components/charts/chart/box-plot.styles.js +1 -1
  34. package/dist/components/charts/chart/chart.class.d.ts +23 -5
  35. package/dist/components/charts/chart/chart.class.js +2 -2
  36. package/dist/components/charts/chart/chart.styles.js +1 -1
  37. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  38. package/dist/components/charts/chart/lite-chart.styles.js +1 -1
  39. package/dist/components/conversation/audio-visualizer/audio-visualizer.class.d.ts +4 -2
  40. package/dist/components/conversation/audio-visualizer/audio-visualizer.class.js +1 -1
  41. package/dist/components/conversation/branch-picker/branch-picker.class.d.ts +4 -2
  42. package/dist/components/conversation/branch-picker/branch-picker.class.js +1 -1
  43. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +4 -3
  44. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  45. package/dist/components/conversation/code-block/code-block-core.class.d.ts +6 -11
  46. package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
  47. package/dist/components/conversation/code-block/code-block-shared.d.ts +29 -1
  48. package/dist/components/conversation/code-block/code-block-shared.js +1 -1
  49. package/dist/components/conversation/code-block/code-block.class.d.ts +6 -11
  50. package/dist/components/conversation/code-block/code-block.class.js +1 -1
  51. package/dist/components/conversation/markdown/markdown-shared.js +2 -2
  52. package/dist/components/conversation/message-actions/message-actions.class.d.ts +4 -2
  53. package/dist/components/conversation/message-actions/message-actions.class.js +2 -2
  54. package/dist/components/conversation/message-parts/message-parts.class.d.ts +17 -2
  55. package/dist/components/conversation/model-select/model-select.class.js +1 -0
  56. package/dist/components/conversation/model-select/model-select.styles.js +1 -1
  57. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +5 -1
  58. package/dist/components/conversation/prompt-input/prompt-input.class.js +2 -2
  59. package/dist/components/conversation/prompt-queue/prompt-queue.class.d.ts +6 -1
  60. package/dist/components/conversation/prompt-queue/prompt-queue.class.js +2 -2
  61. package/dist/components/conversation/realtime-session/realtime-session.class.d.ts +5 -1
  62. package/dist/components/conversation/realtime-session/realtime-session.class.js +1 -1
  63. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -1
  64. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  65. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +13 -2
  66. package/dist/components/conversation/voice-picker/voice-picker.class.js +5 -3
  67. package/dist/components/conversation/voice-picker/voice-picker.styles.js +1 -1
  68. package/dist/components/data/calendar/calendar.class.d.ts +9 -0
  69. package/dist/components/data/calendar/calendar.class.js +2 -2
  70. package/dist/components/data/calendar/calendar.styles.js +1 -1
  71. package/dist/components/data/condition-builder/condition-builder.class.d.ts +5 -1
  72. package/dist/components/data/context-meter/context-meter.class.d.ts +4 -0
  73. package/dist/components/data/context-meter/context-meter.styles.js +1 -1
  74. package/dist/components/data/data-grid/data-grid.class.d.ts +8 -2
  75. package/dist/components/data/data-grid/data-grid.class.js +1 -2
  76. package/dist/components/data/flow-node/flow-node.class.d.ts +7 -4
  77. package/dist/components/data/flow-node/flow-node.styles.js +1 -1
  78. package/dist/components/data/funnel/funnel.class.d.ts +5 -0
  79. package/dist/components/data/funnel/funnel.class.js +4 -3
  80. package/dist/components/data/funnel/funnel.styles.js +1 -1
  81. package/dist/components/data/gauge/gauge.class.d.ts +12 -1
  82. package/dist/components/data/gauge/gauge.styles.js +1 -1
  83. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +50 -13
  84. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
  85. package/dist/components/data/graph-query-builder/graph-query-builder.styles.js +1 -1
  86. package/dist/components/data/heatmap/heatmap.class.d.ts +27 -9
  87. package/dist/components/data/heatmap/heatmap.class.js +5 -3
  88. package/dist/components/data/sequence-strip/sequence-strip.class.d.ts +2 -0
  89. package/dist/components/data/sequence-strip/sequence-strip.styles.js +1 -1
  90. package/dist/components/data/table/table.class.d.ts +8 -0
  91. package/dist/components/data/table/table.class.js +2 -1
  92. package/dist/components/data/tree/tree.class.d.ts +20 -1
  93. package/dist/components/data/tree/tree.class.js +1 -1
  94. package/dist/components/data/word-cloud/word-cloud.class.d.ts +4 -1
  95. package/dist/components/data/word-cloud/word-cloud.class.js +2 -2
  96. package/dist/components/forms/button/button.class.js +1 -1
  97. package/dist/components/forms/checkbox/checkbox.class.d.ts +11 -8
  98. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  99. package/dist/components/forms/checkbox/checkbox.styles.js +1 -1
  100. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +2 -2
  101. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  102. package/dist/components/forms/code-editor/code-editor.class.d.ts +2 -0
  103. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  104. package/dist/components/forms/code-editor/code-editor.styles.js +1 -1
  105. package/dist/components/forms/color-picker/color-picker.class.d.ts +11 -1
  106. package/dist/components/forms/color-picker/color-picker.class.js +4 -3
  107. package/dist/components/forms/combobox/combobox.class.d.ts +67 -18
  108. package/dist/components/forms/combobox/combobox.class.js +7 -6
  109. package/dist/components/forms/combobox/combobox.styles.js +1 -1
  110. package/dist/components/forms/date-picker/date-input.class.d.ts +22 -2
  111. package/dist/components/forms/date-picker/date-input.class.js +4 -2
  112. package/dist/components/forms/date-picker/date-input.styles.js +1 -1
  113. package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +18 -4
  114. package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
  115. package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +18 -4
  116. package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
  117. package/dist/components/forms/emoji-picker/emoji-picker.styles.js +1 -1
  118. package/dist/components/forms/icon-button/icon-button.class.d.ts +1 -1
  119. package/dist/components/forms/input/time-input.class.d.ts +11 -1
  120. package/dist/components/forms/input/time-input.class.js +4 -3
  121. package/dist/components/forms/input/time-input.styles.js +1 -1
  122. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +17 -3
  123. package/dist/components/forms/locale-picker/locale-picker.class.js +3 -2
  124. package/dist/components/forms/locale-picker/locale-picker.styles.js +1 -1
  125. package/dist/components/forms/otp-input/otp-input.class.d.ts +13 -5
  126. package/dist/components/forms/otp-input/otp-input.class.js +2 -2
  127. package/dist/components/forms/otp-input/otp-input.styles.js +1 -1
  128. package/dist/components/forms/phone-input/phone-input.class.d.ts +10 -3
  129. package/dist/components/forms/phone-input/phone-input.class.js +6 -2
  130. package/dist/components/forms/phone-input/phone-input.styles.js +1 -1
  131. package/dist/components/forms/radio/radio-group.class.d.ts +1 -1
  132. package/dist/components/forms/radio/radio-group.class.js +2 -2
  133. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +9 -1
  134. package/dist/components/forms/rubric-form/rubric-form.class.js +5 -3
  135. package/dist/components/forms/select/select.class.d.ts +4 -0
  136. package/dist/components/forms/select/select.styles.js +1 -1
  137. package/dist/components/forms/slider/slider.class.d.ts +5 -1
  138. package/dist/components/forms/slider/slider.class.js +3 -3
  139. package/dist/components/forms/switch/switch.class.d.ts +6 -5
  140. package/dist/components/forms/switch/switch.class.js +1 -1
  141. package/dist/components/forms/time-range/time-range.class.d.ts +2 -2
  142. package/dist/components/forms/token-input/token-input.class.d.ts +13 -3
  143. package/dist/components/forms/token-input/token-input.class.js +3 -1
  144. package/dist/components/layout/carousel/carousel.class.d.ts +4 -1
  145. package/dist/components/layout/carousel/carousel.class.js +1 -1
  146. package/dist/components/layout/command-palette/command-palette.class.d.ts +8 -2
  147. package/dist/components/layout/command-palette/command-palette.class.js +1 -1
  148. package/dist/components/layout/command-palette/command-palette.styles.js +1 -1
  149. package/dist/components/layout/details/accordion.class.js +1 -1
  150. package/dist/components/layout/dock-panel/dock-panel.class.d.ts +10 -7
  151. package/dist/components/layout/dock-panel/dock-panel.class.js +2 -2
  152. package/dist/components/layout/dock-panel/dock-panel.styles.js +1 -1
  153. package/dist/components/layout/menu/menu.class.d.ts +13 -3
  154. package/dist/components/layout/menu/menu.class.js +4 -3
  155. package/dist/components/layout/menu/menu.styles.js +1 -1
  156. package/dist/components/layout/page/page.class.d.ts +7 -1
  157. package/dist/components/layout/reorder-list/reorder-list.class.d.ts +1 -1
  158. package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
  159. package/dist/components/layout/segmented/segmented.class.d.ts +2 -0
  160. package/dist/components/layout/segmented/segmented.styles.js +1 -1
  161. package/dist/components/layout/virtual-list/virtual-list.styles.js +1 -1
  162. package/dist/components/layout/widget/widget.class.d.ts +15 -2
  163. package/dist/components/layout/widget/widget.class.js +1 -1
  164. package/dist/components/layout/widget/widget.styles.js +1 -1
  165. package/dist/components/media/avatar/avatar.class.d.ts +4 -0
  166. package/dist/components/media/avatar/avatar.styles.js +1 -1
  167. package/dist/components/media/avatar-group/avatar-group.class.d.ts +8 -1
  168. package/dist/components/media/avatar-group/avatar-group.styles.js +1 -1
  169. package/dist/components/media/drop-zone/drop-zone.class.d.ts +10 -4
  170. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  171. package/dist/components/media/drop-zone/drop-zone.styles.js +1 -1
  172. package/dist/components/media/flag/flag.class.js +1 -1
  173. package/dist/components/media/map/map.class.d.ts +19 -5
  174. package/dist/components/media/map/map.class.js +3 -3
  175. package/dist/components/media/video-playlist/video-playlist.class.d.ts +6 -3
  176. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  177. package/dist/components/overlays/callout/callout.class.d.ts +4 -1
  178. package/dist/components/overlays/dialog/dialog.class.d.ts +4 -1
  179. package/dist/components/overlays/overlay/overlay.styles.js +1 -1
  180. package/dist/components/overlays/overlay/popover.class.d.ts +9 -1
  181. package/dist/components/overlays/overlay/popover.class.js +3 -2
  182. package/dist/components/overlays/overlay/tooltip.class.d.ts +14 -4
  183. package/dist/components/overlays/overlay/tooltip.class.js +3 -2
  184. package/dist/components/overlays/popup/popup.class.d.ts +15 -1
  185. package/dist/components/overlays/popup/popup.class.js +3 -3
  186. package/dist/components/overlays/popup/popup.styles.js +1 -1
  187. package/dist/components/overlays/progress/progress-bar.class.d.ts +2 -0
  188. package/dist/components/overlays/progress/progress.styles.js +1 -1
  189. package/dist/components/retrieval/citation-badge/citation-badge.class.d.ts +4 -2
  190. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  191. package/dist/components/retrieval/claim-evidence/claim-evidence.class.d.ts +4 -0
  192. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +4 -3
  193. package/dist/components/retrieval/claim-evidence/claim-evidence.styles.js +1 -1
  194. package/dist/components/retrieval/community-card/community-card.class.d.ts +6 -1
  195. package/dist/components/retrieval/community-card/community-card.styles.js +1 -1
  196. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.d.ts +9 -1
  197. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +4 -3
  198. package/dist/components/retrieval/entity-card/entity-card.styles.js +1 -1
  199. package/dist/components/retrieval/entity-chip/entity-chip.class.d.ts +4 -2
  200. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  201. package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +2 -2
  202. package/dist/components/retrieval/graph-legend/graph-legend.class.d.ts +18 -4
  203. package/dist/components/retrieval/graph-legend/graph-legend.class.js +2 -2
  204. package/dist/components/retrieval/grounding-summary/grounding-summary.class.d.ts +7 -0
  205. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +4 -3
  206. package/dist/components/retrieval/grounding-summary/grounding-summary.styles.js +1 -1
  207. package/dist/components/retrieval/memory-panel/memory-panel.class.d.ts +6 -0
  208. package/dist/components/retrieval/memory-panel/memory-panel.class.js +4 -3
  209. package/dist/components/retrieval/memory-panel/memory-panel.styles.js +1 -1
  210. package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +17 -1
  211. package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
  212. package/dist/components/retrieval/mind-map/mind-map.class.d.ts +8 -1
  213. package/dist/components/retrieval/mind-map/mind-map.class.js +3 -2
  214. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +5 -0
  215. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +6 -5
  216. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.styles.js +1 -1
  217. package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.js +5 -5
  218. package/dist/components/retrieval/retrieval-compare/retrieval-compare.styles.js +1 -1
  219. package/dist/components/retrieval/source-list/source-list.class.d.ts +21 -2
  220. package/dist/components/retrieval/source-list/source-list.class.js +2 -2
  221. package/dist/components/retrieval/source-list/source-list.styles.js +1 -1
  222. package/dist/components/retrieval/source-picker/source-picker.class.d.ts +3 -1
  223. package/dist/components/retrieval/source-picker/source-picker.class.js +2 -2
  224. package/dist/components/utility/diff-view/diff-view.class.d.ts +105 -8
  225. package/dist/components/utility/diff-view/diff-view.class.js +21 -5
  226. package/dist/components/utility/diff-view/diff-view.styles.js +1 -1
  227. package/dist/components/utility/export-button/export-button.class.d.ts +26 -2
  228. package/dist/components/utility/export-button/export-button.class.js +4 -2
  229. package/dist/components/utility/export-button/export-button.styles.js +1 -1
  230. package/dist/components/utility/mention-popover/mention-popover.class.d.ts +19 -1
  231. package/dist/components/utility/mention-popover/mention-popover.class.js +3 -2
  232. package/dist/components/utility/mention-popover/mention-popover.styles.js +1 -1
  233. package/dist/components/utility/tour/tour.class.d.ts +1 -3
  234. package/dist/components/utility/tour/tour.class.js +1 -1
  235. package/dist/components/viewers/archive-viewer/archive-viewer.class.d.ts +20 -3
  236. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  237. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  238. package/dist/components/viewers/geojson-view/geojson-view.styles.js +1 -1
  239. package/dist/components/viewers/geojson-view/geojson-viewer.class.d.ts +5 -0
  240. package/dist/components/viewers/geojson-view/geojson-viewer.class.js +6 -3
  241. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +7 -1
  242. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  243. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.d.ts +7 -1
  244. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
  245. package/dist/components/viewers/xml-viewer/xml-viewer.class.d.ts +5 -0
  246. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
  247. package/dist/custom-elements-jsx.d.ts +1 -1
  248. package/dist/events.d.ts +79 -30
  249. package/dist/internal/accessibility-visibility.js +1 -1
  250. package/dist/internal/aria-reflection.js +1 -1
  251. package/dist/internal/catalog-picker.d.ts +14 -3
  252. package/dist/internal/catalog-picker.js +1 -1
  253. package/dist/internal/default-strings.generated.d.ts +1 -1
  254. package/dist/internal/default-strings.generated.js +2 -2
  255. package/dist/internal/localization-types.d.ts +1 -1
  256. package/dist/internal/localization.js +2 -2
  257. package/dist/internal/lyra-element.d.ts +17 -0
  258. package/dist/internal/lyra-element.js +2 -2
  259. package/dist/internal/package-metadata.d.ts +1 -1
  260. package/dist/internal/package-metadata.js +1 -1
  261. package/dist/svelte.d.ts +1 -1
  262. package/dist/testing/lyra-tag-event-map.js +1 -1
  263. package/dist/translations/ar/agent-tools.js +1 -1
  264. package/dist/translations/ar/data.js +1 -1
  265. package/dist/translations/ar/retrieval.js +1 -1
  266. package/dist/translations/ar/shared.js +1 -1
  267. package/dist/translations/ar/viewers.js +1 -1
  268. package/dist/translations/de/agent-tools.js +1 -1
  269. package/dist/translations/de/data.js +1 -1
  270. package/dist/translations/de/retrieval.js +1 -1
  271. package/dist/translations/de/shared.js +1 -1
  272. package/dist/translations/de/viewers.js +1 -1
  273. package/dist/translations/es/agent-tools.js +1 -1
  274. package/dist/translations/es/data.js +1 -1
  275. package/dist/translations/es/retrieval.js +1 -1
  276. package/dist/translations/es/shared.js +1 -1
  277. package/dist/translations/es/viewers.js +1 -1
  278. package/dist/translations/fa/agent-tools.js +1 -1
  279. package/dist/translations/fa/data.js +1 -1
  280. package/dist/translations/fa/retrieval.js +1 -1
  281. package/dist/translations/fa/shared.js +1 -1
  282. package/dist/translations/fa/viewers.js +1 -1
  283. package/dist/translations/fr/agent-tools.js +1 -1
  284. package/dist/translations/fr/data.js +1 -1
  285. package/dist/translations/fr/retrieval.js +1 -1
  286. package/dist/translations/fr/shared.js +1 -1
  287. package/dist/translations/fr/viewers.js +1 -1
  288. package/dist/translations/he/agent-tools.js +1 -1
  289. package/dist/translations/he/data.js +1 -1
  290. package/dist/translations/he/retrieval.js +1 -1
  291. package/dist/translations/he/shared.js +1 -1
  292. package/dist/translations/he/viewers.js +1 -1
  293. package/dist/translations/it/agent-tools.js +1 -1
  294. package/dist/translations/it/data.js +1 -1
  295. package/dist/translations/it/retrieval.js +1 -1
  296. package/dist/translations/it/shared.js +1 -1
  297. package/dist/translations/it/viewers.js +1 -1
  298. package/dist/translations/ja/agent-tools.js +1 -1
  299. package/dist/translations/ja/data.js +1 -1
  300. package/dist/translations/ja/retrieval.js +1 -1
  301. package/dist/translations/ja/shared.js +1 -1
  302. package/dist/translations/ja/viewers.js +1 -1
  303. package/dist/translations/pt-BR/agent-tools.js +1 -1
  304. package/dist/translations/pt-BR/data.js +1 -1
  305. package/dist/translations/pt-BR/retrieval.js +1 -1
  306. package/dist/translations/pt-BR/shared.js +1 -1
  307. package/dist/translations/pt-BR/viewers.js +1 -1
  308. package/dist/translations/ro/agent-tools.js +1 -1
  309. package/dist/translations/ro/data.js +1 -1
  310. package/dist/translations/ro/retrieval.js +1 -1
  311. package/dist/translations/ro/shared.js +1 -1
  312. package/dist/translations/ro/viewers.js +1 -1
  313. package/dist/translations/ru/agent-tools.js +1 -1
  314. package/dist/translations/ru/data.js +1 -1
  315. package/dist/translations/ru/retrieval.js +1 -1
  316. package/dist/translations/ru/shared.js +1 -1
  317. package/dist/translations/ru/viewers.js +1 -1
  318. package/dist/translations/zh-CN/agent-tools.js +1 -1
  319. package/dist/translations/zh-CN/data.js +1 -1
  320. package/dist/translations/zh-CN/retrieval.js +1 -1
  321. package/dist/translations/zh-CN/shared.js +1 -1
  322. package/dist/translations/zh-CN/viewers.js +1 -1
  323. package/dist/vue.d.ts +1 -1
  324. package/llms/components/lr-activity-feed.md +20 -9
  325. package/llms/components/lr-approval-queue.md +3 -2
  326. package/llms/components/lr-archive-viewer.md +8 -1
  327. package/llms/components/lr-artifact-panel.md +3 -1
  328. package/llms/components/lr-audio-visualizer.md +3 -1
  329. package/llms/components/lr-avatar-group.md +13 -6
  330. package/llms/components/lr-avatar.md +6 -2
  331. package/llms/components/lr-bar-chart.md +6 -3
  332. package/llms/components/lr-box-plot.md +6 -2
  333. package/llms/components/lr-branch-picker.md +3 -1
  334. package/llms/components/lr-bubble-chart.md +6 -3
  335. package/llms/components/lr-calendar.md +10 -3
  336. package/llms/components/lr-carousel.md +4 -2
  337. package/llms/components/lr-chart.md +12 -4
  338. package/llms/components/lr-chat-viewport.md +3 -2
  339. package/llms/components/lr-checkbox.md +8 -5
  340. package/llms/components/lr-citation-badge.md +2 -0
  341. package/llms/components/lr-claim-evidence.md +6 -2
  342. package/llms/components/lr-code-editor.md +3 -1
  343. package/llms/components/lr-color-picker.md +20 -8
  344. package/llms/components/lr-combobox.md +26 -3
  345. package/llms/components/lr-command-palette.md +6 -3
  346. package/llms/components/lr-community-card.md +7 -4
  347. package/llms/components/lr-context-inspector.md +3 -2
  348. package/llms/components/lr-context-meter.md +13 -5
  349. package/llms/components/lr-data-grid.md +2 -0
  350. package/llms/components/lr-date-input.md +12 -3
  351. package/llms/components/lr-date-picker.md +11 -2
  352. package/llms/components/lr-diff-view.md +46 -5
  353. package/llms/components/lr-doughnut-chart.md +6 -3
  354. package/llms/components/lr-drop-zone.md +7 -3
  355. package/llms/components/lr-embedding-explorer.md +8 -2
  356. package/llms/components/lr-emoji-picker.md +5 -1
  357. package/llms/components/lr-entity-chip.md +2 -0
  358. package/llms/components/lr-eval-run.md +3 -2
  359. package/llms/components/lr-export-button.md +5 -2
  360. package/llms/components/lr-flow-node.md +7 -4
  361. package/llms/components/lr-funnel.md +7 -2
  362. package/llms/components/lr-gauge.md +7 -2
  363. package/llms/components/lr-geojson-view.md +10 -2
  364. package/llms/components/lr-geojson-viewer.md +10 -2
  365. package/llms/components/lr-graph-legend.md +6 -3
  366. package/llms/components/lr-graph-query-builder.md +21 -11
  367. package/llms/components/lr-grounding-summary.md +8 -2
  368. package/llms/components/lr-heatmap.md +5 -2
  369. package/llms/components/lr-histogram.md +4 -2
  370. package/llms/components/lr-json-schema-viewer.md +7 -5
  371. package/llms/components/lr-line-chart.md +6 -3
  372. package/llms/components/lr-locale-picker.md +4 -1
  373. package/llms/components/lr-map.md +5 -3
  374. package/llms/components/lr-memory-panel.md +6 -2
  375. package/llms/components/lr-mention-popover.md +7 -4
  376. package/llms/components/lr-message-actions.md +3 -1
  377. package/llms/components/lr-message-parts.md +8 -2
  378. package/llms/components/lr-mind-map.md +11 -2
  379. package/llms/components/lr-option.md +25 -2
  380. package/llms/components/lr-otp-input.md +3 -1
  381. package/llms/components/lr-phone-input.md +9 -5
  382. package/llms/components/lr-pie-chart.md +6 -3
  383. package/llms/components/lr-polar-area-chart.md +6 -3
  384. package/llms/components/lr-policy-summary.md +3 -2
  385. package/llms/components/lr-progress-bar.md +4 -1
  386. package/llms/components/lr-prompt-input.md +4 -1
  387. package/llms/components/lr-prompt-queue.md +5 -2
  388. package/llms/components/lr-radar-chart.md +6 -3
  389. package/llms/components/lr-rag-eval-dashboard.md +7 -2
  390. package/llms/components/lr-realtime-session.md +3 -1
  391. package/llms/components/lr-rubric-form.md +6 -1
  392. package/llms/components/lr-scatter-chart.md +6 -3
  393. package/llms/components/lr-segmented.md +3 -1
  394. package/llms/components/lr-select.md +7 -1
  395. package/llms/components/lr-selection-toolbar.md +4 -1
  396. package/llms/components/lr-sequence-strip.md +7 -3
  397. package/llms/components/lr-source-card.md +16 -1
  398. package/llms/components/lr-source-list.md +17 -2
  399. package/llms/components/lr-source-picker.md +3 -1
  400. package/llms/components/lr-subagent-panel.md +6 -3
  401. package/llms/components/lr-switch.md +4 -3
  402. package/llms/components/lr-table.md +6 -1
  403. package/llms/components/lr-thinking-panel.md +8 -5
  404. package/llms/components/lr-token-input.md +15 -1
  405. package/llms/components/lr-tool-call-chip.md +2 -0
  406. package/llms/components/lr-tool-param-form.md +15 -4
  407. package/llms/components/lr-tooltip.md +8 -4
  408. package/llms/components/lr-trace-tree.md +7 -4
  409. package/llms/components/lr-video-playlist.md +7 -5
  410. package/llms/components/lr-voice-picker.md +7 -4
  411. package/llms/components/lr-widget.md +15 -2
  412. package/llms/migration.md +4 -4
  413. package/llms-full.txt +552 -159
  414. package/package.json +11 -9
  415. package/registrations.json +1 -1
  416. package/vscode-css-data.json +1 -1
  417. package/vscode-html-data.json +1 -1
  418. package/web-types.json +1 -1
@@ -144,6 +144,9 @@ readonly ownsFocus?:()=>boolean;}export interface LyraMentionPopoverEventMap{'lr
144
144
  * @csspart empty - The "no matches" message, shown when `items`/`query` produce zero rows.
145
145
  * @cssprop [--lr-mention-popover-option-active-bg=var(--lr-color-brand-quiet)] - Background of the
146
146
  * hovered or `[data-active]` (keyboard-highlighted) suggestion row.
147
+ * @cssprop [--lr-mention-popover-option-active-color=var(--lr-color-brand)] - Text color of the
148
+ * `aria-selected="true"` (keyboard-highlighted) suggestion row, independent of
149
+ * `--lr-mention-popover-option-active-bg`.
147
150
  * @cssprop [--lr-mention-popover-option-disabled-opacity=0.5] - Opacity of a row whose `items` entry sets `disabled`.
148
151
  * @cssprop [--lr-overlay-surface=var(--lr-color-surface-overlay)] - Shared floating-surface fill,
149
152
  * on the listbox.
@@ -185,7 +188,15 @@ emptyText?:string;
185
188
  * a plain `aria-label` attribute on `<lr-mention-popover>` itself, which takes precedence over
186
189
  * this property when present -- matches `<lr-combobox>`'s/`<lr-table>`'s identical host
187
190
  * `aria-label` fallback. */
188
- label?:string;private activeIndex;private readonly _listId;private cleanup?;private virtualAnchor;private _isFirstUpdate;private _silentClose;private _ownsFocus;private _focusOwnerPredicate?;private _focusTransferGeneration;private anchorRelationship?;private announcementSink?;private announcedResultCount?;private announcedResultPosition?;connectedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;disconnectedCallback():void;adoptedCallback():void;private syncAnnouncementSink;private resetResultAnnouncements;private announceResultState;private snapshotAttribute;private restoreAttribute;private captureAnchorCaret;private restoreRelationshipFocus;private restoreAnchorFocus;private attachAnchorRelationship;private detachAnchorRelationship;private syncAnchorRelationship;
191
+ label?:string;private activeIndex;
192
+ /** Removes the settled-closed listbox from layout (`[hidden]` -> `display:none`) so its stale
193
+ * placed coordinates and full-content box stop contributing to whatever ancestor establishes
194
+ * its CSS containing block. Starts `true`, clears as soon as `open` becomes true -- before
195
+ * `reposition()`'s deferred placement runs, so the listbox is still a real, measurable box --
196
+ * and is set back only once the CSS opacity/visibility exit transition has actually finished
197
+ * playing (`settleListboxHidden()`), preserving the existing fade in the meantime. Mirrors
198
+ * `LyraSelect`'s `listboxHidden`. */
199
+ private listboxHidden;private listboxHideToken;private readonly _listId;private cleanup?;private virtualAnchor;private _isFirstUpdate;private _silentClose;private _ownsFocus;private _focusOwnerPredicate?;private _focusTransferGeneration;private anchorRelationship?;private announcementSink?;private announcedResultCount?;private announcedResultPosition?;connectedCallback():void;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;disconnectedCallback():void;adoptedCallback():void;private syncAnnouncementSink;private resetResultAnnouncements;private announceResultState;private snapshotAttribute;private restoreAttribute;private captureAnchorCaret;private restoreRelationshipFocus;private restoreAnchorFocus;private attachAnchorRelationship;private detachAnchorRelationship;private syncAnchorRelationship;
189
200
  /** The current candidate set: runtime rows without a non-blank string `label` are omitted (a
190
201
  * blank/whitespace-only label would otherwise render a focusable `role="option"` with no
191
202
  * accessible name), then the remaining `items` are filtered by `query` via `filter` (or the
@@ -241,6 +252,13 @@ private stepEnabledIndex;private rowId;
241
252
  * emits nothing and changes no state, matching every other declared-non-actionable entry in
242
253
  * this library. */
243
254
  private commit;private reposition;
255
+ /** Removes the listbox from layout only once its CSS opacity/visibility exit transition has
256
+ * actually finished playing -- or immediately when there is none to wait for (reduced motion,
257
+ * or a `--lr-transition-fast` override of `0s`), matching this component's own
258
+ * transition-duration custom property rather than a hardcoded guess. A safety timeout covers a
259
+ * browser that never dispatches the end event. Superseded by a fresh close (a new token) or a
260
+ * reopen (`this.open` true again) at either await point. */
261
+ private settleListboxHidden;
244
262
  /** Resolves what to actually hand `place()` -- a caret-precise virtual
245
263
  * point for a measurable text control, `anchor` itself otherwise. See the
246
264
  * class doc's "Positioning" section. */
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{styles}from"./mention-popover.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions,LYRA_DEFAULT_noMatches}from"../../../internal/default-strings.generated.js";function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"];function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el),mirror=owner.createElement("div");mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length;mirror.append(owner.createTextNode(el.value.slice(0,index)));const marker=owner.createElement("span");marker.textContent=el.value.slice(index)||"​",mirror.appendChild(marker),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{constructor(){super(...arguments),this._textareaFocusSessionGeneration=0,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.filteredItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()}}static{this.defaultStrings={...super.defaultStrings,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items,source=Array.isArray(next)?next:[];this._items=Object.freeze(source.map(item=>Object.freeze({...item}))),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.filteredItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]');active?.scrollIntoView({block:"nearest"}),this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcementSink?.release(),this.announcementSink=void 0,this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.syncAnnouncementSink(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}syncAnnouncementSink(){this.announcementSink?.element?.ownerDocument!==this.ownerDocument&&(this.announcementSink?.release(),this.announcementSink=this.isConnected?acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}):void 0)}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open||!this.announcementSink)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcementSink.announce(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcementSink.announce(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,q=(this.query??"").trim().toLocaleLowerCase(locale);return this.items.filter(item=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):item.label.toLocaleLowerCase(locale).includes(q)||(typeof item.description=="string"?item.description:"").toLocaleLowerCase(locale).includes(q):!0)}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.filteredItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),activeElementIn(this.shadowRoot)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&activeElementIn(this.shadowRoot)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.filteredItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.items.indexOf(item);if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{styles}from"./mention-popover.styles.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_mentionResultCount,LYRA_DEFAULT_mentionResultPosition,LYRA_DEFAULT_mentionSuggestions,LYRA_DEFAULT_noMatches}from"../../../internal/default-strings.generated.js";function parseCssTime(value){const trimmed=value.trim();return trimmed.endsWith("ms")?Number.parseFloat(trimmed):trimmed.endsWith("s")?Number.parseFloat(trimmed)*1e3:0}function maxCssTransitionTime(value){return Math.max(0,...value.split(",").map(parseCssTime).filter(Number.isFinite))}function isTextControl(el){const view=el.ownerDocument.defaultView;return view?el instanceof view.HTMLTextAreaElement?!0:el instanceof view.HTMLInputElement&&(el.type==="text"||el.type==="search"):!1}function isTextareaAnchor(el){const view=el.ownerDocument.defaultView;return!!(view&&el instanceof view.HTMLTextAreaElement)}const MIRROR_CSS_PROPS=["box-sizing","width","padding-top","padding-right","padding-bottom","padding-left","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","font-family","font-size","font-style","font-variant","font-weight","font-stretch","letter-spacing","word-spacing","line-height","text-align","text-indent","text-transform","tab-size","direction"];function caretClientRect(el){const owner=el.ownerDocument,view=owner.defaultView;if(!view)return null;const elRect=el.getBoundingClientRect();if(elRect.width===0||elRect.height===0)return null;const computed=view.getComputedStyle(el),mirror=owner.createElement("div");mirror.style.position="absolute",mirror.style.visibility="hidden",mirror.style.top="0",mirror.style.left="-9999px",mirror.style.whiteSpace=el instanceof view.HTMLTextAreaElement?"pre-wrap":"pre",mirror.style.overflowWrap="break-word";for(const prop of MIRROR_CSS_PROPS)mirror.style.setProperty(prop,computed.getPropertyValue(prop));const index=el.selectionStart??el.value.length;mirror.append(owner.createTextNode(el.value.slice(0,index)));const marker=owner.createElement("span");marker.textContent=el.value.slice(index)||"​",mirror.appendChild(marker),owner.body.appendChild(mirror);const mirrorRect=mirror.getBoundingClientRect(),markerRect=marker.getBoundingClientRect();mirror.remove();const lineHeight=parseFloat(computed.lineHeight)||markerRect.height||16;return new view.DOMRect(elRect.left+(markerRect.left-mirrorRect.left)-el.scrollLeft,elRect.top+(markerRect.top-mirrorRect.top)-el.scrollTop,1,lineHeight)}class LyraMentionPopover extends LyraElement{constructor(){super(...arguments),this._textareaFocusSessionGeneration=0,this._items=Object.freeze([]),this.query="",this.open=!1,this.filter=null,this.activeIndex=0,this.listboxHidden=!0,this.listboxHideToken=0,this._listId=nextId("mention-popover-listbox"),this.virtualAnchor=null,this._isFirstUpdate=!0,this._silentClose=!1,this._ownsFocus=!1,this._focusTransferGeneration=0,this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index)||index<0)return;const item=this.filteredItems[index];item&&this.commit(item)},this.onListboxKeyDown=e=>{e.defaultPrevented||!this._ownsFocus||this.handleKeyDown(e)&&this.open&&this.focusActiveOption()}}static{this.defaultStrings={...super.defaultStrings,mentionResultCount:LYRA_DEFAULT_mentionResultCount,mentionResultPosition:LYRA_DEFAULT_mentionResultPosition,mentionSuggestions:LYRA_DEFAULT_mentionSuggestions,noMatches:LYRA_DEFAULT_noMatches}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={items:{attribute:!1,noAccessor:!0}}}requestUpdate(name,oldValue,options){(name==="open"||name==="anchor"||name==="query"||name==="items"||name==="filter")&&this.hasTextareaFocusSession()&&(this._textareaFocusSessionGeneration+=1),super.requestUpdate(name,oldValue,options)}hasTextareaFocusSession(){const relationshipControl=this.anchorRelationship?.control;return this.anchor!==void 0&&isTextareaAnchor(this.anchor)||relationshipControl!==void 0&&isTextareaAnchor(relationshipControl)}get items(){return this._items}set items(next){const previous=this._items,source=Array.isArray(next)?next:[];this._items=Object.freeze(source.map(item=>Object.freeze({...item}))),this.requestUpdate("items",previous)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.announceResultState()}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,changed.has("open")&&this.open&&(this.listboxHidden=!1),this._ownsFocus&&!this.fallbackFocusIsStillOwned()&&(this._ownsFocus=!1,this._focusOwnerPredicate=void 0),(changed.has("query")||changed.has("items")||changed.has("filter"))&&(this.activeIndex=0);const candidatesChanged=changed.has("query")||changed.has("items")||changed.has("filter");this._ownsFocus&&changed.has("open")&&!this.open?(this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0):this._ownsFocus&&this.open&&candidatesChanged&&this.filteredItems.length===0&&(this.anchor?.isConnected?this.restoreAnchorFocus():this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0}),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),this._ownsFocus&&changed.has("anchor")&&this.anchorRelationship?.control!==this.anchor&&this.detachAnchorRelationship()}updated(changed){if(super.updated(changed),changed.has("open"))if(this.open)this.reposition();else{this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.settleListboxHidden();const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),!this._isFirstUpdate&&!this._silentClose&&queueMicrotask(()=>this.emit("lr-mention-close")),this._silentClose=!1}else this.open&&(changed.has("anchor")||changed.has("query"))&&this.reposition();if(changed.has("activeIndex")||changed.has("query")||changed.has("items")||changed.has("filter")){const active=this.renderRoot.querySelector('[part="option"][data-active]');active?.scrollIntoView({block:"nearest"}),this._ownsFocus&&(!active&&this.anchor?.isConnected?this.restoreFocus():this.restoreFocus(!0))}this.syncAnchorRelationship(),this.open?this.announceResultState():this.resetResultAnnouncements()}disconnectedCallback(){this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.announcementSink?.release(),this.announcementSink=void 0,this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.virtualAnchor?.remove(),this.listboxHideToken++,this.listboxHidden=!0,this.open=!1}adoptedCallback(){super.adoptedCallback(),this._focusTransferGeneration+=1,this.resetResultAnnouncements(),this.syncAnnouncementSink(),this._ownsFocus&&this.callFocusOwner(this._focusOwnerPredicate)&&this.restoreAnchorFocus(),this._ownsFocus=!1,this._focusOwnerPredicate=void 0,this.detachAnchorRelationship(),this.open=!1}syncAnnouncementSink(){this.announcementSink?.element?.ownerDocument!==this.ownerDocument&&(this.announcementSink?.release(),this.announcementSink=this.isConnected?acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}):void 0)}resetResultAnnouncements(){this.announcedResultCount=void 0,this.announcedResultPosition=void 0}announceResultState(){if(!this.open||!this.announcementSink)return;const rows=this.filteredItems,resultState=rows.length===0?this.localize("noMatches"):this.localize("mentionResultCount",void 0,{count:rows.length}),index=this.clampedIndex(rows),position=index<0?void 0:this.localize("mentionResultPosition",void 0,{current:index+1,total:rows.length});if(this._isFirstUpdate){this.announcedResultCount=resultState,this.announcedResultPosition=position;return}if(resultState!==this.announcedResultCount&&(this.announcementSink.announce(resultState),this.announcedResultCount=resultState),position===void 0){this.announcedResultPosition=void 0;return}position!==this.announcedResultPosition&&(this.announcementSink.announce(position),this.announcedResultPosition=position)}snapshotAttribute(control,name){return{present:control.hasAttribute(name),value:control.getAttribute(name)}}restoreAttribute(control,name,snapshot){snapshot.present?control.setAttribute(name,snapshot.value??""):control.removeAttribute(name)}captureAnchorCaret(relationship=this.anchorRelationship){if(!relationship||!isTextareaAnchor(relationship.control))return;const{control}=relationship;relationship.selectionStart=control.selectionStart,relationship.selectionEnd=control.selectionEnd,relationship.selectionDirection=control.selectionDirection}restoreRelationshipFocus(relationship){const{control}=relationship;if(control.isConnected)try{control.focus({preventScroll:!0}),isTextareaAnchor(control)&&relationship.selectionStart!==null&&relationship.selectionStart!==void 0&&relationship.selectionEnd!==null&&relationship.selectionEnd!==void 0&&control.setSelectionRange(relationship.selectionStart,relationship.selectionEnd,relationship.selectionDirection??void 0)}catch{}}restoreAnchorFocus(){const relationship=this.anchorRelationship;if(relationship){this.restoreRelationshipFocus(relationship);return}const anchor=this.anchor;if(anchor?.isConnected)try{anchor.focus({preventScroll:!0})}catch{}}attachAnchorRelationship(control){const reflected=control,textarea=isTextareaAnchor(control),attributes=new Map((textarea?["role","aria-expanded","aria-haspopup","aria-autocomplete","aria-controls","aria-activedescendant"]:["role","aria-expanded","aria-haspopup","aria-controls","aria-activedescendant"]).map(name=>[name,this.snapshotAttribute(control,name)])),activeElement="ariaActiveDescendantElement"in control?reflected.ariaActiveDescendantElement??null:void 0,controlsElements="ariaControlsElements"in control?reflected.ariaControlsElements??null:void 0,capturedTextareaActiveElement=textarea&&attributes.get("aria-activedescendant")?.present&&attributes.get("aria-activedescendant")?.value===""?activeElement??void 0:void 0,capturedTextareaControlsElements=textarea&&attributes.get("aria-controls")?.present&&attributes.get("aria-controls")?.value===""&&controlsElements?.length?controlsElements:void 0,relationship={control,attributes,activeElement:textarea?capturedTextareaActiveElement:activeElement,controlsElements:textarea?capturedTextareaControlsElements:controlsElements,selectionStart:textarea?control.selectionStart:void 0,selectionEnd:textarea?control.selectionEnd:void 0,selectionDirection:textarea?control.selectionDirection:void 0};return this.anchorRelationship=relationship,relationship}detachAnchorRelationship(){const relationship=this.anchorRelationship;if(!relationship)return;if(this.anchorRelationship=void 0,this._ownsFocus&&(this.restoreRelationshipFocus(relationship),this._ownsFocus=!1,this._focusOwnerPredicate=void 0),!isTextareaAnchor(relationship.control)){const reflected2=relationship.control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=relationship.controlsElements}catch{}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);return}for(const[name,snapshot]of relationship.attributes)this.restoreAttribute(relationship.control,name,snapshot);const reflected=relationship.control;if(relationship.activeElement!==void 0)try{reflected.ariaActiveDescendantElement=relationship.activeElement}catch{}if(relationship.controlsElements!==void 0)try{reflected.ariaControlsElements=relationship.controlsElements}catch{}}syncAnchorRelationship(){const next=this.open&&this.anchor&&isTextControl(this.anchor)?this.anchor:void 0;if(this.anchorRelationship?.control!==next&&this.detachAnchorRelationship(),!next)return;const relationship=this.anchorRelationship??this.attachAnchorRelationship(next),control=relationship.control;if(isTextareaAnchor(control)){control.removeAttribute("role"),control.removeAttribute("aria-expanded"),control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant");const reflected2=control;if(relationship.activeElement!==void 0)try{reflected2.ariaActiveDescendantElement=null}catch{}if(relationship.controlsElements!==void 0)try{reflected2.ariaControlsElements=null}catch{}control.removeAttribute("aria-controls"),control.removeAttribute("aria-activedescendant"),control.setAttribute("aria-haspopup","listbox"),control.setAttribute("aria-autocomplete","list");return}relationship.attributes.get("role")?.present||control.setAttribute("role","combobox"),control.setAttribute("aria-expanded","true"),control.setAttribute("aria-haspopup","listbox");const listbox=this.renderRoot.querySelector('[part="listbox"]'),reflected=control;if(listbox&&"ariaControlsElements"in control)try{control.removeAttribute("aria-controls"),reflected.ariaControlsElements=[listbox],reflected.ariaControlsElements?.[0]!==listbox&&(reflected.ariaControlsElements=[this],reflected.ariaControlsElements?.[0]!==this&&control.removeAttribute("aria-controls"))}catch{control.removeAttribute("aria-controls")}else control.removeAttribute("aria-controls");control.removeAttribute("aria-activedescendant"),this.syncActiveDescendant(control)}get filteredItems(){const locale=this.effectiveLocale,q=(this.query??"").trim().toLocaleLowerCase(locale);return this.items.filter(item=>typeof item.label!="string"||item.label.trim().length===0?!1:q?this.filter?this.filter(item,q):item.label.toLocaleLowerCase(locale).includes(q)||(typeof item.description=="string"?item.description:"").toLocaleLowerCase(locale).includes(q):!0)}get activeDescendantId(){if(!this.open)return null;const idx=this.clampedIndex(this.filteredItems);return idx>=0?this.rowId(idx):null}get activeDescendantElement(){const id=this.activeDescendantId,escape=this.ownerDocument.defaultView?.CSS.escape;return id&&escape?this.renderRoot.querySelector(`#${escape(id)}`):null}syncActiveDescendant(_control){if(isTextareaAnchor(_control)||(_control.removeAttribute("aria-activedescendant"),!("ariaActiveDescendantElement"in _control)))return!1;const active=this.activeDescendantElement;try{const reflected=_control;reflected.ariaActiveDescendantElement=active;const accepted=reflected.ariaActiveDescendantElement===active;return accepted||(reflected.ariaActiveDescendantElement=null,_control.removeAttribute("aria-activedescendant")),accepted}catch{return _control.removeAttribute("aria-activedescendant"),!1}}async focusActiveOption(options={}){const ownsFocus=options.ownsFocus??(this._ownsFocus?this._focusOwnerPredicate:void 0);if(!this.open||!this.isConnected||!this.activeDescendantElement||!this.callFocusOwner(ownsFocus))return!1;const generation=++this._focusTransferGeneration,textareaSession=this.anchor!==void 0&&isTextareaAnchor(this.anchor),textareaSessionGeneration=this._textareaFocusSessionGeneration,snapshot={ownerDocument:this.ownerDocument,anchor:this.anchor,items:this.items,query:this.query,filter:this.filter,activeIndex:this.activeIndex};if(await this.updateComplete,await this.cleanup?.ready===!1||generation!==this._focusTransferGeneration||textareaSession&&textareaSessionGeneration!==this._textareaFocusSessionGeneration||!this.isConnected||!this.open||this.ownerDocument!==snapshot.ownerDocument||this.anchor!==snapshot.anchor||this.items!==snapshot.items||this.query!==snapshot.query||this.filter!==snapshot.filter||this.activeIndex!==snapshot.activeIndex||!this.callFocusOwner(ownsFocus))return!1;const active=this.activeDescendantElement;return!active?.isConnected||!this.callFocusOwner(ownsFocus)||(this.captureAnchorCaret(),active.focus({preventScroll:!0}),activeElementIn(this.shadowRoot)!==active)?!1:(this._focusOwnerPredicate=ownsFocus,this._ownsFocus=!0,!0)}async restoreFocus(waitForPlacement=!1){if(waitForPlacement){if(await this.cleanup?.ready===!1||!this._ownsFocus||!this.open)return;if(this.hasTextareaFocusSession()&&!this.fallbackFocusIsStillOwned()){this._ownsFocus=!1,this._focusOwnerPredicate=void 0;return}}const active=this.renderRoot.querySelector('[part="option"][data-active]');active?active.focus({preventScroll:!0}):this.anchor?.isConnected?(this.renderRoot.querySelector('[part="listbox"]')?.setAttribute("tabindex","-1"),this.restoreAnchorFocus(),this.scheduleAfterUpdate(()=>{this._ownsFocus=!1,this._focusOwnerPredicate=void 0})):this.renderRoot.querySelector('[part="listbox"]')?.focus({preventScroll:!0})}callFocusOwner(predicate){try{return predicate?.()??!0}catch{return!1}}fallbackFocusIsStillOwned(){return this.callFocusOwner(this._focusOwnerPredicate)&&activeElementIn(this.shadowRoot)!==null}get listboxId(){return this._listId}handleKeyDown(e){if(!this.open||e.isComposing||e.keyCode===229)return!1;const rows=this.filteredItems;switch(e.key){case"ArrowDown":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),1),!0):!1;case"ArrowUp":return rows.length?(e.preventDefault(),this.activeIndex=this.stepEnabledIndex(rows,this.clampedIndex(rows),-1),!0):!1;case"Enter":case"Tab":{const idx=this.clampedIndex(rows);return idx<0?!1:(e.preventDefault(),this.commit(rows[idx]),!0)}case"Escape":return e.preventDefault(),this.open=!1,!0;default:return!1}}clampedIndex(rows){const count=rows.length;if(!count)return-1;const clamped=Math.min(Math.max(this.activeIndex,0),count-1);if(!rows[clamped]?.disabled)return clamped;for(let forward=clamped+1;forward<count;forward+=1)if(!rows[forward]?.disabled)return forward;for(let backward=clamped-1;backward>=0;backward-=1)if(!rows[backward]?.disabled)return backward;return-1}stepEnabledIndex(rows,from,direction){const count=rows.length;if(!count)return 0;let index=Math.min(Math.max(from+direction,0),count-1);for(let steps=0;steps<count;steps+=1){if(!rows[index]?.disabled)return index;if(index+=direction,index<0||index>=count)break}return from>=0&&from<count&&!rows[from]?.disabled?from:this.activeIndex}rowId(index){return`${this._listId}-opt-${index}`}commit(item){if(item.disabled)return;const index=this.items.indexOf(item);if(index<0)return;const relationshipControl=this.anchorRelationship?.control;relationshipControl&&isTextareaAnchor(relationshipControl)&&this.detachAnchorRelationship(),this.emit("lr-mention-select",Object.freeze({suggestionId:item.suggestionId,index,label:item.label})),this._silentClose=!0,this.open=!1}reposition(){this.cleanup?.(),this.cleanup=void 0;const anchorEl=this.resolveAnchorElement(),popup=this.renderRoot.querySelector('[part="listbox"]');if(anchorEl&&popup){const placement=place(anchorEl,popup,{placement:"bottom-start",strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{positioned||this.cleanup!==placement||!this.open||(this._silentClose=!0,this.open=!1)})}}async settleListboxHidden(){const token=++this.listboxHideToken;if(await this.updateComplete,token!==this.listboxHideToken||this.open)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),view=this.ownerDocument.defaultView;if(listbox&&view&&!prefersReducedMotion(view)){const computed=view.getComputedStyle(listbox),durationMs=maxCssTransitionTime(computed.transitionDuration)+maxCssTransitionTime(computed.transitionDelay);if(durationMs>0&&(await new Promise(resolve=>{let settled=!1,timeout;const finish=()=>{settled||(settled=!0,timeout!==void 0&&view.clearTimeout(timeout),listbox.removeEventListener("transitionend",onEnd),listbox.removeEventListener("transitioncancel",onEnd),resolve())},onEnd=event=>{event.target===listbox&&finish()};listbox.addEventListener("transitionend",onEnd),listbox.addEventListener("transitioncancel",onEnd),timeout=view.setTimeout(finish,durationMs+50)}),token!==this.listboxHideToken||this.open))return}this.listboxHidden=!0}resolveAnchorElement(){const anchor=this.anchor;if(!anchor)return null;if(isTextControl(anchor)){const rect=caretClientRect(anchor);if(rect){const owner=anchor.ownerDocument;this.virtualAnchor&&this.virtualAnchor.ownerDocument!==owner&&(this.virtualAnchor.remove(),this.virtualAnchor=null);const virtual=this.virtualAnchor??(this.virtualAnchor=owner.createElement("div"));return virtual.style.position="fixed",virtual.style.left=`${rect.left}px`,virtual.style.top=`${rect.top}px`,virtual.style.width="0",virtual.style.height=`${rect.height}px`,virtual.style.pointerEvents="none",virtual.isConnected||owner.body.appendChild(virtual),virtual}}return anchor}get effectiveEmptyText(){return this.emptyText===void 0?this.localize("noMatches"):this.emptyText}get effectiveLabel(){return hostAriaLabel(this)??(this.label===void 0?this.localize("mentionSuggestions"):this.label)}renderRow(item,index,activeId){const id=this.rowId(index),active=id===activeId;return html`
2
2
  <div
3
3
  part="option"
4
4
  id=${id}
@@ -19,6 +19,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
19
19
  `}render(){const rows=this.filteredItems,idx=this.clampedIndex(rows),activeId=idx>=0?this.rowId(idx):"";return html`
20
20
  <div
21
21
  part="listbox"
22
+ ?hidden=${this.listboxHidden}
22
23
  id=${this._listId}
23
24
  role="listbox"
24
25
  tabindex=${this._ownsFocus&&rows.length===0?"0":"-1"}
@@ -29,4 +30,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
29
30
  >
30
31
  ${rows.length===0?html`<div part="empty" role="option" aria-selected="false" aria-disabled="true">${this.effectiveEmptyText}</div>`:rows.map((item,i)=>this.renderRow(item,i,activeId))}
31
32
  </div>
32
- `}}__decorate([property({attribute:!1})],LyraMentionPopover.prototype,"anchor",void 0),__decorate([property()],LyraMentionPopover.prototype,"query",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraMentionPopover.prototype,"open",void 0),__decorate([property({attribute:!1})],LyraMentionPopover.prototype,"filter",void 0),__decorate([property({attribute:"empty-text"})],LyraMentionPopover.prototype,"emptyText",void 0),__decorate([property()],LyraMentionPopover.prototype,"label",void 0),__decorate([state()],LyraMentionPopover.prototype,"activeIndex",void 0),__decorate([state()],LyraMentionPopover.prototype,"_ownsFocus",void 0);export{LyraMentionPopover};
33
+ `}}__decorate([property({attribute:!1})],LyraMentionPopover.prototype,"anchor",void 0),__decorate([property()],LyraMentionPopover.prototype,"query",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraMentionPopover.prototype,"open",void 0),__decorate([property({attribute:!1})],LyraMentionPopover.prototype,"filter",void 0),__decorate([property({attribute:"empty-text"})],LyraMentionPopover.prototype,"emptyText",void 0),__decorate([property()],LyraMentionPopover.prototype,"label",void 0),__decorate([state()],LyraMentionPopover.prototype,"activeIndex",void 0),__decorate([state()],LyraMentionPopover.prototype,"listboxHidden",void 0),__decorate([state()],LyraMentionPopover.prototype,"_ownsFocus",void 0);export{LyraMentionPopover};
@@ -1 +1 @@
1
- import{css}from"lit";import{overlaySurface}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: contents; } [part='listbox'] { position: fixed; z-index: var(--lr-layer-dropdown); box-sizing: border-box; max-block-size: min(var(--lr-size-16rem), var(--lr-positioner-available-block-size, var(--lr-size-16rem))); overflow-y: auto; overflow-x: clip; inline-size: max-content; min-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-14rem), var(--lr-positioner-available-inline-size, 100vw)); max-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-24rem), var(--lr-positioner-available-inline-size, 100vw)); padding: var(--lr-space-xs); ${overlaySurface} box-shadow: var(--lr-overlay-shadow-anchored, var(--lr-shadow-m)); visibility: hidden; opacity: 0; transform: translateY(var(--lr-size-neg-0-25rem)); transition: opacity var(--lr-transition-fast), transform var(--lr-transition-fast), visibility 0s linear var(--lr-transition-fast); } :host([open]) [part='listbox'] { visibility: visible; opacity: 1; transform: translateY(0); transition-delay: 0s, 0s, 0s; } @media (prefers-reduced-motion: reduce) { [part='listbox'] { transition: none !important; } } [part='option'] { display: flex; align-items: center; gap: var(--lr-space-xs); inline-size: 100%; min-block-size: var(--lr-icon-button-size); padding: var(--lr-space-xs) var(--lr-space-s); border-radius: var(--lr-radius); cursor: pointer; } [part='option']:where(:not([aria-disabled='true'])):hover, [part='option'][data-active] { background: var(--lr-mention-popover-option-active-bg, var(--lr-color-brand-quiet)); } [part='option']:where(:not([aria-disabled='true'])):active { background: color-mix( in oklab, var(--lr-mention-popover-option-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part='option'][aria-selected='true'] { color: var(--lr-color-brand); } [part='option'][aria-disabled='true'] { cursor: default; opacity: var(--lr-mention-popover-option-disabled-opacity, 0.5); } [part='option-icon'] { flex: 0 0 auto; line-height: var(--lr-line-height-1-4); } [part='option-label'] { display: flex; flex-direction: column; min-inline-size: 0; line-height: var(--lr-line-height-1-4); } [part='option-label'] span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='option-description'] { font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='option']:where(:not([aria-disabled='true'])):hover [part='option-description'], [part='option'][data-active] [part='option-description'] { color: var(--lr-color-text); } [part='empty'] { padding: var(--lr-space-s) var(--lr-space-m); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-md-sm); overflow-wrap: anywhere; } `;export{styles};
1
+ import{css}from"lit";import{overlaySurface}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: contents; } [part='listbox'][hidden] { display: none; } [part='listbox'] { position: fixed; z-index: var(--lr-layer-dropdown); box-sizing: border-box; max-block-size: min(var(--lr-size-16rem), var(--lr-positioner-available-block-size, var(--lr-size-16rem))); overflow-y: auto; overflow-x: clip; inline-size: max-content; min-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-14rem), var(--lr-positioner-available-inline-size, 100vw)); max-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-24rem), var(--lr-positioner-available-inline-size, 100vw)); padding: var(--lr-space-xs); ${overlaySurface} box-shadow: var(--lr-overlay-shadow-anchored, var(--lr-shadow-m)); visibility: hidden; opacity: 0; transform: translateY(var(--lr-size-neg-0-25rem)); transition: opacity var(--lr-transition-fast), transform var(--lr-transition-fast), visibility 0s linear var(--lr-transition-fast); } :host([open]) [part='listbox'] { visibility: visible; opacity: 1; transform: translateY(0); transition-delay: 0s, 0s, 0s; } @media (prefers-reduced-motion: reduce) { [part='listbox'] { transition: none !important; } } [part='option'] { display: flex; align-items: center; gap: var(--lr-space-xs); inline-size: 100%; min-block-size: var(--lr-icon-button-size); padding: var(--lr-space-xs) var(--lr-space-s); border-radius: var(--lr-radius); cursor: pointer; } [part='option']:where(:not([aria-disabled='true'])):hover, [part='option'][data-active] { background: var(--lr-mention-popover-option-active-bg, var(--lr-color-brand-quiet)); } [part='option']:where(:not([aria-disabled='true'])):active { background: color-mix( in oklab, var(--lr-mention-popover-option-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part='option'][aria-selected='true'] { color: var(--lr-mention-popover-option-active-color, var(--lr-color-brand)); } [part='option'][aria-disabled='true'] { cursor: default; opacity: var(--lr-mention-popover-option-disabled-opacity, 0.5); } [part='option-icon'] { flex: 0 0 auto; line-height: var(--lr-line-height-1-4); } [part='option-label'] { display: flex; flex-direction: column; min-inline-size: 0; line-height: var(--lr-line-height-1-4); } [part='option-label'] span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='option-description'] { font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='option']:where(:not([aria-disabled='true'])):hover [part='option-description'], [part='option'][data-active] [part='option-description'] { color: var(--lr-color-text); } [part='empty'] { padding: var(--lr-space-s) var(--lr-space-m); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-md-sm); overflow-wrap: anywhere; } `;export{styles};
@@ -13,9 +13,7 @@ import{type TemplateResult,type PropertyValues}from'lit';import type{Placement}f
13
13
  */
14
14
  export type LyraTourTarget=string|HTMLElement|(()=>HTMLElement|null);export interface LyraTourStep{
15
15
  /** Stable business id for this step, never shown to the user. Collection occurrences remain
16
- * unambiguous through the public `index`/`activeIndex` contract even when ids repeat. A step
17
- * object still carrying the pre-rename `id` field (this property's former name) is accepted as
18
- * a fallback when `stepId` itself is absent -- see `snapshotTourSteps()`. */
16
+ * unambiguous through the public `index`/`activeIndex` contract even when ids repeat. */
19
17
  readonly stepId:string;
20
18
  /** The element this step spotlights and anchors its popover to. */
21
19
  readonly target:LyraTourTarget;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{nextId,hasRealContent}from"../../../internal/a11y.js";import{deferredPlaceReady as place,deferredTrackRect as trackRect}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{styles}from"./tour.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous,LYRA_DEFAULT_tourDone,LYRA_DEFAULT_tourSkip,LYRA_DEFAULT_tourStepOf}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=12,DEFAULT_SPOTLIGHT_PADDING=4,MAX_TOUR_STEPS=256,MAX_STEP_ID_LENGTH=256,MAX_TARGET_SELECTOR_LENGTH=8192,MAX_HEADING_LENGTH=4096,MAX_CONTENT_LENGTH=65536,MAX_STEP_SPOTLIGHT_PADDING=1e4,TOUR_PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function keyholeClipPath(x,y,width,height){const right=x+width,bottom=y+height;return`polygon(evenodd, 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%, ${x}px ${y}px, ${x}px ${bottom}px, ${right}px ${bottom}px, ${right}px ${y}px, ${x}px ${y}px, 0% 0%)`}function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1&&typeof value.localName=="string"&&typeof value.matches=="function"}function isPlainRecord(value){if(typeof value!="object"||value===null)return!1;try{if(Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function safeArrayLength(value){try{if(!Array.isArray(value))return 0;const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return typeof length=="number"&&Number.isFinite(length)?Math.min(MAX_TOUR_STEPS,Math.max(0,Math.floor(length))):0}catch{return 0}}function arrayItem(value,index){try{if(!Array.isArray(value))return;const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value,maxLength){return typeof value=="string"?value.slice(0,maxLength):void 0}function normalizeTourTarget(value){if(typeof value=="string"){const selector=value.slice(0,MAX_TARGET_SELECTOR_LENGTH);return selector||void 0}if(typeof value=="function")return value;try{return isHtmlElement(value)?value:void 0}catch{return}}function snapshotTourSteps(value){const normalized=[],length=safeArrayLength(value);for(let index=0;index<length;index+=1){const candidate=arrayItem(value,index);if(!isPlainRecord(candidate))continue;const stepId=boundedString(ownDataValue(candidate,"stepId"),MAX_STEP_ID_LENGTH)??boundedString(ownDataValue(candidate,"id"),MAX_STEP_ID_LENGTH),target=normalizeTourTarget(ownDataValue(candidate,"target")),heading=boundedString(ownDataValue(candidate,"heading"),MAX_HEADING_LENGTH);if(!stepId||stepId!==stepId.trim()||!target||heading===void 0)continue;const content=boundedString(ownDataValue(candidate,"content"),MAX_CONTENT_LENGTH),rawPlacement=ownDataValue(candidate,"placement"),placement=TOUR_PLACEMENTS.has(rawPlacement)?rawPlacement:void 0,rawPadding=ownDataValue(candidate,"spotlightPadding"),spotlightPadding=typeof rawPadding=="number"&&Number.isFinite(rawPadding)?finiteRange(rawPadding,DEFAULT_SPOTLIGHT_PADDING,0,MAX_STEP_SPOTLIGHT_PADDING):void 0,rawInteractive=ownDataValue(candidate,"interactiveTarget"),interactiveTarget=typeof rawInteractive=="boolean"?rawInteractive:void 0,rawHidePrevious=ownDataValue(candidate,"hidePrevious"),hidePrevious=typeof rawHidePrevious=="boolean"?rawHidePrevious:void 0;normalized.push(Object.freeze({stepId,target,heading,...content!==void 0?{content}:{},...placement!==void 0?{placement}:{},...spotlightPadding!==void 0?{spotlightPadding}:{},...interactiveTarget!==void 0?{interactiveTarget}:{},...hidePrevious!==void 0?{hidePrevious}:{}}))}return Object.freeze(normalized)}class LyraTour extends LyraElement{constructor(){super(...arguments),this.open=!1,this._steps=Object.freeze([]),this.activeIndex=0,this.placement="bottom",this.distance=DEFAULT_DISTANCE,this.spotlightPadding=DEFAULT_SPOTLIGHT_PADDING,this.lightDismiss=!1,this.showProgress=!0,this.accessibleLabel=null,this.unanchored=!1,this.hasSlotContent=!1,this.spotlightPositioned=!1,this.activeTargetSnapshot=null,this.focusReturnTarget=null,this.maskId=nextId("tour-mask"),this.headingId=nextId("tour-heading"),this.bodyId=nextId("tour-body"),this.progressTextId=nextId("tour-progress-text"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onDefaultSlotChange=e=>{this.hasSlotContent=hasRealContent(e.target.assignedNodes({flatten:!0}))},this.onInteractiveScopeKeyDown=event=>{if(event.key!=="Tab"||event.defaultPrevented||!this.open||!this.overlay?.isTopmost())return;const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;const target=this.interactiveKeyboardTarget;if(!target)return;const panelFocusable=collectFocusableElements(popover),targetFocusable=collectFocusableElements(target);if(panelFocusable.length===0&&targetFocusable.length===0){event.preventDefault(),popover.focus();return}const active=deepActiveElement(this.ownerDocument),panelIndex=panelFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),targetIndex=targetFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),destination=panelIndex>=0?event.shiftKey&&panelIndex===0?targetFocusable.at(-1)??panelFocusable.at(-1):!event.shiftKey&&panelIndex===panelFocusable.length-1?targetFocusable[0]??panelFocusable[0]:void 0:targetIndex>=0?event.shiftKey&&targetIndex===0?panelFocusable.at(-1)??targetFocusable.at(-1):!event.shiftKey&&targetIndex===targetFocusable.length-1?panelFocusable[0]??targetFocusable[0]:void 0:active===popover&&!event.shiftKey?void 0:event.shiftKey?targetFocusable.at(-1)??panelFocusable.at(-1):panelFocusable[0]??targetFocusable[0];destination&&(event.preventDefault(),destination.focus())},this.onPopoverKeyDown=event=>{if(event.defaultPrevented||this.ownsDirectionalKeys(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey&&(event.preventDefault(),this.back())}}static{this.defaultStrings={...super.defaultStrings,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,tourDone:LYRA_DEFAULT_tourDone,tourSkip:LYRA_DEFAULT_tourSkip,tourStepOf:LYRA_DEFAULT_tourStepOf}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={steps:{attribute:!1,noAccessor:!0}}}get steps(){return this._steps}set steps(next){const previous=this._steps;this._steps=snapshotTourSteps(next),this.requestUpdate("steps",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("activeIndex")||changed.has("steps")){const maxIndex=Math.max(0,this.steps.length-1),normalizedIndex=finiteInteger(this.activeIndex,0,0,maxIndex);normalizedIndex!==this.activeIndex&&(this.activeIndex=normalizedIndex)}if(this.hasUpdated||(this.hasSlotContent=hasRealContent(this.childNodes)),this.open&&this.steps.length===0)this.open=!1,this.deactivateOverlayInternal();else if(changed.has("open"))if(this.open){const active=deepActiveElement(this.ownerDocument);this.focusReturnTarget=isHtmlElement(active)?active:null,this.activateOverlayInternal()}else this.deactivateOverlayInternal();if(this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const step=this.steps[this.activeIndex];this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1}this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps")||changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding"))&&(this.spotlightPositioned=!1)}updated(changed){super.updated(changed);const activationChanged=changed.has("open")||changed.has("activeIndex")||changed.has("steps"),geometryChanged=changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding");if(this.open&&(activationChanged||geometryChanged)){const preserveInteractiveTargetFocus=changed.has("steps")&&this.canPreserveInteractiveTargetFocus(),overlayChanged=this.activateOverlayInternal(),shouldFocus=changed.has("open")||changed.has("activeIndex")||overlayChanged||changed.has("steps")&&!preserveInteractiveTargetFocus,placement=this.activateStep({scroll:activationChanged,announceMissing:activationChanged});shouldFocus&&this.focusAfterPlacement(placement)}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlayInternal(),queueMicrotask(async()=>{if(!this.isConnected||!this.open)return;const step=this.steps[this.activeIndex];if(this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1,await this.updateComplete,!this.isConnected||!this.open)return;const placement=this.activateStep({scroll:!0,announceMissing:!0});this.focusAfterPlacement(placement)}))}disconnectedCallback(){super.disconnectedCallback(),this.disposePositioning(),this.overlay?.suspend(),this.open&&queueMicrotask(()=>{!this.isConnected&&this.open&&(this.open=!1,this.emit("lr-tour-end","unmount"))})}start(index=0){this.steps.length!==0&&(this.activeIndex=this.clampIndex(index),this.open=!0,this.emit("lr-tour-start",Object.freeze({index:this.activeIndex})))}next(){const total=this.steps.length;if(total!==0){if(this.activeIndex>=total-1){this.end("completed");return}this.transitionTo(this.activeIndex+1,"next")}}back(){this.activeIndex<=0||this.transitionTo(this.activeIndex-1,"back")}goToStep(index){if(this.steps.length===0)return;const clamped=this.clampIndex(index);clamped!==this.activeIndex&&this.transitionTo(clamped,"goto")}skip(){this.end("skip")}end(reason="api"){!this.open||this.emit("lr-tour-end",reason,{cancelable:!0}).defaultPrevented||(this.open=!1)}clampIndex(index){const total=this.steps.length;return total===0?0:finiteInteger(index,0,0,total-1)}transitionTo(index,via){const previousIndex=this.activeIndex,step=this.steps[index];!step||this.emit("lr-tour-step-change",Object.freeze({index,previousIndex,step,via}),{cancelable:!0}).defaultPrevented||(this.activeIndex=index)}resolveTarget(step){try{const{target}=step,resolved=typeof target=="string"?this.ownerDocument.querySelector(target):typeof target=="function"?target():target;return isHtmlElement(resolved)&&resolved.isConnected&&resolved.ownerDocument===this.ownerDocument?resolved:null}catch{return null}}canPreserveInteractiveTargetFocus(){const previousTarget=this.interactiveKeyboardTarget,step=this.steps[this.activeIndex];return!previousTarget?.isConnected||!step?.interactiveTarget?!1:this.activeTargetSnapshot===previousTarget&&composedContains(previousTarget,deepActiveElement(this.ownerDocument))}activateStep(options){this.disposePositioning();const step=this.steps[this.activeIndex];if(!step)return;const target=this.activeTargetSnapshot;if(!target?.isConnected){options.announceMissing&&this.emit("lr-tour-target-missing",Object.freeze({index:this.activeIndex,step}));return}const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;if(options.scroll){const ownerWindow=target.ownerDocument.defaultView,reducedMotion=!ownerWindow||prefersReducedMotion(ownerWindow);target.scrollIntoView({block:"center",inline:"nearest",behavior:reducedMotion?"auto":"smooth"})}const placement=rtlAwarePlacement(step.placement??this.placement,this);this.placeCleanup=place(target,popover,{placement,offset:finiteNumber(this.distance,DEFAULT_DISTANCE),strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const padding=finiteRange(step.spotlightPadding??this.spotlightPadding,DEFAULT_SPOTLIGHT_PADDING,0),interactive=!!step.interactiveTarget;return interactive&&(this.interactiveKeyboardTarget=target,this.interactiveKeyboardDocument=target.ownerDocument,this.interactiveKeyboardDocument.addEventListener("keydown",this.onInteractiveScopeKeyDown,!0)),this.spotlightCleanup=trackRect(target,rect=>this.paintSpotlight(rect,padding,interactive)),this.placeCleanup}focusAfterPlacement(placement){if(!placement){this.overlay?.focusInitial();return}placement.ready.then(positioned=>{if(!(this.placeCleanup!==placement||!this.open||!this.isConnected)){if(positioned){this.overlay?.focusInitial();return}this.open=!1,this.deactivateOverlayInternal()}})}paintSpotlight(rect,padding,interactive){const x=rect.left-padding,y=rect.top-padding,width=Math.max(0,rect.width+padding*2),height=Math.max(0,rect.height+padding*2),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),cutout=this.renderRoot.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot.querySelector('[part="spotlight"]');cutout&&(cutout.setAttribute("x",String(x)),cutout.setAttribute("y",String(y)),cutout.setAttribute("width",String(width)),cutout.setAttribute("height",String(height))),spotlight&&(spotlight.style.left=`${x}px`,spotlight.style.top=`${y}px`,spotlight.style.width=`${width}px`,spotlight.style.height=`${height}px`,spotlight.hidden=!1),backdrop&&(backdrop.style.clipPath=interactive?keyholeClipPath(x,y,width,height):""),this.spotlightPositioned=!0}resetSpotlightGeometry(){this.spotlightPositioned=!1;const cutout=this.renderRoot?.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot?.querySelector('[part="spotlight"]'),backdrop=this.renderRoot?.querySelector('[part="backdrop"]');cutout&&(cutout.setAttribute("x","0"),cutout.setAttribute("y","0"),cutout.setAttribute("width","0"),cutout.setAttribute("height","0")),spotlight&&(spotlight.hidden=!0,spotlight.style.removeProperty("left"),spotlight.style.removeProperty("top"),spotlight.style.removeProperty("width"),spotlight.style.removeProperty("height")),backdrop?.style.removeProperty("clip-path")}disposePositioning(){this.placeCleanup?.(),this.placeCleanup=void 0,this.spotlightCleanup?.(),this.spotlightCleanup=void 0,this.resetSpotlightGeometry(),this.interactiveKeyboardDocument?.removeEventListener("keydown",this.onInteractiveScopeKeyDown,!0),this.interactiveKeyboardDocument=void 0,this.interactiveKeyboardTarget=void 0}activateOverlayInternal(){if(!this.isConnected)return!1;const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;return this.overlay?.isActive()&&this.overlayInteractive===interactive?!1:(this.overlay?.isActive()&&(this.overlay.deactivate({restoreFocus:!1}),this.overlay=void 0),this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="popover"]')??null,onEscape:()=>this.end("escape"),onBackdrop:()=>this.end("skip"),preferredInitialFocus:()=>this.renderRoot.querySelector('[part="popover"]'),restoreFocusTo:()=>{const target=this.focusReturnTarget;return target?.isConnected&&target.ownerDocument===this.ownerDocument?target:null},modal:!interactive,trapFocus:!interactive,lockScroll:!0,suspendWhenUnrendered:!0}),this.overlayInteractive=interactive,!0)}deactivateOverlayInternal(){this.disposePositioning(),this.activeTargetSnapshot=null,this.overlay?.deactivate(),this.overlay=void 0,this.overlayInteractive=void 0,this.focusReturnTarget=null}ownsDirectionalKeys(event){return event.composedPath().some(node=>isElementNode(node)&&node.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="combobox"], [role="grid"], [role="gridcell"], [role="listbox"], [role="menu"], [role="menuitem"], [role="radio"], [role="radiogroup"], [role="scrollbar"], [role="slider"], [role="spinbutton"], [role="tab"], [role="tablist"], [role="tree"], [role="treeitem"]'))}formatProgressNumber(value){try{return getNumberFormat(this.effectiveLocale).format(value)}catch{return String(value)}}render(){const step=this.open?this.steps[this.activeIndex]:void 0;if(!step)return html``;const total=this.steps.length,isLastStep=this.activeIndex>=total-1,headingName=(step.heading??"").trim(),authoredName=this.accessibleLabel,useHeading=authoredName===null&&headingName.length>0,suppliedName=authoredName?.trim()??"",fallbackName=this.localize("tourStepOf",void 0,{current:this.formatProgressNumber(this.activeIndex+1),total:this.formatProgressNumber(total)}),panelName=authoredName===null?fallbackName:suppliedName,describedBy=[this.hasSlotContent||!!step.content?this.bodyId:"",this.showProgress?this.progressTextId:""].filter(id=>id.length>0).join(" ");return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activateOverlay,collectFocusableElements,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{nextId,hasRealContent}from"../../../internal/a11y.js";import{deferredPlaceReady as place,deferredTrackRect as trackRect}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{styles}from"./tour.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous,LYRA_DEFAULT_tourDone,LYRA_DEFAULT_tourSkip,LYRA_DEFAULT_tourStepOf}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=12,DEFAULT_SPOTLIGHT_PADDING=4,MAX_TOUR_STEPS=256,MAX_STEP_ID_LENGTH=256,MAX_TARGET_SELECTOR_LENGTH=8192,MAX_HEADING_LENGTH=4096,MAX_CONTENT_LENGTH=65536,MAX_STEP_SPOTLIGHT_PADDING=1e4,TOUR_PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function keyholeClipPath(x,y,width,height){const right=x+width,bottom=y+height;return`polygon(evenodd, 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%, ${x}px ${y}px, ${x}px ${bottom}px, ${right}px ${bottom}px, ${right}px ${y}px, ${x}px ${y}px, 0% 0%)`}function isElementNode(value){return typeof value=="object"&&value!==null&&value.nodeType===1&&typeof value.localName=="string"&&typeof value.matches=="function"}function isPlainRecord(value){if(typeof value!="object"||value===null)return!1;try{if(Array.isArray(value))return!1;const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function ownDataValue(record,key){try{const descriptor=Object.getOwnPropertyDescriptor(record,key);return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function safeArrayLength(value){try{if(!Array.isArray(value))return 0;const descriptor=Object.getOwnPropertyDescriptor(value,"length"),length=descriptor&&"value"in descriptor?descriptor.value:0;return typeof length=="number"&&Number.isFinite(length)?Math.min(MAX_TOUR_STEPS,Math.max(0,Math.floor(length))):0}catch{return 0}}function arrayItem(value,index){try{if(!Array.isArray(value))return;const descriptor=Object.getOwnPropertyDescriptor(value,String(index));return descriptor&&"value"in descriptor?descriptor.value:void 0}catch{return}}function boundedString(value,maxLength){return typeof value=="string"?value.slice(0,maxLength):void 0}function normalizeTourTarget(value){if(typeof value=="string"){const selector=value.slice(0,MAX_TARGET_SELECTOR_LENGTH);return selector||void 0}if(typeof value=="function")return value;try{return isHtmlElement(value)?value:void 0}catch{return}}function snapshotTourSteps(value){const normalized=[],length=safeArrayLength(value);for(let index=0;index<length;index+=1){const candidate=arrayItem(value,index);if(!isPlainRecord(candidate))continue;const stepId=boundedString(ownDataValue(candidate,"stepId"),MAX_STEP_ID_LENGTH),target=normalizeTourTarget(ownDataValue(candidate,"target")),heading=boundedString(ownDataValue(candidate,"heading"),MAX_HEADING_LENGTH);if(!stepId||stepId!==stepId.trim()||!target||heading===void 0)continue;const content=boundedString(ownDataValue(candidate,"content"),MAX_CONTENT_LENGTH),rawPlacement=ownDataValue(candidate,"placement"),placement=TOUR_PLACEMENTS.has(rawPlacement)?rawPlacement:void 0,rawPadding=ownDataValue(candidate,"spotlightPadding"),spotlightPadding=typeof rawPadding=="number"&&Number.isFinite(rawPadding)?finiteRange(rawPadding,DEFAULT_SPOTLIGHT_PADDING,0,MAX_STEP_SPOTLIGHT_PADDING):void 0,rawInteractive=ownDataValue(candidate,"interactiveTarget"),interactiveTarget=typeof rawInteractive=="boolean"?rawInteractive:void 0,rawHidePrevious=ownDataValue(candidate,"hidePrevious"),hidePrevious=typeof rawHidePrevious=="boolean"?rawHidePrevious:void 0;normalized.push(Object.freeze({stepId,target,heading,...content!==void 0?{content}:{},...placement!==void 0?{placement}:{},...spotlightPadding!==void 0?{spotlightPadding}:{},...interactiveTarget!==void 0?{interactiveTarget}:{},...hidePrevious!==void 0?{hidePrevious}:{}}))}return Object.freeze(normalized)}class LyraTour extends LyraElement{constructor(){super(...arguments),this.open=!1,this._steps=Object.freeze([]),this.activeIndex=0,this.placement="bottom",this.distance=DEFAULT_DISTANCE,this.spotlightPadding=DEFAULT_SPOTLIGHT_PADDING,this.lightDismiss=!1,this.showProgress=!0,this.accessibleLabel=null,this.unanchored=!1,this.hasSlotContent=!1,this.spotlightPositioned=!1,this.activeTargetSnapshot=null,this.focusReturnTarget=null,this.maskId=nextId("tour-mask"),this.headingId=nextId("tour-heading"),this.bodyId=nextId("tour-body"),this.progressTextId=nextId("tour-progress-text"),this.onBackdropClick=()=>{this.lightDismiss&&this.overlay?.dismissBackdrop()},this.onDefaultSlotChange=e=>{this.hasSlotContent=hasRealContent(e.target.assignedNodes({flatten:!0}))},this.onInteractiveScopeKeyDown=event=>{if(event.key!=="Tab"||event.defaultPrevented||!this.open||!this.overlay?.isTopmost())return;const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;const target=this.interactiveKeyboardTarget;if(!target)return;const panelFocusable=collectFocusableElements(popover),targetFocusable=collectFocusableElements(target);if(panelFocusable.length===0&&targetFocusable.length===0){event.preventDefault(),popover.focus();return}const active=deepActiveElement(this.ownerDocument),panelIndex=panelFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),targetIndex=targetFocusable.findIndex(candidate=>active===candidate||composedContains(candidate,active)),destination=panelIndex>=0?event.shiftKey&&panelIndex===0?targetFocusable.at(-1)??panelFocusable.at(-1):!event.shiftKey&&panelIndex===panelFocusable.length-1?targetFocusable[0]??panelFocusable[0]:void 0:targetIndex>=0?event.shiftKey&&targetIndex===0?panelFocusable.at(-1)??targetFocusable.at(-1):!event.shiftKey&&targetIndex===targetFocusable.length-1?panelFocusable[0]??targetFocusable[0]:void 0:active===popover&&!event.shiftKey?void 0:event.shiftKey?targetFocusable.at(-1)??panelFocusable.at(-1):panelFocusable[0]??targetFocusable[0];destination&&(event.preventDefault(),destination.focus())},this.onPopoverKeyDown=event=>{if(event.defaultPrevented||this.ownsDirectionalKeys(event))return;const rtl=this.effectiveDirection==="rtl",forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey&&(event.preventDefault(),this.back())}}static{this.defaultStrings={...super.defaultStrings,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous,tourDone:LYRA_DEFAULT_tourDone,tourSkip:LYRA_DEFAULT_tourSkip,tourStepOf:LYRA_DEFAULT_tourStepOf}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={steps:{attribute:!1,noAccessor:!0}}}get steps(){return this._steps}set steps(next){const previous=this._steps;this._steps=snapshotTourSteps(next),this.requestUpdate("steps",previous)}willUpdate(changed){if(super.willUpdate(changed),changed.has("activeIndex")||changed.has("steps")){const maxIndex=Math.max(0,this.steps.length-1),normalizedIndex=finiteInteger(this.activeIndex,0,0,maxIndex);normalizedIndex!==this.activeIndex&&(this.activeIndex=normalizedIndex)}if(this.hasUpdated||(this.hasSlotContent=hasRealContent(this.childNodes)),this.open&&this.steps.length===0)this.open=!1,this.deactivateOverlayInternal();else if(changed.has("open"))if(this.open){const active=deepActiveElement(this.ownerDocument);this.focusReturnTarget=isHtmlElement(active)?active:null,this.activateOverlayInternal()}else this.deactivateOverlayInternal();if(this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps"))){const step=this.steps[this.activeIndex];this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1}this.open&&(changed.has("open")||changed.has("activeIndex")||changed.has("steps")||changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding"))&&(this.spotlightPositioned=!1)}updated(changed){super.updated(changed);const activationChanged=changed.has("open")||changed.has("activeIndex")||changed.has("steps"),geometryChanged=changed.has("placement")||changed.has("distance")||changed.has("spotlightPadding");if(this.open&&(activationChanged||geometryChanged)){const preserveInteractiveTargetFocus=changed.has("steps")&&this.canPreserveInteractiveTargetFocus(),overlayChanged=this.activateOverlayInternal(),shouldFocus=changed.has("open")||changed.has("activeIndex")||overlayChanged||changed.has("steps")&&!preserveInteractiveTargetFocus,placement=this.activateStep({scroll:activationChanged,announceMissing:activationChanged});shouldFocus&&this.focusAfterPlacement(placement)}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.open&&(this.overlay?.isActive()?this.overlay.resume():this.activateOverlayInternal(),queueMicrotask(async()=>{if(!this.isConnected||!this.open)return;const step=this.steps[this.activeIndex];if(this.activeTargetSnapshot=step?this.resolveTarget(step):null,this.unanchored=step?!this.activeTargetSnapshot:!1,await this.updateComplete,!this.isConnected||!this.open)return;const placement=this.activateStep({scroll:!0,announceMissing:!0});this.focusAfterPlacement(placement)}))}disconnectedCallback(){super.disconnectedCallback(),this.disposePositioning(),this.overlay?.suspend(),this.open&&queueMicrotask(()=>{!this.isConnected&&this.open&&(this.open=!1,this.emit("lr-tour-end","unmount"))})}start(index=0){this.steps.length!==0&&(this.activeIndex=this.clampIndex(index),this.open=!0,this.emit("lr-tour-start",Object.freeze({index:this.activeIndex})))}next(){const total=this.steps.length;if(total!==0){if(this.activeIndex>=total-1){this.end("completed");return}this.transitionTo(this.activeIndex+1,"next")}}back(){this.activeIndex<=0||this.transitionTo(this.activeIndex-1,"back")}goToStep(index){if(this.steps.length===0)return;const clamped=this.clampIndex(index);clamped!==this.activeIndex&&this.transitionTo(clamped,"goto")}skip(){this.end("skip")}end(reason="api"){!this.open||this.emit("lr-tour-end",reason,{cancelable:!0}).defaultPrevented||(this.open=!1)}clampIndex(index){const total=this.steps.length;return total===0?0:finiteInteger(index,0,0,total-1)}transitionTo(index,via){const previousIndex=this.activeIndex,step=this.steps[index];!step||this.emit("lr-tour-step-change",Object.freeze({index,previousIndex,step,via}),{cancelable:!0}).defaultPrevented||(this.activeIndex=index)}resolveTarget(step){try{const{target}=step,resolved=typeof target=="string"?this.ownerDocument.querySelector(target):typeof target=="function"?target():target;return isHtmlElement(resolved)&&resolved.isConnected&&resolved.ownerDocument===this.ownerDocument?resolved:null}catch{return null}}canPreserveInteractiveTargetFocus(){const previousTarget=this.interactiveKeyboardTarget,step=this.steps[this.activeIndex];return!previousTarget?.isConnected||!step?.interactiveTarget?!1:this.activeTargetSnapshot===previousTarget&&composedContains(previousTarget,deepActiveElement(this.ownerDocument))}activateStep(options){this.disposePositioning();const step=this.steps[this.activeIndex];if(!step)return;const target=this.activeTargetSnapshot;if(!target?.isConnected){options.announceMissing&&this.emit("lr-tour-target-missing",Object.freeze({index:this.activeIndex,step}));return}const popover=this.renderRoot.querySelector('[part="popover"]');if(!popover)return;if(options.scroll){const ownerWindow=target.ownerDocument.defaultView,reducedMotion=!ownerWindow||prefersReducedMotion(ownerWindow);target.scrollIntoView({block:"center",inline:"nearest",behavior:reducedMotion?"auto":"smooth"})}const placement=rtlAwarePlacement(step.placement??this.placement,this);this.placeCleanup=place(target,popover,{placement,offset:finiteNumber(this.distance,DEFAULT_DISTANCE),strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});const padding=finiteRange(step.spotlightPadding??this.spotlightPadding,DEFAULT_SPOTLIGHT_PADDING,0),interactive=!!step.interactiveTarget;return interactive&&(this.interactiveKeyboardTarget=target,this.interactiveKeyboardDocument=target.ownerDocument,this.interactiveKeyboardDocument.addEventListener("keydown",this.onInteractiveScopeKeyDown,!0)),this.spotlightCleanup=trackRect(target,rect=>this.paintSpotlight(rect,padding,interactive)),this.placeCleanup}focusAfterPlacement(placement){if(!placement){this.overlay?.focusInitial();return}placement.ready.then(positioned=>{if(!(this.placeCleanup!==placement||!this.open||!this.isConnected)){if(positioned){this.overlay?.focusInitial();return}this.open=!1,this.deactivateOverlayInternal()}})}paintSpotlight(rect,padding,interactive){const x=rect.left-padding,y=rect.top-padding,width=Math.max(0,rect.width+padding*2),height=Math.max(0,rect.height+padding*2),backdrop=this.renderRoot.querySelector('[part="backdrop"]'),cutout=this.renderRoot.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot.querySelector('[part="spotlight"]');cutout&&(cutout.setAttribute("x",String(x)),cutout.setAttribute("y",String(y)),cutout.setAttribute("width",String(width)),cutout.setAttribute("height",String(height))),spotlight&&(spotlight.style.left=`${x}px`,spotlight.style.top=`${y}px`,spotlight.style.width=`${width}px`,spotlight.style.height=`${height}px`,spotlight.hidden=!1),backdrop&&(backdrop.style.clipPath=interactive?keyholeClipPath(x,y,width,height):""),this.spotlightPositioned=!0}resetSpotlightGeometry(){this.spotlightPositioned=!1;const cutout=this.renderRoot?.querySelector('[part="backdrop"] .cutout'),spotlight=this.renderRoot?.querySelector('[part="spotlight"]'),backdrop=this.renderRoot?.querySelector('[part="backdrop"]');cutout&&(cutout.setAttribute("x","0"),cutout.setAttribute("y","0"),cutout.setAttribute("width","0"),cutout.setAttribute("height","0")),spotlight&&(spotlight.hidden=!0,spotlight.style.removeProperty("left"),spotlight.style.removeProperty("top"),spotlight.style.removeProperty("width"),spotlight.style.removeProperty("height")),backdrop?.style.removeProperty("clip-path")}disposePositioning(){this.placeCleanup?.(),this.placeCleanup=void 0,this.spotlightCleanup?.(),this.spotlightCleanup=void 0,this.resetSpotlightGeometry(),this.interactiveKeyboardDocument?.removeEventListener("keydown",this.onInteractiveScopeKeyDown,!0),this.interactiveKeyboardDocument=void 0,this.interactiveKeyboardTarget=void 0}activateOverlayInternal(){if(!this.isConnected)return!1;const interactive=!!this.steps[this.activeIndex]?.interactiveTarget;return this.overlay?.isActive()&&this.overlayInteractive===interactive?!1:(this.overlay?.isActive()&&(this.overlay.deactivate({restoreFocus:!1}),this.overlay=void 0),this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="popover"]')??null,onEscape:()=>this.end("escape"),onBackdrop:()=>this.end("skip"),preferredInitialFocus:()=>this.renderRoot.querySelector('[part="popover"]'),restoreFocusTo:()=>{const target=this.focusReturnTarget;return target?.isConnected&&target.ownerDocument===this.ownerDocument?target:null},modal:!interactive,trapFocus:!interactive,lockScroll:!0,suspendWhenUnrendered:!0}),this.overlayInteractive=interactive,!0)}deactivateOverlayInternal(){this.disposePositioning(),this.activeTargetSnapshot=null,this.overlay?.deactivate(),this.overlay=void 0,this.overlayInteractive=void 0,this.focusReturnTarget=null}ownsDirectionalKeys(event){return event.composedPath().some(node=>isElementNode(node)&&node.matches('input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="combobox"], [role="grid"], [role="gridcell"], [role="listbox"], [role="menu"], [role="menuitem"], [role="radio"], [role="radiogroup"], [role="scrollbar"], [role="slider"], [role="spinbutton"], [role="tab"], [role="tablist"], [role="tree"], [role="treeitem"]'))}formatProgressNumber(value){try{return getNumberFormat(this.effectiveLocale).format(value)}catch{return String(value)}}render(){const step=this.open?this.steps[this.activeIndex]:void 0;if(!step)return html``;const total=this.steps.length,isLastStep=this.activeIndex>=total-1,headingName=(step.heading??"").trim(),authoredName=this.accessibleLabel,useHeading=authoredName===null&&headingName.length>0,suppliedName=authoredName?.trim()??"",fallbackName=this.localize("tourStepOf",void 0,{current:this.formatProgressNumber(this.activeIndex+1),total:this.formatProgressNumber(total)}),panelName=authoredName===null?fallbackName:suppliedName,describedBy=[this.hasSlotContent||!!step.content?this.bodyId:"",this.showProgress?this.progressTextId:""].filter(id=>id.length>0).join(" ");return html`
2
2
  <svg part="backdrop" aria-hidden="true" @click=${this.onBackdropClick}>
3
3
  ${this.unanchored?html`<rect class="scrim" x="0" y="0" width="100%" height="100%"></rect>`:html`
4
4
  <defs>
@@ -5,7 +5,13 @@ import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from
5
5
  * header bounds and supported compression methods, and never inflates entry bodies.
6
6
  * Fragment anchors use the exact ZIP entry path as their `id`; rendered rows do not expose that
7
7
  * path as a DOM `id`, so the viewer resolves entry metadata before mounting and scrolling the
8
- * matching virtual row. Text-quote anchors resolve against each complete entry path. Text
8
+ * matching virtual row. A ZIP central directory may legally repeat an entry path across multiple
9
+ * entries; because a fragment id names only the path, resolution always targets that path's
10
+ * first central-directory occurrence -- a later duplicate is not independently addressable
11
+ * through the fragment/anchor API. In-component search treats duplicate-named entries as
12
+ * distinct matches and correctly follows the true active occurrence (including its virtualized
13
+ * `aria-current` row), since each match is tracked by object identity and row position rather
14
+ * than by name alone. Text-quote anchors resolve against each complete entry path. Text
9
15
  * selections and painted highlights are likewise scoped to entry paths in the nested virtual list.
10
16
  *
11
17
  * @customElement lr-archive-viewer
@@ -53,11 +59,22 @@ maxHeight:string;
53
59
  * at most 4,000,000 path code units; `matchCountExact=false` identifies a truncated lower bound. */
54
60
  search(query:string):Promise<number>;searchNext():Promise<boolean>;searchPrevious():Promise<boolean>;clearSearch():void;private fetchState;private archiveSearchMatches;private archiveSearchActiveIndex;private archiveSearchMatchCountExact;private generation;private archiveSearchQuery;private lastSearchLocale;private pendingSearchResetEvent;private archiveSelectionRoot;private archiveSelectionCleanup?;private styledVirtualListRoot;private archiveNestedUpdatePending;private readonly archiveEntryKey;private readonly announcements;protected willUpdate(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;
55
61
  /** The rows' real DOM lives inside the embedded virtual list, not the archive viewer's own body. */
56
- protected textContentRoot():Element|null;protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;
62
+ protected textContentRoot():Element|null;
63
+ /** Resolves a `fragment` anchor's `id` against the exact ZIP entry path (see the class-level
64
+ * JSDoc) via `Array.prototype.findIndex`, so a duplicate-named entry's `id` always resolves to
65
+ * its first central-directory occurrence -- the same first-occurrence precedent as
66
+ * `document.getElementById()`/`:target` for a duplicated DOM `id`. A `text-quote` anchor is
67
+ * unaffected: it resolves by quote content, not by name, so it can reach any occurrence whose
68
+ * rendered text actually contains the quote. */
69
+ protected applyAnchor(anchor:LyraAnchor):Promise<boolean>;
57
70
  /** A quote emitted from selection is scoped to one entry path; a cross-row selection is not a
58
71
  * stable archive anchor because either endpoint may be unmounted by virtualization. */
59
72
  protected computeSelectionAnchor(range:Range):LyraAnchor|null;private load;private renderEntry;private stopVirtualListEvent;private archiveVirtualList;private waitForArchiveRow;
60
73
  /** Replaces TextViewerTarget's outer-shadow selection binding with one that includes the nested
61
74
  * virtual-list ShadowRoot in composed-range lookup. Highlight painting still uses the mixin, but
62
75
  * its content root is redirected to the same nested spacer above. */
63
- private syncArchiveNestedRoot;private recomputeArchiveSearch;private emitArchiveSearchChange;private scrollActiveArchiveMatch;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-archive-viewer':LyraArchiveViewer;}}export{};
76
+ private syncArchiveNestedRoot;private recomputeArchiveSearch;private emitArchiveSearchChange;private scrollActiveArchiveMatch;
77
+ /** The active search match's row identity, keyed the same occurrence-safe way as
78
+ * `archiveEntryKey` so it addresses the true active occurrence -- not a duplicate-named
79
+ * entry's first occurrence -- for `<lr-virtual-list>`'s `activeItemId`/`aria-current`. */
80
+ private activeArchiveMatchKey;private renderBody;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-archive-viewer':LyraArchiveViewer;}}export{};
@@ -1 +1 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{boundedSelectionRects,boundedSelectionText,buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/attachment-chip.class.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=100*1024*1024;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);function archiveSelectionRange(viewer,contentRoot){const document=viewer.ownerDocument,view=document.defaultView,nestedRoot=contentRoot.getRootNode(),outerRoot=viewer.shadowRoot,ShadowRootCtor=view?.ShadowRoot,shadowRoots=[outerRoot,nestedRoot].filter((root,index,roots)=>ShadowRootCtor!==void 0&&root instanceof ShadowRootCtor&&roots.indexOf(root)===index),globalSelection=view?.getSelection();if(globalSelection?.getComposedRanges){const[composed]=globalSelection.getComposedRanges({shadowRoots});if(composed&&(composed.startContainer!==composed.endContainer||composed.startOffset!==composed.endOffset)){const range=document.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}}const selection=nestedRoot.getSelection?.()??globalSelection??null;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)}class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.archiveSearchMatches=[],this.archiveSearchActiveIndex=-1,this.archiveSearchMatchCountExact=!0,this.generation=0,this.archiveSearchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.archiveSelectionRoot=null,this.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=item=>item.name,this.announcements=new ViewerAnnouncementController(this),this.renderEntry=item=>{const entry=item,kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){return this.archiveSearchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.recomputeArchiveSearch(),await this.updateComplete,this.scrollActiveArchiveMatch(),this.archiveSearchMatches.length}async searchNext(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}async searchPrevious(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}clearSearch(){this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.emitArchiveSearchChange()}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.archiveSearchQuery!==""||this.archiveSearchMatches.length>0||!this.archiveSearchMatchCountExact||this.archiveSearchActiveIndex!==-1,this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.fetchState=this.src?{kind:"loading"}:{kind:"idle"})}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),this.syncArchiveNestedRoot(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitArchiveSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.archiveSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.archiveSearchQuery)},"search")}}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return!1;const loadGeneration=this.generation;let index=-1,resolvedName;if(anchor.kind==="fragment")index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id),resolvedName=this.fetchState.entries[index]?.name;else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span"),workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(let candidateIndex=0;candidateIndex<this.fetchState.entries.length;candidateIndex++){const entry=this.fetchState.entries[candidateIndex],buildCost=Math.max(1,entry.name.length);if(buildCost>workBudget.remainingCodeUnits)break;if(workBudget.remainingCodeUnits-=buildCost,probe.textContent=entry.name,createTextQuoteIndex(scopeFromElement(probe),this.effectiveLocale).resolve(anchor,workBudget)){index=candidateIndex;break}}}if(index<0)return!1;const list=this.archiveVirtualList();if(!list||(list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.waitForArchiveRow(list,index))||(this.requestUpdate(),await this.updateComplete,loadGeneration!==this.generation||this.fetchState.kind!=="loaded"))return!1;if(anchor.kind==="fragment"){const root=this.textContentRoot(),target=root?Array.from(root.querySelectorAll('[part~="entry-name"]')).find(el=>el.textContent===resolvedName):null;return target?.scrollIntoView?.({block:"nearest",behavior:"auto"}),target!=null}return ArchiveTextViewerTargetBase.prototype.applyAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;return(node.nodeType===elementNode?node:node.parentElement)?.closest('[part~="entry-name"]')??null},start=entryName(range.startContainer),end=entryName(range.endContainer);return!start||start!==end?null:buildQuoteAnchor(range,scopeFromElement(start))}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(!this.isConnected||generation!==this.generation)return;const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const metadata=assertZipArchiveMetadataWithinLimits(buffer,{description:"ZIP",maxEntries:MAX_ARCHIVE_ENTRIES,maxUncompressedBytes:MAX_ARCHIVE_UNCOMPRESSED_BYTES,signal});if(!this.isConnected||generation!==this.generation)return;const entries=metadata.entries.map(({name,dir,uncompressedBytes})=>({name,dir,size:uncompressedBytes}));this.fetchState={kind:"loaded",entries},this.archiveSearchQuery&&this.recomputeArchiveSearch()}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation(),!this.archiveNestedUpdatePending&&(this.archiveNestedUpdatePending=!0,queueMicrotask(()=>{this.archiveNestedUpdatePending=!1,this.isConnected&&this.requestUpdate()}))}archiveVirtualList(){return this.renderRoot.querySelector("lr-virtual-list")}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){if(await list.updateComplete,list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return!0;if(!view)return!1;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return!1}syncArchiveNestedRoot(){const root=this.textContentRoot();if(root!==this.archiveSelectionRoot&&(this.unbindTextSelection(),this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=root,root)){const emitSelection=()=>{const range=archiveSelectionRange(this,root);if(!range||!root.contains(range.startContainer)||!root.contains(range.endContainer))return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};root.addEventListener("pointerup",emitSelection),root.addEventListener("keyup",emitSelection),this.archiveSelectionCleanup=()=>{root.removeEventListener("pointerup",emitSelection),root.removeEventListener("keyup",emitSelection)}}const listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot)if(listRoot.querySelector("style[data-lr-archive-highlight-styles]"))this.styledVirtualListRoot=listRoot;else{const style=this.ownerDocument.createElement("style");style.dataset.lrArchiveHighlightStyles="",style.textContent=virtualListHighlightStyles.cssText,listRoot.append(style),this.styledVirtualListRoot=listRoot}if(root)for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]"))mark.hasAttribute("part")||mark.setAttribute("part","highlight")}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[],boundedQuery=boundedViewerSearchQuery(this.archiveSearchQuery,this.effectiveLocale),query=boundedQuery.needle,matches=[],budget=new ViewerSearchWorkBudget;if(boundedQuery.accepted&&query){for(const entry of entries)if(budget.includes(entry.name,query,this.effectiveLocale)&&matches.push(entry),!budget.complete)break}this.archiveSearchMatches=matches,this.archiveSearchMatchCountExact=boundedQuery.accepted&&budget.complete,this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1,this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,matchCountExact:this.archiveSearchMatchCountExact,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match),list=this.renderRoot.querySelector("lr-virtual-list");index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeItemId=${this.archiveSearchMatches[this.archiveSearchActiveIndex]?.name??""} @lr-visible-range-change=${this.stopVirtualListEvent} @lr-virtual-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;case"loading":return renderViewerLoading(this.localize("loadingDocument"));case"error":return html`<div part="error">${this.fetchState.message}</div>`;default:return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`}}render(){const label=viewerSemanticLabel(this,this.name||null),role=label===null?null:viewerSemanticRole(this,"region"),maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${role??nothing} aria-label=${label??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-archive-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0),__decorate([property()],LyraArchiveViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraArchiveViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{srOnly}from"../../../internal/a11y.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{TextViewerTarget}from"../../../internal/text-viewer-target.js";import{fileIcon,folderIcon}from"../../../internal/icons.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{boundedSelectionRects,boundedSelectionText,buildQuoteAnchor,createTextQuoteIndex,scopeFromElement,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../../media/attachment-chip/attachment-chip.class.js";import{assertZipArchiveMetadataWithinLimits}from"./zip-resource-guard.js";import{styles,virtualListHighlightStyles}from"./archive-viewer.styles.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{renderViewerLoading,viewerLoadingStyles}from"../viewer-loading.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../viewer-search-limits.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_archiveViewerEmpty,LYRA_DEFAULT_archiveViewerFile,LYRA_DEFAULT_archiveViewerFolder,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const MAX_ARCHIVE_ENTRIES=1e4,MAX_ARCHIVE_UNCOMPRESSED_BYTES=100*1024*1024;class LyraArchiveViewerBase extends LyraElement{}const ArchiveTextViewerTargetBase=TextViewerTarget(LyraArchiveViewerBase);function archiveSelectionRange(viewer,contentRoot){const document=viewer.ownerDocument,view=document.defaultView,nestedRoot=contentRoot.getRootNode(),outerRoot=viewer.shadowRoot,ShadowRootCtor=view?.ShadowRoot,shadowRoots=[outerRoot,nestedRoot].filter((root,index,roots)=>ShadowRootCtor!==void 0&&root instanceof ShadowRootCtor&&roots.indexOf(root)===index),globalSelection=view?.getSelection();if(globalSelection?.getComposedRanges){const[composed]=globalSelection.getComposedRanges({shadowRoots});if(composed&&(composed.startContainer!==composed.endContainer||composed.startOffset!==composed.endOffset)){const range=document.createRange();return range.setStart(composed.startContainer,composed.startOffset),range.setEnd(composed.endContainer,composed.endOffset),range}}const selection=nestedRoot.getSelection?.()??globalSelection??null;return!selection||selection.rangeCount===0||selection.isCollapsed?null:selection.getRangeAt(0)}class LyraArchiveViewer extends ArchiveTextViewerTargetBase{constructor(){super(...arguments),this.src="",this.name="",this.maxHeight="",this.fetchState={kind:"idle"},this.archiveSearchMatches=[],this.archiveSearchActiveIndex=-1,this.archiveSearchMatchCountExact=!0,this.generation=0,this.archiveSearchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.archiveSelectionRoot=null,this.styledVirtualListRoot=null,this.archiveNestedUpdatePending=!1,this.archiveEntryKey=(item,index)=>`${item.name}\0${index}`,this.announcements=new ViewerAnnouncementController(this),this.renderEntry=item=>{const entry=item,kind=this.localize(entry.dir?"archiveViewerFolder":"archiveViewerFile");return html`<div part="entry" data-dir=${entry.dir?"true":"false"}><span part="entry-icon">${entry.dir?folderIcon():fileIcon()}</span><span class="sr-only">${kind}</span><span part=${entry.dir?"entry-name entry-name-dir":"entry-name"} dir="auto" title=${entry.name}>${entry.name}</span>${entry.dir?nothing:html`<span part="entry-size" dir="auto">${formatFileSize(entry.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}</span>`}</div>`}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,archiveViewerEmpty:LYRA_DEFAULT_archiveViewerEmpty,archiveViewerFile:LYRA_DEFAULT_archiveViewerFile,archiveViewerFolder:LYRA_DEFAULT_archiveViewerFolder,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,documentPreviewEmpty:LYRA_DEFAULT_documentPreviewEmpty,documentPreviewFailedToLoad:LYRA_DEFAULT_documentPreviewFailedToLoad,documentPreviewResourceTooLarge:LYRA_DEFAULT_documentPreviewResourceTooLarge,documentPreviewTypeDocument:LYRA_DEFAULT_documentPreviewTypeDocument,documentPreviewUrlNotAllowed:LYRA_DEFAULT_documentPreviewUrlNotAllowed,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,loadingDocument:LYRA_DEFAULT_loadingDocument,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly,viewerLoadingStyles]}async search(query){return this.archiveSearchQuery=query,this.lastSearchLocale=this.effectiveLocale,this.recomputeArchiveSearch(),await this.updateComplete,this.scrollActiveArchiveMatch(),this.archiveSearchMatches.length}async searchNext(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex+1)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}async searchPrevious(){return this.archiveSearchMatches.length?(this.archiveSearchActiveIndex=(this.archiveSearchActiveIndex-1+this.archiveSearchMatches.length)%this.archiveSearchMatches.length,this.emitArchiveSearchChange(),await this.updateComplete,this.scrollActiveArchiveMatch(),!0):!1}clearSearch(){this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.emitArchiveSearchChange()}willUpdate(changed){super.willUpdate(changed),changed.has("src")&&(this.pendingSearchResetEvent||=this.archiveSearchQuery!==""||this.archiveSearchMatches.length>0||!this.archiveSearchMatchCountExact||this.archiveSearchActiveIndex!==-1,this.archiveSearchQuery="",this.archiveSearchMatches=[],this.archiveSearchMatchCountExact=!0,this.archiveSearchActiveIndex=-1,this.fetchState=this.src?{kind:"loading"}:{kind:"idle"})}updated(changed){super.updated(changed),this.announcements.transition("load",this.fetchState.kind,this.fetchState.kind==="error"?this.fetchState.message:this.localize("loadingDocument")),this.syncArchiveNestedRoot(),changed.has("src")&&this.scheduleAfterUpdate(()=>{this.load()}),changed.has("src")&&this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitArchiveSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=this.archiveSearchQuery!=="";this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.archiveSearchQuery)},"search")}}connectedCallback(){super.connectedCallback(),this.announcements.connect(),this.hasUpdated&&this.src&&this.scheduleAfterUpdate(()=>{this.load()})}disconnectedCallback(){this.generation++,this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=null,this.announcements.disconnect(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}textContentRoot(){return this.archiveVirtualList()?.shadowRoot?.querySelector('[part="spacer"]')??null}async applyAnchor(anchor){if(this.fetchState.kind!=="loaded")return!1;const loadGeneration=this.generation;let index=-1,resolvedName;if(anchor.kind==="fragment")index=this.fetchState.entries.findIndex(entry=>entry.name===anchor.id),resolvedName=this.fetchState.entries[index]?.name;else if(anchor.kind==="text-quote"){const probe=this.ownerDocument.createElement("span"),workBudget={remainingCodeUnits:TEXT_QUOTE_LIMITS.maxSearchWorkCodeUnits};for(let candidateIndex=0;candidateIndex<this.fetchState.entries.length;candidateIndex++){const entry=this.fetchState.entries[candidateIndex],buildCost=Math.max(1,entry.name.length);if(buildCost>workBudget.remainingCodeUnits)break;if(workBudget.remainingCodeUnits-=buildCost,probe.textContent=entry.name,createTextQuoteIndex(scopeFromElement(probe),this.effectiveLocale).resolve(anchor,workBudget)){index=candidateIndex;break}}}if(index<0)return!1;const list=this.archiveVirtualList();if(!list||(list.scrollToIndex(index,{align:"auto",behavior:"auto"}),!await this.waitForArchiveRow(list,index))||(this.requestUpdate(),await this.updateComplete,loadGeneration!==this.generation||this.fetchState.kind!=="loaded"))return!1;if(anchor.kind==="fragment"){const root=this.textContentRoot(),target=root?Array.from(root.querySelectorAll('[part~="entry-name"]')).find(el=>el.textContent===resolvedName):null;return target?.scrollIntoView?.({block:"nearest",behavior:"auto"}),target!=null}return ArchiveTextViewerTargetBase.prototype.applyAnchor.call(this,anchor)}computeSelectionAnchor(range){const entryName=node=>{const elementNode=this.ownerDocument.defaultView?.Node.ELEMENT_NODE??1;return(node.nodeType===elementNode?node:node.parentElement)?.closest('[part~="entry-name"]')??null},start=entryName(range.startContainer),end=entryName(range.endContainer);return!start||start!==end?null:buildQuoteAnchor(range,scopeFromElement(start))}async load(){const generation=++this.generation,signal=this.beginAbortableLoad();if(!this.src){this.fetchState={kind:"idle"};return}const fetchTarget=resolveOwnerFetchTarget(this,this.src);if(!fetchTarget){const error=new LyraUserFacingError(this.localize("documentPreviewUrlNotAllowed"));this.fetchState={kind:"error",message:error.message},this.emit("lr-render-error",{error});return}this.fetchState={kind:"loading"};try{const response=await fetchTarget.view.fetch(fetchTarget.url,signal?{signal}:void 0);if(!response.ok)throw new Error(`${response.status} ${response.statusText}`);if(!this.isConnected||generation!==this.generation)return;const buffer=await readResponseArrayBuffer(response);if(!this.isConnected||generation!==this.generation)return;const metadata=assertZipArchiveMetadataWithinLimits(buffer,{description:"ZIP",maxEntries:MAX_ARCHIVE_ENTRIES,maxUncompressedBytes:MAX_ARCHIVE_UNCOMPRESSED_BYTES,signal});if(!this.isConnected||generation!==this.generation)return;const entries=metadata.entries.map(({name,dir,uncompressedBytes})=>({name,dir,size:uncompressedBytes}));this.fetchState={kind:"loaded",entries},this.archiveSearchQuery&&this.recomputeArchiveSearch()}catch(error){if(isAbortError(error)||!this.isConnected||generation!==this.generation)return;this.fetchState={kind:"error",message:this.localize(isResourceLimitError(error)?"documentPreviewResourceTooLarge":"documentPreviewFailedToLoad")},this.emit("lr-render-error",{error})}}stopVirtualListEvent(event){event.stopPropagation(),!this.archiveNestedUpdatePending&&(this.archiveNestedUpdatePending=!0,queueMicrotask(()=>{this.archiveNestedUpdatePending=!1,this.isConnected&&this.requestUpdate()}))}archiveVirtualList(){return this.renderRoot.querySelector("lr-virtual-list")}async waitForArchiveRow(list,index){const view=this.ownerDocument.defaultView;for(let attempt=0;attempt<5;attempt++){if(await list.updateComplete,list.shadowRoot?.querySelector(`[data-row-index="${index}"]`))return!0;if(!view)return!1;await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()))}return!1}syncArchiveNestedRoot(){const root=this.textContentRoot();if(root!==this.archiveSelectionRoot&&(this.unbindTextSelection(),this.archiveSelectionCleanup?.(),this.archiveSelectionCleanup=void 0,this.archiveSelectionRoot=root,root)){const emitSelection=()=>{const range=archiveSelectionRange(this,root);if(!range||!root.contains(range.startContainer)||!root.contains(range.endContainer))return;const text=boundedSelectionText(range);if(!text)return;const anchor=this.computeSelectionAnchor(range),rects=boundedSelectionRects(range);this.emit("lr-text-select",{text,anchor,rects})};root.addEventListener("pointerup",emitSelection),root.addEventListener("keyup",emitSelection),this.archiveSelectionCleanup=()=>{root.removeEventListener("pointerup",emitSelection),root.removeEventListener("keyup",emitSelection)}}const listRoot=this.archiveVirtualList()?.shadowRoot??null;if(listRoot&&listRoot!==this.styledVirtualListRoot)if(listRoot.querySelector("style[data-lr-archive-highlight-styles]"))this.styledVirtualListRoot=listRoot;else{const style=this.ownerDocument.createElement("style");style.dataset.lrArchiveHighlightStyles="",style.textContent=virtualListHighlightStyles.cssText,listRoot.append(style),this.styledVirtualListRoot=listRoot}if(root)for(const mark of root.querySelectorAll("mark[data-lr-highlight-tone]"))mark.hasAttribute("part")||mark.setAttribute("part","highlight")}recomputeArchiveSearch(){const entries=this.fetchState.kind==="loaded"?this.fetchState.entries:[],boundedQuery=boundedViewerSearchQuery(this.archiveSearchQuery,this.effectiveLocale),query=boundedQuery.needle,matches=[],budget=new ViewerSearchWorkBudget;if(boundedQuery.accepted&&query){for(const entry of entries)if(budget.includes(entry.name,query,this.effectiveLocale)&&matches.push(entry),!budget.complete)break}this.archiveSearchMatches=matches,this.archiveSearchMatchCountExact=boundedQuery.accepted&&budget.complete,this.archiveSearchActiveIndex=this.archiveSearchMatches.length>0?0:-1,this.emitArchiveSearchChange()}emitArchiveSearchChange(){this.emit("lr-search-change",{query:this.archiveSearchQuery,matchCount:this.archiveSearchMatches.length,matchCountExact:this.archiveSearchMatchCountExact,activeIndex:this.archiveSearchActiveIndex})}scrollActiveArchiveMatch(){if(this.fetchState.kind!=="loaded")return;const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return;const index=this.fetchState.entries.indexOf(match),list=this.renderRoot.querySelector("lr-virtual-list");index>=0&&list?.scrollToIndex(index,{behavior:"auto"})}activeArchiveMatchKey(){if(this.fetchState.kind!=="loaded")return"";const match=this.archiveSearchMatches[this.archiveSearchActiveIndex];if(!match)return"";const index=this.fetchState.entries.indexOf(match);return index>=0?this.archiveEntryKey(match,index):""}renderBody(){switch(this.fetchState.kind){case"loaded":return this.fetchState.entries.length?html`<lr-virtual-list exportparts="entry:entry, entry-icon:entry-icon, entry-name:entry-name, entry-name-dir:entry-name-dir, entry-size:entry-size, highlight:highlight" .items=${this.fetchState.entries} .renderItem=${this.renderEntry} .keyFunction=${this.archiveEntryKey} .activeItemId=${this.activeArchiveMatchKey()} @lr-visible-range-change=${this.stopVirtualListEvent} @lr-virtual-scroll=${this.stopVirtualListEvent}></lr-virtual-list>`:html`<p class="empty-note">${this.localize("archiveViewerEmpty")}</p>`;case"loading":return renderViewerLoading(this.localize("loadingDocument"));case"error":return html`<div part="error">${this.fetchState.message}</div>`;default:return html`<p class="empty-note">${this.localize("documentPreviewEmpty",void 0,{type:this.localize("documentPreviewTypeDocument")})}</p>`}}render(){const label=viewerSemanticLabel(this,this.name||null),role=label===null?null:viewerSemanticRole(this,"region"),maxHeight=sanitizeCssLength(this.maxHeight);return html`<div part="base" role=${role??nothing} aria-label=${label??nothing} aria-busy=${this.fetchState.kind==="loading"?"true":"false"} style=${maxHeight?styleMap({"--lr-archive-viewer-max-height":maxHeight}):nothing}><div part="body">${this.renderBody()}</div>${this.renderAnchorLiveRegion()}</div>`}}__decorate([property()],LyraArchiveViewer.prototype,"src",void 0),__decorate([property()],LyraArchiveViewer.prototype,"name",void 0),__decorate([property({attribute:"max-height"})],LyraArchiveViewer.prototype,"maxHeight",void 0),__decorate([state()],LyraArchiveViewer.prototype,"fetchState",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchMatches",void 0),__decorate([state()],LyraArchiveViewer.prototype,"archiveSearchActiveIndex",void 0);export{LyraArchiveViewer};