@aceshooting/lyra-ui 27.0.0 → 28.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (389) hide show
  1. package/CHANGELOG.md +55 -63
  2. package/README.md +7 -3
  3. package/dist/cli/css-declarations.mjs +1 -0
  4. package/dist/cli/lyra-rename-ledger.mjs +1 -1
  5. package/dist/cli/migrate-wa.mjs +9 -4
  6. package/dist/cli/migration-contract.json +1 -1
  7. package/dist/cli/migration-renames.mjs +2 -2
  8. package/dist/cli/migration-theme-scopes.mjs +3 -0
  9. package/dist/cli/theme-scope-vocabulary.generated.mjs +1 -0
  10. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  11. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  12. package/dist/components/agent-tools/agent-question/agent-question.class.js +1 -1
  13. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  14. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  15. package/dist/components/agent-tools/approval-queue/approval-queue.class.js +1 -1
  16. package/dist/components/agent-tools/artifact-panel/artifact-panel.class.js +1 -1
  17. package/dist/components/agent-tools/background-runs/background-runs.class.js +1 -1
  18. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  19. package/dist/components/agent-tools/budget-meter/budget-meter.class.js +1 -1
  20. package/dist/components/agent-tools/change-review/change-review.class.js +1 -1
  21. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  22. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
  23. package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +1 -1
  24. package/dist/components/agent-tools/connector-manager/connector-manager.class.js +1 -1
  25. package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
  26. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  27. package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
  28. package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +1 -1
  29. package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
  30. package/dist/components/agent-tools/permission-grant/permission-grant.class.js +1 -1
  31. package/dist/components/agent-tools/permission-rules/permission-rules.class.js +1 -1
  32. package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
  33. package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +1 -1
  34. package/dist/components/agent-tools/result-card/result-field.class.js +1 -1
  35. package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
  36. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  37. package/dist/components/agent-tools/stack-trace/stack-trace.class.js +1 -1
  38. package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +2 -2
  39. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  40. package/dist/components/agent-tools/terminal/terminal.class.js +1 -1
  41. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  42. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  43. package/dist/components/agent-tools/tool-approval-dialog/tool-approval-dialog.class.js +1 -1
  44. package/dist/components/agent-tools/tool-call-block/tool-call-block.class.js +1 -1
  45. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +1 -1
  46. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  47. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
  48. package/dist/components/agent-tools/tool-result-view/tool-result-view.class.js +1 -1
  49. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
  50. package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +1 -1
  51. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  52. package/dist/components/charts/chart/box-plot.class.js +1 -1
  53. package/dist/components/charts/chart/chart-token-cache.js +2 -2
  54. package/dist/components/charts/chart/chart.class.d.ts +1 -1
  55. package/dist/components/charts/chart/chart.class.js +3 -3
  56. package/dist/components/charts/chart/histogram.class.js +1 -1
  57. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  58. package/dist/components/conversation/agent-workspace/agent-workspace.class.js +1 -1
  59. package/dist/components/conversation/audio-visualizer/audio-visualizer.class.js +1 -1
  60. package/dist/components/conversation/branch-picker/branch-picker.class.js +1 -1
  61. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  62. package/dist/components/conversation/chat-message/chat-message.class.js +1 -1
  63. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  64. package/dist/components/conversation/checkpoint/checkpoint.class.js +1 -1
  65. package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
  66. package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
  67. package/dist/components/conversation/code-block/code-block.class.js +1 -1
  68. package/dist/components/conversation/conversation-item/conversation-item.class.js +1 -1
  69. package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
  70. package/dist/components/conversation/handoff-divider/handoff-divider.class.js +1 -1
  71. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  72. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  73. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  74. package/dist/components/conversation/message-actions/message-actions.class.js +1 -1
  75. package/dist/components/conversation/message-feedback/message-feedback.class.js +1 -1
  76. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  77. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  78. package/dist/components/conversation/model-settings-panel/model-settings-panel.class.js +1 -1
  79. package/dist/components/conversation/prompt-input/prompt-input.class.js +1 -1
  80. package/dist/components/conversation/prompt-queue/prompt-queue.class.js +1 -1
  81. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  82. package/dist/components/conversation/realtime-session/realtime-session.class.js +1 -1
  83. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  84. package/dist/components/conversation/stream-status/stream-status.class.js +1 -1
  85. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +1 -1
  86. package/dist/components/conversation/thread-list/thread-list.class.js +1 -1
  87. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  88. package/dist/components/conversation/typing-indicator/typing-indicator.class.js +1 -1
  89. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  90. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  91. package/dist/components/data/calendar/calendar.class.js +1 -1
  92. package/dist/components/data/condition-builder/condition-builder.class.js +1 -1
  93. package/dist/components/data/context-meter/context-meter.class.js +1 -1
  94. package/dist/components/data/data-grid/data-grid.class.d.ts +2 -2
  95. package/dist/components/data/data-grid/data-grid.class.js +3 -3
  96. package/dist/components/data/document-library/document-library.class.js +1 -1
  97. package/dist/components/data/env-list/env-list.class.js +1 -1
  98. package/dist/components/data/file-tree/file-tree.class.d.ts +2 -2
  99. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  100. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  101. package/dist/components/data/flow-controls/flow-controls.class.js +1 -1
  102. package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
  103. package/dist/components/data/flow-node/flow-node.class.js +1 -1
  104. package/dist/components/data/flow-run-status/flow-run-status.class.js +1 -1
  105. package/dist/components/data/funnel/funnel.class.js +1 -1
  106. package/dist/components/data/gauge/gauge.class.js +1 -1
  107. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  108. package/dist/components/data/heatmap/heatmap.class.js +1 -1
  109. package/dist/components/data/pagination/pagination.class.d.ts +2 -0
  110. package/dist/components/data/pagination/pagination.class.js +1 -1
  111. package/dist/components/data/pagination/pagination.styles.js +1 -1
  112. package/dist/components/data/sequence-strip/sequence-strip.class.js +1 -1
  113. package/dist/components/data/sparkline/sparkline.class.js +1 -1
  114. package/dist/components/data/stat/stat.class.js +1 -1
  115. package/dist/components/data/table/table.class.d.ts +23 -2
  116. package/dist/components/data/table/table.class.js +5 -3
  117. package/dist/components/data/table/table.styles.js +1 -1
  118. package/dist/components/data/timeline/timeline.class.js +1 -1
  119. package/dist/components/data/tree/tree.class.js +1 -1
  120. package/dist/components/data/word-cloud/word-cloud.class.js +1 -1
  121. package/dist/components/forms/button/button.class.js +1 -1
  122. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  123. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  124. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  125. package/dist/components/forms/color-picker/color-picker.class.d.ts +8 -4
  126. package/dist/components/forms/color-picker/color-picker.class.js +2 -2
  127. package/dist/components/forms/combobox/combobox.class.js +1 -1
  128. package/dist/components/forms/country-picker/country-picker.class.js +1 -1
  129. package/dist/components/forms/currency-picker/currency-picker.class.js +1 -1
  130. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  131. package/dist/components/forms/date-picker/date-picker.class.js +1 -1
  132. package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
  133. package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +7 -4
  134. package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
  135. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -0
  136. package/dist/components/forms/icon-button/icon-button.class.js +1 -1
  137. package/dist/components/forms/icon-button/icon-button.styles.js +1 -1
  138. package/dist/components/forms/input/input-shared.js +1 -1
  139. package/dist/components/forms/input/input.class.js +1 -1
  140. package/dist/components/forms/input/native-time-input.class.js +1 -1
  141. package/dist/components/forms/input/number-input.class.js +1 -1
  142. package/dist/components/forms/input/time-input.class.js +1 -1
  143. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  144. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  145. package/dist/components/forms/phone-input/phone-input.class.js +1 -1
  146. package/dist/components/forms/radio/radio-group.class.js +1 -1
  147. package/dist/components/forms/radio/radio.class.js +1 -1
  148. package/dist/components/forms/rubric-form/rubric-form.class.js +4 -4
  149. package/dist/components/forms/select/select.class.js +1 -1
  150. package/dist/components/forms/signature-pad/signature-pad.class.js +1 -1
  151. package/dist/components/forms/slider/slider.class.js +1 -1
  152. package/dist/components/forms/switch/switch.class.js +1 -1
  153. package/dist/components/forms/textarea/textarea.class.js +1 -1
  154. package/dist/components/forms/time-range/time-range.class.js +1 -1
  155. package/dist/components/forms/time-zone-picker/time-zone-picker.class.js +1 -1
  156. package/dist/components/forms/token-input/token-input.class.js +1 -1
  157. package/dist/components/forms/unit-picker/unit-picker.class.js +1 -1
  158. package/dist/components/layout/app-rail/app-rail-item.class.js +1 -1
  159. package/dist/components/layout/app-rail/app-rail.class.d.ts +70 -7
  160. package/dist/components/layout/app-rail/app-rail.class.js +16 -4
  161. package/dist/components/layout/app-rail/app-rail.styles.js +1 -1
  162. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  163. package/dist/components/layout/breadcrumb/breadcrumb.class.js +1 -1
  164. package/dist/components/layout/card/card.class.js +1 -1
  165. package/dist/components/layout/carousel/carousel.class.js +1 -1
  166. package/dist/components/layout/command-palette/command-palette.class.js +1 -1
  167. package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
  168. package/dist/components/layout/details/accordion-item.class.js +1 -1
  169. package/dist/components/layout/details/details.class.js +1 -1
  170. package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
  171. package/dist/components/layout/drilldown-panel/drilldown-panel.class.js +1 -1
  172. package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
  173. package/dist/components/layout/menu/menu.class.js +1 -1
  174. package/dist/components/layout/menubar/menubar.class.js +1 -1
  175. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  176. package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
  177. package/dist/components/layout/page/page.class.js +1 -1
  178. package/dist/components/layout/reorder-list/reorder-item.class.js +1 -1
  179. package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
  180. package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
  181. package/dist/components/layout/scroller/scroller.class.js +1 -1
  182. package/dist/components/layout/segmented/segmented.class.d.ts +7 -4
  183. package/dist/components/layout/segmented/segmented.styles.js +1 -1
  184. package/dist/components/layout/split-panel/split-panel.class.js +1 -1
  185. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  186. package/dist/components/layout/tab-group/tab.class.js +1 -1
  187. package/dist/components/layout/virtual-list/virtual-list.styles.js +1 -1
  188. package/dist/components/layout/widget/widget.class.js +1 -1
  189. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  190. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  191. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  192. package/dist/components/media/av-player/av-player.class.js +1 -1
  193. package/dist/components/media/avatar-group/avatar-group.class.js +1 -1
  194. package/dist/components/media/drop-zone/drop-zone.class.js +1 -1
  195. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  196. package/dist/components/media/file-input/file-input.class.js +1 -1
  197. package/dist/components/media/flag/flag.class.js +1 -1
  198. package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
  199. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -1
  200. package/dist/components/media/image-viewer/image-viewer.class.js +4 -2
  201. package/dist/components/media/image-viewer/image-viewer.styles.js +1 -1
  202. package/dist/components/media/lightbox/lightbox.class.js +1 -1
  203. package/dist/components/media/map/map.class.js +1 -1
  204. package/dist/components/media/media-card/media-card.class.js +1 -1
  205. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  206. package/dist/components/media/qr-code/qr-code.class.d.ts +2 -2
  207. package/dist/components/media/qr-code/qr-code.class.js +1 -1
  208. package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
  209. package/dist/components/media/video/video.class.js +1 -1
  210. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  211. package/dist/components/media/zoomable-frame/zoomable-frame.class.js +1 -1
  212. package/dist/components/overlays/alert/alert.class.js +1 -1
  213. package/dist/components/overlays/badge/tag.class.js +1 -1
  214. package/dist/components/overlays/callout/callout.class.js +1 -1
  215. package/dist/components/overlays/chip/chip-group.class.js +1 -1
  216. package/dist/components/overlays/chip/chip.class.js +1 -1
  217. package/dist/components/overlays/context-menu/context-menu.class.js +1 -1
  218. package/dist/components/overlays/dialog/confirm.js +1 -1
  219. package/dist/components/overlays/dialog/dialog.class.js +1 -1
  220. package/dist/components/overlays/kbd/kbd.class.js +1 -1
  221. package/dist/components/overlays/overlay/popover.class.js +1 -1
  222. package/dist/components/overlays/overlay/tooltip.class.js +1 -1
  223. package/dist/components/overlays/progress/progress-bar.class.js +1 -1
  224. package/dist/components/overlays/progress/progress-ring.class.js +1 -1
  225. package/dist/components/overlays/rating/rating.class.js +1 -1
  226. package/dist/components/overlays/skeleton/skeleton.class.js +1 -1
  227. package/dist/components/overlays/spinner/spinner.class.js +1 -1
  228. package/dist/components/overlays/toast/toast-item.class.js +1 -1
  229. package/dist/components/overlays/toast/toast.class.js +1 -1
  230. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +1 -1
  231. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  232. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  233. package/dist/components/retrieval/community-card/community-card.class.js +1 -1
  234. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +1 -1
  235. package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
  236. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  237. package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
  238. package/dist/components/retrieval/graph/graph.class.js +1 -1
  239. package/dist/components/retrieval/graph-legend/graph-legend.class.js +1 -1
  240. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  241. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +1 -1
  242. package/dist/components/retrieval/knowledge-base/knowledge-base.class.js +1 -1
  243. package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +1 -1
  244. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
  245. package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
  246. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  247. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
  248. package/dist/components/retrieval/node-palette/node-palette.class.js +1 -1
  249. package/dist/components/retrieval/path-strip/path-strip.class.js +1 -1
  250. package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
  251. package/dist/components/retrieval/rag-answer/rag-answer.class.js +1 -1
  252. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
  253. package/dist/components/retrieval/research-progress/research-progress.class.js +1 -1
  254. package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.js +1 -1
  255. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  256. package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +1 -1
  257. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  258. package/dist/components/retrieval/source-card/source-card.class.js +1 -1
  259. package/dist/components/retrieval/source-list/source-list.class.js +1 -1
  260. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  261. package/dist/components/utility/copy-button/copy-button.class.js +1 -1
  262. package/dist/components/utility/diff-view/diff-view.class.js +1 -1
  263. package/dist/components/utility/export-button/export-button.class.js +1 -1
  264. package/dist/components/utility/icon/icon.class.js +1 -1
  265. package/dist/components/utility/json-viewer/json-viewer.class.js +1 -1
  266. package/dist/components/utility/known-date/known-date.class.js +1 -1
  267. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  268. package/dist/components/utility/poll-status/poll-status.class.js +1 -1
  269. package/dist/components/utility/random-content/random-content.class.js +1 -1
  270. package/dist/components/utility/tour/tour.class.js +1 -1
  271. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  272. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  273. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  274. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  275. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +2 -2
  276. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  277. package/dist/components/viewers/document-preview/document-preview.class.js +1 -1
  278. package/dist/components/viewers/document-viewer/document-viewer.class.js +1 -1
  279. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  280. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  281. package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
  282. package/dist/components/viewers/geojson-view/geojson-view.class.js +1 -1
  283. package/dist/components/viewers/geojson-view/geojson-viewer.class.js +1 -1
  284. package/dist/components/viewers/highlight-layer/highlight-layer.class.js +1 -1
  285. package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
  286. package/dist/components/viewers/include/include.class.js +1 -1
  287. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  288. package/dist/components/viewers/page-rail/page-rail.class.d.ts +1 -1
  289. package/dist/components/viewers/page-rail/page-rail.class.js +3 -3
  290. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  291. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  292. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
  293. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  294. package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
  295. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
  296. package/dist/events.d.ts +6 -1
  297. package/dist/framework-types.d.ts +1 -1
  298. package/dist/internal/accessibility-visibility.js +1 -1
  299. package/dist/internal/collection-snapshot.js +1 -1
  300. package/dist/internal/default-strings/agent-tools.generated.js +1 -0
  301. package/dist/internal/default-strings/charts.generated.js +1 -0
  302. package/dist/internal/default-strings/conversation.generated.js +1 -0
  303. package/dist/internal/default-strings/data.generated.js +1 -0
  304. package/dist/internal/default-strings/forms.generated.js +1 -0
  305. package/dist/internal/default-strings/layout.generated.js +1 -0
  306. package/dist/internal/default-strings/media.generated.js +1 -0
  307. package/dist/internal/default-strings/overlays.generated.js +1 -0
  308. package/dist/internal/default-strings/retrieval.generated.js +1 -0
  309. package/dist/internal/default-strings/shared.generated.js +1 -0
  310. package/dist/internal/default-strings/utility.generated.js +1 -0
  311. package/dist/internal/default-strings/viewers.generated.js +5 -0
  312. package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
  313. package/dist/internal/dev-mode-attribute-warning.production.js +1 -1
  314. package/dist/internal/document-tokens.d.ts +11 -0
  315. package/dist/internal/document-tokens.generated.js +15 -0
  316. package/dist/internal/document-tokens.js +3 -0
  317. package/dist/internal/form-associated.d.ts +1 -1
  318. package/dist/internal/form-associated.js +1 -1
  319. package/dist/internal/glass-surface.styles.js +1 -1
  320. package/dist/internal/host-tokens.styles.js +1 -0
  321. package/dist/internal/image-zoom.js +1 -0
  322. package/dist/internal/intl-cache.js +1 -1
  323. package/dist/internal/localization-types.d.ts +1 -1
  324. package/dist/internal/localization.js +2 -2
  325. package/dist/internal/lyra-element.d.ts +4 -2
  326. package/dist/internal/lyra-element.js +2 -2
  327. package/dist/internal/opaque-content-border.styles.js +1 -1
  328. package/dist/internal/open-overlay-raise.styles.js +1 -0
  329. package/dist/internal/optional-peer-failure.js +1 -0
  330. package/dist/internal/package-metadata.js +1 -1
  331. package/dist/internal/prefix.js +1 -1
  332. package/dist/internal/specialist-host-tokens.styles.js +1 -0
  333. package/dist/internal/specialist-tokens.generated.js +2 -0
  334. package/dist/internal/step-value.js +1 -1
  335. package/dist/internal/theme-observation.js +1 -1
  336. package/dist/internal/theme-scopes.d.ts +11 -0
  337. package/dist/internal/theme-scopes.js +1 -0
  338. package/dist/looks/shadcn.css +1 -1
  339. package/dist/lyra.d.ts +1 -1
  340. package/dist/lyra.js +1 -1
  341. package/dist/styles/design-tokens.css +1 -1
  342. package/dist/styles/tokens-root.css +1 -1
  343. package/dist/surfaces/glass.css +1 -1
  344. package/dist/testing/happy-dom-shims.d.ts +21 -2
  345. package/dist/testing/happy-dom-shims.js +1 -1
  346. package/dist/testing/index.d.ts +1 -1
  347. package/dist/testing/index.js +1 -1
  348. package/dist/testing/interaction-drivers.d.ts +66 -7
  349. package/dist/testing/interaction-drivers.js +1 -1
  350. package/dist/testing/jsdom-shims.d.ts +70 -0
  351. package/dist/testing/jsdom-shims.js +1 -0
  352. package/dist/theme/look-inputs.d.ts +1 -1
  353. package/dist/theme/look-inputs.js +37 -41
  354. package/dist/theme/theme.d.ts +13 -0
  355. package/dist/theme/theme.js +1 -1
  356. package/dist/theme.css +1 -1
  357. package/dist/utilities/index.d.ts +1 -1
  358. package/dist/utilities/index.js +1 -1
  359. package/dist/utilities/scoped-registry.d.ts +3 -0
  360. package/dist/utilities/scoped-registry.js +1 -1
  361. package/dist/utilities/theme-scopes.d.ts +1 -0
  362. package/dist/utilities/theme-scopes.js +1 -0
  363. package/dist/utilities/tokens.d.ts +1 -0
  364. package/dist/utilities/tokens.js +1 -0
  365. package/llms/components/lr-app-rail.md +51 -4
  366. package/llms/components/lr-emoji-picker.md +13 -8
  367. package/llms/components/lr-icon-button.md +13 -1
  368. package/llms/components/lr-image-viewer.md +8 -0
  369. package/llms/components/lr-pagination.md +4 -2
  370. package/llms/components/lr-segmented.md +7 -3
  371. package/llms/components/lr-table.md +14 -12
  372. package/llms/components/lr-thread-list.md +4 -3
  373. package/llms/migration.md +9 -0
  374. package/llms/peers.md +1 -1
  375. package/llms/shared/events-and-types.md +41 -0
  376. package/llms/shared/frameworks-and-ssr.md +16 -0
  377. package/llms/shared/imports-and-registration.md +4 -3
  378. package/llms/shared/native-styles-and-utilities.md +38 -3
  379. package/llms/shared/styles-and-tokens.md +242 -102
  380. package/llms/shared/testing-and-utilities.md +90 -6
  381. package/llms/shared.md +431 -114
  382. package/llms/tokens.md +31 -49
  383. package/locales.json +138 -138
  384. package/package.json +14 -7
  385. package/registrations.json +1 -1
  386. package/dist/internal/default-strings.generated.js +0 -5
  387. package/dist/internal/specialist-tokens.styles.js +0 -1
  388. package/dist/internal/tokens/palette.styles.js +0 -1
  389. package/dist/internal/tokens.styles.js +0 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{styles}from"./source-card.styles.js";import{LYRA_DEFAULT_showLess,LYRA_DEFAULT_showMore,LYRA_DEFAULT_sourcePageSuffix,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings.generated.js";class LyraSourceCardBase extends LyraElement{}class LyraSourceCard extends LyraSourceCardBase{constructor(){super(...arguments),this.sourceId="",this.heading="",this.size="m",this.disabled=!1,this.triggerPressed=null,this.triggerCurrent=null,this.frame="card",this.hasFullSlot=!1,this.hasExcerptSlot=!1,this.fullExpanded=!1,this.fullId=nextId("source-card-full"),this.onFullSlotChange=()=>{const count=Array.from(this.children).filter(el=>el.getAttribute("slot")==="full").length;this.hasFullSlot=count>0,count===0&&this.fullExpanded&&(this.fullExpanded=!1,this.emit("lr-expand",{sourceId:this.sourceId,expanded:!1}),this.emit("lr-toggle",{itemId:this.sourceId,expanded:!1}))},this.onExcerptSlotChange=()=>{this.hasExcerptSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="excerpt")},this.onTitleClick=()=>{this.emit("lr-open",{sourceId:this.sourceId,href:this.href})},this.toggleFull=()=>{this.fullExpanded=!this.fullExpanded,this.emit("lr-expand",{sourceId:this.sourceId,expanded:this.fullExpanded}),this.emit("lr-toggle",{itemId:this.sourceId,expanded:this.fullExpanded})}}static{this.defaultStrings={...super.defaultStrings,showLess:LYRA_DEFAULT_showLess,showMore:LYRA_DEFAULT_showMore,sourcePageSuffix:LYRA_DEFAULT_sourcePageSuffix,untitledSource:LYRA_DEFAULT_untitledSource}}static{this.styles=[LyraElement.styles,styles]}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasFullSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="full"),this.hasExcerptSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="excerpt"))}firstUpdated(changed){super.firstUpdated(changed);const fullCount=Array.from(this.children).filter(el=>el.getAttribute("slot")==="full").length;this.hasFullSlot=fullCount>0,fullCount===0&&(this.fullExpanded=!1),this.hasExcerptSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="excerpt")}get titleText(){const base=this.heading||this.localize("untitledSource");return this.page==null||this.page===""?base:this.localize("sourcePageSuffix",void 0,{base,page:this.page})}render(){const pressed=["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing;return html`
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{styles}from"./source-card.styles.js";import{LYRA_DEFAULT_showMore,LYRA_DEFAULT_sourcePageSuffix,LYRA_DEFAULT_untitledSource}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_showLess}from"../../../internal/default-strings/shared.generated.js";class LyraSourceCardBase extends LyraElement{}class LyraSourceCard extends LyraSourceCardBase{constructor(){super(...arguments),this.sourceId="",this.heading="",this.size="m",this.disabled=!1,this.triggerPressed=null,this.triggerCurrent=null,this.frame="card",this.hasFullSlot=!1,this.hasExcerptSlot=!1,this.fullExpanded=!1,this.fullId=nextId("source-card-full"),this.onFullSlotChange=()=>{const count=Array.from(this.children).filter(el=>el.getAttribute("slot")==="full").length;this.hasFullSlot=count>0,count===0&&this.fullExpanded&&(this.fullExpanded=!1,this.emit("lr-expand",{sourceId:this.sourceId,expanded:!1}),this.emit("lr-toggle",{itemId:this.sourceId,expanded:!1}))},this.onExcerptSlotChange=()=>{this.hasExcerptSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="excerpt")},this.onTitleClick=()=>{this.emit("lr-open",{sourceId:this.sourceId,href:this.href})},this.toggleFull=()=>{this.fullExpanded=!this.fullExpanded,this.emit("lr-expand",{sourceId:this.sourceId,expanded:this.fullExpanded}),this.emit("lr-toggle",{itemId:this.sourceId,expanded:this.fullExpanded})}}static{this.defaultStrings={...super.defaultStrings,showLess:LYRA_DEFAULT_showLess,showMore:LYRA_DEFAULT_showMore,sourcePageSuffix:LYRA_DEFAULT_sourcePageSuffix,untitledSource:LYRA_DEFAULT_untitledSource}}static{this.styles=[LyraElement.styles,styles]}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasFullSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="full"),this.hasExcerptSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="excerpt"))}firstUpdated(changed){super.firstUpdated(changed);const fullCount=Array.from(this.children).filter(el=>el.getAttribute("slot")==="full").length;this.hasFullSlot=fullCount>0,fullCount===0&&(this.fullExpanded=!1),this.hasExcerptSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="excerpt")}get titleText(){const base=this.heading||this.localize("untitledSource");return this.page==null||this.page===""?base:this.localize("sourcePageSuffix",void 0,{base,page:this.page})}render(){const pressed=["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing;return html`
2
2
  <div part="base" ?data-disabled=${this.disabled}>
3
3
  <button
4
4
  part="title"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{tag}from"../../../internal/prefix.js";import{isElement}from"../../../internal/rendered-tree-traversal.js";import{styles}from"./source-list.styles.js";import{LYRA_DEFAULT_sourceListDefaultLabel}from"../../../internal/default-strings.generated.js";class LyraSourceList extends LyraElement{constructor(){super(...arguments),this.expanded=!1,this.labelPlural="",this.size="m",this.frame="card",this.slottedCount=0,this.listId=nextId("source-list-region"),this.previousRoles=new Map,this.roleObserverGeneration=0,this.onSlotChange=e=>{const elements=e.target.assignedElements({flatten:!0});this.slottedCount=elements.length,this.syncItemRoles(elements)},this.toggle=()=>{this.expanded=!this.expanded,this.emit("lr-toggle",{expanded:this.expanded})},this.onCardToggle=event=>{const origin=event.composedPath()[0],detail=event.detail;!origin||!isElement(origin)||origin.localName!==tag("source-card")||!this.contains(origin)||!detail||typeof detail.expanded!="boolean"||typeof detail.itemId!="string"||detail.itemId!==origin.sourceId||(event.stopPropagation(),this.emit("lr-toggle",{expanded:detail.expanded,itemId:detail.itemId}))}}static{this.defaultStrings={...super.defaultStrings,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel}}static{this.styles=[LyraElement.styles,styles]}isCompatibleListItem(element){const existingRole=element.getAttribute("role")?.trim(),role=existingRole==="listitem"&&this.previousRoles.has(element)&&this.previousRoles.get(element)!=="listitem"?void 0:existingRole;if(role==="listitem")return!0;if(role||element.hasAttribute("tabindex")||element.isContentEditable)return!1;const localName=element.localName;return localName===tag("source-card")||localName==="div"||localName==="span"}onRoleMutations(records){for(const record of records){const element=record.target;if(!(element.parentElement!==this||element.getAttribute("slot"))){record.attributeName==="role"&&this.previousRoles.has(element)&&this.previousRoles.set(element,element.getAttribute("role")),this.reconcileAssignedItems();return}}}observeRoleChanges(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(!this.roleObserver||this.roleObserverDocument!==ownerDocument){this.resetRoleObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.roleObserverGeneration,observer=new MutationObserverCtor(records=>{this.roleObserver!==observer||this.roleObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onRoleMutations(records)});this.roleObserver=observer,this.roleObserverDocument=ownerDocument}this.roleObserver.observe(this,{attributes:!0,attributeFilter:["role","tabindex","contenteditable"],subtree:!0})}syncItemRoles(elements){this.roleObserver?.disconnect();const assigned=new Set(elements),hasListSemantics=elements.every(element=>this.isCompatibleListItem(element)),list=this.shadowRoot?.querySelector('[part="list"]');this.isConnected&&hasListSemantics?list?.setAttribute("role","list"):list?.removeAttribute("role");for(const[element,role]of this.previousRoles)hasListSemantics&&assigned.has(element)&&element.getAttribute("role")==="listitem"&&role!=="listitem"||(role===null?element.removeAttribute("role"):element.setAttribute("role",role),this.previousRoles.delete(element));if(hasListSemantics)for(const element of elements)element.getAttribute("role")?.trim()||(this.previousRoles.has(element)||this.previousRoles.set(element,element.getAttribute("role")),element.setAttribute("role","listitem"));this.observeRoleChanges()}reconcileAssignedItems(){const slot=this.shadowRoot?.querySelector("slot");if(!slot)return;const elements=slot.assignedElements({flatten:!0});this.slottedCount=elements.length,this.syncItemRoles(elements)}connectedCallback(){if(super.connectedCallback(),this.observeRoleChanges(),this.hasUpdated){const ownerDocument=this.ownerDocument,generation=this.roleObserverGeneration;this.updateComplete.then(()=>{!this.isConnected||this.ownerDocument!==ownerDocument||this.roleObserverGeneration!==generation||this.reconcileAssignedItems()})}}disconnectedCallback(){this.roleObserver?.disconnect(),this.syncItemRoles([]),this.resetRoleObserver(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetRoleObserver()}resetRoleObserver(){this.roleObserverGeneration+=1,this.roleObserver?.disconnect(),this.roleObserver=void 0,this.roleObserverDocument=void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const elements=Array.from(this.children).filter(el=>!el.getAttribute("slot"));this.slottedCount=elements.length}}firstUpdated(changed){super.firstUpdated(changed),this.reconcileAssignedItems()}get sourceCount(){return this.slottedCount}set sourceCount(_value){}render(){const requestedHeaderText=this.labelPlural||(this.label==null?this.localize("sourceListDefaultLabel"):this.label),headerText=requestedHeaderText.trim()===""?this.localize("sourceListDefaultLabel"):requestedHeaderText;return html`
1
+ import{__decorate}from"tslib";import{html}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{tag}from"../../../internal/prefix.js";import{isElement}from"../../../internal/rendered-tree-traversal.js";import{styles}from"./source-list.styles.js";import{LYRA_DEFAULT_sourceListDefaultLabel}from"../../../internal/default-strings/shared.generated.js";class LyraSourceList extends LyraElement{constructor(){super(...arguments),this.expanded=!1,this.labelPlural="",this.size="m",this.frame="card",this.slottedCount=0,this.listId=nextId("source-list-region"),this.previousRoles=new Map,this.roleObserverGeneration=0,this.onSlotChange=e=>{const elements=e.target.assignedElements({flatten:!0});this.slottedCount=elements.length,this.syncItemRoles(elements)},this.toggle=()=>{this.expanded=!this.expanded,this.emit("lr-toggle",{expanded:this.expanded})},this.onCardToggle=event=>{const origin=event.composedPath()[0],detail=event.detail;!origin||!isElement(origin)||origin.localName!==tag("source-card")||!this.contains(origin)||!detail||typeof detail.expanded!="boolean"||typeof detail.itemId!="string"||detail.itemId!==origin.sourceId||(event.stopPropagation(),this.emit("lr-toggle",{expanded:detail.expanded,itemId:detail.itemId}))}}static{this.defaultStrings={...super.defaultStrings,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel}}static{this.styles=[LyraElement.styles,styles]}isCompatibleListItem(element){const existingRole=element.getAttribute("role")?.trim(),role=existingRole==="listitem"&&this.previousRoles.has(element)&&this.previousRoles.get(element)!=="listitem"?void 0:existingRole;if(role==="listitem")return!0;if(role||element.hasAttribute("tabindex")||element.isContentEditable)return!1;const localName=element.localName;return localName===tag("source-card")||localName==="div"||localName==="span"}onRoleMutations(records){for(const record of records){const element=record.target;if(!(element.parentElement!==this||element.getAttribute("slot"))){record.attributeName==="role"&&this.previousRoles.has(element)&&this.previousRoles.set(element,element.getAttribute("role")),this.reconcileAssignedItems();return}}}observeRoleChanges(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(!this.roleObserver||this.roleObserverDocument!==ownerDocument){this.resetRoleObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.roleObserverGeneration,observer=new MutationObserverCtor(records=>{this.roleObserver!==observer||this.roleObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.onRoleMutations(records)});this.roleObserver=observer,this.roleObserverDocument=ownerDocument}this.roleObserver.observe(this,{attributes:!0,attributeFilter:["role","tabindex","contenteditable"],subtree:!0})}syncItemRoles(elements){this.roleObserver?.disconnect();const assigned=new Set(elements),hasListSemantics=elements.every(element=>this.isCompatibleListItem(element)),list=this.shadowRoot?.querySelector('[part="list"]');this.isConnected&&hasListSemantics?list?.setAttribute("role","list"):list?.removeAttribute("role");for(const[element,role]of this.previousRoles)hasListSemantics&&assigned.has(element)&&element.getAttribute("role")==="listitem"&&role!=="listitem"||(role===null?element.removeAttribute("role"):element.setAttribute("role",role),this.previousRoles.delete(element));if(hasListSemantics)for(const element of elements)element.getAttribute("role")?.trim()||(this.previousRoles.has(element)||this.previousRoles.set(element,element.getAttribute("role")),element.setAttribute("role","listitem"));this.observeRoleChanges()}reconcileAssignedItems(){const slot=this.shadowRoot?.querySelector("slot");if(!slot)return;const elements=slot.assignedElements({flatten:!0});this.slottedCount=elements.length,this.syncItemRoles(elements)}connectedCallback(){if(super.connectedCallback(),this.observeRoleChanges(),this.hasUpdated){const ownerDocument=this.ownerDocument,generation=this.roleObserverGeneration;this.updateComplete.then(()=>{!this.isConnected||this.ownerDocument!==ownerDocument||this.roleObserverGeneration!==generation||this.reconcileAssignedItems()})}}disconnectedCallback(){this.roleObserver?.disconnect(),this.syncItemRoles([]),this.resetRoleObserver(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetRoleObserver()}resetRoleObserver(){this.roleObserverGeneration+=1,this.roleObserver?.disconnect(),this.roleObserver=void 0,this.roleObserverDocument=void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const elements=Array.from(this.children).filter(el=>!el.getAttribute("slot"));this.slottedCount=elements.length}}firstUpdated(changed){super.firstUpdated(changed),this.reconcileAssignedItems()}get sourceCount(){return this.slottedCount}set sourceCount(_value){}render(){const requestedHeaderText=this.labelPlural||(this.label==null?this.localize("sourceListDefaultLabel"):this.label),headerText=requestedHeaderText.trim()===""?this.localize("sourceListDefaultLabel"):requestedHeaderText;return html`
2
2
  <div part="base">
3
3
  <button
4
4
  part="header"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport,writeNormalizedOwnedCollection}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_sourcePickerMatches,LYRA_DEFAULT_sourcePickerSelection,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64,EMPTY_SOURCE_ENTRIES=Object.freeze([]),EMPTY_SOURCE_IDS=Object.freeze([]);class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.withoutSelectAll=!1,this.withoutSearch=!1,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.stopOwnedEvent=event=>{event.stopPropagation()},this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerMatches:LYRA_DEFAULT_sourcePickerMatches,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change","lr-sources-change"])}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get sourceEntries(){return Array.isArray(this.sources)?this.sources:EMPTY_SOURCE_ENTRIES}get selectedIds(){return Array.isArray(this.selectedSourceIds)?this.selectedSourceIds:EMPTY_SOURCE_IDS}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sourceEntries&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sourceEntries,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||!isNonBlankIdentity(source.label)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=Array.isArray(source.children)?source.children:[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sourceEntries,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry,selectedIds){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>selectedIds.has(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}matchesQuery(entry){return entry.label.toLocaleLowerCase(this.effectiveLocale).includes(this.query.trim().toLocaleLowerCase(this.effectiveLocale))}isFiltering(){return!this.withoutSearch&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering)for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(this.matchesQuery(node.entry)||node.children.some(child=>matches.has(child)))&&matches.add(node)}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds(),current=this.selectedIds;if(normalized.length!==current.length||normalized.some((id,index)=>id!==current[index])){const shouldAnnounce=this.hasUpdated&&changed.has("sources");writeNormalizedOwnedCollection(this,"selectedSourceIds",()=>{this.selectedSourceIds=normalized}),shouldAnnounce&&this.reportSelection(normalized)}}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds")&&!changed.has("withoutSearch"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(shadowFocusTarget(this)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sourceEntries.length===0||this.withoutSearch?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const count=this.visibleRows().filter(row=>this.matchesQuery(row.entry)).length,signature=`${this.query.trim().toLocaleLowerCase(this.effectiveLocale)}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,this.announcementSink?.announce(count===0?this.localize("noMatches"):this.localize("sourcePickerMatches",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count})))}reportSelection(selectedSourceIds){this.emit("lr-selection-change",{selectedSourceIds}),this.emit("lr-sources-change",{selectedSourceIds})}commitSelection(next){this.selectedSourceIds=next,this.reportSelection(next)}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),set=new Set(this.normalizedSelectedSourceIds()),willSelect=this.checkedState(entry,set)!=="true";for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}selectAllTargets(rows){return this.isFiltering()?rows.filter(row=>!row.hasChildren).map(row=>row.entry.id):this.allLeafIds()}toggleSelectAll(){const targets=this.selectAllTargets(this.visibleRows());if(!targets.length)return;const selected=new Set(this.normalizedSelectedSourceIds()),allSelected=targets.every(id=>selected.has(id));for(const id of targets)allSelected?selected.delete(id):selected.add(id);this.commitSelection([...selected])}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active,selectedIds){const state2=this.checkedState(row.entry,selectedIds),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());return html`
1
+ import{__decorate}from"tslib";import{collectionSupport,writeNormalizedOwnedCollection}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isNonBlankIdentity}from"../retrieval-identity.js";import{isRtl}from"../../../internal/rtl.js";import"../../media/file-icon/file-icon.class.js";import"../../forms/input/input.class.js";import"../../forms/checkbox/checkbox.class.js";import"../../overlays/empty/empty.class.js";import{styles}from"./source-picker.styles.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_selectAllSources,LYRA_DEFAULT_sourcePickerMatches,LYRA_DEFAULT_sourcePickerSelection}from"../../../internal/default-strings/retrieval.generated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_copy,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_sourceListDefaultLabel,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";const MAX_SOURCE_NODES=2e3,MAX_SOURCE_DEPTH=64,EMPTY_SOURCE_ENTRIES=Object.freeze([]),EMPTY_SOURCE_IDS=Object.freeze([]);class LyraSourcePicker extends LyraElement{constructor(){super(...arguments),this.sources=[],this.selectedSourceIds=[],this.withoutSelectAll=!1,this.withoutSearch=!1,this.accessibleLabel=null,this.expandedIds=new Set,this.query="",this.activeId=null,this.keyboardFocusGeneration=0,this.isMounting=!0,this.lastFilterAnnouncement="",this.stopOwnedEvent=event=>{event.stopPropagation()},this.onTreeKeyDown=e=>{const rows=this.visibleRows();if(rows.length===0)return;const currentIndex=Math.max(0,rows.findIndex(r=>r.entry.id===this.activeId)),current=rows[currentIndex],rtl=isRtl(this),expandKey=rtl?"ArrowLeft":"ArrowRight",collapseKey=rtl?"ArrowRight":"ArrowLeft";switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRowByIndex(Math.min(rows.length-1,currentIndex+1),rows);break;case"ArrowUp":e.preventDefault(),this.focusRowByIndex(Math.max(0,currentIndex-1),rows);break;case"Home":e.preventDefault(),this.focusRowByIndex(0,rows);break;case"End":e.preventDefault(),this.focusRowByIndex(rows.length-1,rows);break;case expandKey:if(e.preventDefault(),current.hasChildren&&!this.expandedIds.has(current.entry.id))this.expandedIds=new Set(this.expandedIds).add(current.entry.id);else if(current.hasChildren){const next=this.visibleRows()[currentIndex+1];next&&next.depth>current.depth&&this.focusRowByIndex(currentIndex+1,this.visibleRows())}break;case collapseKey:if(e.preventDefault(),current.hasChildren&&this.expandedIds.has(current.entry.id)){const set=new Set(this.expandedIds);set.delete(current.entry.id),this.expandedIds=set}else for(let i=currentIndex-1;i>=0;i--)if(rows[i].depth<current.depth){this.focusRowByIndex(i,rows);break}break;case"Enter":case" ":e.preventDefault(),this.toggleEntry(current.entry);break;default:return}}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,copy:LYRA_DEFAULT_copy,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,selectAllSources:LYRA_DEFAULT_selectAllSources,sourceListDefaultLabel:LYRA_DEFAULT_sourceListDefaultLabel,sourcePickerMatches:LYRA_DEFAULT_sourcePickerMatches,sourcePickerSelection:LYRA_DEFAULT_sourcePickerSelection,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["sources","selectedSourceIds"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-selection-change","lr-sources-change"])}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get sourceEntries(){return Array.isArray(this.sources)?this.sources:EMPTY_SOURCE_ENTRIES}get selectedIds(){return Array.isArray(this.selectedSourceIds)?this.selectedSourceIds:EMPTY_SOURCE_IDS}connectedCallback(){super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.isMounting=!0,this.lastFilterAnnouncement="",this.announcementSink?.release(),this.announcementSink=void 0,super.disconnectedCallback()}get sourceModel(){if(this.normalizedInput===this.sourceEntries&&this.normalizedModel)return this.normalizedModel;const roots=[],nodes=[],byEntry=new WeakMap,seenObjects=new WeakSet,seenIds=new Set;let limited=!1;const stack=[];stack.push({sources:this.sourceEntries,target:roots,depth:0,index:0});let inspected=0;for(;stack.length;){const frame=stack[stack.length-1];if(frame.index>=frame.sources.length){stack.pop();continue}if(inspected>=MAX_SOURCE_NODES){limited=!0;break}const source=frame.sources[frame.index++];if(inspected++,!source||typeof source!="object"||seenObjects.has(source)||!isNonBlankIdentity(source.id)||!isNonBlankIdentity(source.label)||seenIds.has(source.id)){limited=!0;continue}if(nodes.length>=MAX_SOURCE_NODES||frame.depth>MAX_SOURCE_DEPTH){limited=!0;continue}seenObjects.add(source),seenIds.add(source.id);const declaredGroup=Array.isArray(source.children),entry={id:source.id,label:source.label,...source.mimeType!==void 0?{mimeType:source.mimeType}:{},...source.name!==void 0?{name:source.name}:{},...declaredGroup?{children:[]}:{}},node={entry,depth:frame.depth,children:[],leafIds:[]};declaredGroup&&(entry.children=node.children.map(child=>child.entry)),frame.target.push(node),nodes.push(node),byEntry.set(entry,node);const children=Array.isArray(source.children)?source.children:[];children.length&&frame.depth>=MAX_SOURCE_DEPTH&&(limited=!0),children.length&&frame.depth<MAX_SOURCE_DEPTH&&stack.push({sources:children,target:node.children,depth:frame.depth+1,index:0})}for(let index=nodes.length-1;index>=0;index--){const node=nodes[index];node.entry.children!==void 0&&(node.entry.children=node.children.map(child=>child.entry)),node.leafIds=node.entry.children===void 0?[node.entry.id]:[...new Set(node.children.flatMap(child=>child.leafIds))]}const leafIds=[...new Set(roots.flatMap(root=>root.leafIds))];return this.normalizedInput=this.sourceEntries,this.normalizedModel={roots,nodes,byEntry,leafIds,limited},this.normalizedModel}allLeafIds(){return this.sourceModel.leafIds}descendantLeafIds(entry){return this.sourceModel.byEntry.get(entry)?.leafIds??[]}normalizedSelectedSourceIds(){const valid=new Set(this.allLeafIds()),seen=new Set;return this.selectedIds.filter(id=>!valid.has(id)||seen.has(id)?!1:(seen.add(id),!0))}checkedState(entry,selectedIds){const leaves=this.descendantLeafIds(entry),selected=leaves.filter(id=>selectedIds.has(id));return selected.length===0?"false":selected.length===leaves.length?"true":"mixed"}matchesQuery(entry){return entry.label.toLocaleLowerCase(this.effectiveLocale).includes(this.query.trim().toLocaleLowerCase(this.effectiveLocale))}isFiltering(){return!this.withoutSearch&&this.query.trim().length>0}visibleRows(){const rows=[],filtering=this.isFiltering(),matches=new Set;if(filtering)for(let index=this.sourceModel.nodes.length-1;index>=0;index--){const node=this.sourceModel.nodes[index];(this.matchesQuery(node.entry)||node.children.some(child=>matches.has(child)))&&matches.add(node)}const stack=[...this.sourceModel.roots].reverse();for(;stack.length;){const node=stack.pop();if(filtering&&!matches.has(node))continue;const hasChildren=node.entry.children!==void 0;if(rows.push({entry:node.entry,depth:node.depth,hasChildren}),hasChildren&&(filtering||this.expandedIds.has(node.entry.id)))for(let index=node.children.length-1;index>=0;index--)stack.push(node.children[index])}return rows}willUpdate(changed){if(super.willUpdate(changed),changed.has("sources")||changed.has("selectedSourceIds")){const normalized=this.normalizedSelectedSourceIds(),current=this.selectedIds;if(normalized.length!==current.length||normalized.some((id,index)=>id!==current[index])){const shouldAnnounce=this.hasUpdated&&changed.has("sources");writeNormalizedOwnedCollection(this,"selectedSourceIds",()=>{this.selectedSourceIds=normalized}),shouldAnnounce&&this.reportSelection(normalized)}}if(!changed.has("sources")&&!changed.has("query")&&!changed.has("expandedIds")&&!changed.has("withoutSearch"))return;const focusedIndex=Array.from(this.renderRoot.querySelectorAll('[part~="item"]')).indexOf(shadowFocusTarget(this)),rows=this.visibleRows(),retainedIndex=rows.findIndex(row=>row.entry.id===this.activeId),nextIndex=retainedIndex>=0?retainedIndex:rows.length?Math.min(Math.max(focusedIndex,0),rows.length-1):-1;this.activeId=nextIndex>=0?rows[nextIndex].entry.id:null,focusedIndex>=0&&(this.pendingFocusIndex=nextIndex>=0?nextIndex:this.sourceEntries.length===0||this.withoutSearch?"base":"search")}updated(changed){super.updated(changed);const pending=this.pendingFocusIndex;pending!==void 0&&(this.pendingFocusIndex=void 0,pending==="search"?this.renderRoot.querySelector('[part~="search"]')?.focus():pending==="base"?this.renderRoot.querySelector('[part="base"]')?.focus():this.renderRoot.querySelectorAll('[part~="item"]')[pending]?.focus());const wasMounting=this.isMounting;if(this.isMounting=!1,wasMounting||!changed.has("query")&&!changed.has("sources"))return;if(!this.isFiltering()){this.lastFilterAnnouncement="";return}const count=this.visibleRows().filter(row=>this.matchesQuery(row.entry)).length,signature=`${this.query.trim().toLocaleLowerCase(this.effectiveLocale)}\0${count}`;signature!==this.lastFilterAnnouncement&&(this.lastFilterAnnouncement=signature,this.announcementSink?.announce(count===0?this.localize("noMatches"):this.localize("sourcePickerMatches",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count})))}reportSelection(selectedSourceIds){this.emit("lr-selection-change",{selectedSourceIds}),this.emit("lr-sources-change",{selectedSourceIds})}commitSelection(next){this.selectedSourceIds=next,this.reportSelection(next)}toggleEntry(entry){const leaves=this.descendantLeafIds(entry),set=new Set(this.normalizedSelectedSourceIds()),willSelect=this.checkedState(entry,set)!=="true";for(const id of leaves)willSelect?set.add(id):set.delete(id);this.commitSelection([...set])}selectAllTargets(rows){return this.isFiltering()?rows.filter(row=>!row.hasChildren).map(row=>row.entry.id):this.allLeafIds()}toggleSelectAll(){const targets=this.selectAllTargets(this.visibleRows());if(!targets.length)return;const selected=new Set(this.normalizedSelectedSourceIds()),allSelected=targets.every(id=>selected.has(id));for(const id of targets)allSelected?selected.delete(id):selected.add(id);this.commitSelection([...selected])}focusRowByIndex(index,rows){const targetId=rows[index]?.entry.id;if(!targetId)return;this.activeId=targetId;const generation=++this.keyboardFocusGeneration;this.updateComplete.then(()=>{if(!this.isConnected||generation!==this.keyboardFocusGeneration)return;const currentIndex=this.visibleRows().findIndex(row=>row.entry.id===targetId);if(currentIndex<0)return;this.renderRoot.querySelectorAll('[part~="item"]')[currentIndex]?.focus()})}renderRow(row,active,selectedIds){const state2=this.checkedState(row.entry,selectedIds),expanded=row.hasChildren&&(this.expandedIds.has(row.entry.id)||this.isFiltering());return html`
2
2
  <div
3
3
  part="item"
4
4
  role="treeitem"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{finiteDuration}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{styles}from"./copy-button.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings.generated.js";const DEFAULT_FEEDBACK_DURATION=COPY_FEEDBACK_MS,ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function copyIcon(){return svg`
1
+ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{finiteDuration}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{styles}from"./copy-button.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_FEEDBACK_DURATION=COPY_FEEDBACK_MS,ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function copyIcon(){return svg`
2
2
  <svg
3
3
  width="1em"
4
4
  height="1em"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,Announcer}from"../../../internal/announcer.js";import{advanceViewerSearchIndex,announceSearchResult,viewerSearchDetail}from"../../../internal/viewer-search.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../../viewers/viewer-search-limits.js";import{ViewerAnnouncementController}from"../../viewers/viewer-announcements.js";import{commonAffix,computeLineDiff,pairOpsForSplit}from"./diff-line-diff.js";import{loadShikiHighlighterCore,SHIKI_THEMES}from"../../conversation/code-block/code-loader.js";import{styles}from"./diff-view.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyDiff,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_details,LYRA_DEFAULT_diffViewHiddenLines,LYRA_DEFAULT_diffViewNewLabel,LYRA_DEFAULT_diffViewOldLabel,LYRA_DEFAULT_diffViewTooLarge,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,splitLines=text=>text===""?[]:text.split(/\r\n|\r|\n/),MAX_DIFF_CHARACTERS=1e6,MAX_DIFF_COMPARISONS=4e6,MAX_DIFF_LANGUAGES=1e4,MAX_DIFF_LANGUAGE_INSPECTIONS=MAX_DIFF_LANGUAGES*2,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_HIGHLIGHTS=100;function projectLanguages(value){if(!(value===null||typeof value!="object"))try{if(Array.isArray(value))return;const projected=Object.create(null),keys=Object.getOwnPropertyNames(value);let inspected=0,admitted=0;for(const key of keys){if(inspected>=MAX_DIFF_LANGUAGE_INSPECTIONS||admitted>=MAX_DIFF_LANGUAGES)break;inspected+=1;const descriptor=getOwnDataDescriptor(value,key);descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable||(Object.defineProperty(projected,key,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1}),admitted+=1)}return Object.freeze(projected)}catch{return}}const DIFF_VIEW_LAYOUT=literalSetConverter(["unified","split"],"unified");class LyraDiffViewBase extends LyraElement{}class LyraDiffView extends DocumentAnchorTarget(LyraDiffViewBase){constructor(){super(...arguments),this.oldText="",this.newText="",this.copyable=!1,this.maxHeight="",this._layout="unified",this.language="",this.maxLines=5e3,this.anchorKinds=["line-range"],this.copyStatus="rest",this.diffTooLarge=!1,this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.forcedVisibleOps=new Set,this.searchAnnouncements=new ViewerAnnouncementController(this),this.searchAnnouncer=new Announcer({onFlush:text=>this.searchAnnouncements.announcePolite(text)}),this.highlightedOldLines=null,this.highlightedNewLines=null,this.highlightToken=0,this.loadHighlighterCore=loadShikiHighlighterCore,this.copyGeneration=0,this.oldTextSnapshot="",this.newTextSnapshot="",this.languageSnapshot="",this.diffOps=[],this.opIndexMap=new Map,this.onCopyClick=()=>{this.copy()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyDiff:LYRA_DEFAULT_copyDiff,copyFailed:LYRA_DEFAULT_copyFailed,details:LYRA_DEFAULT_details,diffViewHiddenLines:LYRA_DEFAULT_diffViewHiddenLines,diffViewNewLabel:LYRA_DEFAULT_diffViewNewLabel,diffViewOldLabel:LYRA_DEFAULT_diffViewOldLabel,diffViewTooLarge:LYRA_DEFAULT_diffViewTooLarge,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this._layout}set layout(next){const normalized=DIFF_VIEW_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated||changed.has("oldText")||changed.has("newText")){const oldText=this.oldText,newText=this.newText;this.oldTextSnapshot=typeof oldText=="string"?oldText:"",this.newTextSnapshot=typeof newText=="string"?newText:""}if(!this.hasUpdated||changed.has("language")||changed.has("languages")){const language=this.language;this.languageSnapshot=typeof language=="string"?language:"",this.languagesSnapshot=projectLanguages(this.languages)}if(this.hasUpdated&&(changed.has("oldText")||changed.has("newText")||changed.has("copyable")||changed.has("maxLines"))&&this.resetCopyFeedback(),changed.has("oldText")||changed.has("newText")||changed.has("maxLines")){const oldLines=splitLines(this.oldTextSnapshot),newLines=splitLines(this.newTextSnapshot),maxLines=this.maxLines===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:finiteCount(this.maxLines,5e3),characterCount=this.oldTextSnapshot.length+this.newTextSnapshot.length,[head,tail]=commonAffix(oldLines,newLines),comparisons=(oldLines.length-head-tail)*(newLines.length-head-tail);this.diffTooLarge=oldLines.length>maxLines||newLines.length>maxLines||characterCount>MAX_DIFF_CHARACTERS||comparisons>MAX_DIFF_COMPARISONS,this.diffOps=this.diffTooLarge?[]:computeLineDiff(oldLines,newLines),this.opIndexMap=new Map(this.diffOps.map((op,index)=>[op,index])),this.pendingSearchResetEvent||=this.hasSearchState(),this.forcedVisibleOps=new Set,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}(changed.has("oldText")||changed.has("newText")||changed.has("language")||changed.has("languages")||changed.has("maxLines"))&&this.syncHighlight()}updated(changed){super.updated(changed),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}connectedCallback(){super.connectedCallback(),this.copyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.connect();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}disconnectedCallback(){super.disconnectedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncer.cancel(),this.searchAnnouncements.disconnect()}adoptedCallback(){super.adoptedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncements.adopted();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}syncHighlight(){const token=++this.highlightToken;if(this.diffTooLarge){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const lang=this.languageSnapshot,languages=this.languagesSnapshot;if(!lang||!languages||!Object.hasOwn(languages,lang)){this.highlightedOldLines=null,this.highlightedNewLines=null;return}let loading;try{loading=this.loadHighlighterCore(languages)}catch{this.highlightedOldLines=null,this.highlightedNewLines=null;return}loading.then(hl=>{if(token===this.highlightToken){if(!hl){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=this.tokenizeLines(hl,this.oldTextSnapshot,lang),this.highlightedNewLines=this.tokenizeLines(hl,this.newTextSnapshot,lang)}},()=>{token===this.highlightToken&&(this.highlightedOldLines=null,this.highlightedNewLines=null)})}tokenizeLines(hl,text,lang){try{const html2=hl.codeToHtml(text,{lang,themes:SHIKI_THEMES}),DOMParserCtor=this.ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)return null;const doc=new DOMParserCtor().parseFromString(html2,"text/html"),lines=Array.from(doc.querySelectorAll("code > .line")).map(line=>line.innerHTML),expected=splitLines(text).length;for(;lines.length>expected;)lines.pop();for(;lines.length<expected;)lines.push("");return lines}catch{return null}}computeFolds(){const ops=this.diffOps,visible=new Set(ops),foldBefore=new Map;let trailingFold=0;const ctx=this.contextLines==null||!Number.isFinite(this.contextLines)||this.contextLines<0?void 0:finiteCount(this.contextLines);if(ctx===void 0)return{visible,foldBefore,trailingFold};let i=0;for(;i<ops.length;){if(ops[i].type!=="equal"){i++;continue}let j=i;for(;j<ops.length&&ops[j].type==="equal";)j++;const runLength=j-i,isLeading=i===0,isTrailing=j===ops.length;let runHasForcedReveal=!1;if(this.forcedVisibleOps.size>0){for(let k=i;k<j;k++)if(this.forcedVisibleOps.has(ops[k])){runHasForcedReveal=!0;break}}if(!(isLeading&&isTrailing)){if(!runHasForcedReveal){if(isLeading){const hidden=Math.max(0,runLength-ctx);if(hidden>0){for(let k=i;k<i+hidden;k++)visible.delete(ops[k]);foldBefore.set(ops[i+hidden],hidden)}}else if(isTrailing){const shown=Math.min(ctx,runLength),hidden=runLength-shown;if(hidden>0){for(let k=i+shown;k<j;k++)visible.delete(ops[k]);trailingFold=hidden}}else if(runLength>ctx*2){const hiddenStart=i+ctx,hiddenEnd=j-ctx;for(let k=hiddenStart;k<hiddenEnd;k++)visible.delete(ops[k]);foldBefore.set(ops[hiddenStart],hiddenEnd-hiddenStart)}}}i=j}return{visible,foldBefore,trailingFold}}foldMarker(count){const text=this.localize("diffViewHiddenLines",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});return html`<div part="line" data-type="fold">${text}</div>`}async revealOp(op){if(!this.forcedVisibleOps.has(op)){const next=new Set(this.forcedVisibleOps);next.add(op),this.forcedVisibleOps=next}await this.updateComplete}lineElementForOpIndex(index){return this.renderRoot.querySelector(`[data-op-index="${index}"]`)}async scrollOpIndexIntoView(index){const op=this.diffOps[index];if(!op)return!1;await this.revealOp(op);const target=this.lineElementForOpIndex(index);return target?(target.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"nearest"}),!0):!1}async applyAnchor(anchor){if(anchor.kind!=="line-range")return!1;const index=anchor.start;return!Number.isInteger(index)||index<0||index>=this.diffOps.length?!1:this.scrollOpIndexIntoView(index)}resolvedHighlightOps(){const perOp=new Map,owners=new Map,order=new Map,ops=this.diffOps;if(ops.length===0)return{perOp,owners,order,total:0};const seen=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(order.size>=MAX_PAINTED_HIGHLIGHTS)break;if(seen.has(highlight.id)||(seen.add(highlight.id),highlight.anchor.kind!=="line-range"))continue;const start=Math.max(0,Math.min(highlight.anchor.start,ops.length-1)),end=Math.max(start,Math.min(highlight.anchor.end??highlight.anchor.start,ops.length-1));let resolvedAny=!1;for(let index=start;index<=end;index++){const op=ops[index];resolvedAny=!0,!perOp.has(op)&&(perOp.set(op,highlight),owners.has(highlight)||owners.set(highlight,op))}resolvedAny&&order.set(highlight,order.size)}return{perOp,owners,order,total:order.size}}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}activateHighlight(highlight){this.emit("lr-highlight-activate",{highlightId:highlight.id})}emitSearchChange(){this.emit("lr-search-change",viewerSearchDetail(this.searchQuery,this.searchMatches.length,this.searchMatchCountExact,this.searchActiveIndex)),announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values),this.searchAnnouncer,this.effectiveLocale,this.searchMatches.length,this.searchActiveIndex)}recomputeSearchMatches(){this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(this.searchQuery,this.effectiveLocale),needle=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&needle){const budget=new ViewerSearchWorkBudget;for(let index=0;index<this.diffOps.length;index++){if(budget.includes(this.diffOps[index].text,needle,this.effectiveLocale)){if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push({opIndex:index})}if(!budget.complete){matchCountExact=!1;break}}}this.searchMatches=matches,this.searchMatchCountExact=matchCountExact}async search(query){this.searchQuery=query,this.recomputeSearchMatches(),this.searchActiveIndex=this.searchMatches.length>0?0:-1,this.emitSearchChange();const active=this.searchMatches[this.searchActiveIndex];return active&&await this.scrollOpIndexIntoView(active.opIndex),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,-1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange()}get unifiedText(){return this.diffOps.map(op=>`${op.type==="add"?"+":op.type==="remove"?"-":" "} ${op.text}`).join(`
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{unsafeHTML}from"lit/directives/unsafe-html.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink,Announcer}from"../../../internal/announcer.js";import{advanceViewerSearchIndex,announceSearchResult,viewerSearchDetail}from"../../../internal/viewer-search.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteCount}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedViewerSearchQuery,ViewerSearchWorkBudget}from"../../viewers/viewer-search-limits.js";import{ViewerAnnouncementController}from"../../viewers/viewer-announcements.js";import{commonAffix,computeLineDiff,pairOpsForSplit}from"./diff-line-diff.js";import{loadShikiHighlighterCore,SHIKI_THEMES}from"../../conversation/code-block/code-loader.js";import{styles}from"./diff-view.styles.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_collapse,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_highlightOfTotal,LYRA_DEFAULT_highlightWithLabel,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_remove,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_copyDiff,LYRA_DEFAULT_diffViewHiddenLines,LYRA_DEFAULT_diffViewNewLabel,LYRA_DEFAULT_diffViewOldLabel,LYRA_DEFAULT_diffViewTooLarge}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,splitLines=text=>text===""?[]:text.split(/\r\n|\r|\n/),MAX_DIFF_CHARACTERS=1e6,MAX_DIFF_COMPARISONS=4e6,MAX_DIFF_LANGUAGES=1e4,MAX_DIFF_LANGUAGE_INSPECTIONS=MAX_DIFF_LANGUAGES*2,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_HIGHLIGHTS=100;function projectLanguages(value){if(!(value===null||typeof value!="object"))try{if(Array.isArray(value))return;const projected=Object.create(null),keys=Object.getOwnPropertyNames(value);let inspected=0,admitted=0;for(const key of keys){if(inspected>=MAX_DIFF_LANGUAGE_INSPECTIONS||admitted>=MAX_DIFF_LANGUAGES)break;inspected+=1;const descriptor=getOwnDataDescriptor(value,key);descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable||(Object.defineProperty(projected,key,{value:descriptor.value,enumerable:!0,configurable:!1,writable:!1}),admitted+=1)}return Object.freeze(projected)}catch{return}}const DIFF_VIEW_LAYOUT=literalSetConverter(["unified","split"],"unified");class LyraDiffViewBase extends LyraElement{}class LyraDiffView extends DocumentAnchorTarget(LyraDiffViewBase){constructor(){super(...arguments),this.oldText="",this.newText="",this.copyable=!1,this.maxHeight="",this._layout="unified",this.language="",this.maxLines=5e3,this.anchorKinds=["line-range"],this.copyStatus="rest",this.diffTooLarge=!1,this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.lastSearchLocale="",this.pendingSearchResetEvent=!1,this.forcedVisibleOps=new Set,this.searchAnnouncements=new ViewerAnnouncementController(this),this.searchAnnouncer=new Announcer({onFlush:text=>this.searchAnnouncements.announcePolite(text)}),this.highlightedOldLines=null,this.highlightedNewLines=null,this.highlightToken=0,this.loadHighlighterCore=loadShikiHighlighterCore,this.copyGeneration=0,this.oldTextSnapshot="",this.newTextSnapshot="",this.languageSnapshot="",this.diffOps=[],this.opIndexMap=new Map,this.onCopyClick=()=>{this.copy()}}static{this.defaultStrings={...super.defaultStrings,anchorJumped:LYRA_DEFAULT_anchorJumped,anchorJumpedToPage:LYRA_DEFAULT_anchorJumpedToPage,anchorNotFound:LYRA_DEFAULT_anchorNotFound,collapse:LYRA_DEFAULT_collapse,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyDiff:LYRA_DEFAULT_copyDiff,copyFailed:LYRA_DEFAULT_copyFailed,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,diffViewHiddenLines:LYRA_DEFAULT_diffViewHiddenLines,diffViewNewLabel:LYRA_DEFAULT_diffViewNewLabel,diffViewOldLabel:LYRA_DEFAULT_diffViewOldLabel,diffViewTooLarge:LYRA_DEFAULT_diffViewTooLarge,highlightOfTotal:LYRA_DEFAULT_highlightOfTotal,highlightWithLabel:LYRA_DEFAULT_highlightWithLabel,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,remove:LYRA_DEFAULT_remove,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this._layout}set layout(next){const normalized=DIFF_VIEW_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated||changed.has("oldText")||changed.has("newText")){const oldText=this.oldText,newText=this.newText;this.oldTextSnapshot=typeof oldText=="string"?oldText:"",this.newTextSnapshot=typeof newText=="string"?newText:""}if(!this.hasUpdated||changed.has("language")||changed.has("languages")){const language=this.language;this.languageSnapshot=typeof language=="string"?language:"",this.languagesSnapshot=projectLanguages(this.languages)}if(this.hasUpdated&&(changed.has("oldText")||changed.has("newText")||changed.has("copyable")||changed.has("maxLines"))&&this.resetCopyFeedback(),changed.has("oldText")||changed.has("newText")||changed.has("maxLines")){const oldLines=splitLines(this.oldTextSnapshot),newLines=splitLines(this.newTextSnapshot),maxLines=this.maxLines===Number.POSITIVE_INFINITY?Number.POSITIVE_INFINITY:finiteCount(this.maxLines,5e3),characterCount=this.oldTextSnapshot.length+this.newTextSnapshot.length,[head,tail]=commonAffix(oldLines,newLines),comparisons=(oldLines.length-head-tail)*(newLines.length-head-tail);this.diffTooLarge=oldLines.length>maxLines||newLines.length>maxLines||characterCount>MAX_DIFF_CHARACTERS||comparisons>MAX_DIFF_COMPARISONS,this.diffOps=this.diffTooLarge?[]:computeLineDiff(oldLines,newLines),this.opIndexMap=new Map(this.diffOps.map((op,index)=>[op,index])),this.pendingSearchResetEvent||=this.hasSearchState(),this.forcedVisibleOps=new Set,this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1}(changed.has("oldText")||changed.has("newText")||changed.has("language")||changed.has("languages")||changed.has("maxLines"))&&this.syncHighlight()}updated(changed){super.updated(changed),this.pendingSearchResetEvent&&(this.pendingSearchResetEvent=!1,this.emitSearchChange());const locale=this.effectiveLocale;if(locale!==this.lastSearchLocale){const shouldRecompute=!!this.searchQuery;this.lastSearchLocale=locale,shouldRecompute&&this.scheduleAfterUpdate(()=>{this.search(this.searchQuery)},"search")}}hasSearchState(){return this.searchQuery!==""||this.searchMatches.length>0||!this.searchMatchCountExact||this.searchActiveIndex!==-1}connectedCallback(){super.connectedCallback(),this.copyAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.connect();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}disconnectedCallback(){super.disconnectedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncer.cancel(),this.searchAnnouncements.disconnect()}adoptedCallback(){super.adoptedCallback(),this.resetCopyFeedback(),this.copyAnnouncementSink?.release(),this.copyAnnouncementSink=void 0,this.searchAnnouncements.adopted();const ownerWindow=this.ownerDocument.defaultView;ownerWindow&&this.searchAnnouncer.setTimerHost(ownerWindow)}cancelCopyTimer(){const timer=this.copyTimer;this.copyTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}resetCopyFeedback(){this.copyGeneration+=1,this.cancelCopyTimer(),this.copyStatus="rest"}syncHighlight(){const token=++this.highlightToken;if(this.diffTooLarge){this.highlightedOldLines=null,this.highlightedNewLines=null;return}const lang=this.languageSnapshot,languages=this.languagesSnapshot;if(!lang||!languages||!Object.hasOwn(languages,lang)){this.highlightedOldLines=null,this.highlightedNewLines=null;return}let loading;try{loading=this.loadHighlighterCore(languages)}catch{this.highlightedOldLines=null,this.highlightedNewLines=null;return}loading.then(hl=>{if(token===this.highlightToken){if(!hl){this.highlightedOldLines=null,this.highlightedNewLines=null;return}this.highlightedOldLines=this.tokenizeLines(hl,this.oldTextSnapshot,lang),this.highlightedNewLines=this.tokenizeLines(hl,this.newTextSnapshot,lang)}},()=>{token===this.highlightToken&&(this.highlightedOldLines=null,this.highlightedNewLines=null)})}tokenizeLines(hl,text,lang){try{const html2=hl.codeToHtml(text,{lang,themes:SHIKI_THEMES}),DOMParserCtor=this.ownerDocument.defaultView?.DOMParser;if(!DOMParserCtor)return null;const doc=new DOMParserCtor().parseFromString(html2,"text/html"),lines=Array.from(doc.querySelectorAll("code > .line")).map(line=>line.innerHTML),expected=splitLines(text).length;for(;lines.length>expected;)lines.pop();for(;lines.length<expected;)lines.push("");return lines}catch{return null}}computeFolds(){const ops=this.diffOps,visible=new Set(ops),foldBefore=new Map;let trailingFold=0;const ctx=this.contextLines==null||!Number.isFinite(this.contextLines)||this.contextLines<0?void 0:finiteCount(this.contextLines);if(ctx===void 0)return{visible,foldBefore,trailingFold};let i=0;for(;i<ops.length;){if(ops[i].type!=="equal"){i++;continue}let j=i;for(;j<ops.length&&ops[j].type==="equal";)j++;const runLength=j-i,isLeading=i===0,isTrailing=j===ops.length;let runHasForcedReveal=!1;if(this.forcedVisibleOps.size>0){for(let k=i;k<j;k++)if(this.forcedVisibleOps.has(ops[k])){runHasForcedReveal=!0;break}}if(!(isLeading&&isTrailing)){if(!runHasForcedReveal){if(isLeading){const hidden=Math.max(0,runLength-ctx);if(hidden>0){for(let k=i;k<i+hidden;k++)visible.delete(ops[k]);foldBefore.set(ops[i+hidden],hidden)}}else if(isTrailing){const shown=Math.min(ctx,runLength),hidden=runLength-shown;if(hidden>0){for(let k=i+shown;k<j;k++)visible.delete(ops[k]);trailingFold=hidden}}else if(runLength>ctx*2){const hiddenStart=i+ctx,hiddenEnd=j-ctx;for(let k=hiddenStart;k<hiddenEnd;k++)visible.delete(ops[k]);foldBefore.set(ops[hiddenStart],hiddenEnd-hiddenStart)}}}i=j}return{visible,foldBefore,trailingFold}}foldMarker(count){const text=this.localize("diffViewHiddenLines",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});return html`<div part="line" data-type="fold">${text}</div>`}async revealOp(op){if(!this.forcedVisibleOps.has(op)){const next=new Set(this.forcedVisibleOps);next.add(op),this.forcedVisibleOps=next}await this.updateComplete}lineElementForOpIndex(index){return this.renderRoot.querySelector(`[data-op-index="${index}"]`)}async scrollOpIndexIntoView(index){const op=this.diffOps[index];if(!op)return!1;await this.revealOp(op);const target=this.lineElementForOpIndex(index);return target?(target.scrollIntoView({behavior:prefersReducedMotion(this)?"auto":"smooth",block:"nearest"}),!0):!1}async applyAnchor(anchor){if(anchor.kind!=="line-range")return!1;const index=anchor.start;return!Number.isInteger(index)||index<0||index>=this.diffOps.length?!1:this.scrollOpIndexIntoView(index)}resolvedHighlightOps(){const perOp=new Map,owners=new Map,order=new Map,ops=this.diffOps;if(ops.length===0)return{perOp,owners,order,total:0};const seen=new Set;for(const highlight of prioritizedHighlightCandidates(this.highlights,this.activeHighlightId)){if(order.size>=MAX_PAINTED_HIGHLIGHTS)break;if(seen.has(highlight.id)||(seen.add(highlight.id),highlight.anchor.kind!=="line-range"))continue;const start=Math.max(0,Math.min(highlight.anchor.start,ops.length-1)),end=Math.max(start,Math.min(highlight.anchor.end??highlight.anchor.start,ops.length-1));let resolvedAny=!1;for(let index=start;index<=end;index++){const op=ops[index];resolvedAny=!0,!perOp.has(op)&&(perOp.set(op,highlight),owners.has(highlight)||owners.set(highlight,op))}resolvedAny&&order.set(highlight,order.size)}return{perOp,owners,order,total:order.size}}highlightActionLabel(highlight,index,total){if(highlight.label)return this.localize("highlightWithLabel",void 0,{label:highlight.label});const numberFormat=getNumberFormat(this.effectiveLocale);return this.localize("highlightOfTotal",void 0,{index:numberFormat.format(index+1),total:numberFormat.format(total)})}activateHighlight(highlight){this.emit("lr-highlight-activate",{highlightId:highlight.id})}emitSearchChange(){this.emit("lr-search-change",viewerSearchDetail(this.searchQuery,this.searchMatches.length,this.searchMatchCountExact,this.searchActiveIndex)),announceSearchResult((key,fallback,values)=>this.localize(key,fallback,values),this.searchAnnouncer,this.effectiveLocale,this.searchMatches.length,this.searchActiveIndex)}recomputeSearchMatches(){this.lastSearchLocale=this.effectiveLocale;const boundedQuery=boundedViewerSearchQuery(this.searchQuery,this.effectiveLocale),needle=boundedQuery.needle,matches=[];let matchCountExact=boundedQuery.accepted;if(boundedQuery.accepted&&needle){const budget=new ViewerSearchWorkBudget;for(let index=0;index<this.diffOps.length;index++){if(budget.includes(this.diffOps[index].text,needle,this.effectiveLocale)){if(matches.length===MAX_SEARCH_MATCHES){matchCountExact=!1;break}matches.push({opIndex:index})}if(!budget.complete){matchCountExact=!1;break}}}this.searchMatches=matches,this.searchMatchCountExact=matchCountExact}async search(query){this.searchQuery=query,this.recomputeSearchMatches(),this.searchActiveIndex=this.searchMatches.length>0?0:-1,this.emitSearchChange();const active=this.searchMatches[this.searchActiveIndex];return active&&await this.scrollOpIndexIntoView(active.opIndex),this.searchMatches.length}async searchNext(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}async searchPrevious(){return this.searchMatches.length?(this.searchActiveIndex=advanceViewerSearchIndex(this.searchActiveIndex,this.searchMatches.length,-1),this.emitSearchChange(),await this.scrollOpIndexIntoView(this.searchMatches[this.searchActiveIndex].opIndex),!0):!1}clearSearch(){this.searchQuery="",this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.emitSearchChange()}get unifiedText(){return this.diffOps.map(op=>`${op.type==="add"?"+":op.type==="remove"?"-":" "} ${op.text}`).join(`
2
2
  `)}isCurrentCopy(generation,owner){return this.isConnected&&this.copyable&&!this.diffTooLarge&&generation===this.copyGeneration&&this.ownerDocument.defaultView===owner}showCopyStatus(status,generation){const owner=this.ownerDocument.defaultView;if(!owner||!this.isCurrentCopy(generation,owner))return;this.copyStatus=status,this.copyAnnouncementSink?.announce(status==="success"?this.localize("copied"):this.localize("copyFailed")),this.cancelCopyTimer();let handle=0;handle=owner.setTimeout(()=>{const timer=this.copyTimer;timer?.owner!==owner||timer.handle!==handle||timer.generation!==generation||!this.isCurrentCopy(generation,owner)||(this.copyTimer=void 0,this.copyStatus="rest")},COPY_CONFIRM_MS),this.copyTimer={owner,handle,generation}}async copy(){if(!this.copyable||this.diffTooLarge)return;const generation=++this.copyGeneration;this.cancelCopyTimer(),this.copyStatus="rest";const text=this.unifiedText,owner=this.isConnected?this.ownerDocument.defaultView:null;if(!owner)return;const outcome=await writeClipboardText(owner,text);if(this.isCurrentCopy(generation,owner)){if(!outcome.ok){this.showCopyStatus("error",generation),this.emit("lr-error"),this.emit("lr-copy-error",outcome);return}this.showCopyStatus("success",generation),this.emit("lr-copy",outcome)}}lineRenderContext(){const{perOp,owners,order,total}=this.resolvedHighlightOps();return{perOp,owners,order,total,matchedOpIndexes:new Set(this.searchMatches.map(match=>match.opIndex)),activeMatchOpIndex:this.searchMatches[this.searchActiveIndex]?.opIndex??-1}}renderDiffLine(op,marker,content,context){const index=this.opIndexMap.get(op),isMatch=index!==void 0&&context.matchedOpIndexes.has(index),isActiveMatch=index!==void 0&&index===context.activeMatchOpIndex,highlight=context.perOp.get(op),owner=highlight&&context.owners.get(highlight)===op?highlight:void 0,ownerLabel=owner?this.highlightActionLabel(owner,context.order.get(owner)??0,context.total):"",text=html`${marker} ${content}`;return html`<div
3
3
  part="line"
4
4
  data-type=${op.type}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{waitForTransitionSettle}from"../../../internal/css-motion-time.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{optionalLiteralSetConverter}from"../../../internal/converters.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{sizes}from"../../../internal/sizes.styles.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{nextId}from"../../../internal/a11y.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{buildCsv,downloadBlob}from"./csv.js";import{styles}from"./export-button.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{PopupController}from"../../../internal/popup-controller.js";import{LYRA_DEFAULT_exportButtonLabel,LYRA_DEFAULT_exportFormatMenuLabel,LYRA_DEFAULT_statusError}from"../../../internal/default-strings.generated.js";const EXPORT_BUTTON_APPEARANCE=optionalLiteralSetConverter(["outlined","quiet"]),MAX_EXPORT_FORMATS=1e4;function queueDocumentMicrotask(ownerDocument,callback){const ownerWindow=ownerDocument.defaultView;if(ownerWindow){ownerWindow.queueMicrotask(callback);return}Promise.resolve().then(callback)}function formatArrayLength(value){try{if(!Array.isArray(value))return;const length=getOwnDataDescriptor(value,"length");return length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0?void 0:{source:value,length:Math.min(length.value,MAX_EXPORT_FORMATS)}}catch{return}}function projectExportFormat(value){if(value==="csv"||value==="json")return value;if(value===null||typeof value!="object")return;const formatId=getOwnDataDescriptor(value,"formatId"),label=getOwnDataDescriptor(value,"label");if(formatId===MISSING_OWN_DATA_DESCRIPTOR||formatId===UNSAFE_OWN_DATA_DESCRIPTOR||label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||typeof formatId.value!="string"||formatId.value.trim().length===0||typeof label.value!="string"||label.value.trim().length===0)return;const description=getOwnDataDescriptor(value,"description"),extension=getOwnDataDescriptor(value,"extension");return Object.freeze({formatId:formatId.value,label:label.value,...description!==MISSING_OWN_DATA_DESCRIPTOR&&description!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof description.value=="string"?{description:description.value}:{},...extension!==MISSING_OWN_DATA_DESCRIPTOR&&extension!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof extension.value=="string"?{extension:extension.value}:{}})}class LyraExportButton extends LyraElement{static{this.defaultStrings={...super.defaultStrings,exportButtonLabel:LYRA_DEFAULT_exportButtonLabel,exportFormatMenuLabel:LYRA_DEFAULT_exportFormatMenuLabel,statusError:LYRA_DEFAULT_statusError}}constructor(){super(),this._rows=Object.freeze([]),this._columns=Object.freeze([]),this.filename="export",this.bom=!1,this._formats=Object.freeze(["csv"]),this.disabled=!1,this.loading=!1,this.accessibleLabel=null,this.open=!1,this.exportFailed=!1,this.menuHidden=!0,this.menuHideToken=0,this.menuId=nextId("export-menu"),this.menuPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.connectionGeneration=0,this._isFirstUpdate=!0,this.openVetoed=!1,this.pendingMenuFocusIndex=0,this.injectedHostTabIndex=!1,this.restoreFocusOnMenuClose=!1,this.onDocPointer=e=>{e.composedPath().includes(this)||(this.overlay?.isActive()?this.overlay.dismissBackdrop():this.closeMenu())},this.syncMenuOverlay=()=>{if(this.cleanup?.(),this.cleanup=void 0,this.menuPositioned=!1,this.unbindDocumentPointer(),!this.open||!this.isConnected){const restoreFocus=this.restoreFocusOnMenuClose;this.restoreFocusOnMenuClose=!1,this.deactivateMenuOverlay(restoreFocus),this.settleMenuHidden();return}this.activateMenuOverlay(),this.bindDocumentPointer();const anchor=this.triggerEl,menu=this.menuEl,ownerDocument=this.ownerDocument;if(!anchor||!menu)return;const placement=place(anchor,menu,{strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{if(!(this.cleanup!==placement||!this.open||!this.isConnected||this.ownerDocument!==ownerDocument)){if(!positioned){this.forcedMenuClose="state",this.open=!1;return}this.menuPositioned=!0,this.focusMenuItem(this.pendingMenuFocusIndex),this.pendingMenuFocusIndex=0}})},this.onKeyDown=e=>{if(this.formats.length<=1||this.disabled||this.loading)return;const items=this.menuItemEls(),currentIndex=items.indexOf(e.target);switch(e.key){case"ArrowDown":e.preventDefault(),this.focusMenuItemOnOpen(currentIndex===-1?0:currentIndex+1);break;case"ArrowUp":e.preventDefault(),this.focusMenuItemOnOpen(currentIndex===-1?items.length-1:currentIndex-1);break;case"Home":this.open&&(e.preventDefault(),this.focusMenuItem(0));break;case"End":this.open&&(e.preventDefault(),this.focusMenuItem(items.length-1));break}},new GlassScrollLayer(this,'[part="menu"]',()=>this.open)}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={rows:{attribute:!1,noAccessor:!0},columns:{attribute:!1,noAccessor:!0},formats:{attribute:!1,noAccessor:!0}}}get rows(){return this._rows}set rows(next){if(next===this.rowsSource)return;this.rowsSource=next;const previous=this._rows,source=Array.isArray(next)?next:[];this._rows=Object.freeze(source.map(row=>Object.freeze({...row}))),this.requestUpdate("rows",previous)}get columns(){return this._columns}set columns(next){if(next===this.columnsSource)return;this.columnsSource=next;const previous=this._columns,source=Array.isArray(next)?next:[];this._columns=Object.freeze(source.map(column=>Object.freeze({...column}))),this.requestUpdate("columns",previous)}get formats(){return this._formats}set formats(next){if(next===this.formatsSource)return;this.formatsSource=next;const previous=this._formats,source=formatArrayLength(next),seen=new Set,formats=[];for(let index=0;source&&index<source.length;index+=1){const descriptor=getOwnDataDescriptor(source.source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const snapshot=projectExportFormat(descriptor.value);if(!snapshot)continue;const id=typeof snapshot=="string"?snapshot:snapshot.formatId;typeof id!="string"||id.trim()===""||seen.has(id)||(seen.add(id),formats.push(snapshot))}this._formats=Object.freeze(formats),this.requestUpdate("formats",previous)}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get appearance(){return this._appearance}set appearance(next){const normalized=EXPORT_BUTTON_APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;old!==normalized&&(this._appearance=normalized,this.requestUpdate("appearance",old))}connectedCallback(){const pendingDisconnectDocument=this.pendingDisconnectDocument;if(this.pendingDisconnectDocument=void 0,this.connectionGeneration+=1,this.connectedDocument=this.ownerDocument,super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),pendingDisconnectDocument){if(pendingDisconnectDocument===this.ownerDocument){this.deactivateMenuOverlay(!1),this.restoreFocusOnMenuClose=!1,this.open=!1;return}this.hasUpdated&&this.open&&(this.menuHidden=!1,this.scheduleAfterUpdate(this.syncMenuOverlay,"export-button-menu-overlay"));return}this.hasUpdated&&this.open&&(this.menuHidden=!1,this.scheduleAfterUpdate(this.syncMenuOverlay,"export-button-menu-overlay"))}disconnectedCallback(){const generation=++this.connectionGeneration,disconnectDocument=this.connectedDocument??this.ownerDocument;this.pendingDisconnectDocument=disconnectDocument,super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.menuPositioned=!1,this.unbindDocumentPointer(),this.overlay?.suspend(),this.restoreFocusOnMenuClose=!1,this.sink?.release(),this.sink=void 0,this.menuHideToken++,this.menuHidden=!0,queueDocumentMicrotask(disconnectDocument,()=>{this.connectionGeneration!==generation||this.isConnected||this.pendingDisconnectDocument!==disconnectDocument||(this.pendingDisconnectDocument=void 0,this.deactivateMenuOverlay(!1),this.restoreFocusOnMenuClose=!1,this.open=!1)})}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.overlay?.suspend(),this.sink?.release(),this.sink=void 0}bindDocumentPointer(){this.popupController.bindPointer()}unbindDocumentPointer(){this.popupController.unbindPointer()}openMenu(){this.open||(this.open=!0)}closeMenu(restoreFocus=!1){this.open&&(this.restoreFocusOnMenuClose||=restoreFocus,this.open=!1)}activateMenuOverlay(){if(this.overlay?.isActive()){this.overlay.resume();return}this.overlay=activateNonmodalOverlay({host:this,panel:()=>this.menuEl??null,onEscape:()=>this.closeMenu(!0),onBackdrop:()=>this.closeMenu(),onTab:()=>this.closeMenu(),restoreFocusTo:()=>this.triggerEl??null})}deactivateMenuOverlay(restoreFocus){const overlay=this.overlay;this.overlay=void 0,overlay?.deactivate({restoreFocus}),this.unbindDocumentPointer()}async settleMenuHidden(){const token=++this.menuHideToken;await this.updateComplete,!(token!==this.menuHideToken||this.open)&&(await waitForTransitionSettle(this.menuEl??null,this,{reducedMotion:prefersReducedMotion(this)}).finished,!(token!==this.menuHideToken||this.open)&&(this.menuHidden=!0))}menuItemEls(){return Array.from(this.renderRoot.querySelectorAll('[part="menu-item"]'))}focusMenuItem(index){const items=this.menuItemEls();items.length!==0&&items[Math.max(0,Math.min(items.length-1,index))]?.focus()}focusMenuItemOnOpen(index){this.open&&this.menuPositioned?this.focusMenuItem(index):(this.pendingMenuFocusIndex=index,this.open||this.openMenu())}firstUpdated(changed){super.firstUpdated(changed),this.renderRoot.addEventListener("keydown",this.onKeyDown)}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.setAttribute("aria-busy",String(this.loading)),(changed.has("disabled")||changed.has("loading"))&&(this.disabled||this.loading)){const active=shadowFocusTarget(this);if(active===this.triggerEl||active?.getAttribute("part")==="menu-item"){this.hasAttribute("tabindex")||(this.tabIndex=-1,this.injectedHostTabIndex=!0);const ownerHTMLElement=this.ownerDocument.defaultView?.HTMLElement,nativeFocus=ownerHTMLElement?Reflect.get(ownerHTMLElement.prototype,"focus",this):void 0;typeof nativeFocus=="function"&&nativeFocus.call(this,{preventScroll:!0})}this.open&&(this.open=!1,this.forcedMenuClose="state")}if(changed.has("formats")){const active=shadowFocusTarget(this),index=this.menuItemEls().indexOf(active),previous=changed.get("formats")?.[index];this.formatsFocusSnapshot=index>=0&&previous?{index,id:this.formatId(previous)}:void 0}if(this.open&&this.formats.length<=1){const previousOpen=changed.get("open");this.forcedMenuClose=changed.has("formats")&&changed.get("formats")?.length?"formats":previousOpen===!1||previousOpen===void 0?"invalid-open":"state",this.open=!1}this.announceMenuTransition(changed),this.open&&(this.menuHidden=!1),this.open||(this.menuPositioned=!1)}announceMenuTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate||this.forcedMenuClose)return;const name=this.open?"lr-show":"lr-hide";this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open)}updated(changed){if(super.updated(changed),(changed.has("disabled")||changed.has("loading"))&&!this.disabled&&!this.loading&&this.injectedHostTabIndex){const parked=this.ownerDocument.activeElement===this&&!shadowFocusTarget(this);this.getAttribute("tabindex")==="-1"&&this.removeAttribute("tabindex"),this.injectedHostTabIndex=!1,parked&&this.triggerEl?.focus({preventScroll:!0})}const forcedMenuClose=this.forcedMenuClose;if(this.forcedMenuClose=void 0,(changed.has("open")||forcedMenuClose==="formats"||forcedMenuClose==="state")&&!this.openVetoed?this.syncMenuOverlay():this.openVetoed&&(this.restoreFocusOnMenuClose=!1),changed.has("formats")&&this.formatsFocusSnapshot){const{index,id}=this.formatsFocusSnapshot;this.formatsFocusSnapshot=void 0,this.scheduleAfterUpdate(()=>{if(this.formats.length<=1)this.closeMenu(),this.triggerEl?.focus();else if(this.open){const nextIndex=this.formats.findIndex(format=>this.formatId(format)===id);this.focusMenuItemOnOpen(nextIndex>=0?nextIndex:index)}})}}effectiveColumns(rows){if(this.columns.length>0)return this.columns;const keys=new Set;for(const row of rows)for(const key of Object.keys(row))keys.add(key);return Array.from(keys,key=>({key,label:key}))}rowsToExport(){if(this.getRows===void 0)return this.rows;const supplied=this.getRows();return Array.isArray(supplied)?supplied:[]}rowsForExport(rows){const keys=this.effectiveColumns(rows).map(c=>c.key);return rows.map(row=>{const picked=Object.create(null);for(const key of keys)picked[key]=row[key];return picked})}formatId(format){return typeof format=="string"?format:format.formatId}formatLabel(format){return typeof format=="string"?format.toUpperCase():format.label}doExport(formatOption){if(this.disabled||this.loading)return;this.closeMenu(),this.triggerEl?.focus(),this.exportFailed=!1;const format=this.formatId(formatOption);if(!this.emit("lr-export-request",Object.freeze({format}),{cancelable:!0}).defaultPrevented&&!(format!=="csv"&&format!=="json"))try{const rows=this.rowsToExport();format==="csv"?downloadBlob(buildCsv(rows,this.effectiveColumns(rows),{bom:this.bom}),`${this.filename}.csv`,"text/csv;charset=utf-8;",this.ownerDocument):downloadBlob(JSON.stringify(this.rowsForExport(rows),null,2),`${this.filename}.json`,"application/json",this.ownerDocument),this.emit("lr-export-complete",Object.freeze({format}))}catch(error){this.exportFailed=!0,this.sink?.announce(this.localize("statusError")),this.emit("lr-export-error",Object.freeze({format,error}))}}onTriggerClick(){this.disabled||this.loading||this.formats.length!==0&&(this.formats.length===1?this.doExport(this.formats[0]):this.open?this.closeMenu():this.openMenu())}focus(options){this.triggerEl?.focus(options)}blur(){this.triggerEl?.blur()}click(){this.triggerEl?.click()}get effectiveLabel(){return this.label==null?this.localize("exportButtonLabel"):this.label}render(){const label=this.effectiveLabel,labelNamesTrigger=label.trim().length>0,accessibleLabel=this.accessibleLabel??(labelNamesTrigger?label:this.localize("exportButtonLabel")),triggerAriaLabel=this.accessibleLabel!==null||!labelNamesTrigger?accessibleLabel:nothing;return html`
1
+ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{waitForTransitionSettle}from"../../../internal/css-motion-time.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{optionalLiteralSetConverter}from"../../../internal/converters.js";import{normalizeReflectedOptionalSize,optionalSizeConverter}from"../../../internal/variants.js";import{sizes}from"../../../internal/sizes.styles.js";import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{nextId}from"../../../internal/a11y.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{buildCsv,downloadBlob}from"./csv.js";import{styles}from"./export-button.styles.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{PopupController}from"../../../internal/popup-controller.js";import{LYRA_DEFAULT_statusError}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_exportButtonLabel,LYRA_DEFAULT_exportFormatMenuLabel}from"../../../internal/default-strings/utility.generated.js";const EXPORT_BUTTON_APPEARANCE=optionalLiteralSetConverter(["outlined","quiet"]),MAX_EXPORT_FORMATS=1e4;function queueDocumentMicrotask(ownerDocument,callback){const ownerWindow=ownerDocument.defaultView;if(ownerWindow){ownerWindow.queueMicrotask(callback);return}Promise.resolve().then(callback)}function formatArrayLength(value){try{if(!Array.isArray(value))return;const length=getOwnDataDescriptor(value,"length");return length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0?void 0:{source:value,length:Math.min(length.value,MAX_EXPORT_FORMATS)}}catch{return}}function projectExportFormat(value){if(value==="csv"||value==="json")return value;if(value===null||typeof value!="object")return;const formatId=getOwnDataDescriptor(value,"formatId"),label=getOwnDataDescriptor(value,"label");if(formatId===MISSING_OWN_DATA_DESCRIPTOR||formatId===UNSAFE_OWN_DATA_DESCRIPTOR||label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||typeof formatId.value!="string"||formatId.value.trim().length===0||typeof label.value!="string"||label.value.trim().length===0)return;const description=getOwnDataDescriptor(value,"description"),extension=getOwnDataDescriptor(value,"extension");return Object.freeze({formatId:formatId.value,label:label.value,...description!==MISSING_OWN_DATA_DESCRIPTOR&&description!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof description.value=="string"?{description:description.value}:{},...extension!==MISSING_OWN_DATA_DESCRIPTOR&&extension!==UNSAFE_OWN_DATA_DESCRIPTOR&&typeof extension.value=="string"?{extension:extension.value}:{}})}class LyraExportButton extends LyraElement{static{this.defaultStrings={...super.defaultStrings,exportButtonLabel:LYRA_DEFAULT_exportButtonLabel,exportFormatMenuLabel:LYRA_DEFAULT_exportFormatMenuLabel,statusError:LYRA_DEFAULT_statusError}}constructor(){super(),this._rows=Object.freeze([]),this._columns=Object.freeze([]),this.filename="export",this.bom=!1,this._formats=Object.freeze(["csv"]),this.disabled=!1,this.loading=!1,this.accessibleLabel=null,this.open=!1,this.exportFailed=!1,this.menuHidden=!0,this.menuHideToken=0,this.menuId=nextId("export-menu"),this.menuPositioned=!1,this.popupController=new PopupController({host:this,onPointer:event=>this.onDocPointer(event)}),this.connectionGeneration=0,this._isFirstUpdate=!0,this.openVetoed=!1,this.pendingMenuFocusIndex=0,this.injectedHostTabIndex=!1,this.restoreFocusOnMenuClose=!1,this.onDocPointer=e=>{e.composedPath().includes(this)||(this.overlay?.isActive()?this.overlay.dismissBackdrop():this.closeMenu())},this.syncMenuOverlay=()=>{if(this.cleanup?.(),this.cleanup=void 0,this.menuPositioned=!1,this.unbindDocumentPointer(),!this.open||!this.isConnected){const restoreFocus=this.restoreFocusOnMenuClose;this.restoreFocusOnMenuClose=!1,this.deactivateMenuOverlay(restoreFocus),this.settleMenuHidden();return}this.activateMenuOverlay(),this.bindDocumentPointer();const anchor=this.triggerEl,menu=this.menuEl,ownerDocument=this.ownerDocument;if(!anchor||!menu)return;const placement=place(anchor,menu,{strategy:resolveEffectivePositioningStrategy(this,void 0,"fixed")});this.cleanup=placement,placement.ready.then(positioned=>{if(!(this.cleanup!==placement||!this.open||!this.isConnected||this.ownerDocument!==ownerDocument)){if(!positioned){this.forcedMenuClose="state",this.open=!1;return}this.menuPositioned=!0,this.focusMenuItem(this.pendingMenuFocusIndex),this.pendingMenuFocusIndex=0}})},this.onKeyDown=e=>{if(this.formats.length<=1||this.disabled||this.loading)return;const items=this.menuItemEls(),currentIndex=items.indexOf(e.target);switch(e.key){case"ArrowDown":e.preventDefault(),this.focusMenuItemOnOpen(currentIndex===-1?0:currentIndex+1);break;case"ArrowUp":e.preventDefault(),this.focusMenuItemOnOpen(currentIndex===-1?items.length-1:currentIndex-1);break;case"Home":this.open&&(e.preventDefault(),this.focusMenuItem(0));break;case"End":this.open&&(e.preventDefault(),this.focusMenuItem(items.length-1));break}},new GlassScrollLayer(this,'[part="menu"]',()=>this.open)}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={rows:{attribute:!1,noAccessor:!0},columns:{attribute:!1,noAccessor:!0},formats:{attribute:!1,noAccessor:!0}}}get rows(){return this._rows}set rows(next){if(next===this.rowsSource)return;this.rowsSource=next;const previous=this._rows,source=Array.isArray(next)?next:[];this._rows=Object.freeze(source.map(row=>Object.freeze({...row}))),this.requestUpdate("rows",previous)}get columns(){return this._columns}set columns(next){if(next===this.columnsSource)return;this.columnsSource=next;const previous=this._columns,source=Array.isArray(next)?next:[];this._columns=Object.freeze(source.map(column=>Object.freeze({...column}))),this.requestUpdate("columns",previous)}get formats(){return this._formats}set formats(next){if(next===this.formatsSource)return;this.formatsSource=next;const previous=this._formats,source=formatArrayLength(next),seen=new Set,formats=[];for(let index=0;source&&index<source.length;index+=1){const descriptor=getOwnDataDescriptor(source.source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR||descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const snapshot=projectExportFormat(descriptor.value);if(!snapshot)continue;const id=typeof snapshot=="string"?snapshot:snapshot.formatId;typeof id!="string"||id.trim()===""||seen.has(id)||(seen.add(id),formats.push(snapshot))}this._formats=Object.freeze(formats),this.requestUpdate("formats",previous)}get size(){return this._size}set size(next){const normalized=normalizeReflectedOptionalSize(this,next),old=this._size;old!==normalized&&(this._size=normalized,this.requestUpdate("size",old))}get appearance(){return this._appearance}set appearance(next){const normalized=EXPORT_BUTTON_APPEARANCE.normalizeReflected(this,"appearance",next),old=this._appearance;old!==normalized&&(this._appearance=normalized,this.requestUpdate("appearance",old))}connectedCallback(){const pendingDisconnectDocument=this.pendingDisconnectDocument;if(this.pendingDisconnectDocument=void 0,this.connectionGeneration+=1,this.connectedDocument=this.ownerDocument,super.connectedCallback(),this.sink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),pendingDisconnectDocument){if(pendingDisconnectDocument===this.ownerDocument){this.deactivateMenuOverlay(!1),this.restoreFocusOnMenuClose=!1,this.open=!1;return}this.hasUpdated&&this.open&&(this.menuHidden=!1,this.scheduleAfterUpdate(this.syncMenuOverlay,"export-button-menu-overlay"));return}this.hasUpdated&&this.open&&(this.menuHidden=!1,this.scheduleAfterUpdate(this.syncMenuOverlay,"export-button-menu-overlay"))}disconnectedCallback(){const generation=++this.connectionGeneration,disconnectDocument=this.connectedDocument??this.ownerDocument;this.pendingDisconnectDocument=disconnectDocument,super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.menuPositioned=!1,this.unbindDocumentPointer(),this.overlay?.suspend(),this.restoreFocusOnMenuClose=!1,this.sink?.release(),this.sink=void 0,this.menuHideToken++,this.menuHidden=!0,queueDocumentMicrotask(disconnectDocument,()=>{this.connectionGeneration!==generation||this.isConnected||this.pendingDisconnectDocument!==disconnectDocument||(this.pendingDisconnectDocument=void 0,this.deactivateMenuOverlay(!1),this.restoreFocusOnMenuClose=!1,this.open=!1)})}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.overlay?.suspend(),this.sink?.release(),this.sink=void 0}bindDocumentPointer(){this.popupController.bindPointer()}unbindDocumentPointer(){this.popupController.unbindPointer()}openMenu(){this.open||(this.open=!0)}closeMenu(restoreFocus=!1){this.open&&(this.restoreFocusOnMenuClose||=restoreFocus,this.open=!1)}activateMenuOverlay(){if(this.overlay?.isActive()){this.overlay.resume();return}this.overlay=activateNonmodalOverlay({host:this,panel:()=>this.menuEl??null,onEscape:()=>this.closeMenu(!0),onBackdrop:()=>this.closeMenu(),onTab:()=>this.closeMenu(),restoreFocusTo:()=>this.triggerEl??null})}deactivateMenuOverlay(restoreFocus){const overlay=this.overlay;this.overlay=void 0,overlay?.deactivate({restoreFocus}),this.unbindDocumentPointer()}async settleMenuHidden(){const token=++this.menuHideToken;await this.updateComplete,!(token!==this.menuHideToken||this.open)&&(await waitForTransitionSettle(this.menuEl??null,this,{reducedMotion:prefersReducedMotion(this)}).finished,!(token!==this.menuHideToken||this.open)&&(this.menuHidden=!0))}menuItemEls(){return Array.from(this.renderRoot.querySelectorAll('[part="menu-item"]'))}focusMenuItem(index){const items=this.menuItemEls();items.length!==0&&items[Math.max(0,Math.min(items.length-1,index))]?.focus()}focusMenuItemOnOpen(index){this.open&&this.menuPositioned?this.focusMenuItem(index):(this.pendingMenuFocusIndex=index,this.open||this.openMenu())}firstUpdated(changed){super.firstUpdated(changed),this.renderRoot.addEventListener("keydown",this.onKeyDown)}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.setAttribute("aria-busy",String(this.loading)),(changed.has("disabled")||changed.has("loading"))&&(this.disabled||this.loading)){const active=shadowFocusTarget(this);if(active===this.triggerEl||active?.getAttribute("part")==="menu-item"){this.hasAttribute("tabindex")||(this.tabIndex=-1,this.injectedHostTabIndex=!0);const ownerHTMLElement=this.ownerDocument.defaultView?.HTMLElement,nativeFocus=ownerHTMLElement?Reflect.get(ownerHTMLElement.prototype,"focus",this):void 0;typeof nativeFocus=="function"&&nativeFocus.call(this,{preventScroll:!0})}this.open&&(this.open=!1,this.forcedMenuClose="state")}if(changed.has("formats")){const active=shadowFocusTarget(this),index=this.menuItemEls().indexOf(active),previous=changed.get("formats")?.[index];this.formatsFocusSnapshot=index>=0&&previous?{index,id:this.formatId(previous)}:void 0}if(this.open&&this.formats.length<=1){const previousOpen=changed.get("open");this.forcedMenuClose=changed.has("formats")&&changed.get("formats")?.length?"formats":previousOpen===!1||previousOpen===void 0?"invalid-open":"state",this.open=!1}this.announceMenuTransition(changed),this.open&&(this.menuHidden=!1),this.open||(this.menuPositioned=!1)}announceMenuTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate||this.forcedMenuClose)return;const name=this.open?"lr-show":"lr-hide";this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open)}updated(changed){if(super.updated(changed),(changed.has("disabled")||changed.has("loading"))&&!this.disabled&&!this.loading&&this.injectedHostTabIndex){const parked=this.ownerDocument.activeElement===this&&!shadowFocusTarget(this);this.getAttribute("tabindex")==="-1"&&this.removeAttribute("tabindex"),this.injectedHostTabIndex=!1,parked&&this.triggerEl?.focus({preventScroll:!0})}const forcedMenuClose=this.forcedMenuClose;if(this.forcedMenuClose=void 0,(changed.has("open")||forcedMenuClose==="formats"||forcedMenuClose==="state")&&!this.openVetoed?this.syncMenuOverlay():this.openVetoed&&(this.restoreFocusOnMenuClose=!1),changed.has("formats")&&this.formatsFocusSnapshot){const{index,id}=this.formatsFocusSnapshot;this.formatsFocusSnapshot=void 0,this.scheduleAfterUpdate(()=>{if(this.formats.length<=1)this.closeMenu(),this.triggerEl?.focus();else if(this.open){const nextIndex=this.formats.findIndex(format=>this.formatId(format)===id);this.focusMenuItemOnOpen(nextIndex>=0?nextIndex:index)}})}}effectiveColumns(rows){if(this.columns.length>0)return this.columns;const keys=new Set;for(const row of rows)for(const key of Object.keys(row))keys.add(key);return Array.from(keys,key=>({key,label:key}))}rowsToExport(){if(this.getRows===void 0)return this.rows;const supplied=this.getRows();return Array.isArray(supplied)?supplied:[]}rowsForExport(rows){const keys=this.effectiveColumns(rows).map(c=>c.key);return rows.map(row=>{const picked=Object.create(null);for(const key of keys)picked[key]=row[key];return picked})}formatId(format){return typeof format=="string"?format:format.formatId}formatLabel(format){return typeof format=="string"?format.toUpperCase():format.label}doExport(formatOption){if(this.disabled||this.loading)return;this.closeMenu(),this.triggerEl?.focus(),this.exportFailed=!1;const format=this.formatId(formatOption);if(!this.emit("lr-export-request",Object.freeze({format}),{cancelable:!0}).defaultPrevented&&!(format!=="csv"&&format!=="json"))try{const rows=this.rowsToExport();format==="csv"?downloadBlob(buildCsv(rows,this.effectiveColumns(rows),{bom:this.bom}),`${this.filename}.csv`,"text/csv;charset=utf-8;",this.ownerDocument):downloadBlob(JSON.stringify(this.rowsForExport(rows),null,2),`${this.filename}.json`,"application/json",this.ownerDocument),this.emit("lr-export-complete",Object.freeze({format}))}catch(error){this.exportFailed=!0,this.sink?.announce(this.localize("statusError")),this.emit("lr-export-error",Object.freeze({format,error}))}}onTriggerClick(){this.disabled||this.loading||this.formats.length!==0&&(this.formats.length===1?this.doExport(this.formats[0]):this.open?this.closeMenu():this.openMenu())}focus(options){this.triggerEl?.focus(options)}blur(){this.triggerEl?.blur()}click(){this.triggerEl?.click()}get effectiveLabel(){return this.label==null?this.localize("exportButtonLabel"):this.label}render(){const label=this.effectiveLabel,labelNamesTrigger=label.trim().length>0,accessibleLabel=this.accessibleLabel??(labelNamesTrigger?label:this.localize("exportButtonLabel")),triggerAriaLabel=this.accessibleLabel!==null||!labelNamesTrigger?accessibleLabel:nothing;return html`
2
2
  <button
3
3
  part=${this.exportFailed?"trigger trigger-error":"trigger"}
4
4
  type="button"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",refresh:"M20 11a8 8 0 0 0-14.9-4M4 5v4h4m-4 4a8 8 0 0 0 14.9 4M20 19v-4h-4",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.autoWidth=!1,this.swapOpacity=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-")||isUnsafeSvgCloneElement(element.localName))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value,element.localName)||copy.setAttribute(attribute.name==="xlink:href"?"href":attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&&copy.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
1
+ import{__decorate}from"tslib";import{html,nothing,svg}from"lit";import{property,query,state}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{finiteNumber}from"../../../internal/numbers.js";import{safeFetchUrl}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute,isUnsafeSvgCloneElement}from"../../../internal/safe-svg.js";import{isAbortError,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{getIconLibrary,subscribeIconLibrary}from"./icon-library.js";import{acquireSanitizedIconResource,IconResourceError}from"./icon-resource.js";import{styles}from"./icon.styles.js";import{LYRA_DEFAULT_iconLoadError,LYRA_DEFAULT_iconSanitizerMissing,LYRA_DEFAULT_iconTooLarge}from"../../../internal/default-strings/utility.generated.js";const PATHS={add:"M12 5v14M5 12h14",check:"m5 12 4 4L19 6",close:"m6 6 12 12M18 6 6 18",refresh:"M20 11a8 8 0 0 0-14.9-4M4 5v4h4m-4 4a8 8 0 0 0 14.9 4M20 19v-4h-4",search:"m21 21-4.35-4.35M10.5 18a7.5 7.5 0 1 1 0-15 7.5 7.5 0 0 1 0 15Z",menu:"M4 6h16M4 12h16M4 18h16","chevron-left":"m15 18-6-6 6-6","chevron-right":"m9 18 6-6-6-6","chevron-down":"m6 9 6 6 6-6",calendar:"M6 3v3M18 3v3M4 9h16M5 5h14a1 1 0 0 1 1 1v13H4V6a1 1 0 0 1 1-1Z",command:"M6 6h4v4H6zM14 6h4v4h-4zM6 14h4v4H6zM14 14h4v4h-4z",trash:"M4 7h16M10 11v6M14 11v6M6 7l1 14h10l1-14M9 7V4h6v3"};class LyraIcon extends LyraElement{constructor(){super(...arguments),this._name="",this.path="",this.label="",this.library="default",this.family="",this.variant="",this._src="",this.rotate=0,this.autoWidth=!1,this.swapOpacity=!1,this.fetchState={kind:"idle"},this.generation=0,this.onCustomSlotChange=()=>{this.syncCustomNodes()}}static{this.defaultStrings={...super.defaultStrings,iconLoadError:LYRA_DEFAULT_iconLoadError,iconSanitizerMissing:LYRA_DEFAULT_iconSanitizerMissing,iconTooLarge:LYRA_DEFAULT_iconTooLarge}}static{this.styles=[LyraElement.styles,styles,srOnly]}get name(){return this._name}set name(value){const old=this._name;this._name=value??"",this.requestUpdate("name",old)}get src(){return this._src}set src(value){const old=this._src;this._src=value??"",this.requestUpdate("src",old)}connectedCallback(){super.connectedCallback(),this.stopLibrarySubscription??=subscribeIconLibrary(name=>{name===this.library&&this.load()}),this.hasUpdated&&(queueMicrotask(()=>{this.isConnected&&this.syncCustomNodes()}),this.hasRemoteSource()&&this.scheduleAfterUpdate(()=>{this.load()}))}disconnectedCallback(){this.generation++,this.releaseResourceLease(),this.stopLibrarySubscription?.(),this.stopLibrarySubscription=void 0,this.customContentObserver?.disconnect(),this.customContentObserver=void 0,this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"}),super.disconnectedCallback()}updated(changed){if(super.updated(changed),changed.has("rotate")){const angle=finiteNumber(this.rotate??0,0);angle?this.style.setProperty("--lr-icon-rotate",`${angle}deg`):this.style.removeProperty("--lr-icon-rotate")}this.applyRemoteA11y(),this.syncCustomNodes(),(changed.has("src")||changed.has("library")||changed.has("name")||changed.has("family")||changed.has("variant"))&&this.scheduleAfterUpdate(()=>{this.load()})}syncCustomNodes(){if(this.fetchState.kind!=="idle")return;const svgEl=this.svgEl;if(!svgEl)return;svgEl.querySelectorAll("[data-lr-custom-copy]").forEach(node=>node.remove()),this.customContentObserver?.disconnect();const slot=this.customSlot;if(slot){for(const node of slot.assignedNodes({flatten:!0})){const copy=this.cloneSvgNode(node);copy&&(copy.setAttribute("data-lr-custom-copy",""),svgEl.append(copy))}this.observeCustomContent(slot)}}observeCustomContent(slot){if(this.customContentObserver?.disconnect(),!this.isConnected)return;const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;if(MutationObserverCtor){this.customContentObserver??=new MutationObserverCtor(()=>{this.isConnected&&this.syncCustomNodes()});for(const node of slot.assignedNodes({flatten:!0}))node.nodeType===1&&this.customContentObserver.observe(node,{attributes:!0,childList:!0,subtree:!0})}}cloneSvgNode(node){if(node.nodeType!==1)return null;const element=node;if(element.localName.includes("-")||isUnsafeSvgCloneElement(element.localName))return null;const copy=this.ownerDocument.createElementNS("http://www.w3.org/2000/svg",element.localName);for(const attribute of element.attributes)isUnsafeSvgCloneAttribute(attribute.name,attribute.value,element.localName)||copy.setAttribute(attribute.name==="xlink:href"?"href":attribute.name,attribute.value);for(const child of element.childNodes){const childCopy=this.cloneSvgNode(child);childCopy?copy.append(childCopy):child.nodeType===3&&copy.append(this.ownerDocument.createTextNode(child.textContent??""))}return copy}accessibleLabel(){return this.getAttribute("aria-label")??this.label}hasRemoteSource(){return!!(this.src||this.name&&this.library&&getIconLibrary(this.library))}releaseResourceLease(){this.resourceLease?.release(),this.resourceLease=void 0}async load(){const generation=++this.generation;this.releaseResourceLease();const library=this.name&&this.library?getIconLibrary(this.library):void 0;if(!library&&!this.src){this.fetchState.kind!=="idle"&&(this.fetchState={kind:"idle"});return}this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.fetchState={kind:"loading"};let source=this.src;try{if(library){if(source=await library.resolver(this.name,this.family,this.variant),!this.isConnected||generation!==this.generation)return;if(typeof source!="string")throw new TypeError("icon resolver did not return a URL")}}catch(error){await this.fail("load",generation,this.name,error);return}if(!source){this.isConnected&&generation===this.generation&&(this.fetchState={kind:"idle"});return}const safeSource=safeFetchUrl(source);if(!safeSource){await this.fail("load",generation,source,new Error("icon URL is not allowed"));return}const fetchTarget=resolveOwnerFetchTarget(this,safeSource);if(!fetchTarget){await this.fail("load",generation,safeSource,new Error("icon URL is not available"));return}let lease;try{lease=acquireSanitizedIconResource(fetchTarget),this.resourceLease=lease;const canonical=await lease.promise;if(!this.isConnected||generation!==this.generation)return;if(!canonical){if(this.fetchState={kind:"empty"},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource});return}const node=this.ownerDocument.importNode(canonical,!0);if(library?.mutator?.(node),this.fetchState={kind:"loaded",node},await this.updateComplete,!this.isConnected||generation!==this.generation)return;this.emit("lr-load",{src:safeSource})}catch(error){if(isAbortError(error))return;const reason=error instanceof IconResourceError?error.reason:"load";await this.fail(reason,generation,safeSource,error)}finally{this.resourceLease===lease&&(this.resourceLease=void 0),lease?.release()}}async fail(reason,generation,src,error){!this.isConnected||generation!==this.generation||(this.fetchState={kind:"error",reason},await this.updateComplete,!(!this.isConnected||generation!==this.generation)&&(isAccessibilityVisible(this)&&this.errorAnnouncementSink?.announce(this.errorMessage(reason)),this.emit("lr-error",{src,error})))}errorMessage(reason){return reason==="sanitizer"?this.localize("iconSanitizerMissing"):reason==="too-large"?this.localize("iconTooLarge"):this.localize("iconLoadError")}applyRemoteA11y(){const state2=this.fetchState;if(state2.kind==="loaded"){state2.node.setAttribute("part","svg"),state2.node.setAttribute("focusable","false"),state2.node.setAttribute("aria-hidden","true"),state2.node.removeAttribute("aria-label");for(const use of state2.node.querySelectorAll("use")){const parts=new Set((use.getAttribute("part")??"").split(/\s+/).filter(Boolean));parts.add("use"),use.setAttribute("part",[...parts].join(" "))}}}renderBuiltIn(){const path=this.path||PATHS[this.name]||"";return html`<svg
2
2
  part="svg"
3
3
  viewBox="0 0 24 24"
4
4
  fill="none"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,MAX_JSON_SNAPSHOT_INSPECTIONS=MAX_JSON_NODES*2,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value){const budget={remainingNodes:MAX_JSON_NODES,remainingInspections:MAX_JSON_SNAPSHOT_INSPECTIONS,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes<=0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}projected.length=retainedLength;try{return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total=value.length,count=Math.min(total,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total>count,total,exact:!0}}if(typeof value=="object"&&value!==null){let total=0;for(const key in value)total+=1,entries.length<limit&&entries.push([key,value[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}return{entries,truncated:!1,total:0,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.maxHeight="",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}connectedCallback(){super.connectedCallback(),this.searchAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncementsArmed=!1;const generation=++this.searchAnnouncementGeneration;this.updateComplete.then(()=>{this.isConnected&&generation===this.searchAnnouncementGeneration&&(this.searchAnnouncementsArmed=!0)})}disconnectedCallback(){this.clearCopyFeedback(),this.searchAnnouncementGeneration+=1,this.searchAnnouncementSink?.release(),this.searchAnnouncementSink=void 0,this.searchAnnouncementsArmed=!1,super.disconnectedCallback()}get safeExpandDepth(){return this.expandDepth===void 0?void 0:finiteCount(this.expandDepth)}previewText(type,count,exact=!0){const formattedCount=getNumberFormat(this.effectiveLocale).format(count),localizedCount=exact?formattedCount:`≥${formattedCount}`;return type==="array"?this.localize("jsonItemCount",void 0,{count:localizedCount,pluralCount:count}):this.localize("jsonKeyCount",void 0,{count:localizedCount,pluralCount:count})}isExpanded(pathKey,depth,forceExpand){const override=this.expandedOverrides.get(pathKey);if(override!==void 0)return override;if(forceExpand.has(pathKey))return!0;const expandDepth=this.safeExpandDepth;return!(expandDepth!==void 0&&depth>=expandDepth)}toggleNode(pathKey,currentlyExpanded){const next=new Map(this.expandedOverrides);next.set(pathKey,!currentlyExpanded),this.expandedOverrides=next}reportCopyFailure(outcome){this.searchAnnouncementSink?.announce(this.localize("copyFailed")),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}clearCopyFeedback(){const timer=this.copyFeedbackTimer;timer&&timer.owner.clearTimeout(timer.handle),this.copyFeedbackTimer=void 0,this.copyFeedback=null}showCopyFeedback(key,ok){const owner=this.ownerDocument.defaultView;owner&&(this.clearCopyFeedback(),this.copyFeedback={key,ok},this.copyFeedbackTimer={owner,handle:owner.setTimeout(()=>this.clearCopyFeedback(),COPY_CONFIRM_MS)})}copyLabel(key,rest){const feedback=this.copyFeedback;return feedback?.key===key?this.localize(feedback.ok?"copied":"copyFailed"):rest}async copy(value,key){this.clearCopyFeedback();let text="";try{text=value===void 0?"undefined":this.stringifyForClipboard(value)}catch(error){this.isConnected&&(this.showCopyFeedback(key,!1),this.reportCopyFailure(Object.freeze({ok:!1,text,reason:"failed",error})));return}const owner=this.isConnected?this.ownerDocument.defaultView:null,outcome=await writeClipboardText(owner,text);if(!(!this.isConnected||this.ownerDocument.defaultView!==owner)){if(this.showCopyFeedback(key,outcome.ok),!outcome.ok){this.reportCopyFailure(outcome);return}this.searchAnnouncementSink?.announce(this.localize("copied")),this.emit("lr-copy",outcome)}}stringifyForClipboard(value){const circularMarker=this.localize("circularReference"),stack=[],serialized=JSON.stringify(value,function(_key,v){if(typeof v=="bigint")return v.toString();if(typeof v!="object"||v===null)return v;const holderIndex=stack.indexOf(this);return stack.length=holderIndex+1,stack.includes(v)?circularMarker:(stack.push(v),v)},2);if(serialized!==void 0)return serialized;try{return formatPrimitive(value,valueType(value))}catch{return""}}computeSearch(){const locale=this.effectiveLocale,query=(this.query??"").trim().toLocaleLowerCase(locale),keyMatches=new Set,valueMatches=new Set,forceExpand=new Set,paths=new Set,orderedMatches=[],ancestors=new WeakSet;let truncated=this.dataSnapshotTruncated;const markAncestors=path=>{for(let i=path.length-1;i>=0;i--)forceExpand.add(JSON.stringify(path.slice(0,i)))},stack=[{kind:"visit",value:this.dataSnapshot,path:[]}];let visited=0;for(;stack.length>0;){const frame=stack.pop();if(frame.kind==="leave"){ancestors.delete(frame.value);continue}if(visited>=MAX_JSON_NODES){truncated=!0;break}visited+=1;const{value,path,keyLabel}=frame,pathKey=JSON.stringify(path);paths.add(pathKey);const type=valueType(value);if(query){let hit=!1;keyLabel!==void 0&&keyLabel.toLocaleLowerCase(locale).includes(query)&&(keyMatches.add(pathKey),orderedMatches.push({pathKey,kind:"key"}),hit=!0),type!=="object"&&type!=="array"&&formatPrimitive(value,type).toLocaleLowerCase(locale).includes(query)&&(valueMatches.add(pathKey),orderedMatches.push({pathKey,kind:"value"}),hit=!0),hit&&markAncestors(path)}if((type==="object"||type==="array")&&!ancestors.has(value)){const available=Math.max(0,MAX_JSON_NODES-visited),{entries,truncated:entriesTruncated}=entriesOf(value,available);if(entriesTruncated&&(truncated=!0),path.length>=MAX_JSON_DEPTH){entries.length>0&&(truncated=!0);continue}ancestors.add(value),stack.push({kind:"leave",value});for(let index=entries.length-1;index>=0;index-=1){const[key,child]=entries[index];stack.push({kind:"visit",value:child,path:[...path,key],keyLabel:String(key)})}}}return{keyMatches,valueMatches,forceExpand,paths,orderedMatches,truncated}}renderCopyButton(value,label,pathKey){if(!this.copyable)return nothing;const resolvedLabel=label??this.localize("jsonValue");return html`
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteCount}from"../../../internal/numbers.js";import{viewerSearchDetail}from"../../../internal/viewer-search.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./json-viewer.styles.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{writeClipboardText}from"../../../internal/clipboard.js";import{COPY_FEEDBACK_MS}from"../../../internal/copy-feedback.js";import{LYRA_DEFAULT_copied,LYRA_DEFAULT_copy,LYRA_DEFAULT_copyFailed,LYRA_DEFAULT_viewerSearchActiveMatch,LYRA_DEFAULT_viewerSearchMatchCount,LYRA_DEFAULT_viewerSearchNoMatches}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_circularReference,LYRA_DEFAULT_copyJson,LYRA_DEFAULT_jsonArray,LYRA_DEFAULT_jsonCollapseLabel,LYRA_DEFAULT_jsonCopyLabel,LYRA_DEFAULT_jsonExpandLabel,LYRA_DEFAULT_jsonItemCount,LYRA_DEFAULT_jsonKeyCount,LYRA_DEFAULT_jsonObject,LYRA_DEFAULT_jsonValue,LYRA_DEFAULT_jsonViewerLimit}from"../../../internal/default-strings/utility.generated.js";const COPY_CONFIRM_MS=COPY_FEEDBACK_MS,MAX_JSON_NODES=5e3,MAX_JSON_DEPTH=100,MAX_JSON_SNAPSHOT_INSPECTIONS=MAX_JSON_NODES*2,OMIT_JSON_SNAPSHOT=Symbol("omit-json-viewer-snapshot"),EMPTY_SEARCH={keyMatches:new Set,valueMatches:new Set,forceExpand:new Set,paths:new Set,orderedMatches:[],truncated:!1};function isArrayContainer(value){try{return Array.isArray(value)}catch{return!1}}function isSnapshotArray(value){return Array.isArray(value)}function snapshotJsonData(value){const budget={remainingNodes:MAX_JSON_NODES,remainingInspections:MAX_JSON_SNAPSHOT_INSPECTIONS,truncated:!1},projected=snapshotJsonValue(value,budget,new WeakMap,0);return Object.freeze({value:projected===OMIT_JSON_SNAPSHOT?void 0:projected,truncated:budget.truncated||projected===OMIT_JSON_SNAPSHOT})}function snapshotJsonValue(value,budget,copies,depth){if(budget.remainingNodes<=0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;if(budget.remainingNodes-=1,value==null||typeof value=="string"||typeof value=="number"||typeof value=="boolean"||typeof value=="bigint")return value;if(typeof value!="object")return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const source=value,existing=copies.get(source);if(existing)return existing;const array=isArrayContainer(source);if(depth>=MAX_JSON_DEPTH){budget.truncated=!0;const shell=array?[]:Object.create(null);return copies.set(source,shell),Object.freeze(shell)}return array?snapshotJsonArray(source,budget,copies,depth):snapshotJsonObject(source,budget,copies,depth)}function snapshotJsonArray(source,budget,copies,depth){const length=getOwnDataDescriptor(source,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return budget.truncated=!0,OMIT_JSON_SNAPSHOT;const projected=[];copies.set(source,projected);let retainedLength=0;const count=Math.min(length.value,budget.remainingInspections);count<length.value&&(budget.truncated=!0);for(let index=0;index<count;index+=1){if(budget.remainingNodes<=0||budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1,retainedLength=index+1;const descriptor=getOwnDataDescriptor(source,String(index));if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR){budget.truncated=!0;continue}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}projected[index]=child}projected.length=retainedLength;try{return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function snapshotJsonObject(source,budget,copies,depth){const projected=Object.create(null);copies.set(source,projected);let keys;try{keys=Object.getOwnPropertyNames(source)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}try{for(const key of keys){if(budget.remainingInspections<=0){budget.truncated=!0;break}budget.remainingInspections-=1;const descriptor=getOwnDataDescriptor(source,key);if(descriptor===MISSING_OWN_DATA_DESCRIPTOR)continue;if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR||!descriptor.enumerable){descriptor===UNSAFE_OWN_DATA_DESCRIPTOR&&(budget.truncated=!0);continue}if(budget.remainingNodes<=0){budget.truncated=!0;break}const child=snapshotJsonValue(descriptor.value,budget,copies,depth+1);if(child===OMIT_JSON_SNAPSHOT){budget.truncated=!0;continue}Object.defineProperty(projected,key,{value:child,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(projected)}catch{return copies.delete(source),budget.truncated=!0,OMIT_JSON_SNAPSHOT}}function entriesOf(value,limit){const entries=[];if(isSnapshotArray(value)){const total=value.length,count=Math.min(total,limit);for(let index=0;index<count;index+=1)entries.push([index,Object.hasOwn(value,index)?value[index]:void 0]);return{entries,truncated:total>count,total,exact:!0}}if(typeof value=="object"&&value!==null){let total=0;for(const key in value)total+=1,entries.length<limit&&entries.push([key,value[key]]);return{entries,truncated:total>entries.length,total,exact:!0}}return{entries,truncated:!1,total:0,exact:!0}}function valueType(value){if(value===null)return"null";if(value===void 0)return"undefined";if(isSnapshotArray(value))return"array";const t=typeof value;return t==="string"||t==="number"||t==="boolean"?t:t==="object"?"object":"string"}function formatPrimitive(value,type){return type==="string"&&typeof value=="string"?JSON.stringify(value):String(value)}class LyraJsonViewer extends LyraElement{constructor(){super(...arguments),this.maxHeight="",this.copyable=!1,this.query="",this.expandedOverrides=new Map,this.activeSearchIndex=-1,this.searchState=EMPTY_SEARCH,this.searchLocale="",this.dataSnapshot=void 0,this.dataSnapshotTruncated=!1,this.searchAnnouncementsArmed=!1,this.searchAnnouncementGeneration=0,this.copyFeedback=null}static{this.defaultStrings={...super.defaultStrings,circularReference:LYRA_DEFAULT_circularReference,copied:LYRA_DEFAULT_copied,copy:LYRA_DEFAULT_copy,copyFailed:LYRA_DEFAULT_copyFailed,copyJson:LYRA_DEFAULT_copyJson,jsonArray:LYRA_DEFAULT_jsonArray,jsonCollapseLabel:LYRA_DEFAULT_jsonCollapseLabel,jsonCopyLabel:LYRA_DEFAULT_jsonCopyLabel,jsonExpandLabel:LYRA_DEFAULT_jsonExpandLabel,jsonItemCount:LYRA_DEFAULT_jsonItemCount,jsonKeyCount:LYRA_DEFAULT_jsonKeyCount,jsonObject:LYRA_DEFAULT_jsonObject,jsonValue:LYRA_DEFAULT_jsonValue,jsonViewerLimit:LYRA_DEFAULT_jsonViewerLimit,viewerSearchActiveMatch:LYRA_DEFAULT_viewerSearchActiveMatch,viewerSearchMatchCount:LYRA_DEFAULT_viewerSearchMatchCount,viewerSearchNoMatches:LYRA_DEFAULT_viewerSearchNoMatches}}static{this.styles=[LyraElement.styles,styles,srOnly]}connectedCallback(){super.connectedCallback(),this.searchAnnouncementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncementsArmed=!1;const generation=++this.searchAnnouncementGeneration;this.updateComplete.then(()=>{this.isConnected&&generation===this.searchAnnouncementGeneration&&(this.searchAnnouncementsArmed=!0)})}disconnectedCallback(){this.clearCopyFeedback(),this.searchAnnouncementGeneration+=1,this.searchAnnouncementSink?.release(),this.searchAnnouncementSink=void 0,this.searchAnnouncementsArmed=!1,super.disconnectedCallback()}get safeExpandDepth(){return this.expandDepth===void 0?void 0:finiteCount(this.expandDepth)}previewText(type,count,exact=!0){const formattedCount=getNumberFormat(this.effectiveLocale).format(count),localizedCount=exact?formattedCount:`≥${formattedCount}`;return type==="array"?this.localize("jsonItemCount",void 0,{count:localizedCount,pluralCount:count}):this.localize("jsonKeyCount",void 0,{count:localizedCount,pluralCount:count})}isExpanded(pathKey,depth,forceExpand){const override=this.expandedOverrides.get(pathKey);if(override!==void 0)return override;if(forceExpand.has(pathKey))return!0;const expandDepth=this.safeExpandDepth;return!(expandDepth!==void 0&&depth>=expandDepth)}toggleNode(pathKey,currentlyExpanded){const next=new Map(this.expandedOverrides);next.set(pathKey,!currentlyExpanded),this.expandedOverrides=next}reportCopyFailure(outcome){this.searchAnnouncementSink?.announce(this.localize("copyFailed")),this.emit("lr-error"),this.emit("lr-copy-error",outcome)}clearCopyFeedback(){const timer=this.copyFeedbackTimer;timer&&timer.owner.clearTimeout(timer.handle),this.copyFeedbackTimer=void 0,this.copyFeedback=null}showCopyFeedback(key,ok){const owner=this.ownerDocument.defaultView;owner&&(this.clearCopyFeedback(),this.copyFeedback={key,ok},this.copyFeedbackTimer={owner,handle:owner.setTimeout(()=>this.clearCopyFeedback(),COPY_CONFIRM_MS)})}copyLabel(key,rest){const feedback=this.copyFeedback;return feedback?.key===key?this.localize(feedback.ok?"copied":"copyFailed"):rest}async copy(value,key){this.clearCopyFeedback();let text="";try{text=value===void 0?"undefined":this.stringifyForClipboard(value)}catch(error){this.isConnected&&(this.showCopyFeedback(key,!1),this.reportCopyFailure(Object.freeze({ok:!1,text,reason:"failed",error})));return}const owner=this.isConnected?this.ownerDocument.defaultView:null,outcome=await writeClipboardText(owner,text);if(!(!this.isConnected||this.ownerDocument.defaultView!==owner)){if(this.showCopyFeedback(key,outcome.ok),!outcome.ok){this.reportCopyFailure(outcome);return}this.searchAnnouncementSink?.announce(this.localize("copied")),this.emit("lr-copy",outcome)}}stringifyForClipboard(value){const circularMarker=this.localize("circularReference"),stack=[],serialized=JSON.stringify(value,function(_key,v){if(typeof v=="bigint")return v.toString();if(typeof v!="object"||v===null)return v;const holderIndex=stack.indexOf(this);return stack.length=holderIndex+1,stack.includes(v)?circularMarker:(stack.push(v),v)},2);if(serialized!==void 0)return serialized;try{return formatPrimitive(value,valueType(value))}catch{return""}}computeSearch(){const locale=this.effectiveLocale,query=(this.query??"").trim().toLocaleLowerCase(locale),keyMatches=new Set,valueMatches=new Set,forceExpand=new Set,paths=new Set,orderedMatches=[],ancestors=new WeakSet;let truncated=this.dataSnapshotTruncated;const markAncestors=path=>{for(let i=path.length-1;i>=0;i--)forceExpand.add(JSON.stringify(path.slice(0,i)))},stack=[{kind:"visit",value:this.dataSnapshot,path:[]}];let visited=0;for(;stack.length>0;){const frame=stack.pop();if(frame.kind==="leave"){ancestors.delete(frame.value);continue}if(visited>=MAX_JSON_NODES){truncated=!0;break}visited+=1;const{value,path,keyLabel}=frame,pathKey=JSON.stringify(path);paths.add(pathKey);const type=valueType(value);if(query){let hit=!1;keyLabel!==void 0&&keyLabel.toLocaleLowerCase(locale).includes(query)&&(keyMatches.add(pathKey),orderedMatches.push({pathKey,kind:"key"}),hit=!0),type!=="object"&&type!=="array"&&formatPrimitive(value,type).toLocaleLowerCase(locale).includes(query)&&(valueMatches.add(pathKey),orderedMatches.push({pathKey,kind:"value"}),hit=!0),hit&&markAncestors(path)}if((type==="object"||type==="array")&&!ancestors.has(value)){const available=Math.max(0,MAX_JSON_NODES-visited),{entries,truncated:entriesTruncated}=entriesOf(value,available);if(entriesTruncated&&(truncated=!0),path.length>=MAX_JSON_DEPTH){entries.length>0&&(truncated=!0);continue}ancestors.add(value),stack.push({kind:"leave",value});for(let index=entries.length-1;index>=0;index-=1){const[key,child]=entries[index];stack.push({kind:"visit",value:child,path:[...path,key],keyLabel:String(key)})}}}return{keyMatches,valueMatches,forceExpand,paths,orderedMatches,truncated}}renderCopyButton(value,label,pathKey){if(!this.copyable)return nothing;const resolvedLabel=label??this.localize("jsonValue");return html`
2
2
  <button
3
3
  part="copy-button"
4
4
  type="button"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisible,isAccessibilityVisibilityHidden,nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./known-date.styles.js";import{localeDateOrder,localeDigitMap,normalizeLocaleDigits}from"../../../internal/locale-date.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{formatISO,parseISO}from"../../forms/date-picker/calendar-core.js";import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings.generated.js";const EMPTY_PARTS={day:"",month:"",year:""};class LyraKnownDateBase extends LyraElement{}function addCompatibilityDetail(event,detail){return Object.defineProperty(event,"detail",{configurable:!0,value:detail}),event}class LyraKnownDate extends FormAssociated(LyraKnownDateBase){static{this.defaultStrings={...super.defaultStrings,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,fieldRequired:LYRA_DEFAULT_fieldRequired,knownDateDay:LYRA_DEFAULT_knownDateDay,knownDateMonth:LYRA_DEFAULT_knownDateMonth,knownDateYear:LYRA_DEFAULT_knownDateYear}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},parts:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this.size="m",this.appearance="outlined",this.pill=!1,this.label="",this.hint="",this.errorText="",this.locale="",this.autocomplete="",this.withLabel=!1,this.withHint=!1,this.accessibleLabel=null,this._parts={...EMPTY_PARTS},this.touched=!1,this.slotPresence=new SlotPresenceController(this),this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorTextObserver=new AccessibleTextController(this,["error"],()=>this.announceVisibleError(),["slot"]),this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.errorTextObserver.bind(),this.announceVisibleError())},this.hintId=nextId("known-date-hint"),this.errorId=nextId("known-date-error"),this.dayId=nextId("known-date-day"),this.monthId=nextId("known-date-month"),this.yearId=nextId("known-date-year"),this.onFieldInput=(field,e)=>{e.stopPropagation();const input=e.target,maxLength=field==="year"?4:2,digits=this.normalizeFieldDigits(input.value).slice(0,maxLength);input.value!==digits&&(input.value=digits),this.setFieldText(field,digits),this.lastEditedField=field,this.commitFromFields();const InputEventConstructor=this.ownerDocument.defaultView?.InputEvent??InputEvent,detail=this.detailFor(field),event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),detail);this.dispatchEvent(event),this.emit("lr-input",detail),field!=="year"&&digits.length===maxLength&&this.focusAdjacentField(field,1)},this.onFieldKeydown=(field,e)=>{const input=e.currentTarget;if(isImplicitSubmission(e)){if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,e,{beforeSubmit:()=>this.commitChangeIfNeeded()});return}if(e.key==="Backspace"&&this.textFor(field)===""){e.preventDefault(),this.focusAdjacentField(field,-1);return}if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const atStart=input.selectionStart===0&&input.selectionEnd===0,atEnd=input.selectionStart===input.value.length&&input.selectionEnd===input.value.length,rtl=this.effectiveDirection==="rtl";e.key==="ArrowLeft"&&atStart?(e.preventDefault(),this.focusAdjacentField(field,rtl?1:-1)):e.key==="ArrowRight"&&atEnd&&(e.preventDefault(),this.focusAdjacentField(field,rtl?-1:1))},this.onFieldFocus=e=>{e.stopPropagation(),relayNativeEvent(this,e,{relatedTarget:this.isRenderedFieldTarget(e.relatedTarget)?null:e.relatedTarget})},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=shadowFocusTarget(this);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,e))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.addEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementsArmed=!1;const generation=++this.connectionGeneration;this.updateComplete.then(()=>{const view=this.ownerDocument.defaultView;return typeof view?.requestAnimationFrame=="function"?new Promise(resolve=>view.requestAnimationFrame(()=>resolve())):Promise.resolve()}).then(()=>this.updateComplete).then(()=>{!this.isConnected||generation!==this.connectionGeneration||(this.lastVisibleError=this.visibleErrorText(),this.errorAnnouncementsArmed=!0)})}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.errorTextObserver.adopted(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const owner=this.renderRoot.querySelector('[part="fieldset"]');owner&&(this.externalDescriptionLease?this.externalDescriptionLease.update(owner):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,owner,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get parts(){return this._parts}set parts(next){next!==this.partsSource&&(this.partsSource=next,this.setParts(next,!0))}setParts(next,programmatic){const old=this._parts,parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")};programmatic&&parts.day===old.day&&parts.month===old.month&&parts.year===old.year||(this._parts=parts,programmatic&&(this.commitFromFields(),this.lastCommittedValue=this.value),this.requestUpdate("parts",old))}get value(){return super.value}set value(next){const parsed=this.parseStrictISO(next??"");parsed&&formatISO(parsed)===super.value||(parsed?(this.setParts({day:String(parsed.getDate()),month:String(parsed.getMonth()+1),year:String(parsed.getFullYear())},!1),super.value=formatISO(parsed)):(this.setParts({day:"",month:"",year:""},!1),super.value=""),this.lastCommittedValue=super.value)}get valueAsDate(){return this.value?parseISO(this.value):null}set valueAsDate(next){this.value=next?formatISO(next):""}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}get fieldOrder(){const locale=this.effectiveLocale;return this.fieldOrderCache?.locale!==locale&&(this.fieldOrderCache={locale,order:localeDateOrder(locale)}),this.fieldOrderCache.order}textFor(field){return this._parts[field]}setFieldText(field,text){this.setParts({...this._parts,[field]:text},!1)}idFor(field){return field==="day"?this.dayId:field==="month"?this.monthId:this.yearId}get effectiveDayLabel(){return this.dayLabel??this.localize("knownDateDay")}get effectiveMonthLabel(){return this.monthLabel??this.localize("knownDateMonth")}get effectiveYearLabel(){return this.yearLabel??this.localize("knownDateYear")}labelFor(field){return field==="day"?this.effectiveDayLabel:field==="month"?this.effectiveMonthLabel:this.effectiveYearLabel}autocompleteFor(field){return this.autocomplete?this.autocomplete==="bday"?`bday-${field}`:this.autocomplete==="on"||this.autocomplete==="off"?this.autocomplete:field==="year"?this.autocomplete:"":""}computeCanonicalValue(){if(!this._parts.day||!this._parts.month||!this._parts.year)return"";const iso=`${this._parts.year.padStart(4,"0")}-${this._parts.month.padStart(2,"0")}-${this._parts.day.padStart(2,"0")}`;return parseISO(iso)?iso:""}commitFromFields(){super.value=this.computeCanonicalValue()}get eventDetail(){return{value:this.value,...this._parts}}detailFor(field){return{...this.eventDetail,field}}commitChangeIfNeeded(){if(this.value===this.lastCommittedValue)return;this.lastCommittedValue=this.value;const EventConstructor=this.ownerDocument.defaultView?.Event??Event,detail=this.detailFor(this.lastEditedField),event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),detail);this.dispatchEvent(event),this.emit("lr-change",detail)}fieldInputElement(field){return this.renderRoot?.querySelector(`input[data-field="${field}"]`)??null}isRenderedFieldTarget(target){if(!target||typeof target!="object")return!1;const field=target.dataset?.field;return field!=="day"&&field!=="month"&&field!=="year"?!1:this.fieldInputElement(field)===target}focusAdjacentField(field,delta){const order=this.fieldOrder,targetIndex=order.indexOf(field)+delta;targetIndex<0||targetIndex>=order.length||this.fieldInputElement(order[targetIndex])?.focus()}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";const blank=this._parts.day===""&&this._parts.month===""&&this._parts.year==="";if(this.value==="")this.required&&blank?(flags.valueMissing=!0,message=this.localize("fieldRequired")):blank||(flags.badInput=!0,message=this.localize("dateInputInvalid"));else{const date=parseISO(this.value),min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max);min&&date<min&&(flags.rangeUnderflow=!0,message=this.localize("dateInputMinMessage",void 0,{min:this.min})),max&&date>max&&(flags.rangeOverflow=!0,message||=this.localize("dateInputMaxMessage",void 0,{max:this.max}))}this[SET_ANCHORED_VALIDITY](flags,message)}updated(changed){super.updated(changed),this.syncExternalDescription(),setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("min")||changed.has("max")||changed.has("readonly"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.announceVisibleError()}formResetCallback(){super.formResetCallback(),this.touched=!1}formStateRestoreCallback(state2){this.value=typeof state2=="string"?state2:""}setCustomValidity(message){super.setCustomValidity(message),this.requestUpdate()}get validationTarget(){return this.validationTargetOverride??this.fieldInputElement(this.fieldOrder[0])??void 0}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}visibleErrorText(){const slottedElements=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error");return slottedElements.length>0?slottedElements.map(element=>this.accessibleVisibleText(element)).join(" ").replace(/\s+/g," ").trim():(this.errorText||(this.touched?this.validationMessage:"")).trim()}accessibleVisibleText(node){if(node.nodeType===3)return node.textContent??"";if(node.nodeType!==1)return"";const element=node;if(isAccessibilitySubtreeExcluded(element))return"";const visibilityHidden=isAccessibilityVisibilityHidden(element),accessibleLabel=visibilityHidden?null:element.getAttribute("aria-label");if(accessibleLabel?.trim())return accessibleLabel;const assigned=element.localName==="slot"?element.assignedNodes({flatten:!0}):[];return(assigned.length>0?assigned:Array.from(element.childNodes)).map(child=>child.nodeType===3&&visibilityHidden?"":this.accessibleVisibleText(child)).join(" ")}announceVisibleError(){if(!this.errorAnnouncementsArmed||!isAccessibilityVisible(this))return;const message=this.visibleErrorText();message!==this.lastVisibleError&&(this.lastVisibleError=message,message&&this.errorAnnouncementSink?.announce(message))}normalizeFieldDigits(value){const locale=this.effectiveLocale;return this.digitMapCache?.locale!==locale&&(this.digitMapCache={locale,map:localeDigitMap(locale)}),normalizeLocaleDigits(value,locale,this.digitMapCache.map).replace(/\D/g,"")}focus(options){const target=this.fieldOrder.find(field=>this.textFor(field)==="")??this.fieldOrder[0];this.fieldInputElement(target)?.focus(options)}blur(){this.renderRoot.querySelector("input:focus")?.blur()}click(){this.fieldInputElement(this.fieldOrder[0])?.click()}renderField(field,describedBy,invalid){const id=this.idFor(field),maxLength=field==="year"?4:2;return html`
1
+ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisible,isAccessibilityVisibilityHidden,nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./known-date.styles.js";import{localeDateOrder,localeDigitMap,normalizeLocaleDigits}from"../../../internal/locale-date.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{setCustomState}from"../../../internal/custom-states.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{formatISO,parseISO}from"../../forms/date-picker/calendar-core.js";import{currentValidityValidator}from"../../forms/form-validator.js";import{LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";import{LYRA_DEFAULT_knownDateDay,LYRA_DEFAULT_knownDateMonth,LYRA_DEFAULT_knownDateYear}from"../../../internal/default-strings/utility.generated.js";const EMPTY_PARTS={day:"",month:"",year:""};class LyraKnownDateBase extends LyraElement{}function addCompatibilityDetail(event,detail){return Object.defineProperty(event,"detail",{configurable:!0,value:detail}),event}class LyraKnownDate extends FormAssociated(LyraKnownDateBase){static{this.defaultStrings={...super.defaultStrings,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,fieldRequired:LYRA_DEFAULT_fieldRequired,knownDateDay:LYRA_DEFAULT_knownDateDay,knownDateMonth:LYRA_DEFAULT_knownDateMonth,knownDateYear:LYRA_DEFAULT_knownDateYear}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},parts:{attribute:!1,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this.size="m",this.appearance="outlined",this.pill=!1,this.label="",this.hint="",this.errorText="",this.locale="",this.autocomplete="",this.withLabel=!1,this.withHint=!1,this.accessibleLabel=null,this._parts={...EMPTY_PARTS},this.touched=!1,this.slotPresence=new SlotPresenceController(this),this._min="",this._max="",this._readonly=!1,this.lastCommittedValue="",this.lastEditedField="day",this.errorTextObserver=new AccessibleTextController(this,["error"],()=>this.announceVisibleError(),["slot"]),this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.connectionGeneration=0,this.onForwardedSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||(this.errorTextObserver.bind(),this.announceVisibleError())},this.hintId=nextId("known-date-hint"),this.errorId=nextId("known-date-error"),this.dayId=nextId("known-date-day"),this.monthId=nextId("known-date-month"),this.yearId=nextId("known-date-year"),this.onFieldInput=(field,e)=>{e.stopPropagation();const input=e.target,maxLength=field==="year"?4:2,digits=this.normalizeFieldDigits(input.value).slice(0,maxLength);input.value!==digits&&(input.value=digits),this.setFieldText(field,digits),this.lastEditedField=field,this.commitFromFields();const InputEventConstructor=this.ownerDocument.defaultView?.InputEvent??InputEvent,detail=this.detailFor(field),event=addCompatibilityDetail(new InputEventConstructor("input",{bubbles:!0,composed:!0,inputType:e.inputType||"insertText"}),detail);this.dispatchEvent(event),this.emit("lr-input",detail),field!=="year"&&digits.length===maxLength&&this.focusAdjacentField(field,1)},this.onFieldKeydown=(field,e)=>{const input=e.currentTarget;if(isImplicitSubmission(e)){if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,e,{beforeSubmit:()=>this.commitChangeIfNeeded()});return}if(e.key==="Backspace"&&this.textFor(field)===""){e.preventDefault(),this.focusAdjacentField(field,-1);return}if(e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;const atStart=input.selectionStart===0&&input.selectionEnd===0,atEnd=input.selectionStart===input.value.length&&input.selectionEnd===input.value.length,rtl=this.effectiveDirection==="rtl";e.key==="ArrowLeft"&&atStart?(e.preventDefault(),this.focusAdjacentField(field,rtl?1:-1)):e.key==="ArrowRight"&&atEnd&&(e.preventDefault(),this.focusAdjacentField(field,rtl?-1:1))},this.onFieldFocus=e=>{e.stopPropagation(),relayNativeEvent(this,e,{relatedTarget:this.isRenderedFieldTarget(e.relatedTarget)?null:e.relatedTarget})},this.onFieldBlur=e=>{e.stopPropagation(),this.commitChangeIfNeeded();const related=e.relatedTarget,active=shadowFocusTarget(this);e.isTrusted&&(this.isRenderedFieldTarget(related)||active!==e.target&&this.isRenderedFieldTarget(active))||(this.effectiveDisabled||(this.touched=!0),relayNativeEvent(this,e))},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.errorAnnouncementSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}),this.addEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementsArmed=!1;const generation=++this.connectionGeneration;this.updateComplete.then(()=>{const view=this.ownerDocument.defaultView;return typeof view?.requestAnimationFrame=="function"?new Promise(resolve=>view.requestAnimationFrame(()=>resolve())):Promise.resolve()}).then(()=>this.updateComplete).then(()=>{!this.isConnected||generation!==this.connectionGeneration||(this.lastVisibleError=this.visibleErrorText(),this.errorAnnouncementsArmed=!0)})}disconnectedCallback(){this.releaseExternalDescription(),this.connectionGeneration+=1,this.errorAnnouncementsArmed=!1,this.lastVisibleError="",this.removeEventListener("slotchange",this.onForwardedSlotChange),this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.errorTextObserver.adopted(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const owner=this.renderRoot.querySelector('[part="fieldset"]');owner&&(this.externalDescriptionLease?this.externalDescriptionLease.update(owner):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,owner,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get parts(){return this._parts}set parts(next){next!==this.partsSource&&(this.partsSource=next,this.setParts(next,!0))}setParts(next,programmatic){const old=this._parts,parts={day:String(next?.day??""),month:String(next?.month??""),year:String(next?.year??"")};programmatic&&parts.day===old.day&&parts.month===old.month&&parts.year===old.year||(this._parts=parts,programmatic&&(this.commitFromFields(),this.lastCommittedValue=this.value),this.requestUpdate("parts",old))}get value(){return super.value}set value(next){const parsed=this.parseStrictISO(next??"");parsed&&formatISO(parsed)===super.value||(parsed?(this.setParts({day:String(parsed.getDate()),month:String(parsed.getMonth()+1),year:String(parsed.getFullYear())},!1),super.value=formatISO(parsed)):(this.setParts({day:"",month:"",year:""},!1),super.value=""),this.lastCommittedValue=super.value)}get valueAsDate(){return this.value?parseISO(this.value):null}set valueAsDate(next){this.value=next?formatISO(next):""}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}get fieldOrder(){const locale=this.effectiveLocale;return this.fieldOrderCache?.locale!==locale&&(this.fieldOrderCache={locale,order:localeDateOrder(locale)}),this.fieldOrderCache.order}textFor(field){return this._parts[field]}setFieldText(field,text){this.setParts({...this._parts,[field]:text},!1)}idFor(field){return field==="day"?this.dayId:field==="month"?this.monthId:this.yearId}get effectiveDayLabel(){return this.dayLabel??this.localize("knownDateDay")}get effectiveMonthLabel(){return this.monthLabel??this.localize("knownDateMonth")}get effectiveYearLabel(){return this.yearLabel??this.localize("knownDateYear")}labelFor(field){return field==="day"?this.effectiveDayLabel:field==="month"?this.effectiveMonthLabel:this.effectiveYearLabel}autocompleteFor(field){return this.autocomplete?this.autocomplete==="bday"?`bday-${field}`:this.autocomplete==="on"||this.autocomplete==="off"?this.autocomplete:field==="year"?this.autocomplete:"":""}computeCanonicalValue(){if(!this._parts.day||!this._parts.month||!this._parts.year)return"";const iso=`${this._parts.year.padStart(4,"0")}-${this._parts.month.padStart(2,"0")}-${this._parts.day.padStart(2,"0")}`;return parseISO(iso)?iso:""}commitFromFields(){super.value=this.computeCanonicalValue()}get eventDetail(){return{value:this.value,...this._parts}}detailFor(field){return{...this.eventDetail,field}}commitChangeIfNeeded(){if(this.value===this.lastCommittedValue)return;this.lastCommittedValue=this.value;const EventConstructor=this.ownerDocument.defaultView?.Event??Event,detail=this.detailFor(this.lastEditedField),event=addCompatibilityDetail(new EventConstructor("change",{bubbles:!0,composed:!0}),detail);this.dispatchEvent(event),this.emit("lr-change",detail)}fieldInputElement(field){return this.renderRoot?.querySelector(`input[data-field="${field}"]`)??null}isRenderedFieldTarget(target){if(!target||typeof target!="object")return!1;const field=target.dataset?.field;return field!=="day"&&field!=="month"&&field!=="year"?!1:this.fieldInputElement(field)===target}focusAdjacentField(field,delta){const order=this.fieldOrder,targetIndex=order.indexOf(field)+delta;targetIndex<0||targetIndex>=order.length||this.fieldInputElement(order[targetIndex])?.focus()}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";const blank=this._parts.day===""&&this._parts.month===""&&this._parts.year==="";if(this.value==="")this.required&&blank?(flags.valueMissing=!0,message=this.localize("fieldRequired")):blank||(flags.badInput=!0,message=this.localize("dateInputInvalid"));else{const date=parseISO(this.value),min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max);min&&date<min&&(flags.rangeUnderflow=!0,message=this.localize("dateInputMinMessage",void 0,{min:this.min})),max&&date>max&&(flags.rangeOverflow=!0,message||=this.localize("dateInputMaxMessage",void 0,{max:this.max}))}this[SET_ANCHORED_VALIDITY](flags,message)}updated(changed){super.updated(changed),this.syncExternalDescription(),setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("min")||changed.has("max")||changed.has("readonly"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.announceVisibleError()}formResetCallback(){super.formResetCallback(),this.touched=!1}formStateRestoreCallback(state2){this.value=typeof state2=="string"?state2:""}setCustomValidity(message){super.setCustomValidity(message),this.requestUpdate()}get validationTarget(){return this.validationTargetOverride??this.fieldInputElement(this.fieldOrder[0])??void 0}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}visibleErrorText(){const slottedElements=Array.from(this.children).filter(element=>element.getAttribute("slot")==="error");return slottedElements.length>0?slottedElements.map(element=>this.accessibleVisibleText(element)).join(" ").replace(/\s+/g," ").trim():(this.errorText||(this.touched?this.validationMessage:"")).trim()}accessibleVisibleText(node){if(node.nodeType===3)return node.textContent??"";if(node.nodeType!==1)return"";const element=node;if(isAccessibilitySubtreeExcluded(element))return"";const visibilityHidden=isAccessibilityVisibilityHidden(element),accessibleLabel=visibilityHidden?null:element.getAttribute("aria-label");if(accessibleLabel?.trim())return accessibleLabel;const assigned=element.localName==="slot"?element.assignedNodes({flatten:!0}):[];return(assigned.length>0?assigned:Array.from(element.childNodes)).map(child=>child.nodeType===3&&visibilityHidden?"":this.accessibleVisibleText(child)).join(" ")}announceVisibleError(){if(!this.errorAnnouncementsArmed||!isAccessibilityVisible(this))return;const message=this.visibleErrorText();message!==this.lastVisibleError&&(this.lastVisibleError=message,message&&this.errorAnnouncementSink?.announce(message))}normalizeFieldDigits(value){const locale=this.effectiveLocale;return this.digitMapCache?.locale!==locale&&(this.digitMapCache={locale,map:localeDigitMap(locale)}),normalizeLocaleDigits(value,locale,this.digitMapCache.map).replace(/\D/g,"")}focus(options){const target=this.fieldOrder.find(field=>this.textFor(field)==="")??this.fieldOrder[0];this.fieldInputElement(target)?.focus(options)}blur(){this.renderRoot.querySelector("input:focus")?.blur()}click(){this.fieldInputElement(this.fieldOrder[0])?.click()}renderField(field,describedBy,invalid){const id=this.idFor(field),maxLength=field==="year"?4:2;return html`
2
2
  <div part=${field==="day"?"field field-day":field==="month"?"field field-month":"field field-year"} data-field=${field}>
3
3
  <label part="field-label" for=${id}>${this.labelFor(field)}</label>
4
4
  <input