@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{prefersReducedMotion}from"../../../internal/motion.js";import{observeReducedMotion}from"../../../internal/motion-observer.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisible,isAccessibilityVisibilityHidden}from"../../../internal/accessibility-visibility.js";import{deepActiveElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{composedAccessibilityText}from"../../../internal/announcement-text.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteDuration,finiteInteger}from"../../../internal/numbers.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{composedContains}from"../../../internal/overlay-manager.js";import{SlottedOverlayController}from"../../../internal/slotted-overlay-controller.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{tag}from"../../../internal/prefix.js";import{styles}from"./carousel.styles.js";import{LYRA_DEFAULT_carousel,LYRA_DEFAULT_carouselGoTo,LYRA_DEFAULT_carouselIndicators,LYRA_DEFAULT_carouselLabel,LYRA_DEFAULT_carouselSlide,LYRA_DEFAULT_carouselSlideAnnouncement,LYRA_DEFAULT_carouselSlideAnnouncementSeparator,LYRA_DEFAULT_carouselSlidePosition,LYRA_DEFAULT_next,LYRA_DEFAULT_previous}from"../../../internal/default-strings.generated.js";const SCROLL_SETTLE_MS=120,LOOP_SNAPSHOT_UNSAFE_TAGS=new Set(["audio","canvas","embed","form","iframe","img","input","link","object","picture","script","select","source","style","textarea","track","video"]),CAROUSEL_MANAGED_SLIDE_ATTRIBUTES=new Set(["aria-hidden","aria-label","aria-roledescription","hidden","inert","role"]),SLIDE_SNAPSHOT_KEYS=["hidden","inert","role","label","roleDescription","ariaHidden"];class LyraCarousel extends LyraElement{static{this.defaultStrings={...super.defaultStrings,carousel:LYRA_DEFAULT_carousel,carouselGoTo:LYRA_DEFAULT_carouselGoTo,carouselIndicators:LYRA_DEFAULT_carouselIndicators,carouselLabel:LYRA_DEFAULT_carouselLabel,carouselSlide:LYRA_DEFAULT_carouselSlide,carouselSlideAnnouncement:LYRA_DEFAULT_carouselSlideAnnouncement,carouselSlideAnnouncementSeparator:LYRA_DEFAULT_carouselSlideAnnouncementSeparator,carouselSlidePosition:LYRA_DEFAULT_carouselSlidePosition,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous}}static{this.styles=[LyraElement.styles,styles]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"currentslide"])]}get currentSlide(){return this._currentSlide}set currentSlide(value){this.setCurrentSlideState(value)}get pagination(){return this._pagination}set pagination(value){this.setPaginationState(!!value)}get slides(){return this._slides}constructor(){super(),this._currentSlide=0,this._pagination=!1,this._slides=0,this.loop=!1,this.autoplay=!1,this.autoplayInterval=3e3,this.navigation=!1,this.orientation="horizontal",this.mouseDragging=!1,this.slidesPerPage=1,this.slidesPerMove=1,this.hostAccessibleLabel=null,this.reduceMotion=!1,this.snapshots=new Map,this.appliedSnapshots=new WeakMap,this.scrollSettle=new DebounceController(SCROLL_SETTLE_MS,()=>this.settleScrolledSlide(),()=>this.ownerDocument.defaultView),this.adoptingScrolledSlide=!1,this.hasAlignedOnce=!1,this.loopClonesDirty=!0,this.pointerInteracting=!1,this.focusInteracting=!1,this.slideOverlay=new SlottedOverlayController(this,()=>this.renderRoot?.querySelector("slot:not([name])")),this.slideOverlayWasOpen=!1,this.dragStartCoordinate=0,this.dragStartScroll=0,this.dragMoved=!1,this.suppressClick=!1,this.announcementsArmed=!1,this.changeOrigin="manual",this.manualPending=!1,this.observerGeneration=0,this.passiveTakeOver={handleEvent:()=>this.takeOverViewport(),passive:!0},this.onMotionPreferenceChange=reduced=>{this.reduceMotion=reduced,this.restartAutoplay(),this.requestUpdate()},this.onVisibilityChange=()=>{this.restartAutoplay()},this.onSlotChange=()=>{this.handleSlidesChanged()},this.onViewportScroll=()=>{this.cancelScrollSettle(),this.ownerDocument.defaultView&&this.scrollSettle.push(void 0)},this.onViewportScrollEnd=()=>{this.cancelScrollSettle(),this.settleScrolledSlide()},this.settleScrolledSlide=()=>{if(!this.isConnected)return;const viewport=this.viewport;if(!viewport)return;if(this.alignTarget){if(Math.abs(this.axisOffsetOf(this.alignTarget,viewport))>2)return;const cloneSide=this.alignTarget.dataset.carouselClone;if(cloneSide==="before"||cloneSide==="after"){const realSlide=this.slideElements()[this.alignIndex??-1];if(realSlide){this.alignTarget=realSlide,this.scrollByAxis(viewport,this.axisOffsetOf(realSlide,viewport),"instant");return}}this.clearAlignment();return}const resting=this.restingSlide();if(!resting)return;const changed=resting.index!==this.currentSlide;!changed&&!resting.cloneSide||(this.adoptingScrolledSlide=!0,changed&&(this.currentSlide=resting.index,this.emit("lr-slide-change",{index:resting.index,slide:this.slideElements()[resting.index]})),this.updateComplete.then(()=>{if(resting.cloneSide&&this.isConnected&&this.viewport){const realSlide=this.slideElements()[resting.index];realSlide&&this.scrollByAxis(this.viewport,this.axisOffsetOf(realSlide,this.viewport),"instant")}this.adoptingScrolledSlide=!1}))},this.onViewportPointerEnter=()=>{this.pointerInteracting=!0,this.restartAutoplay()},this.onViewportPointerLeave=()=>{this.dragPointerId===void 0&&(this.pointerInteracting=!1,this.restartAutoplay())},this.onViewportFocusIn=event=>{this.focusInteracting=!0;const slides=new Set(this.slideElements()),focusedSlide=event.composedPath().find(candidate=>candidate.nodeType===1&&slides.has(candidate));focusedSlide&&(this.lastFocusedSlide=focusedSlide),this.restartAutoplay()},this.onViewportFocusOut=()=>{this.queueOwnerMicrotask(()=>{if(!this.isConnected)return;const active=deepActiveElementIn(this.ownerDocument);this.lastFocusedSlide&&!composedContains(this.lastFocusedSlide,active)&&(this.lastFocusedSlide.isConnected||active!==null&&active!==this.ownerDocument.body)&&(this.lastFocusedSlide=void 0),this.focusInteracting=this.matches(":focus-within"),this.restartAutoplay()})},this.onViewportPointerDown=event=>{if(!this.mouseDragging||event.pointerType!=="mouse"||!event.isPrimary||event.button!==0||this.dragPointerId!==void 0||this.targetsInteractiveContent(event))return;this.takeOverViewport();const viewport=this.viewport;if(viewport){this.dragPointerId=event.pointerId,this.dragStartCoordinate=this.effectiveOrientation()==="vertical"?event.clientY:event.clientX,this.dragStartScroll=this.effectiveOrientation()==="vertical"?viewport.scrollTop:viewport.scrollLeft,this.dragMoved=!1,viewport.setAttribute("data-dragging","");try{viewport.setPointerCapture(event.pointerId)}catch{}this.restartAutoplay()}},this.onViewportPointerMove=event=>{if(event.pointerId!==this.dragPointerId)return;const viewport=this.viewport;if(!viewport)return;const delta=(this.effectiveOrientation()==="vertical"?event.clientY:event.clientX)-this.dragStartCoordinate;Math.abs(delta)>2&&(this.dragMoved=!0),this.dragMoved&&(event.preventDefault(),this.effectiveOrientation()==="vertical"?viewport.scrollTo({top:this.dragStartScroll-delta,behavior:"instant"}):viewport.scrollTo({left:this.dragStartScroll-delta,behavior:"instant"}))},this.onViewportPointerUp=event=>{this.finishDrag(event.pointerId,!1)},this.onViewportPointerCancel=event=>{this.finishDrag(event.pointerId,!0)},this.onViewportLostPointerCapture=event=>{this.finishDrag(event.pointerId,!0)},this.onViewportClick=event=>{this.suppressClick&&(event.preventDefault(),event.stopImmediatePropagation())},this.onViewportKeyDown=event=>{if(this.targetsInteractiveContent(event,!0))return;const vertical=this.effectiveOrientation()==="vertical",rtl=this.effectiveDirection==="rtl",forwardKey=vertical?"ArrowDown":rtl?"ArrowLeft":"ArrowRight",backwardKey=vertical?"ArrowUp":rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey?(event.preventDefault(),this.previous()):event.key==="Home"?(event.preventDefault(),this.goToSlide(0)):event.key==="End"&&(event.preventDefault(),this.goToSlide(this.loop?this.slideElements().length-1:this.maxStartIndex()))},this.requestUpdate("currentSlide",void 0),this.requestUpdate("pagination",void 0)}attributeChangedCallback(name,oldValue,newValue){if(name==="currentslide"){oldValue!==newValue&&(this.currentSlide=finiteInteger(Number(newValue??0),0));return}super.attributeChangedCallback(name,oldValue,newValue),name==="current-slide"&&newValue===null&&oldValue!==newValue&&this.hasAttribute("currentslide")&&(this.currentSlide=finiteInteger(Number(this.getAttribute("currentslide")??0),0))}connectedCallback(){this.hasAttribute("current-slide")&&(this.currentSlide=finiteInteger(Number(this.getAttribute("current-slide")??0),0)),super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.announcementsArmed=!1,this.manualPending=!1,this.reduceMotion=prefersReducedMotion(this),this.stopMotionWatch=observeReducedMotion(this,this.onMotionPreferenceChange),this.visibilityDocument=this.ownerDocument,this.visibilityDocument.addEventListener("visibilitychange",this.onVisibilityChange),this.armSlideContentObserver(),this.restartAutoplay(),this.hasUpdated&&this.queueOwnerMicrotask(()=>{this.isConnected&&this.handleSlidesChanged()})}disconnectedCallback(){this.announcementSink?.release(),this.announcementSink=void 0,this.announcementsArmed=!1,this.manualPending=!1,this.cancelDrag(!1),this.stopAutoplay(),this.cancelScrollSettle(),this.cancelClickSuppression(),this.suppressClick=!1,this.pointerInteracting=!1,this.focusInteracting=!1,this.hasAlignedOnce=!1,this.clearAlignment(),this.stopMotionWatch?.(),this.stopMotionWatch=void 0,this.visibilityDocument?.removeEventListener("visibilitychange",this.onVisibilityChange),this.visibilityDocument=void 0,this.resetSlideContentObserver(),this.restoreSlides(),this.lastFocusedSlide=void 0,super.disconnectedCallback()}armSlideContentObserver(){const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;this.resetSlideContentObserver();const generation=this.observerGeneration,observer=new MutationObserverCtor(records=>{this.observer!==observer||this.observerDocument!==ownerDocument||this.observerGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||!records.some(record=>{if(record.target===this)return record.type!=="attributes";if(record.type!=="attributes"||!CAROUSEL_MANAGED_SLIDE_ATTRIBUTES.has(record.attributeName??""))return this.loop;const slide=record.target,snapshot=this.snapshots.get(slide);return snapshot?this.adoptChanges(slide,snapshot):!1})||(this.loop&&(this.loopClonesDirty=!0),this.syncSlides(),this.requestUpdate())});this.observer=observer,this.observerDocument=ownerDocument,observer.observe(this,{attributes:!0,characterData:!0,childList:!0,subtree:!0})}resetSlideContentObserver(){this.observerGeneration+=1,this.observer?.disconnect(),this.observer=void 0,this.observerDocument=void 0}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);if(this.focusedNavButton=active?.matches('[part~="navigation-button"]')?active:void 0,(changed.has("currentSlide")||changed.has("slidesPerPage"))&&this.slideSlot){const normalized=this.normalizedIndex();if(this.currentSlide!==normalized){const forcedBySibling=changed.has("slidesPerPage")&&!changed.has("currentSlide");if(this.currentSlide=normalized,forcedBySibling){const slide=this.slideElements()[normalized];slide&&this.emit("lr-slide-change",{index:normalized,slide})}}}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.slideSlot;this.queueOwnerMicrotask(()=>{collectInitialSlotAssignment(slot,()=>this.handleSlidesChanged())})}updated(changed){super.updated(changed);const shouldAnnounceActivePage=this.announcementsArmed&&(this.manualPending||changed.has("slidesPerPage"));this.slideOverlay.open!==this.slideOverlayWasOpen&&(this.slideOverlayWasOpen=this.slideOverlay.open,this.restartAutoplay()),this.focusedNavButton?.disabled&&(this.focusedNavButton.parentElement.querySelector("button:not(:disabled)")??this.viewport)?.focus(),this.syncSlides(),(this.loopClonesDirty||changed.has("loop")||changed.has("slidesPerPage")||changed.has("slidesPerMove"))&&(this.syncLoopClones(),this.loopClonesDirty=!1),(changed.has("autoplay")||changed.has("autoplayInterval")||changed.has("loop")||changed.has("slidesPerPage"))&&this.restartAutoplay(),!this.adoptingScrolledSlide&&(changed.has("currentSlide")||changed.has("slidesPerPage")||changed.has("orientation")||!this.hasAlignedOnce)&&this.alignToActiveSlide(),this.hasAlignedOnce=!0,shouldAnnounceActivePage&&this.announceActivePage(),this.manualPending=!1,this.announcementsArmed=!0}setCurrentSlideState(value){const old=this._currentSlide,next=finiteInteger(value,0);old!==next&&(this._currentSlide=next,this.changeOrigin==="manual"&&(this.manualPending=!0),this.requestUpdate("currentSlide",old))}setPaginationState(value){const old=this._pagination;old!==value&&(this._pagination=value,this.requestUpdate("pagination",old))}queueOwnerMicrotask(callback){const view=this.ownerDocument.defaultView;view?view.queueMicrotask(callback):queueMicrotask(callback)}effectiveOrientation(){return this.orientation==="vertical"?"vertical":"horizontal"}slideElements(){return(this.slideSlot?.assignedElements({flatten:!0})??[]).filter(element=>element.nodeType===1&&element.namespaceURI==="http://www.w3.org/1999/xhtml")}pageSize(count=this.slideElements().length){return finiteInteger(this.slidesPerPage,1,1,Math.max(1,count))}moveSize(count=this.slideElements().length){return finiteInteger(this.slidesPerMove,1,1,this.pageSize(count))}maxStartIndex(count=this.slideElements().length){return Math.max(0,count-this.pageSize(count))}normalizedIndex(count=this.slideElements().length){if(count===0)return 0;const max=this.loop?count-1:this.maxStartIndex(count);return finiteInteger(this.currentSlide,0,0,max)}pageTargets(count=this.slideElements().length){if(count===0)return[];if(this.loop)return Array.from({length:count},(_unused,index)=>index);const max=this.maxStartIndex(count),move=this.moveSize(count),targets=[0];for(let target=move;target<max;target+=move)targets.push(target);return max>0&&targets.at(-1)!==max&&targets.push(max),targets}visibleIndices(count,current){const visible=new Set,perPage=this.pageSize(count);for(let offset=0;offset<perPage;offset+=1){const index=this.loop?(current+offset)%count:current+offset;index>=0&&index<count&&visible.add(index)}return visible}announceActivePage(){if(!isAccessibilityVisible(this))return;const slides=this.slideElements();if(slides.length===0)return;const current=this.normalizedIndex(slides.length),visible=this.visibleIndices(slides.length,current),format=getNumberFormat(this.effectiveLocale),messages=slides.flatMap((slide,index)=>{if(!visible.has(index))return[];if(isAccessibilitySubtreeExcluded(slide))return[];const slideTextVisible=!isAccessibilityVisibilityHidden(slide),authoredLabel=slideTextVisible?this.snapshots.get(slide)?.label?.trim():"";if(authoredLabel)return[authoredLabel];const position=this.localize("carouselSlidePosition",void 0,{index:format.format(index+1),total:format.format(slides.length)}),content=Array.from(slide.childNodes).map(node=>composedAccessibilityText(node,slideTextVisible)).join(" ").replace(/\s+/g," ").trim();return!slideTextVisible&&!content?[]:[content&&content!==position?this.localize("carouselSlideAnnouncement",void 0,{position,content}):position]});this.announcementSink?.announce(messages.join(this.localize("carouselSlideAnnouncementSeparator")))}restoreAttribute(slide,name,value){value===null?slide.removeAttribute(name):slide.setAttribute(name,value)}snapshotSlide(slide){return{hidden:slide.hidden,inert:slide.inert,role:slide.getAttribute("role"),label:slide.getAttribute("aria-label"),roleDescription:slide.getAttribute("aria-roledescription"),ariaHidden:slide.getAttribute("aria-hidden")}}adoptChanges(slide,snapshot){const applied=this.appliedSnapshots.get(slide);if(!applied)return!1;const current=this.snapshotSlide(slide);let changed=!1;for(const key of SLIDE_SNAPSHOT_KEYS)current[key]!==applied[key]&&(snapshot[key]=current[key],changed=!0);return changed}restoreSlide(slide,snapshot){slide.hidden=snapshot.hidden,slide.inert=snapshot.inert,this.restoreAttribute(slide,"role",snapshot.role),this.restoreAttribute(slide,"aria-label",snapshot.label),this.restoreAttribute(slide,"aria-roledescription",snapshot.roleDescription),this.restoreAttribute(slide,"aria-hidden",snapshot.ariaHidden)}restoreSlides(){for(const[slide,snapshot]of this.snapshots)this.adoptChanges(slide,snapshot),this.restoreSlide(slide,snapshot);this.snapshots.clear()}syncSlides(){const slides=this.slideElements(),assigned=new Set(slides);for(const[slide,snapshot]of this.snapshots)this.adoptChanges(slide,snapshot)&&(this.loopClonesDirty=!0),assigned.has(slide)||(this.restoreSlide(slide,snapshot),this.snapshots.delete(slide));const current=this.normalizedIndex(slides.length);if(this.currentSlide!==current){this.currentSlide=current;const slide=slides[current];slide&&this.emit("lr-slide-change",{index:current,slide})}const visible=this.visibleIndices(slides.length,current);this.repairFocusBeforeSlideExclusion(slides,visible);const format=getNumberFormat(this.effectiveLocale);slides.forEach((slide,slideIndex)=>{const existing=this.snapshots.get(slide),snapshot=existing??this.snapshotSlide(slide);existing||this.snapshots.set(slide,snapshot),slide.localName===tag("carousel-item")?(this.restoreAttribute(slide,"role",snapshot.role??"group"),this.restoreAttribute(slide,"aria-roledescription",snapshot.roleDescription??this.localize("carouselSlide")),this.restoreAttribute(slide,"aria-label",snapshot.label??this.localize("carouselSlidePosition",void 0,{index:format.format(slideIndex+1),total:format.format(slides.length)}))):(this.restoreAttribute(slide,"role",snapshot.role),this.restoreAttribute(slide,"aria-roledescription",snapshot.roleDescription),this.restoreAttribute(slide,"aria-label",snapshot.label)),slide.hidden=snapshot.hidden,visible.has(slideIndex)?(slide.inert=snapshot.inert,this.restoreAttribute(slide,"aria-hidden",snapshot.ariaHidden)):(slide.inert=!0,slide.setAttribute("aria-hidden","true")),this.appliedSnapshots.set(slide,this.snapshotSlide(slide))})}repairFocusBeforeSlideExclusion(slides,visible){const active=deepActiveElementIn(this.ownerDocument),focusedIndex=slides.findIndex(slide=>composedContains(slide,active)),focusedSlideWillBeExcluded=focusedIndex>=0&&!visible.has(focusedIndex),focusedSlideWasRemoved=focusedIndex<0&&this.lastFocusedSlide!==void 0&&!this.lastFocusedSlide.isConnected&&(active===null||active===this.ownerDocument.body);!focusedSlideWillBeExcluded&&!focusedSlideWasRemoved||(this.viewport?.focus(),this.lastFocusedSlide=void 0)}handleSlidesChanged(){const count=this.slideElements().length,active=shadowFocusTarget(this);if(active?.matches('[part~="pagination-item"]')){const children=active.parentElement.children,pages=this.pageTargets(count).length;(pages<2||[...children].indexOf(active)>=pages)&&(pages>1?children[pages-1]:this.viewport)?.focus()}else active?.matches('[part~="navigation-button"]')&&(!this.navigation||count<=this.pageSize(count))&&this.viewport?.focus();if(this._slides!==count){const previous=this._slides;this._slides=count,this.requestUpdate("slides",previous)}this.loopClonesDirty=!0,this.syncSlides(),this.syncLoopClones(),this.loopClonesDirty=!1,this.restartAutoplay(),this.requestUpdate()}prepareClone(original,index,side){if([original,...Array.from(original.querySelectorAll("*"))].some(element=>element.namespaceURI!=="http://www.w3.org/1999/xhtml"||element.localName.includes("-")||LOOP_SNAPSHOT_UNSAFE_TAGS.has(element.localName)))return;const clone=original.cloneNode(!0),descendants=[clone,...Array.from(clone.querySelectorAll("*"))];for(const descendant of descendants)descendant.removeAttribute("id"),descendant.removeAttribute("name"),descendant.removeAttribute("form"),descendant.removeAttribute("for"),descendant.removeAttribute("aria-controls"),descendant.removeAttribute("aria-describedby"),descendant.removeAttribute("aria-labelledby");return clone.removeAttribute("slot"),clone.dataset.carouselClone=side,clone.dataset.carouselIndex=String(index),clone.inert=!0,clone.setAttribute("aria-hidden","true"),clone}syncLoopClones(){const before=this.beforeClones,after=this.afterClones;if(!before||!after)return;before.replaceChildren(),after.replaceChildren();const slides=this.slideElements();if(!this.loop||slides.length<2)return;const cloneCount=Math.min(slides.length,Math.max(this.pageSize(slides.length),this.moveSize(slides.length))),beforeStart=slides.length-cloneCount;for(let index=beforeStart;index<slides.length;index+=1){const clone=this.prepareClone(slides[index],index,"before");clone&&before.append(clone)}for(let index=0;index<cloneCount;index+=1){const clone=this.prepareClone(slides[index],index,"after");clone&&after.append(clone)}}cloneFor(side,index){return(side==="before"?this.beforeClones:this.afterClones)?.querySelector(`[data-carousel-index="${index}"]`)??void 0}changeTo(index,behavior="smooth",origin="manual"){const slides=this.slideElements(),count=slides.length;if(count===0||!Number.isFinite(index))return;const requested=Math.trunc(index);let next,loopSide;if(this.loop?(next=(requested%count+count)%count,requested<0?loopSide="before":requested>=count&&(loopSide="after")):next=Math.min(this.maxStartIndex(count),Math.max(0,requested)),next===this.currentSlide)return;this.requestedBehavior=behavior,this.loopSide=loopSide;const previousOrigin=this.changeOrigin;this.changeOrigin=origin;try{this.currentSlide=next}finally{this.changeOrigin=previousOrigin}this.emit("lr-slide-change",{index:next,slide:slides[next]})}next(behavior="smooth"){this.changeTo(this.currentSlide+this.moveSize(),behavior)}previous(behavior="smooth"){this.changeTo(this.currentSlide-this.moveSize(),behavior)}goToSlide(index,behavior="smooth"){this.changeTo(index,behavior)}addSlide(slide){slide?.nodeType!==1||slide?.namespaceURI!=="http://www.w3.org/1999/xhtml"||(this.append(slide),this.queueOwnerMicrotask(()=>{this.isConnected&&this.handleSlidesChanged()}))}removeSlide(index){if(!Number.isFinite(index))return;const target=this.slideElements()[Math.trunc(index)];target&&(target.remove(),this.queueOwnerMicrotask(()=>{this.isConnected&&this.handleSlidesChanged()}))}stopAutoplay(){this.timer!==void 0&&this.timerWindow?.clearInterval(this.timer),this.timer=void 0,this.timerWindow=void 0}restartAutoplay(){this.stopAutoplay();const count=this.slideElements().length,doc=this.visibilityDocument??this.ownerDocument,view=doc.defaultView;if(!this.isConnected||!view||!this.autoplay||this.reduceMotion||this.pointerInteracting||this.focusInteracting||this.slideOverlay.open||this.dragPointerId!==void 0||doc.visibilityState!=="visible"||count<=this.pageSize(count))return;const interval=finiteDuration(this.autoplayInterval,3e3,1e3);this.timerWindow=view,this.timer=view.setInterval(()=>{this.loop||this.currentSlide<this.maxStartIndex()?this.changeTo(this.currentSlide+this.moveSize(),"smooth","autoplay"):this.stopAutoplay()},interval)}scrollPaddingStart(){const rect=this.scrollHintProbe?.getBoundingClientRect();if(!rect)return 0;const pixels=this.effectiveOrientation()==="vertical"?rect.height:rect.width;return Number.isFinite(pixels)?pixels:0}axisOffsetOf(slide,viewport){const viewportRect=viewport.getBoundingClientRect(),slideRect=slide.getBoundingClientRect(),padding=this.scrollPaddingStart();return this.effectiveOrientation()==="vertical"?slideRect.top-(viewportRect.top+padding):this.effectiveDirection==="rtl"?slideRect.right-(viewportRect.right-padding):slideRect.left-(viewportRect.left+padding)}scrollByAxis(viewport,distance,behavior){this.effectiveOrientation()==="vertical"?viewport.scrollBy({top:distance,behavior}):viewport.scrollBy({left:distance,behavior})}restingSlide(){const viewport=this.viewport,slides=this.slideElements();if(!viewport||slides.length===0)return;const candidates=slides.map((element,index)=>({element,index}));for(const clone of this.shadowRoot?.querySelectorAll("[data-carousel-clone]")??[]){const index=Number(clone.dataset.carouselIndex),cloneSide=clone.dataset.carouselClone;Number.isInteger(index)&&index>=0&&index<slides.length&&(cloneSide==="before"||cloneSide==="after")&&candidates.push({element:clone,index,cloneSide})}let nearest,nearestDistance=Number.POSITIVE_INFINITY;for(const candidate of candidates){const distance=Math.abs(this.axisOffsetOf(candidate.element,viewport));distance<nearestDistance&&(nearestDistance=distance,nearest=candidate)}return nearest}alignToActiveSlide(){const viewport=this.viewport,targetIndex=this.normalizedIndex(),realSlide=this.slideElements()[targetIndex];if(!viewport||!realSlide)return;const loopSide=this.loopSide,requestedBehavior=this.requestedBehavior;this.loopSide=void 0,this.requestedBehavior=void 0;const target=loopSide?this.cloneFor(loopSide,targetIndex)??realSlide:realSlide,offset=this.axisOffsetOf(target,viewport);if(Math.round(offset)===0){this.clearAlignment();return}this.alignIndex=targetIndex,this.alignTarget=target;const behavior=this.motionAwareScrollBehavior(requestedBehavior??"smooth",!0);this.scrollByAxis(viewport,offset,behavior)}motionAwareScrollBehavior(requested,instantBeforeFirstAlignment=!1){return this.reduceMotion||instantBeforeFirstAlignment&&!this.hasAlignedOnce?"instant":requested}cancelScrollSettle(){this.scrollSettle.cancel()}clearAlignment(){this.alignTarget=void 0,this.alignIndex=void 0,this.loopSide=void 0,this.requestedBehavior=void 0}takeOverViewport(){this.clearAlignment()}targetsInteractiveContent(event,includeSlideEditors=!1){const slides=new Set(this.slideElements()),slideRoot=event.composedPath().find(target=>typeof target=="object"&&target!==null&&target.nodeType===1&&slides.has(target));return keyEventOwnedByInnerControl(event,{container:!includeSlideEditors&&slideRoot?slideRoot:this,ownsButtons:!0,ownsCustomElements:!0,ignoreCustomElements:slides})}finishDrag(pointerId,canceled){if(pointerId!==this.dragPointerId)return;const viewport=this.viewport,moved=this.dragMoved;if(this.dragPointerId=void 0,this.dragMoved=!1,viewport?.removeAttribute("data-dragging"),viewport?.hasPointerCapture(pointerId))try{viewport.releasePointerCapture(pointerId)}catch{}if(moved){this.suppressClick=!0,this.cancelClickSuppression();const view=this.ownerDocument.defaultView;view?(this.clickTimerWindow=view,this.clickTimer=view.setTimeout(()=>{this.suppressClick=!1,this.clickTimer=void 0,this.clickTimerWindow=void 0},0)):this.suppressClick=!1}if(canceled&&viewport){const active=this.slideElements()[this.normalizedIndex()];active&&this.scrollByAxis(viewport,this.axisOffsetOf(active,viewport),this.motionAwareScrollBehavior("smooth"))}else canceled||this.onViewportScroll();this.matches(":hover")||(this.pointerInteracting=!1),this.restartAutoplay()}cancelClickSuppression(){this.clickTimer!==void 0&&this.clickTimerWindow?.clearTimeout(this.clickTimer),this.clickTimer=void 0,this.clickTimerWindow=void 0}cancelDrag(realign){this.dragPointerId!==void 0&&this.finishDrag(this.dragPointerId,realign)}computedSlideBasis(perPage){return perPage===1?"100%":`calc((100% - (${perPage-1} * var(--slide-gap, var(--lr-space-m)))) / ${perPage})`}render(){const count=this.slideElements().length,current=this.normalizedIndex(count),pageTargets=this.pageTargets(count),exactCurrentPage=pageTargets.indexOf(current),currentPage=exactCurrentPage>=0?exactCurrentPage:pageTargets.reduce((nearest,target,pageIndex)=>Math.abs(target-current)<Math.abs(pageTargets[nearest]-current)?pageIndex:nearest,0),hasNavigation=this.navigation&&count>this.pageSize(count),hasPagination=this.pagination&&pageTargets.length>1,label=this.hostAccessibleLabel??this.localize("carouselLabel"),numberFormat=getNumberFormat(this.effectiveLocale),orientation=this.effectiveOrientation(),perPage=this.pageSize(count);return html`<section
1
+ import{__decorate}from"tslib";import{prefersReducedMotion}from"../../../internal/motion.js";import{observeReducedMotion}from"../../../internal/motion-observer.js";import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isAccessibilitySubtreeExcluded,isAccessibilityVisible,isAccessibilityVisibilityHidden}from"../../../internal/accessibility-visibility.js";import{deepActiveElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{composedAccessibilityText}from"../../../internal/announcement-text.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{finiteDuration,finiteInteger}from"../../../internal/numbers.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{keyEventOwnedByInnerControl}from"../../../internal/hotkey.js";import{composedContains}from"../../../internal/overlay-manager.js";import{SlottedOverlayController}from"../../../internal/slotted-overlay-controller.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{tag}from"../../../internal/prefix.js";import{styles}from"./carousel.styles.js";import{LYRA_DEFAULT_carousel,LYRA_DEFAULT_carouselGoTo,LYRA_DEFAULT_carouselIndicators,LYRA_DEFAULT_carouselLabel,LYRA_DEFAULT_carouselSlide,LYRA_DEFAULT_carouselSlideAnnouncement,LYRA_DEFAULT_carouselSlideAnnouncementSeparator,LYRA_DEFAULT_carouselSlidePosition}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_next,LYRA_DEFAULT_previous}from"../../../internal/default-strings/shared.generated.js";const SCROLL_SETTLE_MS=120,LOOP_SNAPSHOT_UNSAFE_TAGS=new Set(["audio","canvas","embed","form","iframe","img","input","link","object","picture","script","select","source","style","textarea","track","video"]),CAROUSEL_MANAGED_SLIDE_ATTRIBUTES=new Set(["aria-hidden","aria-label","aria-roledescription","hidden","inert","role"]),SLIDE_SNAPSHOT_KEYS=["hidden","inert","role","label","roleDescription","ariaHidden"];class LyraCarousel extends LyraElement{static{this.defaultStrings={...super.defaultStrings,carousel:LYRA_DEFAULT_carousel,carouselGoTo:LYRA_DEFAULT_carouselGoTo,carouselIndicators:LYRA_DEFAULT_carouselIndicators,carouselLabel:LYRA_DEFAULT_carouselLabel,carouselSlide:LYRA_DEFAULT_carouselSlide,carouselSlideAnnouncement:LYRA_DEFAULT_carouselSlideAnnouncement,carouselSlideAnnouncementSeparator:LYRA_DEFAULT_carouselSlideAnnouncementSeparator,carouselSlidePosition:LYRA_DEFAULT_carouselSlidePosition,next:LYRA_DEFAULT_next,previous:LYRA_DEFAULT_previous}}static{this.styles=[LyraElement.styles,styles]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"currentslide"])]}get currentSlide(){return this._currentSlide}set currentSlide(value){this.setCurrentSlideState(value)}get pagination(){return this._pagination}set pagination(value){this.setPaginationState(!!value)}get slides(){return this._slides}constructor(){super(),this._currentSlide=0,this._pagination=!1,this._slides=0,this.loop=!1,this.autoplay=!1,this.autoplayInterval=3e3,this.navigation=!1,this.orientation="horizontal",this.mouseDragging=!1,this.slidesPerPage=1,this.slidesPerMove=1,this.hostAccessibleLabel=null,this.reduceMotion=!1,this.snapshots=new Map,this.appliedSnapshots=new WeakMap,this.scrollSettle=new DebounceController(SCROLL_SETTLE_MS,()=>this.settleScrolledSlide(),()=>this.ownerDocument.defaultView),this.adoptingScrolledSlide=!1,this.hasAlignedOnce=!1,this.loopClonesDirty=!0,this.pointerInteracting=!1,this.focusInteracting=!1,this.slideOverlay=new SlottedOverlayController(this,()=>this.renderRoot?.querySelector("slot:not([name])")),this.slideOverlayWasOpen=!1,this.dragStartCoordinate=0,this.dragStartScroll=0,this.dragMoved=!1,this.suppressClick=!1,this.announcementsArmed=!1,this.changeOrigin="manual",this.manualPending=!1,this.observerGeneration=0,this.passiveTakeOver={handleEvent:()=>this.takeOverViewport(),passive:!0},this.onMotionPreferenceChange=reduced=>{this.reduceMotion=reduced,this.restartAutoplay(),this.requestUpdate()},this.onVisibilityChange=()=>{this.restartAutoplay()},this.onSlotChange=()=>{this.handleSlidesChanged()},this.onViewportScroll=()=>{this.cancelScrollSettle(),this.ownerDocument.defaultView&&this.scrollSettle.push(void 0)},this.onViewportScrollEnd=()=>{this.cancelScrollSettle(),this.settleScrolledSlide()},this.settleScrolledSlide=()=>{if(!this.isConnected)return;const viewport=this.viewport;if(!viewport)return;if(this.alignTarget){if(Math.abs(this.axisOffsetOf(this.alignTarget,viewport))>2)return;const cloneSide=this.alignTarget.dataset.carouselClone;if(cloneSide==="before"||cloneSide==="after"){const realSlide=this.slideElements()[this.alignIndex??-1];if(realSlide){this.alignTarget=realSlide,this.scrollByAxis(viewport,this.axisOffsetOf(realSlide,viewport),"instant");return}}this.clearAlignment();return}const resting=this.restingSlide();if(!resting)return;const changed=resting.index!==this.currentSlide;!changed&&!resting.cloneSide||(this.adoptingScrolledSlide=!0,changed&&(this.currentSlide=resting.index,this.emit("lr-slide-change",{index:resting.index,slide:this.slideElements()[resting.index]})),this.updateComplete.then(()=>{if(resting.cloneSide&&this.isConnected&&this.viewport){const realSlide=this.slideElements()[resting.index];realSlide&&this.scrollByAxis(this.viewport,this.axisOffsetOf(realSlide,this.viewport),"instant")}this.adoptingScrolledSlide=!1}))},this.onViewportPointerEnter=()=>{this.pointerInteracting=!0,this.restartAutoplay()},this.onViewportPointerLeave=()=>{this.dragPointerId===void 0&&(this.pointerInteracting=!1,this.restartAutoplay())},this.onViewportFocusIn=event=>{this.focusInteracting=!0;const slides=new Set(this.slideElements()),focusedSlide=event.composedPath().find(candidate=>candidate.nodeType===1&&slides.has(candidate));focusedSlide&&(this.lastFocusedSlide=focusedSlide),this.restartAutoplay()},this.onViewportFocusOut=()=>{this.queueOwnerMicrotask(()=>{if(!this.isConnected)return;const active=deepActiveElementIn(this.ownerDocument);this.lastFocusedSlide&&!composedContains(this.lastFocusedSlide,active)&&(this.lastFocusedSlide.isConnected||active!==null&&active!==this.ownerDocument.body)&&(this.lastFocusedSlide=void 0),this.focusInteracting=this.matches(":focus-within"),this.restartAutoplay()})},this.onViewportPointerDown=event=>{if(!this.mouseDragging||event.pointerType!=="mouse"||!event.isPrimary||event.button!==0||this.dragPointerId!==void 0||this.targetsInteractiveContent(event))return;this.takeOverViewport();const viewport=this.viewport;if(viewport){this.dragPointerId=event.pointerId,this.dragStartCoordinate=this.effectiveOrientation()==="vertical"?event.clientY:event.clientX,this.dragStartScroll=this.effectiveOrientation()==="vertical"?viewport.scrollTop:viewport.scrollLeft,this.dragMoved=!1,viewport.setAttribute("data-dragging","");try{viewport.setPointerCapture(event.pointerId)}catch{}this.restartAutoplay()}},this.onViewportPointerMove=event=>{if(event.pointerId!==this.dragPointerId)return;const viewport=this.viewport;if(!viewport)return;const delta=(this.effectiveOrientation()==="vertical"?event.clientY:event.clientX)-this.dragStartCoordinate;Math.abs(delta)>2&&(this.dragMoved=!0),this.dragMoved&&(event.preventDefault(),this.effectiveOrientation()==="vertical"?viewport.scrollTo({top:this.dragStartScroll-delta,behavior:"instant"}):viewport.scrollTo({left:this.dragStartScroll-delta,behavior:"instant"}))},this.onViewportPointerUp=event=>{this.finishDrag(event.pointerId,!1)},this.onViewportPointerCancel=event=>{this.finishDrag(event.pointerId,!0)},this.onViewportLostPointerCapture=event=>{this.finishDrag(event.pointerId,!0)},this.onViewportClick=event=>{this.suppressClick&&(event.preventDefault(),event.stopImmediatePropagation())},this.onViewportKeyDown=event=>{if(this.targetsInteractiveContent(event,!0))return;const vertical=this.effectiveOrientation()==="vertical",rtl=this.effectiveDirection==="rtl",forwardKey=vertical?"ArrowDown":rtl?"ArrowLeft":"ArrowRight",backwardKey=vertical?"ArrowUp":rtl?"ArrowRight":"ArrowLeft";event.key===forwardKey?(event.preventDefault(),this.next()):event.key===backwardKey?(event.preventDefault(),this.previous()):event.key==="Home"?(event.preventDefault(),this.goToSlide(0)):event.key==="End"&&(event.preventDefault(),this.goToSlide(this.loop?this.slideElements().length-1:this.maxStartIndex()))},this.requestUpdate("currentSlide",void 0),this.requestUpdate("pagination",void 0)}attributeChangedCallback(name,oldValue,newValue){if(name==="currentslide"){oldValue!==newValue&&(this.currentSlide=finiteInteger(Number(newValue??0),0));return}super.attributeChangedCallback(name,oldValue,newValue),name==="current-slide"&&newValue===null&&oldValue!==newValue&&this.hasAttribute("currentslide")&&(this.currentSlide=finiteInteger(Number(this.getAttribute("currentslide")??0),0))}connectedCallback(){this.hasAttribute("current-slide")&&(this.currentSlide=finiteInteger(Number(this.getAttribute("current-slide")??0),0)),super.connectedCallback(),this.announcementSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.announcementsArmed=!1,this.manualPending=!1,this.reduceMotion=prefersReducedMotion(this),this.stopMotionWatch=observeReducedMotion(this,this.onMotionPreferenceChange),this.visibilityDocument=this.ownerDocument,this.visibilityDocument.addEventListener("visibilitychange",this.onVisibilityChange),this.armSlideContentObserver(),this.restartAutoplay(),this.hasUpdated&&this.queueOwnerMicrotask(()=>{this.isConnected&&this.handleSlidesChanged()})}disconnectedCallback(){this.announcementSink?.release(),this.announcementSink=void 0,this.announcementsArmed=!1,this.manualPending=!1,this.cancelDrag(!1),this.stopAutoplay(),this.cancelScrollSettle(),this.cancelClickSuppression(),this.suppressClick=!1,this.pointerInteracting=!1,this.focusInteracting=!1,this.hasAlignedOnce=!1,this.clearAlignment(),this.stopMotionWatch?.(),this.stopMotionWatch=void 0,this.visibilityDocument?.removeEventListener("visibilitychange",this.onVisibilityChange),this.visibilityDocument=void 0,this.resetSlideContentObserver(),this.restoreSlides(),this.lastFocusedSlide=void 0,super.disconnectedCallback()}armSlideContentObserver(){const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;this.resetSlideContentObserver();const generation=this.observerGeneration,observer=new MutationObserverCtor(records=>{this.observer!==observer||this.observerDocument!==ownerDocument||this.observerGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||!records.some(record=>{if(record.target===this)return record.type!=="attributes";if(record.type!=="attributes"||!CAROUSEL_MANAGED_SLIDE_ATTRIBUTES.has(record.attributeName??""))return this.loop;const slide=record.target,snapshot=this.snapshots.get(slide);return snapshot?this.adoptChanges(slide,snapshot):!1})||(this.loop&&(this.loopClonesDirty=!0),this.syncSlides(),this.requestUpdate())});this.observer=observer,this.observerDocument=ownerDocument,observer.observe(this,{attributes:!0,characterData:!0,childList:!0,subtree:!0})}resetSlideContentObserver(){this.observerGeneration+=1,this.observer?.disconnect(),this.observer=void 0,this.observerDocument=void 0}willUpdate(changed){super.willUpdate(changed);const active=shadowFocusTarget(this);if(this.focusedNavButton=active?.matches('[part~="navigation-button"]')?active:void 0,(changed.has("currentSlide")||changed.has("slidesPerPage"))&&this.slideSlot){const normalized=this.normalizedIndex();if(this.currentSlide!==normalized){const forcedBySibling=changed.has("slidesPerPage")&&!changed.has("currentSlide");if(this.currentSlide=normalized,forcedBySibling){const slide=this.slideElements()[normalized];slide&&this.emit("lr-slide-change",{index:normalized,slide})}}}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.slideSlot;this.queueOwnerMicrotask(()=>{collectInitialSlotAssignment(slot,()=>this.handleSlidesChanged())})}updated(changed){super.updated(changed);const shouldAnnounceActivePage=this.announcementsArmed&&(this.manualPending||changed.has("slidesPerPage"));this.slideOverlay.open!==this.slideOverlayWasOpen&&(this.slideOverlayWasOpen=this.slideOverlay.open,this.restartAutoplay()),this.focusedNavButton?.disabled&&(this.focusedNavButton.parentElement.querySelector("button:not(:disabled)")??this.viewport)?.focus(),this.syncSlides(),(this.loopClonesDirty||changed.has("loop")||changed.has("slidesPerPage")||changed.has("slidesPerMove"))&&(this.syncLoopClones(),this.loopClonesDirty=!1),(changed.has("autoplay")||changed.has("autoplayInterval")||changed.has("loop")||changed.has("slidesPerPage"))&&this.restartAutoplay(),!this.adoptingScrolledSlide&&(changed.has("currentSlide")||changed.has("slidesPerPage")||changed.has("orientation")||!this.hasAlignedOnce)&&this.alignToActiveSlide(),this.hasAlignedOnce=!0,shouldAnnounceActivePage&&this.announceActivePage(),this.manualPending=!1,this.announcementsArmed=!0}setCurrentSlideState(value){const old=this._currentSlide,next=finiteInteger(value,0);old!==next&&(this._currentSlide=next,this.changeOrigin==="manual"&&(this.manualPending=!0),this.requestUpdate("currentSlide",old))}setPaginationState(value){const old=this._pagination;old!==value&&(this._pagination=value,this.requestUpdate("pagination",old))}queueOwnerMicrotask(callback){const view=this.ownerDocument.defaultView;view?view.queueMicrotask(callback):queueMicrotask(callback)}effectiveOrientation(){return this.orientation==="vertical"?"vertical":"horizontal"}slideElements(){return(this.slideSlot?.assignedElements({flatten:!0})??[]).filter(element=>element.nodeType===1&&element.namespaceURI==="http://www.w3.org/1999/xhtml")}pageSize(count=this.slideElements().length){return finiteInteger(this.slidesPerPage,1,1,Math.max(1,count))}moveSize(count=this.slideElements().length){return finiteInteger(this.slidesPerMove,1,1,this.pageSize(count))}maxStartIndex(count=this.slideElements().length){return Math.max(0,count-this.pageSize(count))}normalizedIndex(count=this.slideElements().length){if(count===0)return 0;const max=this.loop?count-1:this.maxStartIndex(count);return finiteInteger(this.currentSlide,0,0,max)}pageTargets(count=this.slideElements().length){if(count===0)return[];if(this.loop)return Array.from({length:count},(_unused,index)=>index);const max=this.maxStartIndex(count),move=this.moveSize(count),targets=[0];for(let target=move;target<max;target+=move)targets.push(target);return max>0&&targets.at(-1)!==max&&targets.push(max),targets}visibleIndices(count,current){const visible=new Set,perPage=this.pageSize(count);for(let offset=0;offset<perPage;offset+=1){const index=this.loop?(current+offset)%count:current+offset;index>=0&&index<count&&visible.add(index)}return visible}announceActivePage(){if(!isAccessibilityVisible(this))return;const slides=this.slideElements();if(slides.length===0)return;const current=this.normalizedIndex(slides.length),visible=this.visibleIndices(slides.length,current),format=getNumberFormat(this.effectiveLocale),messages=slides.flatMap((slide,index)=>{if(!visible.has(index))return[];if(isAccessibilitySubtreeExcluded(slide))return[];const slideTextVisible=!isAccessibilityVisibilityHidden(slide),authoredLabel=slideTextVisible?this.snapshots.get(slide)?.label?.trim():"";if(authoredLabel)return[authoredLabel];const position=this.localize("carouselSlidePosition",void 0,{index:format.format(index+1),total:format.format(slides.length)}),content=Array.from(slide.childNodes).map(node=>composedAccessibilityText(node,slideTextVisible)).join(" ").replace(/\s+/g," ").trim();return!slideTextVisible&&!content?[]:[content&&content!==position?this.localize("carouselSlideAnnouncement",void 0,{position,content}):position]});this.announcementSink?.announce(messages.join(this.localize("carouselSlideAnnouncementSeparator")))}restoreAttribute(slide,name,value){value===null?slide.removeAttribute(name):slide.setAttribute(name,value)}snapshotSlide(slide){return{hidden:slide.hidden,inert:slide.inert,role:slide.getAttribute("role"),label:slide.getAttribute("aria-label"),roleDescription:slide.getAttribute("aria-roledescription"),ariaHidden:slide.getAttribute("aria-hidden")}}adoptChanges(slide,snapshot){const applied=this.appliedSnapshots.get(slide);if(!applied)return!1;const current=this.snapshotSlide(slide);let changed=!1;for(const key of SLIDE_SNAPSHOT_KEYS)current[key]!==applied[key]&&(snapshot[key]=current[key],changed=!0);return changed}restoreSlide(slide,snapshot){slide.hidden=snapshot.hidden,slide.inert=snapshot.inert,this.restoreAttribute(slide,"role",snapshot.role),this.restoreAttribute(slide,"aria-label",snapshot.label),this.restoreAttribute(slide,"aria-roledescription",snapshot.roleDescription),this.restoreAttribute(slide,"aria-hidden",snapshot.ariaHidden)}restoreSlides(){for(const[slide,snapshot]of this.snapshots)this.adoptChanges(slide,snapshot),this.restoreSlide(slide,snapshot);this.snapshots.clear()}syncSlides(){const slides=this.slideElements(),assigned=new Set(slides);for(const[slide,snapshot]of this.snapshots)this.adoptChanges(slide,snapshot)&&(this.loopClonesDirty=!0),assigned.has(slide)||(this.restoreSlide(slide,snapshot),this.snapshots.delete(slide));const current=this.normalizedIndex(slides.length);if(this.currentSlide!==current){this.currentSlide=current;const slide=slides[current];slide&&this.emit("lr-slide-change",{index:current,slide})}const visible=this.visibleIndices(slides.length,current);this.repairFocusBeforeSlideExclusion(slides,visible);const format=getNumberFormat(this.effectiveLocale);slides.forEach((slide,slideIndex)=>{const existing=this.snapshots.get(slide),snapshot=existing??this.snapshotSlide(slide);existing||this.snapshots.set(slide,snapshot),slide.localName===tag("carousel-item")?(this.restoreAttribute(slide,"role",snapshot.role??"group"),this.restoreAttribute(slide,"aria-roledescription",snapshot.roleDescription??this.localize("carouselSlide")),this.restoreAttribute(slide,"aria-label",snapshot.label??this.localize("carouselSlidePosition",void 0,{index:format.format(slideIndex+1),total:format.format(slides.length)}))):(this.restoreAttribute(slide,"role",snapshot.role),this.restoreAttribute(slide,"aria-roledescription",snapshot.roleDescription),this.restoreAttribute(slide,"aria-label",snapshot.label)),slide.hidden=snapshot.hidden,visible.has(slideIndex)?(slide.inert=snapshot.inert,this.restoreAttribute(slide,"aria-hidden",snapshot.ariaHidden)):(slide.inert=!0,slide.setAttribute("aria-hidden","true")),this.appliedSnapshots.set(slide,this.snapshotSlide(slide))})}repairFocusBeforeSlideExclusion(slides,visible){const active=deepActiveElementIn(this.ownerDocument),focusedIndex=slides.findIndex(slide=>composedContains(slide,active)),focusedSlideWillBeExcluded=focusedIndex>=0&&!visible.has(focusedIndex),focusedSlideWasRemoved=focusedIndex<0&&this.lastFocusedSlide!==void 0&&!this.lastFocusedSlide.isConnected&&(active===null||active===this.ownerDocument.body);!focusedSlideWillBeExcluded&&!focusedSlideWasRemoved||(this.viewport?.focus(),this.lastFocusedSlide=void 0)}handleSlidesChanged(){const count=this.slideElements().length,active=shadowFocusTarget(this);if(active?.matches('[part~="pagination-item"]')){const children=active.parentElement.children,pages=this.pageTargets(count).length;(pages<2||[...children].indexOf(active)>=pages)&&(pages>1?children[pages-1]:this.viewport)?.focus()}else active?.matches('[part~="navigation-button"]')&&(!this.navigation||count<=this.pageSize(count))&&this.viewport?.focus();if(this._slides!==count){const previous=this._slides;this._slides=count,this.requestUpdate("slides",previous)}this.loopClonesDirty=!0,this.syncSlides(),this.syncLoopClones(),this.loopClonesDirty=!1,this.restartAutoplay(),this.requestUpdate()}prepareClone(original,index,side){if([original,...Array.from(original.querySelectorAll("*"))].some(element=>element.namespaceURI!=="http://www.w3.org/1999/xhtml"||element.localName.includes("-")||LOOP_SNAPSHOT_UNSAFE_TAGS.has(element.localName)))return;const clone=original.cloneNode(!0),descendants=[clone,...Array.from(clone.querySelectorAll("*"))];for(const descendant of descendants)descendant.removeAttribute("id"),descendant.removeAttribute("name"),descendant.removeAttribute("form"),descendant.removeAttribute("for"),descendant.removeAttribute("aria-controls"),descendant.removeAttribute("aria-describedby"),descendant.removeAttribute("aria-labelledby");return clone.removeAttribute("slot"),clone.dataset.carouselClone=side,clone.dataset.carouselIndex=String(index),clone.inert=!0,clone.setAttribute("aria-hidden","true"),clone}syncLoopClones(){const before=this.beforeClones,after=this.afterClones;if(!before||!after)return;before.replaceChildren(),after.replaceChildren();const slides=this.slideElements();if(!this.loop||slides.length<2)return;const cloneCount=Math.min(slides.length,Math.max(this.pageSize(slides.length),this.moveSize(slides.length))),beforeStart=slides.length-cloneCount;for(let index=beforeStart;index<slides.length;index+=1){const clone=this.prepareClone(slides[index],index,"before");clone&&before.append(clone)}for(let index=0;index<cloneCount;index+=1){const clone=this.prepareClone(slides[index],index,"after");clone&&after.append(clone)}}cloneFor(side,index){return(side==="before"?this.beforeClones:this.afterClones)?.querySelector(`[data-carousel-index="${index}"]`)??void 0}changeTo(index,behavior="smooth",origin="manual"){const slides=this.slideElements(),count=slides.length;if(count===0||!Number.isFinite(index))return;const requested=Math.trunc(index);let next,loopSide;if(this.loop?(next=(requested%count+count)%count,requested<0?loopSide="before":requested>=count&&(loopSide="after")):next=Math.min(this.maxStartIndex(count),Math.max(0,requested)),next===this.currentSlide)return;this.requestedBehavior=behavior,this.loopSide=loopSide;const previousOrigin=this.changeOrigin;this.changeOrigin=origin;try{this.currentSlide=next}finally{this.changeOrigin=previousOrigin}this.emit("lr-slide-change",{index:next,slide:slides[next]})}next(behavior="smooth"){this.changeTo(this.currentSlide+this.moveSize(),behavior)}previous(behavior="smooth"){this.changeTo(this.currentSlide-this.moveSize(),behavior)}goToSlide(index,behavior="smooth"){this.changeTo(index,behavior)}addSlide(slide){slide?.nodeType!==1||slide?.namespaceURI!=="http://www.w3.org/1999/xhtml"||(this.append(slide),this.queueOwnerMicrotask(()=>{this.isConnected&&this.handleSlidesChanged()}))}removeSlide(index){if(!Number.isFinite(index))return;const target=this.slideElements()[Math.trunc(index)];target&&(target.remove(),this.queueOwnerMicrotask(()=>{this.isConnected&&this.handleSlidesChanged()}))}stopAutoplay(){this.timer!==void 0&&this.timerWindow?.clearInterval(this.timer),this.timer=void 0,this.timerWindow=void 0}restartAutoplay(){this.stopAutoplay();const count=this.slideElements().length,doc=this.visibilityDocument??this.ownerDocument,view=doc.defaultView;if(!this.isConnected||!view||!this.autoplay||this.reduceMotion||this.pointerInteracting||this.focusInteracting||this.slideOverlay.open||this.dragPointerId!==void 0||doc.visibilityState!=="visible"||count<=this.pageSize(count))return;const interval=finiteDuration(this.autoplayInterval,3e3,1e3);this.timerWindow=view,this.timer=view.setInterval(()=>{this.loop||this.currentSlide<this.maxStartIndex()?this.changeTo(this.currentSlide+this.moveSize(),"smooth","autoplay"):this.stopAutoplay()},interval)}scrollPaddingStart(){const rect=this.scrollHintProbe?.getBoundingClientRect();if(!rect)return 0;const pixels=this.effectiveOrientation()==="vertical"?rect.height:rect.width;return Number.isFinite(pixels)?pixels:0}axisOffsetOf(slide,viewport){const viewportRect=viewport.getBoundingClientRect(),slideRect=slide.getBoundingClientRect(),padding=this.scrollPaddingStart();return this.effectiveOrientation()==="vertical"?slideRect.top-(viewportRect.top+padding):this.effectiveDirection==="rtl"?slideRect.right-(viewportRect.right-padding):slideRect.left-(viewportRect.left+padding)}scrollByAxis(viewport,distance,behavior){this.effectiveOrientation()==="vertical"?viewport.scrollBy({top:distance,behavior}):viewport.scrollBy({left:distance,behavior})}restingSlide(){const viewport=this.viewport,slides=this.slideElements();if(!viewport||slides.length===0)return;const candidates=slides.map((element,index)=>({element,index}));for(const clone of this.shadowRoot?.querySelectorAll("[data-carousel-clone]")??[]){const index=Number(clone.dataset.carouselIndex),cloneSide=clone.dataset.carouselClone;Number.isInteger(index)&&index>=0&&index<slides.length&&(cloneSide==="before"||cloneSide==="after")&&candidates.push({element:clone,index,cloneSide})}let nearest,nearestDistance=Number.POSITIVE_INFINITY;for(const candidate of candidates){const distance=Math.abs(this.axisOffsetOf(candidate.element,viewport));distance<nearestDistance&&(nearestDistance=distance,nearest=candidate)}return nearest}alignToActiveSlide(){const viewport=this.viewport,targetIndex=this.normalizedIndex(),realSlide=this.slideElements()[targetIndex];if(!viewport||!realSlide)return;const loopSide=this.loopSide,requestedBehavior=this.requestedBehavior;this.loopSide=void 0,this.requestedBehavior=void 0;const target=loopSide?this.cloneFor(loopSide,targetIndex)??realSlide:realSlide,offset=this.axisOffsetOf(target,viewport);if(Math.round(offset)===0){this.clearAlignment();return}this.alignIndex=targetIndex,this.alignTarget=target;const behavior=this.motionAwareScrollBehavior(requestedBehavior??"smooth",!0);this.scrollByAxis(viewport,offset,behavior)}motionAwareScrollBehavior(requested,instantBeforeFirstAlignment=!1){return this.reduceMotion||instantBeforeFirstAlignment&&!this.hasAlignedOnce?"instant":requested}cancelScrollSettle(){this.scrollSettle.cancel()}clearAlignment(){this.alignTarget=void 0,this.alignIndex=void 0,this.loopSide=void 0,this.requestedBehavior=void 0}takeOverViewport(){this.clearAlignment()}targetsInteractiveContent(event,includeSlideEditors=!1){const slides=new Set(this.slideElements()),slideRoot=event.composedPath().find(target=>typeof target=="object"&&target!==null&&target.nodeType===1&&slides.has(target));return keyEventOwnedByInnerControl(event,{container:!includeSlideEditors&&slideRoot?slideRoot:this,ownsButtons:!0,ownsCustomElements:!0,ignoreCustomElements:slides})}finishDrag(pointerId,canceled){if(pointerId!==this.dragPointerId)return;const viewport=this.viewport,moved=this.dragMoved;if(this.dragPointerId=void 0,this.dragMoved=!1,viewport?.removeAttribute("data-dragging"),viewport?.hasPointerCapture(pointerId))try{viewport.releasePointerCapture(pointerId)}catch{}if(moved){this.suppressClick=!0,this.cancelClickSuppression();const view=this.ownerDocument.defaultView;view?(this.clickTimerWindow=view,this.clickTimer=view.setTimeout(()=>{this.suppressClick=!1,this.clickTimer=void 0,this.clickTimerWindow=void 0},0)):this.suppressClick=!1}if(canceled&&viewport){const active=this.slideElements()[this.normalizedIndex()];active&&this.scrollByAxis(viewport,this.axisOffsetOf(active,viewport),this.motionAwareScrollBehavior("smooth"))}else canceled||this.onViewportScroll();this.matches(":hover")||(this.pointerInteracting=!1),this.restartAutoplay()}cancelClickSuppression(){this.clickTimer!==void 0&&this.clickTimerWindow?.clearTimeout(this.clickTimer),this.clickTimer=void 0,this.clickTimerWindow=void 0}cancelDrag(realign){this.dragPointerId!==void 0&&this.finishDrag(this.dragPointerId,realign)}computedSlideBasis(perPage){return perPage===1?"100%":`calc((100% - (${perPage-1} * var(--slide-gap, var(--lr-space-m)))) / ${perPage})`}render(){const count=this.slideElements().length,current=this.normalizedIndex(count),pageTargets=this.pageTargets(count),exactCurrentPage=pageTargets.indexOf(current),currentPage=exactCurrentPage>=0?exactCurrentPage:pageTargets.reduce((nearest,target,pageIndex)=>Math.abs(target-current)<Math.abs(pageTargets[nearest]-current)?pageIndex:nearest,0),hasNavigation=this.navigation&&count>this.pageSize(count),hasPagination=this.pagination&&pageTargets.length>1,label=this.hostAccessibleLabel??this.localize("carouselLabel"),numberFormat=getNumberFormat(this.effectiveLocale),orientation=this.effectiveOrientation(),perPage=this.pageSize(count);return html`<section
2
2
  part="base carousel"
3
3
  role="region"
4
4
  aria-roledescription=${this.localize("carousel")}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{parseHotkey,matchesHotkey,isIgnorableKeyEvent,registerHotkeyOwner,unregisterHotkeyOwner,resolveHotkeyOwner}from"../../../internal/hotkey.js";import{detectPlatform}from"../../../internal/platform.js";import{nextId}from"../../../internal/a11y.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./command-palette.styles.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{closeIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_commandPaletteEmpty,LYRA_DEFAULT_commandPaletteLabel,LYRA_DEFAULT_commandPalettePlaceholder,LYRA_DEFAULT_commandPaletteResultCount,LYRA_DEFAULT_commandPaletteResults}from"../../../internal/default-strings.generated.js";const SEARCH_ICON=svg`<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="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"></path></svg>`,COMMAND_ROW_HEIGHT=48,GROUP_ROW_HEIGHT=32,RESULT_OVERSCAN_ROWS=6,MAX_COMMAND_PALETTE_COMMANDS=1e4,MAX_COMMAND_PALETTE_KEYWORDS=1e4,EMPTY_CANONICAL_COMMANDS=Object.freeze([]),EMPTY_COMMAND_KEYWORDS=Object.freeze([]);function projectCommandKeywords(value){try{if(!Array.isArray(value))return EMPTY_COMMAND_KEYWORDS;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return EMPTY_COMMAND_KEYWORDS;const keywords=[];for(let index=0;index<Math.min(length.value,MAX_COMMAND_PALETTE_KEYWORDS);index+=1){const entry=getOwnDataDescriptor(value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value!="string"||keywords.push(entry.value)}return Object.freeze(keywords)}catch{return EMPTY_COMMAND_KEYWORDS}}function projectCommand(candidate){try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))return;const commandId=getOwnDataDescriptor(candidate,"commandId"),label=getOwnDataDescriptor(candidate,"label"),description=getOwnDataDescriptor(candidate,"description"),group=getOwnDataDescriptor(candidate,"group"),shortcut=getOwnDataDescriptor(candidate,"shortcut"),keywords=getOwnDataDescriptor(candidate,"keywords"),disabled=getOwnDataDescriptor(candidate,"disabled"),icon=getOwnDataDescriptor(candidate,"icon"),onSelect=getOwnDataDescriptor(candidate,"onSelect");if(commandId===MISSING_OWN_DATA_DESCRIPTOR||commandId===UNSAFE_OWN_DATA_DESCRIPTOR||label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR||group===UNSAFE_OWN_DATA_DESCRIPTOR||shortcut===UNSAFE_OWN_DATA_DESCRIPTOR||keywords===UNSAFE_OWN_DATA_DESCRIPTOR||disabled===UNSAFE_OWN_DATA_DESCRIPTOR||icon===UNSAFE_OWN_DATA_DESCRIPTOR||onSelect===UNSAFE_OWN_DATA_DESCRIPTOR||typeof commandId.value!="string"||commandId.value.trim()===""||typeof label.value!="string"||label.value.trim()==="")return;const descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR?void 0:description.value,groupValue=group===MISSING_OWN_DATA_DESCRIPTOR?void 0:group.value,shortcutValue=shortcut===MISSING_OWN_DATA_DESCRIPTOR?void 0:shortcut.value,keywordsValue=keywords===MISSING_OWN_DATA_DESCRIPTOR?void 0:keywords.value,disabledValue=disabled===MISSING_OWN_DATA_DESCRIPTOR?void 0:disabled.value,iconValue=icon===MISSING_OWN_DATA_DESCRIPTOR?void 0:icon.value,onSelectValue=onSelect===MISSING_OWN_DATA_DESCRIPTOR?void 0:onSelect.value;if(descriptionValue!==void 0&&typeof descriptionValue!="string"||groupValue!==void 0&&typeof groupValue!="string"||shortcutValue!==void 0&&typeof shortcutValue!="string"||disabledValue!==void 0&&typeof disabledValue!="boolean"||onSelectValue!==void 0&&typeof onSelectValue!="function")return;const keywordValues=projectCommandKeywords(keywordsValue);return Object.freeze({source:candidate,commandId:commandId.value,label:label.value,...descriptionValue===void 0?{}:{description:descriptionValue},...groupValue===void 0?{}:{group:groupValue},...shortcutValue===void 0?{}:{shortcut:shortcutValue},keywords:keywordValues,disabled:disabledValue??!1,...iconValue===void 0?{}:{icon:iconValue},...onSelectValue===void 0?{}:{onSelect:onSelectValue}})}catch{return}}function projectCommands(value){try{if(!Array.isArray(value))return EMPTY_CANONICAL_COMMANDS;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return EMPTY_CANONICAL_COMMANDS;const commands=[],seen=new Set;for(let index=0;index<Math.min(length.value,MAX_COMMAND_PALETTE_COMMANDS);index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const command=projectCommand(entry.value);!command||seen.has(command.commandId)||(seen.add(command.commandId),commands.push(command))}return Object.freeze(commands)}catch{return EMPTY_CANONICAL_COMMANDS}}class LyraCommandPalette extends LyraElement{constructor(){super(...arguments),this._open=!1,this.hasShown=!1,this.commands=[],this.hotkey="mod+k",this.queryText="",this.activeIndex=0,this.listScrollTop=0,this.listViewportHeight=COMMAND_ROW_HEIGHT*10,this.rowPitch=COMMAND_ROW_HEIGHT,this.groupPitch=GROUP_ROW_HEIGHT,this.listId=nextId("command-list"),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.close("escape")},onUnexpectedClose:()=>{this.close("escape"),this.open&&this.modalSurface.show()}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal,()=>this.renderRoot.querySelector('[part="backdrop"]')),this.haystacksLocale="",this.haystacks=[],this.filteredForQuery="",this.filteredForLocale="",this.filteredRows=[],this.normalizedRows=EMPTY_CANONICAL_COMMANDS,this.panelPressed=!1,this.announcements=new AnnouncementSinkController(this),this.completedInitialUpdate=!1,this.onGlobalKeyDown=event=>{if(isIgnorableKeyEvent(event))return;const view=this.runtimeWindow;!view||!this.matchesShortcut(event)||resolveHotkeyOwner(view,event)!==this||(event.preventDefault(),this.openPalette())},this.onKeyDown=event=>{if(event.isComposing||event.keyCode===229)return;const rows=this.filtered;if(event.key==="ArrowDown"){event.preventDefault();const next=this.seekEnabled(rows,this.activeIndex+1,1);next!==-1&&this.setActiveIndex(rows,next)}else if(event.key==="ArrowUp"){event.preventDefault();const previous=this.seekEnabled(rows,this.activeIndex-1,-1);previous!==-1&&this.setActiveIndex(rows,previous)}else if(event.key==="Enter"){const active=rows[this.activeIndex];active&&(event.preventDefault(),this.select(active))}else if(rows.length&&["Home","End","PageUp","PageDown"].includes(event.key)){event.preventDefault();const step=event.key==="Home"||event.key==="PageDown"?1:-1,page=Math.max(1,Math.floor(this.listViewportHeight/this.rowPitch)),from=event.key==="Home"?0:event.key==="End"?rows.length-1:Math.min(rows.length-1,Math.max(0,this.activeIndex+step*page)),next=this.seekEnabled(rows,from,step);next!==-1&&this.setActiveIndex(rows,next)}},this.onInput=event=>{event.stopPropagation(),this.queryText=event.target.value,this.listScrollTop=0;const list=this.renderRoot.querySelector('[part="list"]');list&&(list.scrollTop=0);const rows=this.filtered;this.setActiveIndex(rows,this.seekEnabled(rows,0,1))},this.onClearSearch=()=>{if(this.queryText==="")return;this.queryText="",this.listScrollTop=0;const list=this.renderRoot.querySelector('[part="list"]');list&&(list.scrollTop=0);const rows=this.filtered;this.setActiveIndex(rows,this.seekEnabled(rows,0,1)),this.renderRoot.querySelector('[part="input"]')?.focus()},this.onSearchFocus=event=>{relayNativeEvent(this,event)},this.onSearchBlur=event=>{relayNativeEvent(this,event)},this.onListScroll=event=>{const list=event.currentTarget;if(this.listScrollFrame!==void 0)return;const view=this.runtimeWindow??this.ownerDocument.defaultView;if(!view){this.listScrollTop=list.scrollTop;return}this.listScrollFrame=view.requestAnimationFrame(()=>{this.listScrollFrame=void 0,this.listScrollTop=list.scrollTop})}}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,commandPaletteEmpty:LYRA_DEFAULT_commandPaletteEmpty,commandPaletteLabel:LYRA_DEFAULT_commandPaletteLabel,commandPalettePlaceholder:LYRA_DEFAULT_commandPalettePlaceholder,commandPaletteResultCount:LYRA_DEFAULT_commandPaletteResultCount,commandPaletteResults:LYRA_DEFAULT_commandPaletteResults}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["commands"])}static{this.identityCollectionProperties=Object.freeze(["commands"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["command"])})}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-select"])}get open(){return this._open}set open(next){const normalized=!!next;if(normalized!==this._open){if(!this.hasUpdated){this.commitOpen(normalized);return}this.requestOpen(normalized)}}get effectiveCommands(){return this.normalizedForCommands!==this.commands&&(this.normalizedForCommands=this.commands,this.normalizedRows=projectCommands(this.commands)),this.normalizedRows}get searchHaystacks(){const locale=this.effectiveLocale,commands=this.effectiveCommands;return(this.haystacksFor!==commands||this.haystacksLocale!==locale)&&(this.haystacksFor=commands,this.haystacksLocale=locale,this.haystacks=commands.map(command=>[command.label,command.description??"",command.group??"",...command.keywords].join(" ").toLocaleLowerCase(locale))),this.haystacks}willUpdate(changed){if(super.willUpdate(changed),changed.has("open"))if(this.open)this.modalSurface.open(()=>this.activateOverlay());else{const hadOverlay=this.overlay!==void 0;this.releaseResultsSink(),this.modalSurface.close(hadOverlay,()=>{this.overlay?.deactivate(),this.overlay=void 0},()=>!this.open)}const rows=this.filtered;let nextIndex=this.activeCommandId?rows.findIndex(command=>command.commandId===this.activeCommandId):-1;if(nextIndex<0||rows[nextIndex]?.disabled){const start=Math.min(Math.max(this.activeIndex,0),Math.max(0,rows.length-1));nextIndex=this.seekEnabled(rows,start,1),nextIndex===-1&&(nextIndex=this.seekEnabled(rows,start-1,-1))}this.activeIndex=nextIndex,this.activeCommandId=nextIndex>=0?rows[nextIndex].commandId:void 0}updated(changed){if(super.updated(changed),changed.has("open")&&this.open&&(this.enterTopLayer(),this.overlay?.focusInitial()),changed.has("open")&&(this.open||this.hasShown)&&(this.hasShown=this.open,this.emit(this.open?"lr-after-show":"lr-after-hide")),changed.has("activeIndex")&&this.scrollActiveIntoView(),this.open&&this.queryText.trim()!==""){const count=this.filtered.length,resultText=count===0?this.localize("commandPaletteEmpty"):this.localize("commandPaletteResultCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});this.completedInitialUpdate&&resultText!==this.announcedResultText&&this.announcements.announcePolite(resultText),this.announcedResultText=resultText}else this.queryText.trim()===""&&(this.announcedResultText=void 0);this.completedInitialUpdate=!0;const list=this.renderRoot.querySelector('[part="list"]');this.observeList(list??void 0)}observeList(list){list!==this.observedList&&(this.observedList&&this.listResizeObserver?.unobserve(this.observedList),this.clearPitchSentinels(),this.observedList=list,list&&(this.listResizeObserver?.observe(list),queueMicrotask(()=>{this.isConnected&&this.observedList===list&&this.measureRowPitch()}))),this.observePitchSentinels()}observePitchSentinels(){const row=this.renderRoot.querySelector('[part="command"]')??void 0,group=this.renderRoot.querySelector('[part="group"]')??void 0;row!==this.observedRow&&(this.observedRow&&this.listResizeObserver?.unobserve(this.observedRow),this.observedRow=row,row&&this.listResizeObserver?.observe(row)),group!==this.observedGroup&&(this.observedGroup&&this.listResizeObserver?.unobserve(this.observedGroup),this.observedGroup=group,group&&this.listResizeObserver?.observe(group))}clearPitchSentinels(){this.observedRow&&this.listResizeObserver?.unobserve(this.observedRow),this.observedGroup&&this.listResizeObserver?.unobserve(this.observedGroup),this.observedRow=void 0,this.observedGroup=void 0}measureRowPitch(){const style=this.ownerDocument.defaultView?.getComputedStyle(this);if(!style)return;const row=resolveCssTokenLength(style.getPropertyValue("--lr-command-palette-row-height").trim()||style.getPropertyValue("--_lr-command-palette-row-height").trim(),{host:this}),group=resolveCssTokenLength(style.getPropertyValue("--lr-command-palette-group-height").trim()||style.getPropertyValue("--_lr-command-palette-group-height").trim(),{host:this});row!==void 0&&row>0&&row!==this.rowPitch&&(this.rowPitch=row),group!==void 0&&group>0&&group!==this.groupPitch&&(this.groupPitch=group)}scheduleRowPitchMeasurement(){if(this.rowPitchFrame!==void 0)return;const view=this.runtimeWindow??this.ownerDocument.defaultView;if(!view){this.measureRowPitch();return}this.rowPitchFrame=view.requestAnimationFrame(()=>{this.rowPitchFrame=void 0,this.isConnected&&this.measureRowPitch()})}connectedCallback(){super.connectedCallback();const view=this.ownerDocument.defaultView;this.runtimeWindow=view??void 0,view&&(registerHotkeyOwner(view,this,event=>this.isConnected&&this.matchesShortcut(event)),view.addEventListener("keydown",this.onGlobalKeyDown));const ResizeObserverCtor=view?.ResizeObserver;if(ResizeObserverCtor&&view){let observer;observer=new ResizeObserverCtor(entries=>{if(this.listResizeObserver!==observer||this.runtimeWindow!==view)return;this.scheduleRowPitchMeasurement();const entry=entries.find(candidate=>candidate.target===this.observedList);if(!entry)return;const height=entry.borderBoxSize?.[0]?.blockSize??entry.contentRect.height;height>0&&this.listViewportHeight!==height&&(this.listViewportHeight=height)}),this.listResizeObserver=observer}else this.listResizeObserver=void 0;this.hasUpdated&&this.observeList(this.renderRoot.querySelector('[part="list"]')??void 0),this.hasUpdated&&this.open&&(this.activateOverlay(),queueMicrotask(()=>{!this.isConnected||!this.open||(this.enterTopLayer(),this.overlay?.focusInitial())}))}disconnectedCallback(){super.disconnectedCallback();const view=this.runtimeWindow;view&&(unregisterHotkeyOwner(view,this),view.removeEventListener("keydown",this.onGlobalKeyDown)),this.modalSurface.disconnect(),this.overlay?.suspend(),this.releaseResultsSink(),this.listResizeObserver?.disconnect(),this.listResizeObserver=void 0,this.observedList=void 0,this.observedRow=void 0,this.observedGroup=void 0,this.listScrollFrame!==void 0&&(view?.cancelAnimationFrame(this.listScrollFrame),this.listScrollFrame=void 0),this.rowPitchFrame!==void 0&&(view?.cancelAnimationFrame(this.rowPitchFrame),this.rowPitchFrame=void 0),this.runtimeWindow=void 0}releaseResultsSink(){this.announcements.releaseChannel("polite"),this.announcedResultText=void 0}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}enterTopLayer(){this.modalSurface.show()}activateOverlay(){if(this.overlay?.isActive()){this.overlay.resume();return}this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="dialog"]')??null,onEscape:()=>this.close("escape"),onBackdrop:()=>this.close("backdrop"),lockScroll:!0,suspendWhenUnrendered:!0})}openPalette(){this.requestOpen(!0)}close(reason="api"){this.requestOpen(!1,reason)}show(){this.openPalette()}hide(){this.close()}requestOpen(next,reason="api"){if(next===this._open||this.openRequestTarget===next)return!1;this.openRequestTarget=next;let prevented;return next?prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented:prevented=this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented,this.openRequestTarget=void 0,prevented?(this.toggleAttribute("open",this._open),!1):(next?this.resetOpeningState():this.emit("lr-hide",{reason}),this.commitOpen(next),next||this.emit("lr-close",{reason}),!0)}resetOpeningState(){this.queryText="",this.listScrollTop=0;const rows=this.filtered;this.setActiveIndex(rows,this.seekEnabled(rows,0,1))}commitOpen(next){if(next===this._open)return;const old=this._open;this._open=next,this.requestUpdate("open",old)}registerCommand(command){return this.commands=[...this.commands,command],()=>{this.commands=this.commands.filter(item=>item!==command)}}matchesShortcut(event){return matchesHotkey(parseHotkey(this.hotkey),event,detectPlatform((this.runtimeWindow??this.ownerDocument.defaultView)?.navigator)==="mac")}get filtered(){const locale=this.effectiveLocale,query=this.queryText.trim().toLocaleLowerCase(locale),commands=this.effectiveCommands;if(this.filteredForCommands!==commands||this.filteredForQuery!==query||this.filteredForLocale!==locale)if(this.filteredForCommands=commands,this.filteredForQuery=query,this.filteredForLocale=locale,!query)this.filteredRows=[...commands];else{const haystacks=this.searchHaystacks;this.filteredRows=commands.filter((_,index)=>haystacks[index].includes(query))}return this.filteredRows}select(command){command.disabled||(this.emit("lr-select",{command:command.source}),command.onSelect?.(),this.close("select"))}seekEnabled(rows,from,step){for(let index=from;index>=0&&index<rows.length;index+=step)if(!rows[index].disabled)return index;return-1}setActiveIndex(rows,index){this.activeIndex=index,this.activeCommandId=index>=0?rows[index].commandId:void 0}get resultModel(){const rows=this.filtered;if(this.resultModelFor===rows&&this.resultModelRowPitch===this.rowPitch&&this.resultModelGroupPitch===this.groupPitch&&this.resultModelCache)return this.resultModelCache;const resultRows=[],groups=[];let top=0,previousGroup,group;for(let index=0;index<rows.length;index++){const command=rows[index],label=command.group??"";(!group||label!==previousGroup)&&(group={index:groups.length,label,headingTop:label?top:void 0,rows:[]},groups.push(group),previousGroup=label,label&&(top+=this.groupPitch));const row={command,index,top,groupIndex:group.index};group.rows.push(row),resultRows.push(row),top+=this.rowPitch}return this.resultModelFor=rows,this.resultModelRowPitch=this.rowPitch,this.resultModelGroupPitch=this.groupPitch,this.resultModelCache={rows:resultRows,groups,totalHeight:top},this.resultModelCache}visibleGroups(model){if(model.rows.length===0)return[];const minimum=Math.max(0,this.listScrollTop-this.rowPitch*RESULT_OVERSCAN_ROWS),maximum=this.listScrollTop+this.listViewportHeight+this.rowPitch*RESULT_OVERSCAN_ROWS;let low=0,high=model.rows.length-1;for(;low<high;){const middle=low+high>>1;model.rows[middle].top+this.rowPitch<minimum?low=middle+1:high=middle}const groups=[];let group;const appendRow=row=>{group?.index!==row.groupIndex&&(group={...model.groups[row.groupIndex],rows:[]},groups.push(group)),group.rows.push(row)},active=model.rows[this.activeIndex];active&&this.activeIndex<low&&appendRow(active);let index=low;for(;index<model.rows.length;index++){const row=model.rows[index];if(row.top>maximum)break;appendRow(row)}return active&&this.activeIndex>=index&&appendRow(active),groups}optionId(index){return`${this.listId}-opt-${index}`}scrollActiveIntoView(){if(this.activeIndex<0)return;const list=this.renderRoot.querySelector('[part="list"]'),row=this.resultModel.rows[this.activeIndex];if(!list||!row)return;const top=row.top+(list.firstElementChild?.offsetTop??0),bottom=top+this.rowPitch;top<list.scrollTop?list.scrollTop=top:bottom>list.scrollTop+list.clientHeight&&(list.scrollTop=Math.max(0,bottom-list.clientHeight))}renderCommand(row,total){const command=row.command,active=row.index===this.activeIndex;return html`<button
1
+ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{NativeModalCarrier}from"../../../internal/native-modal-carrier.js";import{nativeModalCarrierStyles}from"../../../internal/native-modal-carrier.styles.js";import{ModalSurfaceController}from"../../../internal/modal-surface-controller.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing,svg}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{parseHotkey,matchesHotkey,isIgnorableKeyEvent,registerHotkeyOwner,unregisterHotkeyOwner,resolveHotkeyOwner}from"../../../internal/hotkey.js";import{detectPlatform}from"../../../internal/platform.js";import{nextId}from"../../../internal/a11y.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./command-palette.styles.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{closeIcon}from"../../../internal/icons.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_commandPaletteEmpty,LYRA_DEFAULT_commandPaletteLabel,LYRA_DEFAULT_commandPalettePlaceholder,LYRA_DEFAULT_commandPaletteResultCount,LYRA_DEFAULT_commandPaletteResults}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_clear}from"../../../internal/default-strings/shared.generated.js";const SEARCH_ICON=svg`<svg width="1em" height="1em" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="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"></path></svg>`,COMMAND_ROW_HEIGHT=48,GROUP_ROW_HEIGHT=32,RESULT_OVERSCAN_ROWS=6,MAX_COMMAND_PALETTE_COMMANDS=1e4,MAX_COMMAND_PALETTE_KEYWORDS=1e4,EMPTY_CANONICAL_COMMANDS=Object.freeze([]),EMPTY_COMMAND_KEYWORDS=Object.freeze([]);function projectCommandKeywords(value){try{if(!Array.isArray(value))return EMPTY_COMMAND_KEYWORDS;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return EMPTY_COMMAND_KEYWORDS;const keywords=[];for(let index=0;index<Math.min(length.value,MAX_COMMAND_PALETTE_KEYWORDS);index+=1){const entry=getOwnDataDescriptor(value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value!="string"||keywords.push(entry.value)}return Object.freeze(keywords)}catch{return EMPTY_COMMAND_KEYWORDS}}function projectCommand(candidate){try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))return;const commandId=getOwnDataDescriptor(candidate,"commandId"),label=getOwnDataDescriptor(candidate,"label"),description=getOwnDataDescriptor(candidate,"description"),group=getOwnDataDescriptor(candidate,"group"),shortcut=getOwnDataDescriptor(candidate,"shortcut"),keywords=getOwnDataDescriptor(candidate,"keywords"),disabled=getOwnDataDescriptor(candidate,"disabled"),icon=getOwnDataDescriptor(candidate,"icon"),onSelect=getOwnDataDescriptor(candidate,"onSelect");if(commandId===MISSING_OWN_DATA_DESCRIPTOR||commandId===UNSAFE_OWN_DATA_DESCRIPTOR||label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR||group===UNSAFE_OWN_DATA_DESCRIPTOR||shortcut===UNSAFE_OWN_DATA_DESCRIPTOR||keywords===UNSAFE_OWN_DATA_DESCRIPTOR||disabled===UNSAFE_OWN_DATA_DESCRIPTOR||icon===UNSAFE_OWN_DATA_DESCRIPTOR||onSelect===UNSAFE_OWN_DATA_DESCRIPTOR||typeof commandId.value!="string"||commandId.value.trim()===""||typeof label.value!="string"||label.value.trim()==="")return;const descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR?void 0:description.value,groupValue=group===MISSING_OWN_DATA_DESCRIPTOR?void 0:group.value,shortcutValue=shortcut===MISSING_OWN_DATA_DESCRIPTOR?void 0:shortcut.value,keywordsValue=keywords===MISSING_OWN_DATA_DESCRIPTOR?void 0:keywords.value,disabledValue=disabled===MISSING_OWN_DATA_DESCRIPTOR?void 0:disabled.value,iconValue=icon===MISSING_OWN_DATA_DESCRIPTOR?void 0:icon.value,onSelectValue=onSelect===MISSING_OWN_DATA_DESCRIPTOR?void 0:onSelect.value;if(descriptionValue!==void 0&&typeof descriptionValue!="string"||groupValue!==void 0&&typeof groupValue!="string"||shortcutValue!==void 0&&typeof shortcutValue!="string"||disabledValue!==void 0&&typeof disabledValue!="boolean"||onSelectValue!==void 0&&typeof onSelectValue!="function")return;const keywordValues=projectCommandKeywords(keywordsValue);return Object.freeze({source:candidate,commandId:commandId.value,label:label.value,...descriptionValue===void 0?{}:{description:descriptionValue},...groupValue===void 0?{}:{group:groupValue},...shortcutValue===void 0?{}:{shortcut:shortcutValue},keywords:keywordValues,disabled:disabledValue??!1,...iconValue===void 0?{}:{icon:iconValue},...onSelectValue===void 0?{}:{onSelect:onSelectValue}})}catch{return}}function projectCommands(value){try{if(!Array.isArray(value))return EMPTY_CANONICAL_COMMANDS;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return EMPTY_CANONICAL_COMMANDS;const commands=[],seen=new Set;for(let index=0;index<Math.min(length.value,MAX_COMMAND_PALETTE_COMMANDS);index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const command=projectCommand(entry.value);!command||seen.has(command.commandId)||(seen.add(command.commandId),commands.push(command))}return Object.freeze(commands)}catch{return EMPTY_CANONICAL_COMMANDS}}class LyraCommandPalette extends LyraElement{constructor(){super(...arguments),this._open=!1,this.hasShown=!1,this.commands=[],this.hotkey="mod+k",this.queryText="",this.activeIndex=0,this.listScrollTop=0,this.listViewportHeight=COMMAND_ROW_HEIGHT*10,this.rowPitch=COMMAND_ROW_HEIGHT,this.groupPitch=GROUP_ROW_HEIGHT,this.listId=nextId("command-list"),this.nativeModal=new NativeModalCarrier(this,{onCancel:()=>{this.overlay?.isTopmost()&&this.close("escape")},onUnexpectedClose:()=>{this.close("escape"),this.open&&this.modalSurface.show()}}),this.modalSurface=new ModalSurfaceController(this,this.nativeModal,()=>this.renderRoot.querySelector('[part="backdrop"]')),this.haystacksLocale="",this.haystacks=[],this.filteredForQuery="",this.filteredForLocale="",this.filteredRows=[],this.normalizedRows=EMPTY_CANONICAL_COMMANDS,this.panelPressed=!1,this.announcements=new AnnouncementSinkController(this),this.completedInitialUpdate=!1,this.onGlobalKeyDown=event=>{if(isIgnorableKeyEvent(event))return;const view=this.runtimeWindow;!view||!this.matchesShortcut(event)||resolveHotkeyOwner(view,event)!==this||(event.preventDefault(),this.openPalette())},this.onKeyDown=event=>{if(event.isComposing||event.keyCode===229)return;const rows=this.filtered;if(event.key==="ArrowDown"){event.preventDefault();const next=this.seekEnabled(rows,this.activeIndex+1,1);next!==-1&&this.setActiveIndex(rows,next)}else if(event.key==="ArrowUp"){event.preventDefault();const previous=this.seekEnabled(rows,this.activeIndex-1,-1);previous!==-1&&this.setActiveIndex(rows,previous)}else if(event.key==="Enter"){const active=rows[this.activeIndex];active&&(event.preventDefault(),this.select(active))}else if(rows.length&&["Home","End","PageUp","PageDown"].includes(event.key)){event.preventDefault();const step=event.key==="Home"||event.key==="PageDown"?1:-1,page=Math.max(1,Math.floor(this.listViewportHeight/this.rowPitch)),from=event.key==="Home"?0:event.key==="End"?rows.length-1:Math.min(rows.length-1,Math.max(0,this.activeIndex+step*page)),next=this.seekEnabled(rows,from,step);next!==-1&&this.setActiveIndex(rows,next)}},this.onInput=event=>{event.stopPropagation(),this.queryText=event.target.value,this.listScrollTop=0;const list=this.renderRoot.querySelector('[part="list"]');list&&(list.scrollTop=0);const rows=this.filtered;this.setActiveIndex(rows,this.seekEnabled(rows,0,1))},this.onClearSearch=()=>{if(this.queryText==="")return;this.queryText="",this.listScrollTop=0;const list=this.renderRoot.querySelector('[part="list"]');list&&(list.scrollTop=0);const rows=this.filtered;this.setActiveIndex(rows,this.seekEnabled(rows,0,1)),this.renderRoot.querySelector('[part="input"]')?.focus()},this.onSearchFocus=event=>{relayNativeEvent(this,event)},this.onSearchBlur=event=>{relayNativeEvent(this,event)},this.onListScroll=event=>{const list=event.currentTarget;if(this.listScrollFrame!==void 0)return;const view=this.runtimeWindow??this.ownerDocument.defaultView;if(!view){this.listScrollTop=list.scrollTop;return}this.listScrollFrame=view.requestAnimationFrame(()=>{this.listScrollFrame=void 0,this.listScrollTop=list.scrollTop})}}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,commandPaletteEmpty:LYRA_DEFAULT_commandPaletteEmpty,commandPaletteLabel:LYRA_DEFAULT_commandPaletteLabel,commandPalettePlaceholder:LYRA_DEFAULT_commandPalettePlaceholder,commandPaletteResultCount:LYRA_DEFAULT_commandPaletteResultCount,commandPaletteResults:LYRA_DEFAULT_commandPaletteResults}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["commands"])}static{this.identityCollectionProperties=Object.freeze(["commands"])}static{this.identityEventDetailProperties=Object.freeze({"lr-select":Object.freeze(["command"])})}static{this.styles=[LyraElement.styles,nativeModalCarrierStyles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-select"])}get open(){return this._open}set open(next){const normalized=!!next;if(normalized!==this._open){if(!this.hasUpdated){this.commitOpen(normalized);return}this.requestOpen(normalized)}}get effectiveCommands(){return this.normalizedForCommands!==this.commands&&(this.normalizedForCommands=this.commands,this.normalizedRows=projectCommands(this.commands)),this.normalizedRows}get searchHaystacks(){const locale=this.effectiveLocale,commands=this.effectiveCommands;return(this.haystacksFor!==commands||this.haystacksLocale!==locale)&&(this.haystacksFor=commands,this.haystacksLocale=locale,this.haystacks=commands.map(command=>[command.label,command.description??"",command.group??"",...command.keywords].join(" ").toLocaleLowerCase(locale))),this.haystacks}willUpdate(changed){if(super.willUpdate(changed),changed.has("open"))if(this.open)this.modalSurface.open(()=>this.activateOverlay());else{const hadOverlay=this.overlay!==void 0;this.releaseResultsSink(),this.modalSurface.close(hadOverlay,()=>{this.overlay?.deactivate(),this.overlay=void 0},()=>!this.open)}const rows=this.filtered;let nextIndex=this.activeCommandId?rows.findIndex(command=>command.commandId===this.activeCommandId):-1;if(nextIndex<0||rows[nextIndex]?.disabled){const start=Math.min(Math.max(this.activeIndex,0),Math.max(0,rows.length-1));nextIndex=this.seekEnabled(rows,start,1),nextIndex===-1&&(nextIndex=this.seekEnabled(rows,start-1,-1))}this.activeIndex=nextIndex,this.activeCommandId=nextIndex>=0?rows[nextIndex].commandId:void 0}updated(changed){if(super.updated(changed),changed.has("open")&&this.open&&(this.enterTopLayer(),this.overlay?.focusInitial()),changed.has("open")&&(this.open||this.hasShown)&&(this.hasShown=this.open,this.emit(this.open?"lr-after-show":"lr-after-hide")),changed.has("activeIndex")&&this.scrollActiveIntoView(),this.open&&this.queryText.trim()!==""){const count=this.filtered.length,resultText=count===0?this.localize("commandPaletteEmpty"):this.localize("commandPaletteResultCount",void 0,{count:getNumberFormat(this.effectiveLocale).format(count),pluralCount:count});this.completedInitialUpdate&&resultText!==this.announcedResultText&&this.announcements.announcePolite(resultText),this.announcedResultText=resultText}else this.queryText.trim()===""&&(this.announcedResultText=void 0);this.completedInitialUpdate=!0;const list=this.renderRoot.querySelector('[part="list"]');this.observeList(list??void 0)}observeList(list){list!==this.observedList&&(this.observedList&&this.listResizeObserver?.unobserve(this.observedList),this.clearPitchSentinels(),this.observedList=list,list&&(this.listResizeObserver?.observe(list),queueMicrotask(()=>{this.isConnected&&this.observedList===list&&this.measureRowPitch()}))),this.observePitchSentinels()}observePitchSentinels(){const row=this.renderRoot.querySelector('[part="command"]')??void 0,group=this.renderRoot.querySelector('[part="group"]')??void 0;row!==this.observedRow&&(this.observedRow&&this.listResizeObserver?.unobserve(this.observedRow),this.observedRow=row,row&&this.listResizeObserver?.observe(row)),group!==this.observedGroup&&(this.observedGroup&&this.listResizeObserver?.unobserve(this.observedGroup),this.observedGroup=group,group&&this.listResizeObserver?.observe(group))}clearPitchSentinels(){this.observedRow&&this.listResizeObserver?.unobserve(this.observedRow),this.observedGroup&&this.listResizeObserver?.unobserve(this.observedGroup),this.observedRow=void 0,this.observedGroup=void 0}measureRowPitch(){const style=this.ownerDocument.defaultView?.getComputedStyle(this);if(!style)return;const row=resolveCssTokenLength(style.getPropertyValue("--lr-command-palette-row-height").trim()||style.getPropertyValue("--_lr-command-palette-row-height").trim(),{host:this}),group=resolveCssTokenLength(style.getPropertyValue("--lr-command-palette-group-height").trim()||style.getPropertyValue("--_lr-command-palette-group-height").trim(),{host:this});row!==void 0&&row>0&&row!==this.rowPitch&&(this.rowPitch=row),group!==void 0&&group>0&&group!==this.groupPitch&&(this.groupPitch=group)}scheduleRowPitchMeasurement(){if(this.rowPitchFrame!==void 0)return;const view=this.runtimeWindow??this.ownerDocument.defaultView;if(!view){this.measureRowPitch();return}this.rowPitchFrame=view.requestAnimationFrame(()=>{this.rowPitchFrame=void 0,this.isConnected&&this.measureRowPitch()})}connectedCallback(){super.connectedCallback();const view=this.ownerDocument.defaultView;this.runtimeWindow=view??void 0,view&&(registerHotkeyOwner(view,this,event=>this.isConnected&&this.matchesShortcut(event)),view.addEventListener("keydown",this.onGlobalKeyDown));const ResizeObserverCtor=view?.ResizeObserver;if(ResizeObserverCtor&&view){let observer;observer=new ResizeObserverCtor(entries=>{if(this.listResizeObserver!==observer||this.runtimeWindow!==view)return;this.scheduleRowPitchMeasurement();const entry=entries.find(candidate=>candidate.target===this.observedList);if(!entry)return;const height=entry.borderBoxSize?.[0]?.blockSize??entry.contentRect.height;height>0&&this.listViewportHeight!==height&&(this.listViewportHeight=height)}),this.listResizeObserver=observer}else this.listResizeObserver=void 0;this.hasUpdated&&this.observeList(this.renderRoot.querySelector('[part="list"]')??void 0),this.hasUpdated&&this.open&&(this.activateOverlay(),queueMicrotask(()=>{!this.isConnected||!this.open||(this.enterTopLayer(),this.overlay?.focusInitial())}))}disconnectedCallback(){super.disconnectedCallback();const view=this.runtimeWindow;view&&(unregisterHotkeyOwner(view,this),view.removeEventListener("keydown",this.onGlobalKeyDown)),this.modalSurface.disconnect(),this.overlay?.suspend(),this.releaseResultsSink(),this.listResizeObserver?.disconnect(),this.listResizeObserver=void 0,this.observedList=void 0,this.observedRow=void 0,this.observedGroup=void 0,this.listScrollFrame!==void 0&&(view?.cancelAnimationFrame(this.listScrollFrame),this.listScrollFrame=void 0),this.rowPitchFrame!==void 0&&(view?.cancelAnimationFrame(this.rowPitchFrame),this.rowPitchFrame=void 0),this.runtimeWindow=void 0}releaseResultsSink(){this.announcements.releaseChannel("polite"),this.announcedResultText=void 0}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}enterTopLayer(){this.modalSurface.show()}activateOverlay(){if(this.overlay?.isActive()){this.overlay.resume();return}this.overlay=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="dialog"]')??null,onEscape:()=>this.close("escape"),onBackdrop:()=>this.close("backdrop"),lockScroll:!0,suspendWhenUnrendered:!0})}openPalette(){this.requestOpen(!0)}close(reason="api"){this.requestOpen(!1,reason)}show(){this.openPalette()}hide(){this.close()}requestOpen(next,reason="api"){if(next===this._open||this.openRequestTarget===next)return!1;this.openRequestTarget=next;let prevented;return next?prevented=this.emit("lr-show",null,{cancelable:!0}).defaultPrevented:prevented=this.emit("lr-close-request",{reason},{cancelable:!0}).defaultPrevented,this.openRequestTarget=void 0,prevented?(this.toggleAttribute("open",this._open),!1):(next?this.resetOpeningState():this.emit("lr-hide",{reason}),this.commitOpen(next),next||this.emit("lr-close",{reason}),!0)}resetOpeningState(){this.queryText="",this.listScrollTop=0;const rows=this.filtered;this.setActiveIndex(rows,this.seekEnabled(rows,0,1))}commitOpen(next){if(next===this._open)return;const old=this._open;this._open=next,this.requestUpdate("open",old)}registerCommand(command){return this.commands=[...this.commands,command],()=>{this.commands=this.commands.filter(item=>item!==command)}}matchesShortcut(event){return matchesHotkey(parseHotkey(this.hotkey),event,detectPlatform((this.runtimeWindow??this.ownerDocument.defaultView)?.navigator)==="mac")}get filtered(){const locale=this.effectiveLocale,query=this.queryText.trim().toLocaleLowerCase(locale),commands=this.effectiveCommands;if(this.filteredForCommands!==commands||this.filteredForQuery!==query||this.filteredForLocale!==locale)if(this.filteredForCommands=commands,this.filteredForQuery=query,this.filteredForLocale=locale,!query)this.filteredRows=[...commands];else{const haystacks=this.searchHaystacks;this.filteredRows=commands.filter((_,index)=>haystacks[index].includes(query))}return this.filteredRows}select(command){command.disabled||(this.emit("lr-select",{command:command.source}),command.onSelect?.(),this.close("select"))}seekEnabled(rows,from,step){for(let index=from;index>=0&&index<rows.length;index+=step)if(!rows[index].disabled)return index;return-1}setActiveIndex(rows,index){this.activeIndex=index,this.activeCommandId=index>=0?rows[index].commandId:void 0}get resultModel(){const rows=this.filtered;if(this.resultModelFor===rows&&this.resultModelRowPitch===this.rowPitch&&this.resultModelGroupPitch===this.groupPitch&&this.resultModelCache)return this.resultModelCache;const resultRows=[],groups=[];let top=0,previousGroup,group;for(let index=0;index<rows.length;index++){const command=rows[index],label=command.group??"";(!group||label!==previousGroup)&&(group={index:groups.length,label,headingTop:label?top:void 0,rows:[]},groups.push(group),previousGroup=label,label&&(top+=this.groupPitch));const row={command,index,top,groupIndex:group.index};group.rows.push(row),resultRows.push(row),top+=this.rowPitch}return this.resultModelFor=rows,this.resultModelRowPitch=this.rowPitch,this.resultModelGroupPitch=this.groupPitch,this.resultModelCache={rows:resultRows,groups,totalHeight:top},this.resultModelCache}visibleGroups(model){if(model.rows.length===0)return[];const minimum=Math.max(0,this.listScrollTop-this.rowPitch*RESULT_OVERSCAN_ROWS),maximum=this.listScrollTop+this.listViewportHeight+this.rowPitch*RESULT_OVERSCAN_ROWS;let low=0,high=model.rows.length-1;for(;low<high;){const middle=low+high>>1;model.rows[middle].top+this.rowPitch<minimum?low=middle+1:high=middle}const groups=[];let group;const appendRow=row=>{group?.index!==row.groupIndex&&(group={...model.groups[row.groupIndex],rows:[]},groups.push(group)),group.rows.push(row)},active=model.rows[this.activeIndex];active&&this.activeIndex<low&&appendRow(active);let index=low;for(;index<model.rows.length;index++){const row=model.rows[index];if(row.top>maximum)break;appendRow(row)}return active&&this.activeIndex>=index&&appendRow(active),groups}optionId(index){return`${this.listId}-opt-${index}`}scrollActiveIntoView(){if(this.activeIndex<0)return;const list=this.renderRoot.querySelector('[part="list"]'),row=this.resultModel.rows[this.activeIndex];if(!list||!row)return;const top=row.top+(list.firstElementChild?.offsetTop??0),bottom=top+this.rowPitch;top<list.scrollTop?list.scrollTop=top:bottom>list.scrollTop+list.clientHeight&&(list.scrollTop=Math.max(0,bottom-list.clientHeight))}renderCommand(row,total){const command=row.command,active=row.index===this.activeIndex;return html`<button
2
2
  id=${this.optionId(row.index)}
3
3
  part="command"
4
4
  role="option"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{resolveCssLength}from"../../../internal/css-length.js";import{tag}from"../../../internal/prefix.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{Announcer,acquireAnnouncementSink}from"../../../internal/announcer.js";import{isRtl}from"../../../internal/rtl.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{isArrowKey,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{styles}from"./dashboard-grid.styles.js";import{clampDashboardCandidate,createDashboardSpatialIndex,findDashboardCollisions,normalizeLyraDashboardCollisionPolicy,projectDashboardLayout,resolveDashboardPlacement,snapshotDashboardLayout,sortDashboardSpatial}from"./layout-internal.js";import{createWidgetDocument}from"../../conversation/widget-renderer/resolve.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dashboardCellCollisionRejected,LYRA_DEFAULT_dashboardCellMoved,LYRA_DEFAULT_dashboardCellResized,LYRA_DEFAULT_dashboardGridLabel,LYRA_DEFAULT_flowItemAnnouncement,LYRA_DEFAULT_noData}from"../../../internal/default-strings.generated.js";const INTERACTIVE_DESCENDANT_SELECTOR='button, a[href], area[href], input, select, textarea, summary, label, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="switch"], [role="slider"], [role="spinbutton"], [role="textbox"], [role="combobox"], [role="option"], [role="menuitem"], [tabindex]:not([part="cell"])',DASHBOARD_LENGTH_CONVERTER={fromAttribute:value=>{if(value===null)return value;const number=Number(value);return Number.isNaN(number)?value:number}},GEOMETRY_KEYS=["cellId","x","y","w","h","minW","maxW","minH","maxH","locked"],sortedByLayout=new WeakMap,assignedWidgets=new WeakMap,handledPointerDowns=new WeakSet;function sameGeometry(a,b){return a===b||a.length===b.length&&a.every((cell,i)=>GEOMETRY_KEYS.every(key=>cell[key]===b[i][key]))}const UNMATCHED_AUTHORED_CELL_WARNING_KEY="lyra-dashboard-grid-unmatched-authored-cell",UNMATCHED_AUTHORED_CELL_WARNING="<lr-dashboard-grid>: an authored child has a cell-id that matches no layout entry and will not render.";class LyraDashboardGrid extends LyraElement{constructor(){super(...arguments),this.authoredLayout=Object.freeze([]),this.effectiveLayout=Object.freeze([]),this.columns=12,this.rowHeight=80,this.gap=8,this.collisionValue="reject",this.cellsDraggable=!1,this.cellsResizable=!1,this.readonly=!1,this.accessibleLabel=null,this.announcer=new Announcer({onFlush:text=>{this.liveText=text,isAccessibilityVisible(this)&&this.announcementSink?.announce(text)}}),this.liveText="",this.activeCellIndex=0,this.activeCellId="",this.rehomeCellFocus=!1,this.defaultCellSyncQueued=!1,this.ownedDefaultCells=new WeakSet,this.warnedUnmatchedCells=new WeakSet,this.authoredSlotBaselines=new WeakMap,this.managedAuthoredCells=new Set,this.suppressedClickCellId="",this.onCellPointerMove=e=>{const drag=this.cellDrag;if(!(!drag||e.pointerId!==drag.pointerId)){if(!this.canDragCell(drag.cellId)){this.cancelCellDrag();return}drag.pendingClientX=e.clientX,drag.pendingClientY=e.clientY,drag.previewFrame===void 0&&(drag.previewFrame=drag.ownerWindow.requestAnimationFrame(()=>{drag.previewFrame=void 0,this.cellDrag===drag&&this.applyDragPreview(drag)}))}},this.onCellPointerUp=e=>{const drag=this.cellDrag;if(!drag||e.pointerId!==drag.pointerId)return;if(e.type!=="pointerup"||!this.canDragCell(drag.cellId)){this.cancelCellDrag();return}this.flushDragPreview(drag),this.cellDrag=void 0,this.releaseGesturePointerCapture(drag.wrapper,drag.pointerId),drag.wrapper.removeAttribute("data-dragging"),drag.ownerWindow.removeEventListener("pointermove",this.onCellPointerMove),drag.ownerWindow.removeEventListener("pointerup",this.onCellPointerUp),drag.ownerWindow.removeEventListener("pointercancel",this.onCellPointerUp),drag.ownerWindow.removeEventListener("lostpointercapture",this.onCellPointerUp);const x=drag.currentX??drag.startX,y=drag.currentY??drag.startY;(x!==drag.startX||y!==drag.startY)&&this.commitPlacement(drag.cellId,{x,y,w:drag.w,h:drag.h},"move"),drag.moved&&this.armClickSuppression(drag.cellId,drag.ownerWindow),this.resetCellInlineStyle(drag.cellId,drag.wrapper),this.requestUpdate()},this.onResizeHandlePointerMove=e=>{const resize=this.cellResize;if(!(!resize||e.pointerId!==resize.pointerId)){if(!this.canResizeCell(resize.cellId)){this.cancelCellResize();return}resize.pendingClientX=e.clientX,resize.pendingClientY=e.clientY,resize.previewFrame===void 0&&(resize.previewFrame=resize.ownerWindow.requestAnimationFrame(()=>{resize.previewFrame=void 0,this.cellResize===resize&&this.applyResizePreview(resize)}))}},this.onResizeHandlePointerUp=e=>{const resize=this.cellResize;if(!resize||e.pointerId!==resize.pointerId)return;if(e.type!=="pointerup"||!this.canResizeCell(resize.cellId)){this.cancelCellResize();return}this.flushResizePreview(resize),this.cellResize=void 0,this.releaseGesturePointerCapture(resize.captureTarget,resize.pointerId),resize.wrapper.removeAttribute("data-resizing"),resize.ownerWindow.removeEventListener("pointermove",this.onResizeHandlePointerMove),resize.ownerWindow.removeEventListener("pointerup",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("pointercancel",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("lostpointercapture",this.onResizeHandlePointerUp);const w=resize.currentW??resize.startW,h=resize.currentH??resize.startH;(w!==resize.startW||h!==resize.startH)&&this.commitPlacement(resize.cellId,{x:resize.x,y:resize.y,w,h},"resize"),resize.moved&&this.armClickSuppression(resize.cellId,resize.ownerWindow),this.resetCellInlineStyle(resize.cellId,resize.wrapper),this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,dashboardCellCollisionRejected:LYRA_DEFAULT_dashboardCellCollisionRejected,dashboardCellMoved:LYRA_DEFAULT_dashboardCellMoved,dashboardCellResized:LYRA_DEFAULT_dashboardCellResized,dashboardGridLabel:LYRA_DEFAULT_dashboardGridLabel,flowItemAnnouncement:LYRA_DEFAULT_flowItemAnnouncement,noData:LYRA_DEFAULT_noData}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-collision","lr-layout-change"])}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this.effectiveLayout}set layout(value){if(value===this.layoutInput)return;this.layoutInput=value;const previous=this.effectiveLayout;this.authoredLayout=snapshotDashboardLayout(value),this.effectiveLayout=projectDashboardLayout(this.authoredLayout,this.safeColumns),this.announceAppliedPlacement(),this.requestUpdate("layout",previous)}get collision(){return this.collisionValue}set collision(value){const previous=this.collisionValue;this.collisionValue=normalizeLyraDashboardCollisionPolicy(value),this.requestUpdate("collision",previous)}get safeColumns(){return finiteInteger(this.columns,12,1,48)}get safeRowHeight(){return finiteRange(this.lengthInPixels(this.rowHeight),80,1)}get safeGap(){return finiteRange(this.lengthInPixels(this.gap),8,0)}lengthInPixels(value){return typeof value=="number"?value:typeof value!="string"?Number.NaN:resolveCssLength(value,{host:this})??Number.NaN}get sortedLayout(){const layout=this.effectiveLayout;let sorted=sortedByLayout.get(layout);return sorted||sortedByLayout.set(layout,sorted=sortDashboardSpatial(layout)),sorted}connectedCallback(){super.connectedCallback(),this.bindOwnerRealmResources(),this.scheduleDefaultCellSync()}disconnectedCallback(){this.announcer.cancel(),this.announcementSink?.release(),this.announcementSink=void 0,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0,this.defaultCellSyncQueued=!1,this.restoreManagedAuthoredSlots(),this.clearSuppressedClick(),this.pendingPlacementAnnouncement=void 0,this.cancelCellDrag(),this.cancelCellResize(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0,this.announcementSink?.release(),this.announcementSink=void 0,this.clearSuppressedClick(),this.isConnected&&(this.bindOwnerRealmResources(),this.scheduleDefaultCellSync())}bindOwnerRealmResources(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcementSink??=acquireAnnouncementSink("polite",{document:ownerDocument,source:this}),this.childObserver&&this.childObserverDocument===ownerDocument)return;this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0;const MutationObserverCtor=ownerWindow?.MutationObserver;if(!MutationObserverCtor)return;const observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||!records.some(record=>record.type==="childList"?record.target===this:record.target.parentNode===this)||this.scheduleDefaultCellSync()});observer.observe(this,{childList:!0,attributes:!0,attributeFilter:["cell-id"],subtree:!0}),this.childObserver=observer,this.childObserverDocument=ownerDocument}scheduleDefaultCellSync(){!this.isConnected||this.defaultCellSyncQueued||(this.defaultCellSyncQueued=!0,queueMicrotask(()=>{this.defaultCellSyncQueued=!1,this.isConnected&&this.syncDefaultCells()}))}willUpdate(changed){if(super.willUpdate(changed),changed.has("columns")&&(this.effectiveLayout=projectDashboardLayout(this.authoredLayout,this.safeColumns)),changed.has("layout")||changed.has("columns")){this.rehomeCellFocus=shadowFocusTarget(this)?.getAttribute("part")==="cell",this.ownerDocument&&this.isConnected&&(this.hasUpdated?this.syncDefaultCells():this.seedFirstRenderState(()=>this.syncDefaultCells()));const cells=this.sortedLayout,retainedIndex=cells.findIndex(cell=>cell.cellId===this.activeCellId),nextIndex=cells.length===0?0:retainedIndex>=0?retainedIndex:Math.min(this.activeCellIndex,cells.length-1);this.activeCellIndex=nextIndex,this.activeCellId=cells[nextIndex]?.cellId??""}this.cellDrag&&(!sameGeometry(this.cellDrag.layout,this.effectiveLayout)||changed.has("columns")||changed.has("rowHeight")||changed.has("gap")||(changed.has("cellsDraggable")||changed.has("readonly"))&&!this.canDragCell(this.cellDrag.cellId))&&this.cancelCellDrag(),this.cellResize&&(!sameGeometry(this.cellResize.layout,this.effectiveLayout)||changed.has("columns")||changed.has("rowHeight")||changed.has("gap")||(changed.has("cellsResizable")||changed.has("readonly"))&&!this.canResizeCell(this.cellResize.cellId))&&this.cancelCellResize()}updated(changed){super.updated(changed),this.rehomeCellFocus&&(this.rehomeCellFocus=!1,this.renderRoot.querySelector('[part="cell"][tabindex="0"]')?.focus())}cellLabel(cell){return cell.label||cell.cellId}restoreAuthoredSlot(child){if(!this.authoredSlotBaselines.has(child))return;const baseline=this.authoredSlotBaselines.get(child);baseline===null?child.removeAttribute("slot"):baseline!==void 0&&child.setAttribute("slot",baseline),this.authoredSlotBaselines.delete(child),this.managedAuthoredCells.delete(child)}restoreManagedAuthoredSlots(){for(const child of this.managedAuthoredCells)this.restoreAuthoredSlot(child);this.managedAuthoredCells.clear()}syncDefaultCells(){if(!this.isConnected)return;const ids=new Set(this.effectiveLayout.map(cell=>cell.cellId)),authoredById=new Map,ownedById=new Map;for(const child of Array.from(this.children)){if(this.ownedDefaultCells.has(child)){const ownedCellId=child.getAttribute("data-cell-id");if(!ownedCellId){child.remove();continue}const matches=ownedById.get(ownedCellId)??[];matches.push(child),ownedById.set(ownedCellId,matches);continue}const cellId=child.getAttribute("cell-id");cellId&&ids.has(cellId)&&!authoredById.has(cellId)?(authoredById.set(cellId,child),this.warnedUnmatchedCells.delete(child),this.authoredSlotBaselines.has(child)||this.authoredSlotBaselines.set(child,child.getAttribute("slot")),this.managedAuthoredCells.add(child),child.setAttribute("slot",`cell-${cellId}`)):(this.restoreAuthoredSlot(child),cellId&&!ids.has(cellId)&&!this.warnedUnmatchedCells.has(child)&&(this.warnedUnmatchedCells.add(child),devWarnOnce(UNMATCHED_AUTHORED_CELL_WARNING_KEY,UNMATCHED_AUTHORED_CELL_WARNING)))}const selectedAuthored=new Set(authoredById.values());for(const managed of[...this.managedAuthoredCells])(!this.contains(managed)||!selectedAuthored.has(managed))&&this.restoreAuthoredSlot(managed);for(const cell of this.effectiveLayout){const owned=ownedById.get(cell.cellId)??[];if(authoredById.has(cell.cellId)){for(const defaultCell of owned)defaultCell.remove();continue}const existing=owned.shift();existing?(existing.setAttribute("slot",`cell-${cell.cellId}`),this.updateDefaultCell(existing,cell)):this.appendChild(this.createDefaultCell(cell));for(const duplicate of owned)duplicate.remove();ownedById.delete(cell.cellId)}for(const stale of ownedById.values())for(const defaultCell of stale)defaultCell.remove()}createDefaultCell(cell){const ownerDocument=this.ownerDocument,widget=ownerDocument.createElement(tag("widget"));widget.setAttribute("data-cell-id",cell.cellId),widget.setAttribute("data-dashboard-grid-default-cell",""),widget.setAttribute("slot",`cell-${cell.cellId}`),this.ownedDefaultCells.add(widget);const renderer=ownerDocument.createElement(tag("widget-renderer"));return widget.appendChild(renderer),this.updateDefaultCell(widget,cell),widget}updateDefaultCell(widget,cell){widget.label=this.cellLabel(cell);const renderer=widget.querySelector(tag("widget-renderer"));renderer&&assignedWidgets.get(renderer)!==cell.widget&&(assignedWidgets.set(renderer,cell.widget),renderer.document=cell.widget==null?null:createWidgetDocument(cell.widget))}onCellFocus(cellId){const index=this.sortedLayout.findIndex(cell=>cell.cellId===cellId);index>=0&&(this.activeCellIndex!==index&&(this.activeCellIndex=index),this.activeCellId!==cellId&&(this.activeCellId=cellId))}cellElement(cellId){const ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=this.renderRoot.querySelector(`[part="cell"][data-cell-id="${ownerCss.escape(cellId)}"]`);if(candidate?.getAttribute("data-cell-id")===cellId)return candidate}catch{}return Array.from(this.renderRoot.querySelectorAll('[part="cell"][data-cell-id]')).find(candidate=>candidate.getAttribute("data-cell-id")===cellId)??null}focusCellAt(index){const cells=this.sortedLayout;if(index<0||index>=cells.length)return;this.activeCellIndex=index;const cell=cells[index];this.activeCellId=cell.cellId;const number=getNumberFormat(this.effectiveLocale);this.announcer.announce(this.localize("flowItemAnnouncement",void 0,{item:this.cellLabel(cell),index:number.format(index+1),total:number.format(cells.length)})),this.updateComplete.then(()=>{this.cellElement(cell.cellId)?.focus()})}onCellKeyDown(e,cell){const owner=e.currentTarget;if(e.composedPath()[0]!==owner)return;const isMod=e.ctrlKey||e.metaKey;if(isMod&&isArrowKey(e.key)){(e.shiftKey?this.keyboardResize(cell,e.key):this.keyboardMove(cell,e.key))&&e.preventDefault();return}if(e.altKey||isMod||e.isComposing)return;const cells=this.sortedLayout,index=cells.findIndex(c=>c.cellId===cell.cellId);if(index<0)return;const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=index;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(cells.length-1,index+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,index-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=cells.length-1;else return;next!==index&&(e.preventDefault(),this.focusCellAt(next))}keyboardMove(cell,key){if(!this.cellsDraggable||this.readonly||cell.locked)return!1;const rtlFlip=isRtl(this)?-1:1;let dx=0,dy=0;if(key==="ArrowRight")dx=rtlFlip;else if(key==="ArrowLeft")dx=-rtlFlip;else if(key==="ArrowDown")dy=1;else if(key==="ArrowUp")dy=-1;else return!1;return this.commitPlacement(cell.cellId,{x:cell.x+dx,y:cell.y+dy,w:cell.w,h:cell.h},"move")}keyboardResize(cell,key){if(!this.cellsResizable||this.readonly||cell.locked)return!1;let dw=0,dh=0;if(key==="ArrowRight")dw=1;else if(key==="ArrowLeft")dw=-1;else if(key==="ArrowDown")dh=1;else if(key==="ArrowUp")dh=-1;else return!1;return this.commitPlacement(cell.cellId,{x:cell.x,y:cell.y,w:cell.w+dw,h:cell.h+dh},"resize")}announceAppliedPlacement(){const pending=this.pendingPlacementAnnouncement;if(!pending)return;this.pendingPlacementAnnouncement=void 0;const cell=this.effectiveLayout.find(candidate=>candidate.cellId===pending.cellId);if(!cell||!(pending.kind==="move"?cell.x===pending.x&&cell.y===pending.y:cell.w===pending.w&&cell.h===pending.h))return;const number=getNumberFormat(this.effectiveLocale);if(pending.kind==="move"){this.announcer.announce(this.localize("dashboardCellMoved",void 0,{label:this.cellLabel(cell),x:number.format(cell.x+1),y:number.format(cell.y+1)}));return}this.announcer.announce(this.localize("dashboardCellResized",void 0,{label:this.cellLabel(cell),w:number.format(cell.w),h:number.format(cell.h)}))}commitPlacement(cellId,requested,kind){const layout=this.effectiveLayout,cell=layout.find(candidate=>candidate.cellId===cellId);if(!cell)return!1;const result=resolveDashboardPlacement(layout,cellId,requested,this.safeColumns,this.collision);if(result.collidedCellIds.length>0&&this.emit("lr-collision",Object.freeze({cellId,collidedCellIds:result.collidedCellIds,policy:this.collision,accepted:result.accepted})),!result.accepted)return this.announcer.announce(this.localize("dashboardCellCollisionRejected",void 0,{label:this.cellLabel(cell)})),!0;const updated=result.layout.find(candidate=>candidate.cellId===cellId);return(kind==="move"?updated.x===cell.x&&updated.y===cell.y:updated.w===cell.w&&updated.h===cell.h)?!1:(this.pendingPlacementAnnouncement={cellId,kind,x:updated.x,y:updated.y,w:updated.w,h:updated.h},kind==="move"?this.emit("lr-cell-move",Object.freeze({cellId,position:Object.freeze({x:updated.x,y:updated.y}),previous:Object.freeze({x:cell.x,y:cell.y})})):this.emit("lr-cell-resize",Object.freeze({cellId,size:Object.freeze({w:updated.w,h:updated.h}),previous:Object.freeze({w:cell.w,h:cell.h})})),this.emit("lr-layout-change",Object.freeze({layout:result.layout})),!0)}cellStyle(cell){return{"grid-column":`${cell.x+1} / span ${cell.w}`,"grid-row":`${cell.y+1} / span ${cell.h}`}}measurePitch(){const baseEl=this.renderRoot.querySelector('[part="base"]');if(!baseEl)return null;const ownerWindow=baseEl.ownerDocument.defaultView;if(!ownerWindow)return null;const rect=baseEl.getBoundingClientRect(),computed=ownerWindow.getComputedStyle(baseEl),columns=this.safeColumns,contentWidth=rect.width-finiteRange(Number.parseFloat(computed.borderLeftWidth),0,0)-finiteRange(Number.parseFloat(computed.borderRightWidth),0,0)-finiteRange(Number.parseFloat(computed.paddingLeft),0,0)-finiteRange(Number.parseFloat(computed.paddingRight),0,0),contentHeight=rect.height-finiteRange(Number.parseFloat(computed.borderTopWidth),0,0)-finiteRange(Number.parseFloat(computed.borderBottomWidth),0,0)-finiteRange(Number.parseFloat(computed.paddingTop),0,0)-finiteRange(Number.parseFloat(computed.paddingBottom),0,0),resolveGap=(value,basis)=>{if(value==="normal")return 0;const magnitude=Number.parseFloat(value);return finiteRange(value.endsWith("%")?magnitude*basis/100:magnitude,this.safeGap,0)},columnGap=resolveGap(computed.columnGap,contentWidth),rowGap=resolveGap(computed.rowGap,contentHeight),columnWidth=finiteRange(Number.parseFloat(computed.gridTemplateColumns),Math.max(0,(contentWidth-columnGap*(columns-1))/columns),0),rowHeight=finiteRange(Number.parseFloat(computed.gridAutoRows),this.safeRowHeight,0),colPitch=columnWidth+columnGap,rowPitch=rowHeight+rowGap;return{colPitch:colPitch>0?colPitch:1,rowPitch:rowPitch>0?rowPitch:1}}resetCellInlineStyle(cellId,wrapper){wrapper.removeAttribute("data-collision");const cell=this.effectiveLayout.find(candidate=>candidate.cellId===cellId);if(cell){const style=this.cellStyle(cell);wrapper.style.gridColumn=style["grid-column"],wrapper.style.gridRow=style["grid-row"]}}canDragCell(cellId){const cell=this.layout.find(candidate=>candidate.cellId===cellId);return this.cellsDraggable&&!this.readonly&&cell!==void 0&&!cell.locked}canResizeCell(cellId){const cell=this.layout.find(candidate=>candidate.cellId===cellId);return this.cellsResizable&&!this.readonly&&cell!==void 0&&!cell.locked}capturePointer(target,pointerId){try{target.setPointerCapture?.(pointerId)}catch{}}releaseGesturePointerCapture(target,pointerId){try{target.releasePointerCapture?.(pointerId)}catch{}}cancelCellDrag(){const drag=this.cellDrag;drag&&(this.cellDrag=void 0,drag.previewFrame!==void 0&&drag.ownerWindow.cancelAnimationFrame(drag.previewFrame),this.releaseGesturePointerCapture(drag.wrapper,drag.pointerId),drag.wrapper.removeAttribute("data-dragging"),this.resetCellInlineStyle(drag.cellId,drag.wrapper),drag.ownerWindow.removeEventListener("pointermove",this.onCellPointerMove),drag.ownerWindow.removeEventListener("pointerup",this.onCellPointerUp),drag.ownerWindow.removeEventListener("pointercancel",this.onCellPointerUp),drag.ownerWindow.removeEventListener("lostpointercapture",this.onCellPointerUp))}cancelCellResize(){const resize=this.cellResize;resize&&(this.cellResize=void 0,resize.previewFrame!==void 0&&resize.ownerWindow.cancelAnimationFrame(resize.previewFrame),this.releaseGesturePointerCapture(resize.captureTarget,resize.pointerId),resize.wrapper.removeAttribute("data-resizing"),this.resetCellInlineStyle(resize.cellId,resize.wrapper),resize.ownerWindow.removeEventListener("pointermove",this.onResizeHandlePointerMove),resize.ownerWindow.removeEventListener("pointerup",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("pointercancel",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("lostpointercapture",this.onResizeHandlePointerUp))}hasInteractiveTarget(e,wrapper){const path=e.composedPath(),stop=path.indexOf(wrapper);for(const node of stop<0?path:path.slice(0,stop)){const element=node;if(typeof element.matches=="function"&&node!==wrapper&&element.matches(INTERACTIVE_DESCENDANT_SELECTOR))return!0}return!1}onCellPointerDown(e,cell){if(!this.cellsDraggable||this.readonly||cell.locked||this.cellDrag||handledPointerDowns.has(e)||!e.isPrimary||e.button!==0)return;const wrapper=e.currentTarget;if(this.hasInteractiveTarget(e,wrapper))return;const ownerWindow=wrapper.ownerDocument.defaultView;if(!ownerWindow)return;const pitch=this.measurePitch();if(!pitch)return;const layout=this.effectiveLayout;handledPointerDowns.add(e),this.cellDrag={pointerId:e.pointerId,cellId:cell.cellId,startClientX:e.clientX,startClientY:e.clientY,startX:cell.x,startY:cell.y,w:cell.w,h:cell.h,...pitch,wrapper,ownerWindow,rtlFlip:isRtl(this)?-1:1,layout,spatialIndex:createDashboardSpatialIndex(layout,this.safeColumns)},this.capturePointer(wrapper,e.pointerId),wrapper.setAttribute("data-dragging",""),ownerWindow.addEventListener("pointermove",this.onCellPointerMove),ownerWindow.addEventListener("pointerup",this.onCellPointerUp),ownerWindow.addEventListener("pointercancel",this.onCellPointerUp),ownerWindow.addEventListener("lostpointercapture",this.onCellPointerUp)}applyDragPreview(drag){if(drag.pendingClientX===void 0||drag.pendingClientY===void 0)return;const clientX=drag.pendingClientX,clientY=drag.pendingClientY;drag.pendingClientX=void 0,drag.pendingClientY=void 0;const dxUnits=Math.round((clientX-drag.startClientX)*drag.rtlFlip/drag.colPitch),dyUnits=Math.round((clientY-drag.startClientY)/drag.rowPitch),{x,y}=clampDashboardCandidate({},{x:drag.startX+dxUnits,y:drag.startY+dyUnits,w:drag.w,h:drag.h},drag.spatialIndex.columns);if(drag.wrapper.style.gridColumn=`${x+1} / span ${drag.w}`,drag.wrapper.style.gridRow=`${y+1} / span ${drag.h}`,this.collision!=="overlap"){const collides=findDashboardCollisions(drag.spatialIndex,{cellId:drag.cellId,x,y,w:drag.w,h:drag.h}).length>0;drag.wrapper.toggleAttribute("data-collision",collides)}else drag.wrapper.removeAttribute("data-collision");drag.currentX=x,drag.currentY=y,(x!==drag.startX||y!==drag.startY)&&(drag.moved=!0)}flushDragPreview(drag){drag.previewFrame!==void 0&&(drag.ownerWindow.cancelAnimationFrame(drag.previewFrame),drag.previewFrame=void 0),this.applyDragPreview(drag)}onResizeHandlePointerDown(e,cell){if(!this.cellsResizable||this.readonly||cell.locked||this.cellResize||!e.isPrimary||e.button!==0)return;const wrapper=e.currentTarget.closest('[part="cell"]');if(!wrapper)return;const ownerWindow=wrapper.ownerDocument.defaultView;if(!ownerWindow)return;const pitch=this.measurePitch();if(!pitch)return;const layout=this.effectiveLayout;handledPointerDowns.add(e);const captureTarget=e.currentTarget;this.cellResize={pointerId:e.pointerId,cellId:cell.cellId,startClientX:e.clientX,startClientY:e.clientY,startW:cell.w,startH:cell.h,x:cell.x,y:cell.y,...pitch,wrapper,captureTarget,ownerWindow,rtlFlip:isRtl(this)?-1:1,layout,spatialIndex:createDashboardSpatialIndex(layout,this.safeColumns)},this.capturePointer(captureTarget,e.pointerId),wrapper.setAttribute("data-resizing",""),ownerWindow.addEventListener("pointermove",this.onResizeHandlePointerMove),ownerWindow.addEventListener("pointerup",this.onResizeHandlePointerUp),ownerWindow.addEventListener("pointercancel",this.onResizeHandlePointerUp),ownerWindow.addEventListener("lostpointercapture",this.onResizeHandlePointerUp)}applyResizePreview(resize){if(resize.pendingClientX===void 0||resize.pendingClientY===void 0)return;const clientX=resize.pendingClientX,clientY=resize.pendingClientY;resize.pendingClientX=void 0,resize.pendingClientY=void 0;const dwUnits=Math.round((clientX-resize.startClientX)*resize.rtlFlip/resize.colPitch),dhUnits=Math.round((clientY-resize.startClientY)/resize.rowPitch),{w,h}=clampDashboardCandidate(resize.spatialIndex.byId.get(resize.cellId)??{},{x:resize.x,y:resize.y,w:resize.startW+dwUnits,h:resize.startH+dhUnits},resize.spatialIndex.columns);if(resize.wrapper.style.gridColumn=`${resize.x+1} / span ${w}`,resize.wrapper.style.gridRow=`${resize.y+1} / span ${h}`,this.collision!=="overlap"){const collides=findDashboardCollisions(resize.spatialIndex,{cellId:resize.cellId,x:resize.x,y:resize.y,w,h}).length>0;resize.wrapper.toggleAttribute("data-collision",collides)}else resize.wrapper.removeAttribute("data-collision");resize.currentW=w,resize.currentH=h,(w!==resize.startW||h!==resize.startH)&&(resize.moved=!0)}flushResizePreview(resize){resize.previewFrame!==void 0&&(resize.ownerWindow.cancelAnimationFrame(resize.previewFrame),resize.previewFrame=void 0),this.applyResizePreview(resize)}clearSuppressedClick(){this.suppressedClickTimer!==void 0&&this.suppressedClickWindow&&this.suppressedClickWindow.clearTimeout(this.suppressedClickTimer),this.suppressedClickTimer=void 0,this.suppressedClickWindow=void 0,this.suppressedClickCellId=""}armClickSuppression(cellId,ownerWindow){this.clearSuppressedClick(),this.suppressedClickCellId=cellId,this.suppressedClickWindow=ownerWindow,this.suppressedClickTimer=ownerWindow.setTimeout(()=>{this.suppressedClickTimer=void 0,this.suppressedClickWindow=void 0,this.suppressedClickCellId=""},0)}onCellClick(e,cellId){this.suppressedClickCellId===cellId&&(this.clearSuppressedClick(),e.preventDefault(),e.stopImmediatePropagation())}renderCell(cell,active){const resizableHere=this.cellsResizable&&!this.readonly&&!cell.locked;return html`<div
1
+ import{__decorate}from"tslib";import{eventCollectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{resolveCssLength}from"../../../internal/css-length.js";import{tag}from"../../../internal/prefix.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{Announcer,acquireAnnouncementSink}from"../../../internal/announcer.js";import{isRtl}from"../../../internal/rtl.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{isArrowKey,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{styles}from"./dashboard-grid.styles.js";import{clampDashboardCandidate,createDashboardSpatialIndex,findDashboardCollisions,normalizeLyraDashboardCollisionPolicy,projectDashboardLayout,resolveDashboardPlacement,snapshotDashboardLayout,sortDashboardSpatial}from"./layout-internal.js";import{createWidgetDocument}from"../../conversation/widget-renderer/resolve.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dashboardCellCollisionRejected,LYRA_DEFAULT_dashboardCellMoved,LYRA_DEFAULT_dashboardCellResized,LYRA_DEFAULT_dashboardGridLabel}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_flowItemAnnouncement,LYRA_DEFAULT_noData}from"../../../internal/default-strings/shared.generated.js";const INTERACTIVE_DESCENDANT_SELECTOR='button, a[href], area[href], input, select, textarea, summary, label, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="switch"], [role="slider"], [role="spinbutton"], [role="textbox"], [role="combobox"], [role="option"], [role="menuitem"], [tabindex]:not([part="cell"])',DASHBOARD_LENGTH_CONVERTER={fromAttribute:value=>{if(value===null)return value;const number=Number(value);return Number.isNaN(number)?value:number}},GEOMETRY_KEYS=["cellId","x","y","w","h","minW","maxW","minH","maxH","locked"],sortedByLayout=new WeakMap,assignedWidgets=new WeakMap,handledPointerDowns=new WeakSet;function sameGeometry(a,b){return a===b||a.length===b.length&&a.every((cell,i)=>GEOMETRY_KEYS.every(key=>cell[key]===b[i][key]))}const UNMATCHED_AUTHORED_CELL_WARNING_KEY="lyra-dashboard-grid-unmatched-authored-cell",UNMATCHED_AUTHORED_CELL_WARNING="<lr-dashboard-grid>: an authored child has a cell-id that matches no layout entry and will not render.";class LyraDashboardGrid extends LyraElement{constructor(){super(...arguments),this.authoredLayout=Object.freeze([]),this.effectiveLayout=Object.freeze([]),this.columns=12,this.rowHeight=80,this.gap=8,this.collisionValue="reject",this.cellsDraggable=!1,this.cellsResizable=!1,this.readonly=!1,this.accessibleLabel=null,this.announcer=new Announcer({onFlush:text=>{this.liveText=text,isAccessibilityVisible(this)&&this.announcementSink?.announce(text)}}),this.liveText="",this.activeCellIndex=0,this.activeCellId="",this.rehomeCellFocus=!1,this.defaultCellSyncQueued=!1,this.ownedDefaultCells=new WeakSet,this.warnedUnmatchedCells=new WeakSet,this.authoredSlotBaselines=new WeakMap,this.managedAuthoredCells=new Set,this.suppressedClickCellId="",this.onCellPointerMove=e=>{const drag=this.cellDrag;if(!(!drag||e.pointerId!==drag.pointerId)){if(!this.canDragCell(drag.cellId)){this.cancelCellDrag();return}drag.pendingClientX=e.clientX,drag.pendingClientY=e.clientY,drag.previewFrame===void 0&&(drag.previewFrame=drag.ownerWindow.requestAnimationFrame(()=>{drag.previewFrame=void 0,this.cellDrag===drag&&this.applyDragPreview(drag)}))}},this.onCellPointerUp=e=>{const drag=this.cellDrag;if(!drag||e.pointerId!==drag.pointerId)return;if(e.type!=="pointerup"||!this.canDragCell(drag.cellId)){this.cancelCellDrag();return}this.flushDragPreview(drag),this.cellDrag=void 0,this.releaseGesturePointerCapture(drag.wrapper,drag.pointerId),drag.wrapper.removeAttribute("data-dragging"),drag.ownerWindow.removeEventListener("pointermove",this.onCellPointerMove),drag.ownerWindow.removeEventListener("pointerup",this.onCellPointerUp),drag.ownerWindow.removeEventListener("pointercancel",this.onCellPointerUp),drag.ownerWindow.removeEventListener("lostpointercapture",this.onCellPointerUp);const x=drag.currentX??drag.startX,y=drag.currentY??drag.startY;(x!==drag.startX||y!==drag.startY)&&this.commitPlacement(drag.cellId,{x,y,w:drag.w,h:drag.h},"move"),drag.moved&&this.armClickSuppression(drag.cellId,drag.ownerWindow),this.resetCellInlineStyle(drag.cellId,drag.wrapper),this.requestUpdate()},this.onResizeHandlePointerMove=e=>{const resize=this.cellResize;if(!(!resize||e.pointerId!==resize.pointerId)){if(!this.canResizeCell(resize.cellId)){this.cancelCellResize();return}resize.pendingClientX=e.clientX,resize.pendingClientY=e.clientY,resize.previewFrame===void 0&&(resize.previewFrame=resize.ownerWindow.requestAnimationFrame(()=>{resize.previewFrame=void 0,this.cellResize===resize&&this.applyResizePreview(resize)}))}},this.onResizeHandlePointerUp=e=>{const resize=this.cellResize;if(!resize||e.pointerId!==resize.pointerId)return;if(e.type!=="pointerup"||!this.canResizeCell(resize.cellId)){this.cancelCellResize();return}this.flushResizePreview(resize),this.cellResize=void 0,this.releaseGesturePointerCapture(resize.captureTarget,resize.pointerId),resize.wrapper.removeAttribute("data-resizing"),resize.ownerWindow.removeEventListener("pointermove",this.onResizeHandlePointerMove),resize.ownerWindow.removeEventListener("pointerup",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("pointercancel",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("lostpointercapture",this.onResizeHandlePointerUp);const w=resize.currentW??resize.startW,h=resize.currentH??resize.startH;(w!==resize.startW||h!==resize.startH)&&this.commitPlacement(resize.cellId,{x:resize.x,y:resize.y,w,h},"resize"),resize.moved&&this.armClickSuppression(resize.cellId,resize.ownerWindow),this.resetCellInlineStyle(resize.cellId,resize.wrapper),this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,dashboardCellCollisionRejected:LYRA_DEFAULT_dashboardCellCollisionRejected,dashboardCellMoved:LYRA_DEFAULT_dashboardCellMoved,dashboardCellResized:LYRA_DEFAULT_dashboardCellResized,dashboardGridLabel:LYRA_DEFAULT_dashboardGridLabel,flowItemAnnouncement:LYRA_DEFAULT_flowItemAnnouncement,noData:LYRA_DEFAULT_noData}}static{this.collectionSupport=eventCollectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-collision","lr-layout-change"])}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this.effectiveLayout}set layout(value){if(value===this.layoutInput)return;this.layoutInput=value;const previous=this.effectiveLayout;this.authoredLayout=snapshotDashboardLayout(value),this.effectiveLayout=projectDashboardLayout(this.authoredLayout,this.safeColumns),this.announceAppliedPlacement(),this.requestUpdate("layout",previous)}get collision(){return this.collisionValue}set collision(value){const previous=this.collisionValue;this.collisionValue=normalizeLyraDashboardCollisionPolicy(value),this.requestUpdate("collision",previous)}get safeColumns(){return finiteInteger(this.columns,12,1,48)}get safeRowHeight(){return finiteRange(this.lengthInPixels(this.rowHeight),80,1)}get safeGap(){return finiteRange(this.lengthInPixels(this.gap),8,0)}lengthInPixels(value){return typeof value=="number"?value:typeof value!="string"?Number.NaN:resolveCssLength(value,{host:this})??Number.NaN}get sortedLayout(){const layout=this.effectiveLayout;let sorted=sortedByLayout.get(layout);return sorted||sortedByLayout.set(layout,sorted=sortDashboardSpatial(layout)),sorted}connectedCallback(){super.connectedCallback(),this.bindOwnerRealmResources(),this.scheduleDefaultCellSync()}disconnectedCallback(){this.announcer.cancel(),this.announcementSink?.release(),this.announcementSink=void 0,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0,this.defaultCellSyncQueued=!1,this.restoreManagedAuthoredSlots(),this.clearSuppressedClick(),this.pendingPlacementAnnouncement=void 0,this.cancelCellDrag(),this.cancelCellResize(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0,this.announcementSink?.release(),this.announcementSink=void 0,this.clearSuppressedClick(),this.isConnected&&(this.bindOwnerRealmResources(),this.scheduleDefaultCellSync())}bindOwnerRealmResources(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcementSink??=acquireAnnouncementSink("polite",{document:ownerDocument,source:this}),this.childObserver&&this.childObserverDocument===ownerDocument)return;this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0;const MutationObserverCtor=ownerWindow?.MutationObserver;if(!MutationObserverCtor)return;const observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||!records.some(record=>record.type==="childList"?record.target===this:record.target.parentNode===this)||this.scheduleDefaultCellSync()});observer.observe(this,{childList:!0,attributes:!0,attributeFilter:["cell-id"],subtree:!0}),this.childObserver=observer,this.childObserverDocument=ownerDocument}scheduleDefaultCellSync(){!this.isConnected||this.defaultCellSyncQueued||(this.defaultCellSyncQueued=!0,queueMicrotask(()=>{this.defaultCellSyncQueued=!1,this.isConnected&&this.syncDefaultCells()}))}willUpdate(changed){if(super.willUpdate(changed),changed.has("columns")&&(this.effectiveLayout=projectDashboardLayout(this.authoredLayout,this.safeColumns)),changed.has("layout")||changed.has("columns")){this.rehomeCellFocus=shadowFocusTarget(this)?.getAttribute("part")==="cell",this.ownerDocument&&this.isConnected&&(this.hasUpdated?this.syncDefaultCells():this.seedFirstRenderState(()=>this.syncDefaultCells()));const cells=this.sortedLayout,retainedIndex=cells.findIndex(cell=>cell.cellId===this.activeCellId),nextIndex=cells.length===0?0:retainedIndex>=0?retainedIndex:Math.min(this.activeCellIndex,cells.length-1);this.activeCellIndex=nextIndex,this.activeCellId=cells[nextIndex]?.cellId??""}this.cellDrag&&(!sameGeometry(this.cellDrag.layout,this.effectiveLayout)||changed.has("columns")||changed.has("rowHeight")||changed.has("gap")||(changed.has("cellsDraggable")||changed.has("readonly"))&&!this.canDragCell(this.cellDrag.cellId))&&this.cancelCellDrag(),this.cellResize&&(!sameGeometry(this.cellResize.layout,this.effectiveLayout)||changed.has("columns")||changed.has("rowHeight")||changed.has("gap")||(changed.has("cellsResizable")||changed.has("readonly"))&&!this.canResizeCell(this.cellResize.cellId))&&this.cancelCellResize()}updated(changed){super.updated(changed),this.rehomeCellFocus&&(this.rehomeCellFocus=!1,this.renderRoot.querySelector('[part="cell"][tabindex="0"]')?.focus())}cellLabel(cell){return cell.label||cell.cellId}restoreAuthoredSlot(child){if(!this.authoredSlotBaselines.has(child))return;const baseline=this.authoredSlotBaselines.get(child);baseline===null?child.removeAttribute("slot"):baseline!==void 0&&child.setAttribute("slot",baseline),this.authoredSlotBaselines.delete(child),this.managedAuthoredCells.delete(child)}restoreManagedAuthoredSlots(){for(const child of this.managedAuthoredCells)this.restoreAuthoredSlot(child);this.managedAuthoredCells.clear()}syncDefaultCells(){if(!this.isConnected)return;const ids=new Set(this.effectiveLayout.map(cell=>cell.cellId)),authoredById=new Map,ownedById=new Map;for(const child of Array.from(this.children)){if(this.ownedDefaultCells.has(child)){const ownedCellId=child.getAttribute("data-cell-id");if(!ownedCellId){child.remove();continue}const matches=ownedById.get(ownedCellId)??[];matches.push(child),ownedById.set(ownedCellId,matches);continue}const cellId=child.getAttribute("cell-id");cellId&&ids.has(cellId)&&!authoredById.has(cellId)?(authoredById.set(cellId,child),this.warnedUnmatchedCells.delete(child),this.authoredSlotBaselines.has(child)||this.authoredSlotBaselines.set(child,child.getAttribute("slot")),this.managedAuthoredCells.add(child),child.setAttribute("slot",`cell-${cellId}`)):(this.restoreAuthoredSlot(child),cellId&&!ids.has(cellId)&&!this.warnedUnmatchedCells.has(child)&&(this.warnedUnmatchedCells.add(child),devWarnOnce(UNMATCHED_AUTHORED_CELL_WARNING_KEY,UNMATCHED_AUTHORED_CELL_WARNING)))}const selectedAuthored=new Set(authoredById.values());for(const managed of[...this.managedAuthoredCells])(!this.contains(managed)||!selectedAuthored.has(managed))&&this.restoreAuthoredSlot(managed);for(const cell of this.effectiveLayout){const owned=ownedById.get(cell.cellId)??[];if(authoredById.has(cell.cellId)){for(const defaultCell of owned)defaultCell.remove();continue}const existing=owned.shift();existing?(existing.setAttribute("slot",`cell-${cell.cellId}`),this.updateDefaultCell(existing,cell)):this.appendChild(this.createDefaultCell(cell));for(const duplicate of owned)duplicate.remove();ownedById.delete(cell.cellId)}for(const stale of ownedById.values())for(const defaultCell of stale)defaultCell.remove()}createDefaultCell(cell){const ownerDocument=this.ownerDocument,widget=ownerDocument.createElement(tag("widget"));widget.setAttribute("data-cell-id",cell.cellId),widget.setAttribute("data-dashboard-grid-default-cell",""),widget.setAttribute("slot",`cell-${cell.cellId}`),this.ownedDefaultCells.add(widget);const renderer=ownerDocument.createElement(tag("widget-renderer"));return widget.appendChild(renderer),this.updateDefaultCell(widget,cell),widget}updateDefaultCell(widget,cell){widget.label=this.cellLabel(cell);const renderer=widget.querySelector(tag("widget-renderer"));renderer&&assignedWidgets.get(renderer)!==cell.widget&&(assignedWidgets.set(renderer,cell.widget),renderer.document=cell.widget==null?null:createWidgetDocument(cell.widget))}onCellFocus(cellId){const index=this.sortedLayout.findIndex(cell=>cell.cellId===cellId);index>=0&&(this.activeCellIndex!==index&&(this.activeCellIndex=index),this.activeCellId!==cellId&&(this.activeCellId=cellId))}cellElement(cellId){const ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=this.renderRoot.querySelector(`[part="cell"][data-cell-id="${ownerCss.escape(cellId)}"]`);if(candidate?.getAttribute("data-cell-id")===cellId)return candidate}catch{}return Array.from(this.renderRoot.querySelectorAll('[part="cell"][data-cell-id]')).find(candidate=>candidate.getAttribute("data-cell-id")===cellId)??null}focusCellAt(index){const cells=this.sortedLayout;if(index<0||index>=cells.length)return;this.activeCellIndex=index;const cell=cells[index];this.activeCellId=cell.cellId;const number=getNumberFormat(this.effectiveLocale);this.announcer.announce(this.localize("flowItemAnnouncement",void 0,{item:this.cellLabel(cell),index:number.format(index+1),total:number.format(cells.length)})),this.updateComplete.then(()=>{this.cellElement(cell.cellId)?.focus()})}onCellKeyDown(e,cell){const owner=e.currentTarget;if(e.composedPath()[0]!==owner)return;const isMod=e.ctrlKey||e.metaKey;if(isMod&&isArrowKey(e.key)){(e.shiftKey?this.keyboardResize(cell,e.key):this.keyboardMove(cell,e.key))&&e.preventDefault();return}if(e.altKey||isMod||e.isComposing)return;const cells=this.sortedLayout,index=cells.findIndex(c=>c.cellId===cell.cellId);if(index<0)return;const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=index;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(cells.length-1,index+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,index-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=cells.length-1;else return;next!==index&&(e.preventDefault(),this.focusCellAt(next))}keyboardMove(cell,key){if(!this.cellsDraggable||this.readonly||cell.locked)return!1;const rtlFlip=isRtl(this)?-1:1;let dx=0,dy=0;if(key==="ArrowRight")dx=rtlFlip;else if(key==="ArrowLeft")dx=-rtlFlip;else if(key==="ArrowDown")dy=1;else if(key==="ArrowUp")dy=-1;else return!1;return this.commitPlacement(cell.cellId,{x:cell.x+dx,y:cell.y+dy,w:cell.w,h:cell.h},"move")}keyboardResize(cell,key){if(!this.cellsResizable||this.readonly||cell.locked)return!1;let dw=0,dh=0;if(key==="ArrowRight")dw=1;else if(key==="ArrowLeft")dw=-1;else if(key==="ArrowDown")dh=1;else if(key==="ArrowUp")dh=-1;else return!1;return this.commitPlacement(cell.cellId,{x:cell.x,y:cell.y,w:cell.w+dw,h:cell.h+dh},"resize")}announceAppliedPlacement(){const pending=this.pendingPlacementAnnouncement;if(!pending)return;this.pendingPlacementAnnouncement=void 0;const cell=this.effectiveLayout.find(candidate=>candidate.cellId===pending.cellId);if(!cell||!(pending.kind==="move"?cell.x===pending.x&&cell.y===pending.y:cell.w===pending.w&&cell.h===pending.h))return;const number=getNumberFormat(this.effectiveLocale);if(pending.kind==="move"){this.announcer.announce(this.localize("dashboardCellMoved",void 0,{label:this.cellLabel(cell),x:number.format(cell.x+1),y:number.format(cell.y+1)}));return}this.announcer.announce(this.localize("dashboardCellResized",void 0,{label:this.cellLabel(cell),w:number.format(cell.w),h:number.format(cell.h)}))}commitPlacement(cellId,requested,kind){const layout=this.effectiveLayout,cell=layout.find(candidate=>candidate.cellId===cellId);if(!cell)return!1;const result=resolveDashboardPlacement(layout,cellId,requested,this.safeColumns,this.collision);if(result.collidedCellIds.length>0&&this.emit("lr-collision",Object.freeze({cellId,collidedCellIds:result.collidedCellIds,policy:this.collision,accepted:result.accepted})),!result.accepted)return this.announcer.announce(this.localize("dashboardCellCollisionRejected",void 0,{label:this.cellLabel(cell)})),!0;const updated=result.layout.find(candidate=>candidate.cellId===cellId);return(kind==="move"?updated.x===cell.x&&updated.y===cell.y:updated.w===cell.w&&updated.h===cell.h)?!1:(this.pendingPlacementAnnouncement={cellId,kind,x:updated.x,y:updated.y,w:updated.w,h:updated.h},kind==="move"?this.emit("lr-cell-move",Object.freeze({cellId,position:Object.freeze({x:updated.x,y:updated.y}),previous:Object.freeze({x:cell.x,y:cell.y})})):this.emit("lr-cell-resize",Object.freeze({cellId,size:Object.freeze({w:updated.w,h:updated.h}),previous:Object.freeze({w:cell.w,h:cell.h})})),this.emit("lr-layout-change",Object.freeze({layout:result.layout})),!0)}cellStyle(cell){return{"grid-column":`${cell.x+1} / span ${cell.w}`,"grid-row":`${cell.y+1} / span ${cell.h}`}}measurePitch(){const baseEl=this.renderRoot.querySelector('[part="base"]');if(!baseEl)return null;const ownerWindow=baseEl.ownerDocument.defaultView;if(!ownerWindow)return null;const rect=baseEl.getBoundingClientRect(),computed=ownerWindow.getComputedStyle(baseEl),columns=this.safeColumns,contentWidth=rect.width-finiteRange(Number.parseFloat(computed.borderLeftWidth),0,0)-finiteRange(Number.parseFloat(computed.borderRightWidth),0,0)-finiteRange(Number.parseFloat(computed.paddingLeft),0,0)-finiteRange(Number.parseFloat(computed.paddingRight),0,0),contentHeight=rect.height-finiteRange(Number.parseFloat(computed.borderTopWidth),0,0)-finiteRange(Number.parseFloat(computed.borderBottomWidth),0,0)-finiteRange(Number.parseFloat(computed.paddingTop),0,0)-finiteRange(Number.parseFloat(computed.paddingBottom),0,0),resolveGap=(value,basis)=>{if(value==="normal")return 0;const magnitude=Number.parseFloat(value);return finiteRange(value.endsWith("%")?magnitude*basis/100:magnitude,this.safeGap,0)},columnGap=resolveGap(computed.columnGap,contentWidth),rowGap=resolveGap(computed.rowGap,contentHeight),columnWidth=finiteRange(Number.parseFloat(computed.gridTemplateColumns),Math.max(0,(contentWidth-columnGap*(columns-1))/columns),0),rowHeight=finiteRange(Number.parseFloat(computed.gridAutoRows),this.safeRowHeight,0),colPitch=columnWidth+columnGap,rowPitch=rowHeight+rowGap;return{colPitch:colPitch>0?colPitch:1,rowPitch:rowPitch>0?rowPitch:1}}resetCellInlineStyle(cellId,wrapper){wrapper.removeAttribute("data-collision");const cell=this.effectiveLayout.find(candidate=>candidate.cellId===cellId);if(cell){const style=this.cellStyle(cell);wrapper.style.gridColumn=style["grid-column"],wrapper.style.gridRow=style["grid-row"]}}canDragCell(cellId){const cell=this.layout.find(candidate=>candidate.cellId===cellId);return this.cellsDraggable&&!this.readonly&&cell!==void 0&&!cell.locked}canResizeCell(cellId){const cell=this.layout.find(candidate=>candidate.cellId===cellId);return this.cellsResizable&&!this.readonly&&cell!==void 0&&!cell.locked}capturePointer(target,pointerId){try{target.setPointerCapture?.(pointerId)}catch{}}releaseGesturePointerCapture(target,pointerId){try{target.releasePointerCapture?.(pointerId)}catch{}}cancelCellDrag(){const drag=this.cellDrag;drag&&(this.cellDrag=void 0,drag.previewFrame!==void 0&&drag.ownerWindow.cancelAnimationFrame(drag.previewFrame),this.releaseGesturePointerCapture(drag.wrapper,drag.pointerId),drag.wrapper.removeAttribute("data-dragging"),this.resetCellInlineStyle(drag.cellId,drag.wrapper),drag.ownerWindow.removeEventListener("pointermove",this.onCellPointerMove),drag.ownerWindow.removeEventListener("pointerup",this.onCellPointerUp),drag.ownerWindow.removeEventListener("pointercancel",this.onCellPointerUp),drag.ownerWindow.removeEventListener("lostpointercapture",this.onCellPointerUp))}cancelCellResize(){const resize=this.cellResize;resize&&(this.cellResize=void 0,resize.previewFrame!==void 0&&resize.ownerWindow.cancelAnimationFrame(resize.previewFrame),this.releaseGesturePointerCapture(resize.captureTarget,resize.pointerId),resize.wrapper.removeAttribute("data-resizing"),this.resetCellInlineStyle(resize.cellId,resize.wrapper),resize.ownerWindow.removeEventListener("pointermove",this.onResizeHandlePointerMove),resize.ownerWindow.removeEventListener("pointerup",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("pointercancel",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("lostpointercapture",this.onResizeHandlePointerUp))}hasInteractiveTarget(e,wrapper){const path=e.composedPath(),stop=path.indexOf(wrapper);for(const node of stop<0?path:path.slice(0,stop)){const element=node;if(typeof element.matches=="function"&&node!==wrapper&&element.matches(INTERACTIVE_DESCENDANT_SELECTOR))return!0}return!1}onCellPointerDown(e,cell){if(!this.cellsDraggable||this.readonly||cell.locked||this.cellDrag||handledPointerDowns.has(e)||!e.isPrimary||e.button!==0)return;const wrapper=e.currentTarget;if(this.hasInteractiveTarget(e,wrapper))return;const ownerWindow=wrapper.ownerDocument.defaultView;if(!ownerWindow)return;const pitch=this.measurePitch();if(!pitch)return;const layout=this.effectiveLayout;handledPointerDowns.add(e),this.cellDrag={pointerId:e.pointerId,cellId:cell.cellId,startClientX:e.clientX,startClientY:e.clientY,startX:cell.x,startY:cell.y,w:cell.w,h:cell.h,...pitch,wrapper,ownerWindow,rtlFlip:isRtl(this)?-1:1,layout,spatialIndex:createDashboardSpatialIndex(layout,this.safeColumns)},this.capturePointer(wrapper,e.pointerId),wrapper.setAttribute("data-dragging",""),ownerWindow.addEventListener("pointermove",this.onCellPointerMove),ownerWindow.addEventListener("pointerup",this.onCellPointerUp),ownerWindow.addEventListener("pointercancel",this.onCellPointerUp),ownerWindow.addEventListener("lostpointercapture",this.onCellPointerUp)}applyDragPreview(drag){if(drag.pendingClientX===void 0||drag.pendingClientY===void 0)return;const clientX=drag.pendingClientX,clientY=drag.pendingClientY;drag.pendingClientX=void 0,drag.pendingClientY=void 0;const dxUnits=Math.round((clientX-drag.startClientX)*drag.rtlFlip/drag.colPitch),dyUnits=Math.round((clientY-drag.startClientY)/drag.rowPitch),{x,y}=clampDashboardCandidate({},{x:drag.startX+dxUnits,y:drag.startY+dyUnits,w:drag.w,h:drag.h},drag.spatialIndex.columns);if(drag.wrapper.style.gridColumn=`${x+1} / span ${drag.w}`,drag.wrapper.style.gridRow=`${y+1} / span ${drag.h}`,this.collision!=="overlap"){const collides=findDashboardCollisions(drag.spatialIndex,{cellId:drag.cellId,x,y,w:drag.w,h:drag.h}).length>0;drag.wrapper.toggleAttribute("data-collision",collides)}else drag.wrapper.removeAttribute("data-collision");drag.currentX=x,drag.currentY=y,(x!==drag.startX||y!==drag.startY)&&(drag.moved=!0)}flushDragPreview(drag){drag.previewFrame!==void 0&&(drag.ownerWindow.cancelAnimationFrame(drag.previewFrame),drag.previewFrame=void 0),this.applyDragPreview(drag)}onResizeHandlePointerDown(e,cell){if(!this.cellsResizable||this.readonly||cell.locked||this.cellResize||!e.isPrimary||e.button!==0)return;const wrapper=e.currentTarget.closest('[part="cell"]');if(!wrapper)return;const ownerWindow=wrapper.ownerDocument.defaultView;if(!ownerWindow)return;const pitch=this.measurePitch();if(!pitch)return;const layout=this.effectiveLayout;handledPointerDowns.add(e);const captureTarget=e.currentTarget;this.cellResize={pointerId:e.pointerId,cellId:cell.cellId,startClientX:e.clientX,startClientY:e.clientY,startW:cell.w,startH:cell.h,x:cell.x,y:cell.y,...pitch,wrapper,captureTarget,ownerWindow,rtlFlip:isRtl(this)?-1:1,layout,spatialIndex:createDashboardSpatialIndex(layout,this.safeColumns)},this.capturePointer(captureTarget,e.pointerId),wrapper.setAttribute("data-resizing",""),ownerWindow.addEventListener("pointermove",this.onResizeHandlePointerMove),ownerWindow.addEventListener("pointerup",this.onResizeHandlePointerUp),ownerWindow.addEventListener("pointercancel",this.onResizeHandlePointerUp),ownerWindow.addEventListener("lostpointercapture",this.onResizeHandlePointerUp)}applyResizePreview(resize){if(resize.pendingClientX===void 0||resize.pendingClientY===void 0)return;const clientX=resize.pendingClientX,clientY=resize.pendingClientY;resize.pendingClientX=void 0,resize.pendingClientY=void 0;const dwUnits=Math.round((clientX-resize.startClientX)*resize.rtlFlip/resize.colPitch),dhUnits=Math.round((clientY-resize.startClientY)/resize.rowPitch),{w,h}=clampDashboardCandidate(resize.spatialIndex.byId.get(resize.cellId)??{},{x:resize.x,y:resize.y,w:resize.startW+dwUnits,h:resize.startH+dhUnits},resize.spatialIndex.columns);if(resize.wrapper.style.gridColumn=`${resize.x+1} / span ${w}`,resize.wrapper.style.gridRow=`${resize.y+1} / span ${h}`,this.collision!=="overlap"){const collides=findDashboardCollisions(resize.spatialIndex,{cellId:resize.cellId,x:resize.x,y:resize.y,w,h}).length>0;resize.wrapper.toggleAttribute("data-collision",collides)}else resize.wrapper.removeAttribute("data-collision");resize.currentW=w,resize.currentH=h,(w!==resize.startW||h!==resize.startH)&&(resize.moved=!0)}flushResizePreview(resize){resize.previewFrame!==void 0&&(resize.ownerWindow.cancelAnimationFrame(resize.previewFrame),resize.previewFrame=void 0),this.applyResizePreview(resize)}clearSuppressedClick(){this.suppressedClickTimer!==void 0&&this.suppressedClickWindow&&this.suppressedClickWindow.clearTimeout(this.suppressedClickTimer),this.suppressedClickTimer=void 0,this.suppressedClickWindow=void 0,this.suppressedClickCellId=""}armClickSuppression(cellId,ownerWindow){this.clearSuppressedClick(),this.suppressedClickCellId=cellId,this.suppressedClickWindow=ownerWindow,this.suppressedClickTimer=ownerWindow.setTimeout(()=>{this.suppressedClickTimer=void 0,this.suppressedClickWindow=void 0,this.suppressedClickCellId=""},0)}onCellClick(e,cellId){this.suppressedClickCellId===cellId&&(this.clearSuppressedClick(),e.preventDefault(),e.stopImmediatePropagation())}renderCell(cell,active){const resizableHere=this.cellsResizable&&!this.readonly&&!cell.locked;return html`<div
2
2
  part="cell"
3
3
  role="group"
4
4
  tabindex=${active?"0":"-1"}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./accordion-item.styles.js";import{DisclosureMotionController}from"./disclosure-motion.js";import{accordionItemOwnerContext,notifyAccordionItemStateChanged,notifyAccordionItemTransitionSettled,registerAccordionItemStateController,requestAccordionItemTransition}from"./accordion-owner.js";import{LYRA_DEFAULT_details}from"../../../internal/default-strings.generated.js";class LyraAccordionItem extends LyraElement{static{this.defaultStrings={...super.defaultStrings,details:LYRA_DEFAULT_details}}static{this.styles=[LyraElement.styles,sizes,styles]}constructor(){super(),this.itemInternals=attachInternalsSafely(this),this.disclosureMotion=new DisclosureMotionController(this,this.itemInternals,()=>this.renderRoot,'[part~="accordion-item"]'),this._expanded=!1,this.hasLabel=!1,this.settledClosed=!0,this.label="",this.disabled=!1,this.headingLevel="3",this.iconPlacement="end",this.appearance="outlined",this.isTabbable=!0,this.onTrigger=()=>{this.disabled||this.transitionTo(!this.expanded,"user")},this.onLabel=event=>{this.hasLabel=event.target.assignedElements({flatten:!0}).length>0},this.onBeforeMatch=event=>{const clip=event.currentTarget;this.transitionTo(!0,"user"),queueMicrotask(()=>{!this._expanded&&this.settledClosed&&clip.setAttribute("hidden","until-found")})},registerAccordionItemStateController(this,(expanded,announce)=>this.transitionTo(expanded,"programmatic",!0,announce))}get expanded(){return this._expanded}set expanded(next){const normalized=!!next;if(normalized!==this._expanded){if(!this.hasUpdated){this.applyExpandedState(normalized);return}this.transitionTo(normalized,"programmatic")}}disconnectedCallback(){this.disclosureMotion.cancel(),this.settledClosed=!this._expanded,super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabel=Array.from(this.children).some(child=>child.getAttribute("slot")==="label"))}updated(changed){super.updated(changed),changed.has("disabled")&&notifyAccordionItemStateChanged(this)}applyExpandedState(next){const old=this._expanded,panel=this.renderRoot?.querySelector("#panel");next?this.settledClosed=!1:panel&&this.disclosureMotion.repairFocus(panel,this.button),this._expanded=next,this.requestUpdate("expanded",old)}syncExpandedAttribute(){this.toggleAttribute("expanded",this._expanded)}async transitionTo(expanded,source,ownerPreflighted=!1,announceOwner=!0){if(expanded!==this._expanded){if(!ownerPreflighted&&this.disabled){this.syncExpandedAttribute();return}if(!ownerPreflighted&&requestAccordionItemTransition(this,expanded,source)===!1){this.syncExpandedAttribute();return}this.applyExpandedState(expanded),await this.disclosureMotion.settle()&&(this.settledClosed=!this._expanded,announceOwner&&notifyAccordionItemTransitionSettled(this,expanded))}}expand(){return this.transitionTo(!0,"programmatic")}collapse(){return this.transitionTo(!1,"programmatic")}toggle(){return this.transitionTo(!this.expanded,"programmatic")}focus(options){this.button?.focus(options)}click(){const trigger=this.button;trigger?trigger.click():super.click()}get button(){return this.renderRoot.querySelector('[part~="button"]')}heading(level,button){switch(level){case"1":return html`<h1 part="heading">${button}</h1>`;case"2":return html`<h2 part="heading">${button}</h2>`;case"4":return html`<h4 part="heading">${button}</h4>`;case"5":return html`<h5 part="heading">${button}</h5>`;case"6":return html`<h6 part="heading">${button}</h6>`;default:return html`<h3 part="heading">${button}</h3>`}}get effectiveAppearance(){return accordionItemOwnerContext(this)?.appearance??this.appearance}get effectiveHeadingLevel(){return accordionItemOwnerContext(this)?.headingLevel??this.headingLevel}get effectiveIconPlacement(){return accordionItemOwnerContext(this)?.iconPlacement??this.iconPlacement}render(){const fallbackLabel=this.label||this.localize("details"),hostLabel=hostAriaLabel(this),level=resolveHeadingLevel(this.effectiveHeadingLevel),button=html`<button
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{resolveHeadingLevel}from"../../../internal/heading-level.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./accordion-item.styles.js";import{DisclosureMotionController}from"./disclosure-motion.js";import{accordionItemOwnerContext,notifyAccordionItemStateChanged,notifyAccordionItemTransitionSettled,registerAccordionItemStateController,requestAccordionItemTransition}from"./accordion-owner.js";import{LYRA_DEFAULT_details}from"../../../internal/default-strings/shared.generated.js";class LyraAccordionItem extends LyraElement{static{this.defaultStrings={...super.defaultStrings,details:LYRA_DEFAULT_details}}static{this.styles=[LyraElement.styles,sizes,styles]}constructor(){super(),this.itemInternals=attachInternalsSafely(this),this.disclosureMotion=new DisclosureMotionController(this,this.itemInternals,()=>this.renderRoot,'[part~="accordion-item"]'),this._expanded=!1,this.hasLabel=!1,this.settledClosed=!0,this.label="",this.disabled=!1,this.headingLevel="3",this.iconPlacement="end",this.appearance="outlined",this.isTabbable=!0,this.onTrigger=()=>{this.disabled||this.transitionTo(!this.expanded,"user")},this.onLabel=event=>{this.hasLabel=event.target.assignedElements({flatten:!0}).length>0},this.onBeforeMatch=event=>{const clip=event.currentTarget;this.transitionTo(!0,"user"),queueMicrotask(()=>{!this._expanded&&this.settledClosed&&clip.setAttribute("hidden","until-found")})},registerAccordionItemStateController(this,(expanded,announce)=>this.transitionTo(expanded,"programmatic",!0,announce))}get expanded(){return this._expanded}set expanded(next){const normalized=!!next;if(normalized!==this._expanded){if(!this.hasUpdated){this.applyExpandedState(normalized);return}this.transitionTo(normalized,"programmatic")}}disconnectedCallback(){this.disclosureMotion.cancel(),this.settledClosed=!this._expanded,super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasLabel=Array.from(this.children).some(child=>child.getAttribute("slot")==="label"))}updated(changed){super.updated(changed),changed.has("disabled")&&notifyAccordionItemStateChanged(this)}applyExpandedState(next){const old=this._expanded,panel=this.renderRoot?.querySelector("#panel");next?this.settledClosed=!1:panel&&this.disclosureMotion.repairFocus(panel,this.button),this._expanded=next,this.requestUpdate("expanded",old)}syncExpandedAttribute(){this.toggleAttribute("expanded",this._expanded)}async transitionTo(expanded,source,ownerPreflighted=!1,announceOwner=!0){if(expanded!==this._expanded){if(!ownerPreflighted&&this.disabled){this.syncExpandedAttribute();return}if(!ownerPreflighted&&requestAccordionItemTransition(this,expanded,source)===!1){this.syncExpandedAttribute();return}this.applyExpandedState(expanded),await this.disclosureMotion.settle()&&(this.settledClosed=!this._expanded,announceOwner&&notifyAccordionItemTransitionSettled(this,expanded))}}expand(){return this.transitionTo(!0,"programmatic")}collapse(){return this.transitionTo(!1,"programmatic")}toggle(){return this.transitionTo(!this.expanded,"programmatic")}focus(options){this.button?.focus(options)}click(){const trigger=this.button;trigger?trigger.click():super.click()}get button(){return this.renderRoot.querySelector('[part~="button"]')}heading(level,button){switch(level){case"1":return html`<h1 part="heading">${button}</h1>`;case"2":return html`<h2 part="heading">${button}</h2>`;case"4":return html`<h4 part="heading">${button}</h4>`;case"5":return html`<h5 part="heading">${button}</h5>`;case"6":return html`<h6 part="heading">${button}</h6>`;default:return html`<h3 part="heading">${button}</h3>`}}get effectiveAppearance(){return accordionItemOwnerContext(this)?.appearance??this.appearance}get effectiveHeadingLevel(){return accordionItemOwnerContext(this)?.headingLevel??this.headingLevel}get effectiveIconPlacement(){return accordionItemOwnerContext(this)?.iconPlacement??this.iconPlacement}render(){const fallbackLabel=this.label||this.localize("details"),hostLabel=hostAriaLabel(this),level=resolveHeadingLevel(this.effectiveHeadingLevel),button=html`<button
2
2
  id="trigger"
3
3
  part="button"
4
4
  type="button"
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{chevronIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{sizes}from"../../../internal/sizes.styles.js";import{DisclosureMotionController}from"./disclosure-motion.js";import{styles}from"./details.styles.js";import{LYRA_DEFAULT_details}from"../../../internal/default-strings.generated.js";class LyraDetails extends LyraElement{constructor(){super(...arguments),this.detailsInternals=attachInternalsSafely(this),this.disclosureMotion=new DisclosureMotionController(this,this.detailsInternals,()=>this.renderRoot,'[part~="base"]'),this._open=!1,this.contentId=nextId("details-content"),this.contentGateMode="until-found",this.contentGateGeneration=0,this.fragmentNavigationGeneration=0,this.disabled=!1,this.name="",this.appearance="outlined",this.iconPlacement="end",this.size="m",this.summary="",this.hasSummarySlot=!1,this.hasHeaderActionsSlot=!1,this.onBeforeMatch=event=>{const gate=event.currentTarget;if(this._open){this.setContentGateMode("open",gate);return}if(this.beginShow()){this.settleTransition("lr-after-show","programmatic");return}this.rearmContentGate(gate)},this.onHashChange=()=>{this.revealFragmentTarget()},this.onClick=event=>{const path=event.composedPath();if(path.some(node=>node?.nodeType===1&&node.matches('[part~="header-actions"]')))return;const summaryIndex=path.findIndex(node=>node?.nodeType===1&&node.localName==="summary");if(!path.slice(0,summaryIndex<0?0:summaryIndex).some(node=>node?.nodeType===1&&node.matches('a[href], button, input, select, textarea, [contenteditable]:not([contenteditable="false"])'))){if(event.preventDefault(),this.disabled){event.stopPropagation();return}this._open?this.hideWithSource("user"):this.showWithSource("user")}},this.onToggle=event=>{const details=event.currentTarget;details.open!==this._open&&(details.open?this.show():this.hide())},this.onSummarySlotChange=e=>{this.hasSummarySlot=e.target.assignedElements({flatten:!0}).length>0},this.onHeaderActionsSlotChange=e=>{this.hasHeaderActionsSlot=e.target.assignedElements({flatten:!0}).length>0}}static{this.defaultStrings={...super.defaultStrings,details:LYRA_DEFAULT_details}}static{this.styles=[LyraElement.styles,sizes,styles]}get open(){return this._open}set open(next){const normalized=!!next;if(normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.hide()}}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasSummarySlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="summary"),this.hasHeaderActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="header-actions")),this.hasUpdated&&changed.has("name")&&this._open&&!this.closeNamedPeers()&&(this.name=changed.get("name")??"")}connectedCallback(){super.connectedCallback(),this.setContentGateMode(this._open?"open":"until-found"),this.armFragmentNavigation(),!(!this.hasUpdated||!this._open)&&queueMicrotask(()=>{this.isConnected&&this._open&&this.closeNamedPeers()})}disconnectedCallback(){this.disclosureMotion.cancel(),this.disarmFragmentNavigation(),this.contentGateGeneration+=1,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.disarmFragmentNavigation(),this.contentGateGeneration+=1,this.setContentGateMode(this._open?"open":"until-found"),this.isConnected&&this.armFragmentNavigation()}firstUpdated(changed){super.firstUpdated(changed),this._open&&this.closeNamedPeers()}async show(){await this.showWithSource("programmatic")}async showWithSource(source){this.beginShow()&&await this.settleTransition("lr-after-show",source)}beginShow(){if(this._open)return!1;if(this.disabled)return this.syncOpenAttribute(),!1;let opened=!1;return requestThenCommit({requestDetail:null,emitRequest:(detail,init)=>this.emit("lr-show",detail,init),commit:()=>{this.closeNamedPeers()&&(this.applyOpenState(!0),opened=!0)}}),opened||this.syncOpenAttribute(),opened}async hide(){await this.hideWithSource("programmatic")}async hideWithSource(source){if(!this._open)return;let closed=!1;if(requestThenCommit({requestDetail:null,emitRequest:(detail,init)=>this.emit("lr-hide",detail,init),commit:()=>{this.applyOpenState(!1),closed=!0}}),!closed){this.syncOpenAttribute();return}await this.settleTransition("lr-after-hide",source)}closeNamedPeers(){if(!this.name)return!0;const root=this.getRootNode();if(typeof root.querySelectorAll!="function")return!0;let allClosed=!0;for(const candidate of root.querySelectorAll(this.localName))candidate!==this&&candidate instanceof LyraDetails&&candidate.name===this.name&&candidate.open&&(candidate.hideWithSource("peer"),candidate.open&&(allClosed=!1));return allClosed}applyOpenState(next){const old=this._open,gate=this.contentGate;next||this.disclosureMotion.repairFocus(gate,this.summaryElement),this._open=next,this.contentGateGeneration+=1,this.setContentGateMode(next?"open":"until-found"),this.syncNativeDetailsState(),this.syncSummaryState(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open),this.contentGateGeneration+=1,this.setContentGateMode(this._open?"open":"until-found"),this.syncNativeDetailsState(),this.syncSummaryState()}get nativeDetails(){return this.renderRoot?.querySelector("details")??null}get summaryElement(){return this.renderRoot?.querySelector('[part="summary"]')??null}get contentGate(){return this.renderRoot?.querySelector('[part="content"]')?.parentElement??null}setContentGateMode(mode,gate=this.contentGate){this.contentGateMode=mode,gate&&(mode==="open"?gate.removeAttribute("hidden"):gate.setAttribute("hidden",mode==="until-found"?"until-found":""))}syncNativeDetailsState(){const nativeDetails=this.nativeDetails;nativeDetails&&nativeDetails.open!==this._open&&(nativeDetails.open=this._open)}syncSummaryState(){this.summaryElement?.setAttribute("aria-expanded",this._open?"true":"false")}rearmContentGate(gate){const generation=++this.contentGateGeneration;this.setContentGateMode("ordinary-hidden",gate),queueMicrotask(()=>{generation!==this.contentGateGeneration||!this.isConnected||this._open||gate!==this.contentGate||(this.setContentGateMode("until-found",gate),this.requestUpdate())})}armFragmentNavigation(){const view=this.ownerDocument.defaultView;view&&(this.fragmentListenerWindow!==view&&(this.disarmFragmentNavigation(),this.fragmentListenerWindow=view,view.addEventListener("hashchange",this.onHashChange)),this.queueFragmentReveal())}disarmFragmentNavigation(){this.fragmentNavigationGeneration+=1,this.fragmentListenerWindow?.removeEventListener("hashchange",this.onHashChange),this.fragmentListenerWindow=void 0}queueFragmentReveal(){const generation=++this.fragmentNavigationGeneration;queueMicrotask(()=>{generation!==this.fragmentNavigationGeneration||!this.isConnected||this.ownerDocument.defaultView!==this.fragmentListenerWindow||this.revealFragmentTarget()})}revealFragmentTarget(){if(this._open)return;const hash=this.ownerDocument.defaultView?.location.hash;if(!hash||hash.length<2)return;let targetId;try{targetId=decodeURIComponent(hash.slice(1))}catch{return}const target=this.ownerDocument.getElementById(targetId);!target||!this.isDefaultContentTarget(target)||this.showWithSource("programmatic")}isDefaultContentTarget(target){if(target===this||!this.contains(target))return!1;let topLevel=target;for(;topLevel.parentElement&&topLevel.parentElement!==this;)topLevel=topLevel.parentElement;return topLevel.parentElement===this&&(topLevel.getAttribute("slot")??"")===""}async settleTransition(event,source){await this.disclosureMotion.settle(()=>{this.emit("lr-toggle",{expanded:this._open,source})})&&this.emit(event,null)}render(){const gateHidden=this.contentGateMode==="open"?nothing:this.contentGateMode==="until-found"?"until-found":"";return html`
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{chevronIcon}from"../../../internal/icons.js";import{LyraElement}from"../../../internal/lyra-element.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{sizes}from"../../../internal/sizes.styles.js";import{DisclosureMotionController}from"./disclosure-motion.js";import{styles}from"./details.styles.js";import{LYRA_DEFAULT_details}from"../../../internal/default-strings/shared.generated.js";class LyraDetails extends LyraElement{constructor(){super(...arguments),this.detailsInternals=attachInternalsSafely(this),this.disclosureMotion=new DisclosureMotionController(this,this.detailsInternals,()=>this.renderRoot,'[part~="base"]'),this._open=!1,this.contentId=nextId("details-content"),this.contentGateMode="until-found",this.contentGateGeneration=0,this.fragmentNavigationGeneration=0,this.disabled=!1,this.name="",this.appearance="outlined",this.iconPlacement="end",this.size="m",this.summary="",this.hasSummarySlot=!1,this.hasHeaderActionsSlot=!1,this.onBeforeMatch=event=>{const gate=event.currentTarget;if(this._open){this.setContentGateMode("open",gate);return}if(this.beginShow()){this.settleTransition("lr-after-show","programmatic");return}this.rearmContentGate(gate)},this.onHashChange=()=>{this.revealFragmentTarget()},this.onClick=event=>{const path=event.composedPath();if(path.some(node=>node?.nodeType===1&&node.matches('[part~="header-actions"]')))return;const summaryIndex=path.findIndex(node=>node?.nodeType===1&&node.localName==="summary");if(!path.slice(0,summaryIndex<0?0:summaryIndex).some(node=>node?.nodeType===1&&node.matches('a[href], button, input, select, textarea, [contenteditable]:not([contenteditable="false"])'))){if(event.preventDefault(),this.disabled){event.stopPropagation();return}this._open?this.hideWithSource("user"):this.showWithSource("user")}},this.onToggle=event=>{const details=event.currentTarget;details.open!==this._open&&(details.open?this.show():this.hide())},this.onSummarySlotChange=e=>{this.hasSummarySlot=e.target.assignedElements({flatten:!0}).length>0},this.onHeaderActionsSlotChange=e=>{this.hasHeaderActionsSlot=e.target.assignedElements({flatten:!0}).length>0}}static{this.defaultStrings={...super.defaultStrings,details:LYRA_DEFAULT_details}}static{this.styles=[LyraElement.styles,sizes,styles]}get open(){return this._open}set open(next){const normalized=!!next;if(normalized!==this._open){if(!this.hasUpdated){this.applyOpenState(normalized);return}normalized?this.show():this.hide()}}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasSummarySlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="summary"),this.hasHeaderActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="header-actions")),this.hasUpdated&&changed.has("name")&&this._open&&!this.closeNamedPeers()&&(this.name=changed.get("name")??"")}connectedCallback(){super.connectedCallback(),this.setContentGateMode(this._open?"open":"until-found"),this.armFragmentNavigation(),!(!this.hasUpdated||!this._open)&&queueMicrotask(()=>{this.isConnected&&this._open&&this.closeNamedPeers()})}disconnectedCallback(){this.disclosureMotion.cancel(),this.disarmFragmentNavigation(),this.contentGateGeneration+=1,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.disarmFragmentNavigation(),this.contentGateGeneration+=1,this.setContentGateMode(this._open?"open":"until-found"),this.isConnected&&this.armFragmentNavigation()}firstUpdated(changed){super.firstUpdated(changed),this._open&&this.closeNamedPeers()}async show(){await this.showWithSource("programmatic")}async showWithSource(source){this.beginShow()&&await this.settleTransition("lr-after-show",source)}beginShow(){if(this._open)return!1;if(this.disabled)return this.syncOpenAttribute(),!1;let opened=!1;return requestThenCommit({requestDetail:null,emitRequest:(detail,init)=>this.emit("lr-show",detail,init),commit:()=>{this.closeNamedPeers()&&(this.applyOpenState(!0),opened=!0)}}),opened||this.syncOpenAttribute(),opened}async hide(){await this.hideWithSource("programmatic")}async hideWithSource(source){if(!this._open)return;let closed=!1;if(requestThenCommit({requestDetail:null,emitRequest:(detail,init)=>this.emit("lr-hide",detail,init),commit:()=>{this.applyOpenState(!1),closed=!0}}),!closed){this.syncOpenAttribute();return}await this.settleTransition("lr-after-hide",source)}closeNamedPeers(){if(!this.name)return!0;const root=this.getRootNode();if(typeof root.querySelectorAll!="function")return!0;let allClosed=!0;for(const candidate of root.querySelectorAll(this.localName))candidate!==this&&candidate instanceof LyraDetails&&candidate.name===this.name&&candidate.open&&(candidate.hideWithSource("peer"),candidate.open&&(allClosed=!1));return allClosed}applyOpenState(next){const old=this._open,gate=this.contentGate;next||this.disclosureMotion.repairFocus(gate,this.summaryElement),this._open=next,this.contentGateGeneration+=1,this.setContentGateMode(next?"open":"until-found"),this.syncNativeDetailsState(),this.syncSummaryState(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open),this.contentGateGeneration+=1,this.setContentGateMode(this._open?"open":"until-found"),this.syncNativeDetailsState(),this.syncSummaryState()}get nativeDetails(){return this.renderRoot?.querySelector("details")??null}get summaryElement(){return this.renderRoot?.querySelector('[part="summary"]')??null}get contentGate(){return this.renderRoot?.querySelector('[part="content"]')?.parentElement??null}setContentGateMode(mode,gate=this.contentGate){this.contentGateMode=mode,gate&&(mode==="open"?gate.removeAttribute("hidden"):gate.setAttribute("hidden",mode==="until-found"?"until-found":""))}syncNativeDetailsState(){const nativeDetails=this.nativeDetails;nativeDetails&&nativeDetails.open!==this._open&&(nativeDetails.open=this._open)}syncSummaryState(){this.summaryElement?.setAttribute("aria-expanded",this._open?"true":"false")}rearmContentGate(gate){const generation=++this.contentGateGeneration;this.setContentGateMode("ordinary-hidden",gate),queueMicrotask(()=>{generation!==this.contentGateGeneration||!this.isConnected||this._open||gate!==this.contentGate||(this.setContentGateMode("until-found",gate),this.requestUpdate())})}armFragmentNavigation(){const view=this.ownerDocument.defaultView;view&&(this.fragmentListenerWindow!==view&&(this.disarmFragmentNavigation(),this.fragmentListenerWindow=view,view.addEventListener("hashchange",this.onHashChange)),this.queueFragmentReveal())}disarmFragmentNavigation(){this.fragmentNavigationGeneration+=1,this.fragmentListenerWindow?.removeEventListener("hashchange",this.onHashChange),this.fragmentListenerWindow=void 0}queueFragmentReveal(){const generation=++this.fragmentNavigationGeneration;queueMicrotask(()=>{generation!==this.fragmentNavigationGeneration||!this.isConnected||this.ownerDocument.defaultView!==this.fragmentListenerWindow||this.revealFragmentTarget()})}revealFragmentTarget(){if(this._open)return;const hash=this.ownerDocument.defaultView?.location.hash;if(!hash||hash.length<2)return;let targetId;try{targetId=decodeURIComponent(hash.slice(1))}catch{return}const target=this.ownerDocument.getElementById(targetId);!target||!this.isDefaultContentTarget(target)||this.showWithSource("programmatic")}isDefaultContentTarget(target){if(target===this||!this.contains(target))return!1;let topLevel=target;for(;topLevel.parentElement&&topLevel.parentElement!==this;)topLevel=topLevel.parentElement;return topLevel.parentElement===this&&(topLevel.getAttribute("slot")??"")===""}async settleTransition(event,source){await this.disclosureMotion.settle(()=>{this.emit("lr-toggle",{expanded:this._open,source})})&&this.emit(event,null)}render(){const gateHidden=this.contentGateMode==="open"?nothing:this.contentGateMode==="until-found"?"until-found":"";return html`
2
2
  <div part="base details">
3
3
  <div part="header">
4
4
  <details
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{flattenedParentElement}from"../../../internal/composed-tree.js";import{styles}from"./dock-panel.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{SeparatorDragController,separatorArrowDirection,separatorCoordinate}from"../../../internal/separator-drag.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dockPanelCollapse,LYRA_DEFAULT_dockPanelExpand,LYRA_DEFAULT_dockPanelResize,LYRA_DEFAULT_resizeValuePixels}from"../../../internal/default-strings.generated.js";const KEYBOARD_STEP_PX=16;class LyraDockPanel extends LyraElement{constructor(){super(...arguments),this.placement="end",this._extent="280px",this.minExtent="160px",this.maxExtent="",this.collapsible=!1,this.toggleWriteGuard=new VetoWriteGuard,this._collapsed=!1,this.withoutResize=!1,this.drag=null,this.resizeWriteGuard=new VetoWriteGuard,this.resizeRequestSequence=0,this.dragController=new SeparatorDragController(this,event=>this.onPointerMove(event),event=>event.type==="pointerup"?this.onPointerUp(event):this.onPointerCancel(event)),this.contentId=nextId("dock-panel-content"),this.onPointerDown=e=>{if(!e.isPrimary||e.button!==0||this.withoutResize||this.collapsed||this.drag)return;const handle=e.currentTarget;if(!this.dragController.start(e,handle))return;const axis=this.axis,growSign=this.growSign,containerPx=this.containerPx(),startSizePx=this.currentSizePx();this.drag={pointerId:e.pointerId,startPos:separatorCoordinate(e,axis),startSizePx,axis,growSign,placement:this.placement,minExtent:this.minExtent,maxExtent:this.maxExtent,containerPx,bounds:this.resolveBoundsPx(containerPx),currentSizePx:startSizePx,expectedExtent:this.extent,finalExtent:this.extent,acceptedResize:!1}},this.onPointerMove=e=>{const drag=this.drag;if(!drag||e.pointerId!==drag.pointerId)return;if(this.withoutResize||this.collapsed||this.placement!==drag.placement||this.axis!==drag.axis||this.growSign!==drag.growSign||this.extent!==drag.expectedExtent||this.minExtent!==drag.minExtent||this.maxExtent!==drag.maxExtent){this.endDrag();return}const pos=separatorCoordinate(e,drag.axis),delta=drag.growSign*(pos-drag.startPos),proposal=this.resolveProposal(drag.startSizePx+delta,drag.bounds,drag.currentSizePx);if(!proposal)return;const extent=this.requestResize(proposal.bounds,proposal.nextExtent);!extent||this.drag!==drag||(drag.expectedExtent=extent,drag.finalExtent=extent,drag.currentSizePx=parseFloat(extent),drag.acceptedResize=!0,this.emitResize("lr-resize",extent),!(this.drag!==drag||this.extent!==extent||this.collapsed||this.withoutResize)&&this.emitResize("lr-resize-input",extent))},this.onPointerUp=e=>{const drag=this.drag;if(!drag||e.pointerId!==drag.pointerId)return;const shouldCommit=drag.acceptedResize&&this.dragSnapshotIsCurrent(drag),finalExtent=drag.finalExtent;this.endDrag(),shouldCommit&&this.emitResize("lr-resize-change",finalExtent)},this.onPointerCancel=e=>{!this.drag||e.pointerId!==this.drag.pointerId||this.endDrag()},this.onHandleKeyDown=e=>{if(this.withoutResize||this.collapsed||e.altKey||e.ctrlKey||e.metaKey||e.isComposing)return;const arrowDirection=separatorArrowDirection(e,this.axis,!1);let proposal;if(e.key==="Home"||e.key==="End"){e.preventDefault();const{minPx,maxPx}=this.resolveBoundsPx();proposal=this.resolveProposal(e.key==="Home"?minPx:maxPx)}else arrowDirection===1?(e.preventDefault(),proposal=this.resolveProposal(this.currentSizePx()+this.growSign*KEYBOARD_STEP_PX)):arrowDirection===-1&&(e.preventDefault(),proposal=this.resolveProposal(this.currentSizePx()-this.growSign*KEYBOARD_STEP_PX));if(!proposal)return;const extent=this.requestResize(proposal.bounds,proposal.nextExtent);extent&&(this.emitResize("lr-resize",extent),!(this.extent!==extent||this.collapsed||this.withoutResize)&&(this.emitResize("lr-resize-input",extent),!(this.extent!==extent||this.collapsed||this.withoutResize)&&this.emitResize("lr-resize-change",extent)))},this.dispatchingToggle=!1,this.toggleCollapsed=()=>{if(this.dispatchingToggle)return;const previous=this.collapsed,detail=()=>Object.freeze({expanded:previous});this.dispatchingToggle=!0;try{requestThenCommit({requestDetail:detail(),emitRequest:(proposal,init)=>{const request=this.emit("lr-toggle-request",proposal,init);return this.emit("lr-collapse-request",detail(),init).defaultPrevented&&request.preventDefault(),request},guard:this.toggleWriteGuard,commit:()=>{this.collapsed===previous&&(this.collapsed=!previous,this.emit("lr-collapse-change",detail()),this.emit("lr-toggle",detail()))}})}finally{this.dispatchingToggle=!1}}}static{this.defaultStrings={...super.defaultStrings,dockPanelCollapse:LYRA_DEFAULT_dockPanelCollapse,dockPanelExpand:LYRA_DEFAULT_dockPanelExpand,dockPanelResize:LYRA_DEFAULT_dockPanelResize,resizeValuePixels:LYRA_DEFAULT_resizeValuePixels}}static{this.styles=[LyraElement.styles,styles]}get extent(){return this._extent}set extent(value){const old=this._extent;this._extent=value,markVetoGuardWrite(this.resizeWriteGuard),this.requestUpdate("extent",old)}get collapsed(){return this._collapsed}set collapsed(next){const old=this._collapsed;this._collapsed=next,markVetoGuardWrite(this.toggleWriteGuard),this.requestUpdate("collapsed",old)}connectedCallback(){super.connectedCallback(),this.renderBounds=void 0,this.renderSizePx=void 0,this.applyHostSize(),this.armContainerResizeObserver()}disconnectedCallback(){super.disconnectedCallback(),this.endDrag(),this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0}adoptedCallback(){super.adoptedCallback(),this.renderBounds=void 0,this.renderSizePx=void 0,this.endDrag(),this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0}armContainerResizeObserver(){const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver,container=this.container;!container||!ResizeObserverCtor||(this.containerResizeObserver??=new ResizeObserverCtor(()=>{this.isConnected&&(this.drag&&!this.dragSnapshotIsCurrent(this.drag)&&this.endDrag(),this.reconcileLiveExtent(),this.requestUpdate())}),this.containerResizeObserver.observe(container),this.containerResizeObserver.observe(this))}get container(){let parent=flattenedParentElement(this);for(;parent?.localName==="slot";)parent=flattenedParentElement(parent);return parent}relocateFocus(){const toggle=this.renderRoot.querySelector('[part="collapse-toggle"]');if(toggle){toggle.focus();return}this.hasAttribute("tabindex")||(this.tabIndex=-1,this.addEventListener("blur",()=>this.removeAttribute("tabindex"),{once:!0})),this.focus()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&(changed.has("collapsed")&&this.collapsed&&this.matches(":focus-within")||changed.has("withoutResize")&&this.withoutResize&&shadowFocusTarget(this)?.matches('[part="handle"]'))&&this.relocateFocus(),changed.has("extent")||changed.has("minExtent")||changed.has("maxExtent")||changed.has("collapsed")||changed.has("placement")?(this.drag&&!this.dragSnapshotIsCurrent(this.drag)&&this.endDrag(),this.reconcileLiveExtent()):this.drag&&(changed.has("withoutResize")&&this.withoutResize||changed.has("collapsed")&&this.collapsed)&&this.endDrag()}get axis(){return this.placement==="start"||this.placement==="end"?"inline":"block"}get growSign(){if(this.placement==="top")return 1;if(this.placement==="bottom")return-1;const rtl=isRtl(this);return this.placement==="start"?rtl?-1:1:rtl?1:-1}applyHostSize(bounds=this.resolveBoundsPx()){const value=this.collapsed?"var(--lr-dock-panel-collapsed-size, var(--_lr-dock-panel-collapsed-size))":this.extent;this.axis==="inline"?(this.style.inlineSize=value,this.style.blockSize="",this.style.minBlockSize="",this.style.maxBlockSize="",this.style.minInlineSize=this.collapsed?"":`${bounds.minPx}px`,this.style.maxInlineSize=this.collapsed?"":`${bounds.maxPx}px`):(this.style.blockSize=value,this.style.inlineSize="",this.style.minInlineSize="",this.style.maxInlineSize="",this.style.minBlockSize=this.collapsed?"":`${bounds.minPx}px`,this.style.maxBlockSize=this.collapsed?"":`${bounds.maxPx}px`)}containerPx(){const rect=this.container?.getBoundingClientRect(),ownerWindow=this.ownerDocument.defaultView;return this.axis==="inline"?rect?.width??ownerWindow?.innerWidth??0:rect?.height??ownerWindow?.innerHeight??0}resolveBoundsPx(containerSize=this.containerPx()){const containerPx=Math.max(0,containerSize),lengthContext={host:this,percentBase:containerPx,viewportBasis:this.ownerDocument.defaultView??void 0},authoredMax=Math.max(0,resolveCssLength(this.maxExtent,lengthContext)??containerPx),maxPx=Math.min(containerPx,authoredMax),authoredMin=Math.max(0,resolveCssLength(this.minExtent,lengthContext)??0);return{minPx:Math.min(authoredMin,maxPx),maxPx}}currentSizePx(){const rect=this.getBoundingClientRect();return this.axis==="inline"?rect.width:rect.height}resizeValueText(sizePx){return this.localize("resizeValuePixels",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(sizePx))})}reconcileLiveExtent(){const containerPx=this.containerPx(),bounds=this.resolveBoundsPx(containerPx);if(this.applyHostSize(bounds),this.renderBounds=bounds,this.collapsed)return;const authoredPx=resolveCssLength(this.extent,{host:this,percentBase:containerPx,viewportBasis:this.ownerDocument.defaultView??void 0}),renderedPx=this.currentSizePx();this.renderSizePx=renderedPx;const candidate=authoredPx??renderedPx;if(!Number.isFinite(candidate))return;const clamped=Math.min(Math.max(candidate,bounds.minPx),bounds.maxPx),renderedOutsideBounds=Number.isFinite(renderedPx)&&(renderedPx<bounds.minPx-.5||renderedPx>bounds.maxPx+.5);if(Math.abs(candidate-clamped)<=.5&&!renderedOutsideBounds)return;const nextExtent=`${Math.round(clamped)}px`;this.extent!==nextExtent&&(this.extent=nextExtent),this.applyHostSize(bounds),this.renderSizePx=this.currentSizePx()}resolveProposal(px,bounds=this.resolveBoundsPx(),currentSizePx=this.currentSizePx()){const clamped=Math.min(Math.max(px,bounds.minPx),bounds.maxPx),nextExtent=`${Math.round(clamped)}px`,currentExtent=`${Math.round(currentSizePx)}px`;if(nextExtent!==currentExtent)return{bounds,nextExtent}}applyProposal(bounds,nextExtent){this.extent=nextExtent,this.applyHostSize(bounds)}requestResize(bounds,extent){const requestSequence=++this.resizeRequestSequence,snapshot={drag:this.drag,extent:this.extent,placement:this.placement,collapsed:this.collapsed,withoutResize:this.withoutResize,minExtent:this.minExtent,maxExtent:this.maxExtent,growSign:this.growSign,containerPx:this.drag?.containerPx??this.containerPx()};let committed;return requestThenCommit({requestDetail:Object.freeze({extent}),emitRequest:(detail,init)=>this.emit("lr-resize-request",detail,init),guard:this.resizeWriteGuard,commit:()=>{const currentBounds=this.resolveBoundsPx(snapshot.containerPx);if(this.drag!==snapshot.drag||this.collapsed||this.collapsed!==snapshot.collapsed||this.resizeRequestSequence!==requestSequence||this.withoutResize||this.withoutResize!==snapshot.withoutResize||this.extent!==snapshot.extent||this.placement!==snapshot.placement||this.minExtent!==snapshot.minExtent||this.maxExtent!==snapshot.maxExtent||this.growSign!==snapshot.growSign||Math.abs(this.containerPx()-snapshot.containerPx)>.5||Math.abs(currentBounds.minPx-bounds.minPx)>.5||Math.abs(currentBounds.maxPx-bounds.maxPx)>.5){snapshot.drag&&this.drag===snapshot.drag&&this.endDrag();return}this.applyProposal(bounds,extent),committed=this.extent}}),committed}emitResize(type,extent){this.emit(type,Object.freeze({extent}))}dragSnapshotIsCurrent(drag){return!this.withoutResize&&!this.collapsed&&this.placement===drag.placement&&this.axis===drag.axis&&this.growSign===drag.growSign&&this.extent===drag.expectedExtent&&this.minExtent===drag.minExtent&&this.maxExtent===drag.maxExtent&&Math.abs(this.containerPx()-drag.containerPx)<=.5}endDrag(){const pointerId=this.drag?.pointerId;this.drag=null,pointerId!=null&&this.dragController.end(pointerId)}get topBottomChevronDeg(){if(this.placement==="top")return this.collapsed?90:-90;if(this.placement==="bottom")return this.collapsed?-90:90}handleTemplate(){if(this.withoutResize||this.collapsed)return nothing;const{minPx,maxPx}=this.renderBounds??this.resolveBoundsPx(),nowPx=Math.min(Math.max(this.renderSizePx??this.currentSizePx(),minPx),maxPx);return html`<div
1
+ import{__decorate}from"tslib";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{flattenedParentElement}from"../../../internal/composed-tree.js";import{styles}from"./dock-panel.styles.js";import{resolveCssLength}from"../../../internal/css-length.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{SeparatorDragController,separatorArrowDirection,separatorCoordinate}from"../../../internal/separator-drag.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{shadowFocusTarget}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dockPanelCollapse,LYRA_DEFAULT_dockPanelExpand,LYRA_DEFAULT_dockPanelResize}from"../../../internal/default-strings/layout.generated.js";import{LYRA_DEFAULT_resizeValuePixels}from"../../../internal/default-strings/shared.generated.js";const KEYBOARD_STEP_PX=16;class LyraDockPanel extends LyraElement{constructor(){super(...arguments),this.placement="end",this._extent="280px",this.minExtent="160px",this.maxExtent="",this.collapsible=!1,this.toggleWriteGuard=new VetoWriteGuard,this._collapsed=!1,this.withoutResize=!1,this.drag=null,this.resizeWriteGuard=new VetoWriteGuard,this.resizeRequestSequence=0,this.dragController=new SeparatorDragController(this,event=>this.onPointerMove(event),event=>event.type==="pointerup"?this.onPointerUp(event):this.onPointerCancel(event)),this.contentId=nextId("dock-panel-content"),this.onPointerDown=e=>{if(!e.isPrimary||e.button!==0||this.withoutResize||this.collapsed||this.drag)return;const handle=e.currentTarget;if(!this.dragController.start(e,handle))return;const axis=this.axis,growSign=this.growSign,containerPx=this.containerPx(),startSizePx=this.currentSizePx();this.drag={pointerId:e.pointerId,startPos:separatorCoordinate(e,axis),startSizePx,axis,growSign,placement:this.placement,minExtent:this.minExtent,maxExtent:this.maxExtent,containerPx,bounds:this.resolveBoundsPx(containerPx),currentSizePx:startSizePx,expectedExtent:this.extent,finalExtent:this.extent,acceptedResize:!1}},this.onPointerMove=e=>{const drag=this.drag;if(!drag||e.pointerId!==drag.pointerId)return;if(this.withoutResize||this.collapsed||this.placement!==drag.placement||this.axis!==drag.axis||this.growSign!==drag.growSign||this.extent!==drag.expectedExtent||this.minExtent!==drag.minExtent||this.maxExtent!==drag.maxExtent){this.endDrag();return}const pos=separatorCoordinate(e,drag.axis),delta=drag.growSign*(pos-drag.startPos),proposal=this.resolveProposal(drag.startSizePx+delta,drag.bounds,drag.currentSizePx);if(!proposal)return;const extent=this.requestResize(proposal.bounds,proposal.nextExtent);!extent||this.drag!==drag||(drag.expectedExtent=extent,drag.finalExtent=extent,drag.currentSizePx=parseFloat(extent),drag.acceptedResize=!0,this.emitResize("lr-resize",extent),!(this.drag!==drag||this.extent!==extent||this.collapsed||this.withoutResize)&&this.emitResize("lr-resize-input",extent))},this.onPointerUp=e=>{const drag=this.drag;if(!drag||e.pointerId!==drag.pointerId)return;const shouldCommit=drag.acceptedResize&&this.dragSnapshotIsCurrent(drag),finalExtent=drag.finalExtent;this.endDrag(),shouldCommit&&this.emitResize("lr-resize-change",finalExtent)},this.onPointerCancel=e=>{!this.drag||e.pointerId!==this.drag.pointerId||this.endDrag()},this.onHandleKeyDown=e=>{if(this.withoutResize||this.collapsed||e.altKey||e.ctrlKey||e.metaKey||e.isComposing)return;const arrowDirection=separatorArrowDirection(e,this.axis,!1);let proposal;if(e.key==="Home"||e.key==="End"){e.preventDefault();const{minPx,maxPx}=this.resolveBoundsPx();proposal=this.resolveProposal(e.key==="Home"?minPx:maxPx)}else arrowDirection===1?(e.preventDefault(),proposal=this.resolveProposal(this.currentSizePx()+this.growSign*KEYBOARD_STEP_PX)):arrowDirection===-1&&(e.preventDefault(),proposal=this.resolveProposal(this.currentSizePx()-this.growSign*KEYBOARD_STEP_PX));if(!proposal)return;const extent=this.requestResize(proposal.bounds,proposal.nextExtent);extent&&(this.emitResize("lr-resize",extent),!(this.extent!==extent||this.collapsed||this.withoutResize)&&(this.emitResize("lr-resize-input",extent),!(this.extent!==extent||this.collapsed||this.withoutResize)&&this.emitResize("lr-resize-change",extent)))},this.dispatchingToggle=!1,this.toggleCollapsed=()=>{if(this.dispatchingToggle)return;const previous=this.collapsed,detail=()=>Object.freeze({expanded:previous});this.dispatchingToggle=!0;try{requestThenCommit({requestDetail:detail(),emitRequest:(proposal,init)=>{const request=this.emit("lr-toggle-request",proposal,init);return this.emit("lr-collapse-request",detail(),init).defaultPrevented&&request.preventDefault(),request},guard:this.toggleWriteGuard,commit:()=>{this.collapsed===previous&&(this.collapsed=!previous,this.emit("lr-collapse-change",detail()),this.emit("lr-toggle",detail()))}})}finally{this.dispatchingToggle=!1}}}static{this.defaultStrings={...super.defaultStrings,dockPanelCollapse:LYRA_DEFAULT_dockPanelCollapse,dockPanelExpand:LYRA_DEFAULT_dockPanelExpand,dockPanelResize:LYRA_DEFAULT_dockPanelResize,resizeValuePixels:LYRA_DEFAULT_resizeValuePixels}}static{this.styles=[LyraElement.styles,styles]}get extent(){return this._extent}set extent(value){const old=this._extent;this._extent=value,markVetoGuardWrite(this.resizeWriteGuard),this.requestUpdate("extent",old)}get collapsed(){return this._collapsed}set collapsed(next){const old=this._collapsed;this._collapsed=next,markVetoGuardWrite(this.toggleWriteGuard),this.requestUpdate("collapsed",old)}connectedCallback(){super.connectedCallback(),this.renderBounds=void 0,this.renderSizePx=void 0,this.applyHostSize(),this.armContainerResizeObserver()}disconnectedCallback(){super.disconnectedCallback(),this.endDrag(),this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0}adoptedCallback(){super.adoptedCallback(),this.renderBounds=void 0,this.renderSizePx=void 0,this.endDrag(),this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0}armContainerResizeObserver(){const ResizeObserverCtor=this.ownerDocument.defaultView?.ResizeObserver,container=this.container;!container||!ResizeObserverCtor||(this.containerResizeObserver??=new ResizeObserverCtor(()=>{this.isConnected&&(this.drag&&!this.dragSnapshotIsCurrent(this.drag)&&this.endDrag(),this.reconcileLiveExtent(),this.requestUpdate())}),this.containerResizeObserver.observe(container),this.containerResizeObserver.observe(this))}get container(){let parent=flattenedParentElement(this);for(;parent?.localName==="slot";)parent=flattenedParentElement(parent);return parent}relocateFocus(){const toggle=this.renderRoot.querySelector('[part="collapse-toggle"]');if(toggle){toggle.focus();return}this.hasAttribute("tabindex")||(this.tabIndex=-1,this.addEventListener("blur",()=>this.removeAttribute("tabindex"),{once:!0})),this.focus()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated&&(changed.has("collapsed")&&this.collapsed&&this.matches(":focus-within")||changed.has("withoutResize")&&this.withoutResize&&shadowFocusTarget(this)?.matches('[part="handle"]'))&&this.relocateFocus(),changed.has("extent")||changed.has("minExtent")||changed.has("maxExtent")||changed.has("collapsed")||changed.has("placement")?(this.drag&&!this.dragSnapshotIsCurrent(this.drag)&&this.endDrag(),this.reconcileLiveExtent()):this.drag&&(changed.has("withoutResize")&&this.withoutResize||changed.has("collapsed")&&this.collapsed)&&this.endDrag()}get axis(){return this.placement==="start"||this.placement==="end"?"inline":"block"}get growSign(){if(this.placement==="top")return 1;if(this.placement==="bottom")return-1;const rtl=isRtl(this);return this.placement==="start"?rtl?-1:1:rtl?1:-1}applyHostSize(bounds=this.resolveBoundsPx()){const value=this.collapsed?"var(--lr-dock-panel-collapsed-size, var(--_lr-dock-panel-collapsed-size))":this.extent;this.axis==="inline"?(this.style.inlineSize=value,this.style.blockSize="",this.style.minBlockSize="",this.style.maxBlockSize="",this.style.minInlineSize=this.collapsed?"":`${bounds.minPx}px`,this.style.maxInlineSize=this.collapsed?"":`${bounds.maxPx}px`):(this.style.blockSize=value,this.style.inlineSize="",this.style.minInlineSize="",this.style.maxInlineSize="",this.style.minBlockSize=this.collapsed?"":`${bounds.minPx}px`,this.style.maxBlockSize=this.collapsed?"":`${bounds.maxPx}px`)}containerPx(){const rect=this.container?.getBoundingClientRect(),ownerWindow=this.ownerDocument.defaultView;return this.axis==="inline"?rect?.width??ownerWindow?.innerWidth??0:rect?.height??ownerWindow?.innerHeight??0}resolveBoundsPx(containerSize=this.containerPx()){const containerPx=Math.max(0,containerSize),lengthContext={host:this,percentBase:containerPx,viewportBasis:this.ownerDocument.defaultView??void 0},authoredMax=Math.max(0,resolveCssLength(this.maxExtent,lengthContext)??containerPx),maxPx=Math.min(containerPx,authoredMax),authoredMin=Math.max(0,resolveCssLength(this.minExtent,lengthContext)??0);return{minPx:Math.min(authoredMin,maxPx),maxPx}}currentSizePx(){const rect=this.getBoundingClientRect();return this.axis==="inline"?rect.width:rect.height}resizeValueText(sizePx){return this.localize("resizeValuePixels",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(sizePx))})}reconcileLiveExtent(){const containerPx=this.containerPx(),bounds=this.resolveBoundsPx(containerPx);if(this.applyHostSize(bounds),this.renderBounds=bounds,this.collapsed)return;const authoredPx=resolveCssLength(this.extent,{host:this,percentBase:containerPx,viewportBasis:this.ownerDocument.defaultView??void 0}),renderedPx=this.currentSizePx();this.renderSizePx=renderedPx;const candidate=authoredPx??renderedPx;if(!Number.isFinite(candidate))return;const clamped=Math.min(Math.max(candidate,bounds.minPx),bounds.maxPx),renderedOutsideBounds=Number.isFinite(renderedPx)&&(renderedPx<bounds.minPx-.5||renderedPx>bounds.maxPx+.5);if(Math.abs(candidate-clamped)<=.5&&!renderedOutsideBounds)return;const nextExtent=`${Math.round(clamped)}px`;this.extent!==nextExtent&&(this.extent=nextExtent),this.applyHostSize(bounds),this.renderSizePx=this.currentSizePx()}resolveProposal(px,bounds=this.resolveBoundsPx(),currentSizePx=this.currentSizePx()){const clamped=Math.min(Math.max(px,bounds.minPx),bounds.maxPx),nextExtent=`${Math.round(clamped)}px`,currentExtent=`${Math.round(currentSizePx)}px`;if(nextExtent!==currentExtent)return{bounds,nextExtent}}applyProposal(bounds,nextExtent){this.extent=nextExtent,this.applyHostSize(bounds)}requestResize(bounds,extent){const requestSequence=++this.resizeRequestSequence,snapshot={drag:this.drag,extent:this.extent,placement:this.placement,collapsed:this.collapsed,withoutResize:this.withoutResize,minExtent:this.minExtent,maxExtent:this.maxExtent,growSign:this.growSign,containerPx:this.drag?.containerPx??this.containerPx()};let committed;return requestThenCommit({requestDetail:Object.freeze({extent}),emitRequest:(detail,init)=>this.emit("lr-resize-request",detail,init),guard:this.resizeWriteGuard,commit:()=>{const currentBounds=this.resolveBoundsPx(snapshot.containerPx);if(this.drag!==snapshot.drag||this.collapsed||this.collapsed!==snapshot.collapsed||this.resizeRequestSequence!==requestSequence||this.withoutResize||this.withoutResize!==snapshot.withoutResize||this.extent!==snapshot.extent||this.placement!==snapshot.placement||this.minExtent!==snapshot.minExtent||this.maxExtent!==snapshot.maxExtent||this.growSign!==snapshot.growSign||Math.abs(this.containerPx()-snapshot.containerPx)>.5||Math.abs(currentBounds.minPx-bounds.minPx)>.5||Math.abs(currentBounds.maxPx-bounds.maxPx)>.5){snapshot.drag&&this.drag===snapshot.drag&&this.endDrag();return}this.applyProposal(bounds,extent),committed=this.extent}}),committed}emitResize(type,extent){this.emit(type,Object.freeze({extent}))}dragSnapshotIsCurrent(drag){return!this.withoutResize&&!this.collapsed&&this.placement===drag.placement&&this.axis===drag.axis&&this.growSign===drag.growSign&&this.extent===drag.expectedExtent&&this.minExtent===drag.minExtent&&this.maxExtent===drag.maxExtent&&Math.abs(this.containerPx()-drag.containerPx)<=.5}endDrag(){const pointerId=this.drag?.pointerId;this.drag=null,pointerId!=null&&this.dragController.end(pointerId)}get topBottomChevronDeg(){if(this.placement==="top")return this.collapsed?90:-90;if(this.placement==="bottom")return this.collapsed?-90:90}handleTemplate(){if(this.withoutResize||this.collapsed)return nothing;const{minPx,maxPx}=this.renderBounds??this.resolveBoundsPx(),nowPx=Math.min(Math.max(this.renderSizePx??this.currentSizePx(),minPx),maxPx);return html`<div
2
2
  part="handle"
3
3
  role="separator"
4
4
  aria-label=${this.localize("dockPanelResize")}