@aceshooting/lyra-ui 27.0.0 → 28.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (397) hide show
  1. package/CHANGELOG.md +67 -63
  2. package/README.md +7 -3
  3. package/dist/cli/css-declarations.mjs +1 -0
  4. package/dist/cli/lyra-rename-ledger.mjs +1 -1
  5. package/dist/cli/migrate-wa.mjs +9 -4
  6. package/dist/cli/migration-contract.json +1 -1
  7. package/dist/cli/migration-renames.mjs +2 -2
  8. package/dist/cli/migration-theme-scopes.mjs +3 -0
  9. package/dist/cli/theme-scope-vocabulary.generated.mjs +1 -0
  10. package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
  11. package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
  12. package/dist/components/agent-tools/agent-question/agent-question.class.js +1 -1
  13. package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
  14. package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
  15. package/dist/components/agent-tools/approval-queue/approval-queue.class.js +1 -1
  16. package/dist/components/agent-tools/artifact-panel/artifact-panel.class.js +1 -1
  17. package/dist/components/agent-tools/background-runs/background-runs.class.js +1 -1
  18. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
  19. package/dist/components/agent-tools/budget-meter/budget-meter.class.js +1 -1
  20. package/dist/components/agent-tools/change-review/change-review.class.js +1 -1
  21. package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
  22. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +1 -1
  23. package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +1 -1
  24. package/dist/components/agent-tools/connector-manager/connector-manager.class.js +1 -1
  25. package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
  26. package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +1 -1
  27. package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
  28. package/dist/components/agent-tools/evaluation-run/evaluation-run.class.js +1 -1
  29. package/dist/components/agent-tools/mcp-app/mcp-app.class.js +1 -1
  30. package/dist/components/agent-tools/permission-grant/permission-grant.class.js +1 -1
  31. package/dist/components/agent-tools/permission-rules/permission-rules.class.js +1 -1
  32. package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
  33. package/dist/components/agent-tools/prompt-studio/prompt-studio.class.js +1 -1
  34. package/dist/components/agent-tools/result-card/result-field.class.js +1 -1
  35. package/dist/components/agent-tools/schema-viewer/schema-viewer.class.js +1 -1
  36. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  37. package/dist/components/agent-tools/stack-trace/stack-trace.class.js +1 -1
  38. package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +2 -2
  39. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  40. package/dist/components/agent-tools/terminal/terminal.class.js +1 -1
  41. package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
  42. package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
  43. package/dist/components/agent-tools/tool-approval-dialog/tool-approval-dialog.class.js +1 -1
  44. package/dist/components/agent-tools/tool-call-block/tool-call-block.class.js +1 -1
  45. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +1 -1
  46. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  47. package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
  48. package/dist/components/agent-tools/tool-result-view/tool-result-view.class.js +1 -1
  49. package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +1 -1
  50. package/dist/components/agent-tools/tool-timeline/tool-timeline.class.js +1 -1
  51. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  52. package/dist/components/charts/chart/box-plot.class.d.ts +4 -2
  53. package/dist/components/charts/chart/box-plot.class.js +6 -5
  54. package/dist/components/charts/chart/chart-token-cache.js +2 -2
  55. package/dist/components/charts/chart/chart.class.d.ts +6 -4
  56. package/dist/components/charts/chart/chart.class.js +8 -7
  57. package/dist/components/charts/chart/histogram.class.js +1 -1
  58. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  59. package/dist/components/conversation/agent-workspace/agent-workspace.class.js +1 -1
  60. package/dist/components/conversation/audio-visualizer/audio-visualizer.class.js +1 -1
  61. package/dist/components/conversation/branch-picker/branch-picker.class.js +1 -1
  62. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  63. package/dist/components/conversation/chat-message/chat-message.class.js +1 -1
  64. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  65. package/dist/components/conversation/checkpoint/checkpoint.class.js +1 -1
  66. package/dist/components/conversation/code-block/code-block-base.class.js +1 -1
  67. package/dist/components/conversation/code-block/code-block-core.class.js +1 -1
  68. package/dist/components/conversation/code-block/code-block.class.js +1 -1
  69. package/dist/components/conversation/conversation-item/conversation-item.class.js +1 -1
  70. package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
  71. package/dist/components/conversation/handoff-divider/handoff-divider.class.js +1 -1
  72. package/dist/components/conversation/markdown/markdown-base.class.js +1 -1
  73. package/dist/components/conversation/markdown/markdown-core.class.js +1 -1
  74. package/dist/components/conversation/markdown/markdown.class.js +1 -1
  75. package/dist/components/conversation/message-actions/message-actions.class.js +1 -1
  76. package/dist/components/conversation/message-feedback/message-feedback.class.js +1 -1
  77. package/dist/components/conversation/message-parts/message-parts.class.js +1 -1
  78. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  79. package/dist/components/conversation/model-settings-panel/model-settings-panel.class.js +1 -1
  80. package/dist/components/conversation/prompt-input/prompt-input.class.js +1 -1
  81. package/dist/components/conversation/prompt-queue/prompt-queue.class.js +1 -1
  82. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  83. package/dist/components/conversation/realtime-session/realtime-session.class.js +1 -1
  84. package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
  85. package/dist/components/conversation/stream-status/stream-status.class.js +1 -1
  86. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +1 -1
  87. package/dist/components/conversation/thread-list/thread-list.class.js +1 -1
  88. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  89. package/dist/components/conversation/typing-indicator/typing-indicator.class.js +1 -1
  90. package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
  91. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  92. package/dist/components/data/calendar/calendar.class.js +1 -1
  93. package/dist/components/data/condition-builder/condition-builder.class.js +1 -1
  94. package/dist/components/data/context-meter/context-meter.class.js +1 -1
  95. package/dist/components/data/data-grid/data-grid.class.d.ts +2 -2
  96. package/dist/components/data/data-grid/data-grid.class.js +3 -3
  97. package/dist/components/data/document-library/document-library.class.js +1 -1
  98. package/dist/components/data/env-list/env-list.class.js +1 -1
  99. package/dist/components/data/file-tree/file-tree.class.d.ts +2 -2
  100. package/dist/components/data/file-tree/file-tree.class.js +1 -1
  101. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  102. package/dist/components/data/flow-controls/flow-controls.class.js +1 -1
  103. package/dist/components/data/flow-minimap/flow-minimap.class.js +1 -1
  104. package/dist/components/data/flow-node/flow-node.class.js +1 -1
  105. package/dist/components/data/flow-run-status/flow-run-status.class.js +1 -1
  106. package/dist/components/data/funnel/funnel.class.js +1 -1
  107. package/dist/components/data/gauge/gauge.class.js +1 -1
  108. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  109. package/dist/components/data/heatmap/heatmap.class.d.ts +2 -1
  110. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  111. package/dist/components/data/heatmap/heatmap.styles.js +1 -1
  112. package/dist/components/data/pagination/pagination.class.d.ts +2 -0
  113. package/dist/components/data/pagination/pagination.class.js +1 -1
  114. package/dist/components/data/pagination/pagination.styles.js +1 -1
  115. package/dist/components/data/sequence-strip/sequence-strip.class.js +1 -1
  116. package/dist/components/data/sparkline/sparkline.class.js +1 -1
  117. package/dist/components/data/stat/stat.class.js +1 -1
  118. package/dist/components/data/table/table.class.d.ts +23 -2
  119. package/dist/components/data/table/table.class.js +5 -3
  120. package/dist/components/data/table/table.styles.js +1 -1
  121. package/dist/components/data/timeline/timeline.class.js +1 -1
  122. package/dist/components/data/tree/tree.class.js +1 -1
  123. package/dist/components/data/word-cloud/word-cloud.class.js +1 -1
  124. package/dist/components/forms/button/button.class.js +1 -1
  125. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  126. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  127. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  128. package/dist/components/forms/color-picker/color-picker.class.d.ts +8 -4
  129. package/dist/components/forms/color-picker/color-picker.class.js +2 -2
  130. package/dist/components/forms/combobox/combobox.class.js +1 -1
  131. package/dist/components/forms/country-picker/country-picker.class.js +1 -1
  132. package/dist/components/forms/currency-picker/currency-picker.class.js +1 -1
  133. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  134. package/dist/components/forms/date-picker/date-picker.class.js +1 -1
  135. package/dist/components/forms/emoji-picker/emoji-data-loader.js +1 -1
  136. package/dist/components/forms/emoji-picker/emoji-picker.class.d.ts +7 -4
  137. package/dist/components/forms/emoji-picker/emoji-picker.class.js +5 -5
  138. package/dist/components/forms/icon-button/icon-button.class.d.ts +4 -0
  139. package/dist/components/forms/icon-button/icon-button.class.js +1 -1
  140. package/dist/components/forms/icon-button/icon-button.styles.js +1 -1
  141. package/dist/components/forms/input/input-shared.js +1 -1
  142. package/dist/components/forms/input/input.class.js +1 -1
  143. package/dist/components/forms/input/native-time-input.class.js +1 -1
  144. package/dist/components/forms/input/number-input.class.js +1 -1
  145. package/dist/components/forms/input/time-input.class.js +1 -1
  146. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  147. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  148. package/dist/components/forms/phone-input/phone-input.class.js +1 -1
  149. package/dist/components/forms/radio/radio-group.class.js +1 -1
  150. package/dist/components/forms/radio/radio.class.js +1 -1
  151. package/dist/components/forms/rubric-form/rubric-form.class.js +4 -4
  152. package/dist/components/forms/select/select.class.js +1 -1
  153. package/dist/components/forms/signature-pad/signature-pad.class.js +1 -1
  154. package/dist/components/forms/slider/slider.class.js +1 -1
  155. package/dist/components/forms/switch/switch.class.js +1 -1
  156. package/dist/components/forms/textarea/textarea.class.js +1 -1
  157. package/dist/components/forms/time-range/time-range.class.js +1 -1
  158. package/dist/components/forms/time-zone-picker/time-zone-picker.class.js +1 -1
  159. package/dist/components/forms/token-input/token-input.class.js +1 -1
  160. package/dist/components/forms/unit-picker/unit-picker.class.js +1 -1
  161. package/dist/components/layout/app-rail/app-rail-item.class.js +1 -1
  162. package/dist/components/layout/app-rail/app-rail.class.d.ts +70 -7
  163. package/dist/components/layout/app-rail/app-rail.class.js +16 -4
  164. package/dist/components/layout/app-rail/app-rail.styles.js +1 -1
  165. package/dist/components/layout/app-rail-group/app-rail-group.class.js +1 -1
  166. package/dist/components/layout/breadcrumb/breadcrumb.class.js +1 -1
  167. package/dist/components/layout/card/card.class.js +1 -1
  168. package/dist/components/layout/carousel/carousel.class.js +1 -1
  169. package/dist/components/layout/command-palette/command-palette.class.js +1 -1
  170. package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
  171. package/dist/components/layout/details/accordion-item.class.js +1 -1
  172. package/dist/components/layout/details/details.class.js +1 -1
  173. package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
  174. package/dist/components/layout/drilldown-panel/drilldown-panel.class.js +1 -1
  175. package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
  176. package/dist/components/layout/menu/menu.class.js +1 -1
  177. package/dist/components/layout/menubar/menubar.class.js +1 -1
  178. package/dist/components/layout/multi-split/multi-split.class.js +1 -1
  179. package/dist/components/layout/navigation-menu/navigation-menu.class.js +1 -1
  180. package/dist/components/layout/page/page.class.js +1 -1
  181. package/dist/components/layout/reorder-list/reorder-item.class.js +1 -1
  182. package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
  183. package/dist/components/layout/responsive-panel/responsive-panel.class.js +1 -1
  184. package/dist/components/layout/scroller/scroller.class.js +1 -1
  185. package/dist/components/layout/segmented/segmented.class.d.ts +7 -4
  186. package/dist/components/layout/segmented/segmented.styles.js +1 -1
  187. package/dist/components/layout/split-panel/split-panel.class.js +1 -1
  188. package/dist/components/layout/tab-group/tab-group.class.js +1 -1
  189. package/dist/components/layout/tab-group/tab.class.js +1 -1
  190. package/dist/components/layout/virtual-list/virtual-list.styles.js +1 -1
  191. package/dist/components/layout/widget/widget.class.js +1 -1
  192. package/dist/components/media/animated-image/animated-image.class.js +1 -1
  193. package/dist/components/media/attachment-chip/attachment-chip.class.js +1 -1
  194. package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
  195. package/dist/components/media/av-player/av-player.class.js +1 -1
  196. package/dist/components/media/avatar-group/avatar-group.class.js +1 -1
  197. package/dist/components/media/drop-zone/drop-zone.class.js +1 -1
  198. package/dist/components/media/file-icon/file-icon.class.js +1 -1
  199. package/dist/components/media/file-input/file-input.class.js +1 -1
  200. package/dist/components/media/flag/flag.class.js +1 -1
  201. package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
  202. package/dist/components/media/image-viewer/image-viewer.class.d.ts +2 -1
  203. package/dist/components/media/image-viewer/image-viewer.class.js +4 -2
  204. package/dist/components/media/image-viewer/image-viewer.styles.js +1 -1
  205. package/dist/components/media/lightbox/lightbox.class.js +1 -1
  206. package/dist/components/media/map/map.class.js +1 -1
  207. package/dist/components/media/media-card/media-card.class.js +1 -1
  208. package/dist/components/media/pan-zoom/pan-zoom.class.js +1 -1
  209. package/dist/components/media/qr-code/qr-code.class.d.ts +2 -2
  210. package/dist/components/media/qr-code/qr-code.class.js +1 -1
  211. package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
  212. package/dist/components/media/video/video.class.js +1 -1
  213. package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
  214. package/dist/components/media/zoomable-frame/zoomable-frame.class.js +1 -1
  215. package/dist/components/overlays/alert/alert.class.js +1 -1
  216. package/dist/components/overlays/badge/tag.class.js +1 -1
  217. package/dist/components/overlays/callout/callout.class.js +1 -1
  218. package/dist/components/overlays/chip/chip-group.class.js +1 -1
  219. package/dist/components/overlays/chip/chip.class.js +1 -1
  220. package/dist/components/overlays/context-menu/context-menu.class.js +1 -1
  221. package/dist/components/overlays/dialog/confirm.js +1 -1
  222. package/dist/components/overlays/dialog/dialog.class.js +1 -1
  223. package/dist/components/overlays/kbd/kbd.class.js +1 -1
  224. package/dist/components/overlays/overlay/popover.class.js +1 -1
  225. package/dist/components/overlays/overlay/tooltip.class.js +1 -1
  226. package/dist/components/overlays/progress/progress-bar.class.js +1 -1
  227. package/dist/components/overlays/progress/progress-ring.class.js +1 -1
  228. package/dist/components/overlays/rating/rating.class.js +1 -1
  229. package/dist/components/overlays/skeleton/skeleton.class.js +1 -1
  230. package/dist/components/overlays/spinner/spinner.class.js +1 -1
  231. package/dist/components/overlays/toast/toast-item.class.js +1 -1
  232. package/dist/components/overlays/toast/toast.class.js +1 -1
  233. package/dist/components/retrieval/chunk-inspector/chunk-inspector.class.js +1 -1
  234. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  235. package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
  236. package/dist/components/retrieval/community-card/community-card.class.js +1 -1
  237. package/dist/components/retrieval/embedding-explorer/embedding-explorer.class.js +1 -1
  238. package/dist/components/retrieval/entity-card/entity-card.class.js +1 -1
  239. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  240. package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
  241. package/dist/components/retrieval/graph/graph.class.js +1 -1
  242. package/dist/components/retrieval/graph-legend/graph-legend.class.js +1 -1
  243. package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
  244. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +1 -1
  245. package/dist/components/retrieval/knowledge-base/knowledge-base.class.js +1 -1
  246. package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +1 -1
  247. package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +1 -1
  248. package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
  249. package/dist/components/retrieval/mind-map/mind-map.class.js +1 -1
  250. package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +1 -1
  251. package/dist/components/retrieval/node-palette/node-palette.class.js +1 -1
  252. package/dist/components/retrieval/path-strip/path-strip.class.js +1 -1
  253. package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
  254. package/dist/components/retrieval/rag-answer/rag-answer.class.js +1 -1
  255. package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
  256. package/dist/components/retrieval/research-progress/research-progress.class.js +1 -1
  257. package/dist/components/retrieval/retrieval-compare/retrieval-compare.class.js +1 -1
  258. package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
  259. package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +1 -1
  260. package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
  261. package/dist/components/retrieval/source-card/source-card.class.js +1 -1
  262. package/dist/components/retrieval/source-list/source-list.class.js +1 -1
  263. package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
  264. package/dist/components/utility/copy-button/copy-button.class.js +1 -1
  265. package/dist/components/utility/diff-view/diff-view.class.js +1 -1
  266. package/dist/components/utility/export-button/export-button.class.js +1 -1
  267. package/dist/components/utility/icon/icon.class.js +1 -1
  268. package/dist/components/utility/json-viewer/json-viewer.class.js +1 -1
  269. package/dist/components/utility/known-date/known-date.class.js +1 -1
  270. package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
  271. package/dist/components/utility/poll-status/poll-status.class.js +1 -1
  272. package/dist/components/utility/random-content/random-content.class.js +1 -1
  273. package/dist/components/utility/tour/tour.class.js +1 -1
  274. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  275. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  276. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  277. package/dist/components/viewers/csv-viewer/csv-viewer.class.js +1 -1
  278. package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +2 -2
  279. package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
  280. package/dist/components/viewers/document-preview/document-preview.class.js +1 -1
  281. package/dist/components/viewers/document-viewer/document-viewer.class.js +1 -1
  282. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  283. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
  284. package/dist/components/viewers/email-viewer/email-viewer.class.js +1 -1
  285. package/dist/components/viewers/geojson-view/geojson-view.class.js +1 -1
  286. package/dist/components/viewers/geojson-view/geojson-viewer.class.js +1 -1
  287. package/dist/components/viewers/highlight-layer/highlight-layer.class.js +1 -1
  288. package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
  289. package/dist/components/viewers/include/include.class.js +1 -1
  290. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
  291. package/dist/components/viewers/page-rail/page-rail.class.d.ts +1 -1
  292. package/dist/components/viewers/page-rail/page-rail.class.js +3 -3
  293. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +2 -2
  294. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  295. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
  296. package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +1 -1
  297. package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
  298. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +1 -1
  299. package/dist/events.d.ts +6 -1
  300. package/dist/framework-types.d.ts +1 -1
  301. package/dist/internal/accessibility-visibility.js +1 -1
  302. package/dist/internal/collection-snapshot.js +1 -1
  303. package/dist/internal/default-strings/agent-tools.generated.js +1 -0
  304. package/dist/internal/default-strings/charts.generated.js +1 -0
  305. package/dist/internal/default-strings/conversation.generated.js +1 -0
  306. package/dist/internal/default-strings/data.generated.js +1 -0
  307. package/dist/internal/default-strings/forms.generated.js +1 -0
  308. package/dist/internal/default-strings/layout.generated.js +1 -0
  309. package/dist/internal/default-strings/media.generated.js +1 -0
  310. package/dist/internal/default-strings/overlays.generated.js +1 -0
  311. package/dist/internal/default-strings/retrieval.generated.js +1 -0
  312. package/dist/internal/default-strings/shared.generated.js +1 -0
  313. package/dist/internal/default-strings/utility.generated.js +1 -0
  314. package/dist/internal/default-strings/viewers.generated.js +5 -0
  315. package/dist/internal/dev-mode-attribute-warning.development.js +1 -1
  316. package/dist/internal/dev-mode-attribute-warning.production.js +1 -1
  317. package/dist/internal/document-tokens.d.ts +11 -0
  318. package/dist/internal/document-tokens.generated.js +15 -0
  319. package/dist/internal/document-tokens.js +3 -0
  320. package/dist/internal/form-associated.d.ts +1 -1
  321. package/dist/internal/form-associated.js +1 -1
  322. package/dist/internal/glass-surface.styles.js +1 -1
  323. package/dist/internal/host-tokens.styles.js +1 -0
  324. package/dist/internal/image-zoom.js +1 -0
  325. package/dist/internal/intl-cache.js +1 -1
  326. package/dist/internal/localization-types.d.ts +1 -1
  327. package/dist/internal/localization.js +2 -2
  328. package/dist/internal/lyra-element.d.ts +4 -2
  329. package/dist/internal/lyra-element.js +2 -2
  330. package/dist/internal/nonmodal-overlay-manager.js +1 -1
  331. package/dist/internal/opaque-content-border.styles.js +1 -1
  332. package/dist/internal/open-overlay-ancestors.js +1 -0
  333. package/dist/internal/open-overlay-raise.styles.js +1 -0
  334. package/dist/internal/optional-peer-failure.js +1 -0
  335. package/dist/internal/package-metadata.js +1 -1
  336. package/dist/internal/prefix.js +1 -1
  337. package/dist/internal/specialist-host-tokens.styles.js +1 -0
  338. package/dist/internal/specialist-tokens.generated.js +2 -0
  339. package/dist/internal/step-value.js +1 -1
  340. package/dist/internal/theme-observation.js +1 -1
  341. package/dist/internal/theme-scopes.d.ts +11 -0
  342. package/dist/internal/theme-scopes.js +1 -0
  343. package/dist/looks/shadcn.css +1 -1
  344. package/dist/lyra.d.ts +1 -1
  345. package/dist/lyra.js +1 -1
  346. package/dist/styles/design-tokens.css +1 -1
  347. package/dist/styles/tokens-root.css +1 -1
  348. package/dist/surfaces/glass.css +1 -1
  349. package/dist/testing/happy-dom-shims.d.ts +22 -1
  350. package/dist/testing/happy-dom-shims.js +1 -1
  351. package/dist/testing/index.d.ts +1 -1
  352. package/dist/testing/index.js +1 -1
  353. package/dist/testing/interaction-drivers.d.ts +66 -7
  354. package/dist/testing/interaction-drivers.js +1 -1
  355. package/dist/testing/jsdom-shims.d.ts +70 -0
  356. package/dist/testing/jsdom-shims.js +1 -0
  357. package/dist/theme/look-inputs.d.ts +1 -1
  358. package/dist/theme/look-inputs.js +37 -41
  359. package/dist/theme/theme.d.ts +13 -0
  360. package/dist/theme/theme.js +1 -1
  361. package/dist/theme.css +1 -1
  362. package/dist/utilities/index.d.ts +1 -1
  363. package/dist/utilities/index.js +1 -1
  364. package/dist/utilities/scoped-registry.d.ts +3 -0
  365. package/dist/utilities/scoped-registry.js +1 -1
  366. package/dist/utilities/theme-scopes.d.ts +1 -0
  367. package/dist/utilities/theme-scopes.js +1 -0
  368. package/dist/utilities/tokens.d.ts +1 -0
  369. package/dist/utilities/tokens.js +1 -0
  370. package/llms/components/lr-app-rail.md +51 -4
  371. package/llms/components/lr-box-plot.md +5 -0
  372. package/llms/components/lr-chart.md +6 -0
  373. package/llms/components/lr-emoji-picker.md +13 -8
  374. package/llms/components/lr-heatmap.md +10 -2
  375. package/llms/components/lr-icon-button.md +13 -1
  376. package/llms/components/lr-image-viewer.md +8 -0
  377. package/llms/components/lr-pagination.md +4 -2
  378. package/llms/components/lr-segmented.md +7 -3
  379. package/llms/components/lr-table.md +14 -12
  380. package/llms/components/lr-thread-list.md +4 -3
  381. package/llms/migration.md +9 -0
  382. package/llms/peers.md +1 -1
  383. package/llms/shared/events-and-types.md +41 -0
  384. package/llms/shared/frameworks-and-ssr.md +16 -0
  385. package/llms/shared/imports-and-registration.md +4 -3
  386. package/llms/shared/native-styles-and-utilities.md +38 -3
  387. package/llms/shared/styles-and-tokens.md +242 -102
  388. package/llms/shared/testing-and-utilities.md +104 -7
  389. package/llms/shared.md +445 -115
  390. package/llms/tokens.md +31 -49
  391. package/locales.json +138 -138
  392. package/package.json +16 -8
  393. package/registrations.json +1 -1
  394. package/dist/internal/default-strings.generated.js +0 -5
  395. package/dist/internal/specialist-tokens.styles.js +0 -1
  396. package/dist/internal/tokens/palette.styles.js +0 -1
  397. package/dist/internal/tokens.styles.js +0 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{nativeAutocorrectAttribute,setNativeRangeText}from"../../../internal/native-text-control.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{observeReactivePropertyWrites}from"../../../internal/reactive-property-writes.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./phone-input.styles.js";import{digitsBefore,fallbackParse,indexAfterDigits,normalizeCountry,normalizeCountryCatalog,normalizeParseResult}from"./phone-number-adapter.js";import{loadLibphonenumberAdapter}from"./phone-number-adapter.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{declaredDefaultConverter,autocorrectConverter,normalizeAutocorrect,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_countryPickerLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_phoneInputIncomplete,LYRA_DEFAULT_phoneInputLabel,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";class LyraPhoneInputBase extends LyraElement{}class LyraPhoneInput extends FormAssociated(LyraPhoneInputBase){static{this.defaultStrings={...super.defaultStrings,countryPickerLabel:LYRA_DEFAULT_countryPickerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,phoneInputIncomplete:LYRA_DEFAULT_phoneInputIncomplete,phoneInputLabel:LYRA_DEFAULT_phoneInputLabel,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={country:{noAccessor:!0}}}get adapter(){return this._adapter}set adapter(next){const previous=this._adapter;this._adapter=next,this.adapterCountries=normalizeCountryCatalog(next?.countries),this.requestUpdate("adapter",previous)}get countries(){return this._countries}set countries(next){const previous=this._countries;this._countries=next===void 0?void 0:normalizeCountryCatalog(next),this.requestUpdate("countries",previous)}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??"tel"}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}constructor(){super(),this.flags=!1,this.adapterCountries=Object.freeze([]),this.defaultCountry="",this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.placeholder="",this.size="m",this.pill=!1,this.appearance="outlined",this.accessibleLabel=null,this.countryLabel="Country",this.countryLabelAuthored=!1,this.phoneLabel="",this.incompleteText="This phone number is incomplete.",this.incompleteTextAuthored=!1,this.invalidText="The value is invalid.",this.invalidTextAuthored=!1,this.autocomplete="tel",this.inputMode="tel",this.enterKeyHint="",this.readonly=!1,this.autofocus=!1,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.editableValue="",this.status="empty",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.hasCountryPrefixSlot=!1,this.hasEndSlot=!1,this.inputId=nextId("phone-input"),this.hintId=nextId("phone-hint"),this.errorId=nextId("phone-error"),this.explicitCountry="",this.compositionPending=!1,this.compositionCommitted=!1,this.hostDescription=new HostDescriptionController(this,()=>this.inputElement??null),this.onInput=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}const input=event.currentTarget;if(event.isComposing){this.compositionPending=!0,relayNativeEvent(this,event);return}const alreadyCommitted=this.compositionCommitted&&input.value===this.editableValue;this.compositionCommitted=!1,this.compositionPending=!1,alreadyCommitted||this.commitTypedText(input),relayNativeEvent(this,event),alreadyCommitted||this.emit("lr-input",this.eventDetail)},this.onCompositionEnd=event=>{!this.compositionPending||this.liveDisabled||this.readonly||(this.compositionPending=!1,this.commitTypedText(event.currentTarget),this.compositionCommitted=!0,this.emit("lr-input",this.eventDetail))},this.onChange=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}this.touched=!0,relayNativeEvent(this,event),this.emit("lr-change",this.eventDetail)},this.onCountryChange=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}this.country=normalizeCountry(event.currentTarget.value),this.applyParsed(this.editableValue,this.parse(this.editableValue)),dispatchNativeInputEvent(this),this.emit("lr-input",this.eventDetail),relayNativeEvent(this,event),this.emit("lr-change",this.eventDetail)},this.onKeyDown=event=>{this.liveDisabled||submitOnEnter(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onCountryPrefixSlotChange=()=>{this.hasCountryPrefixSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="country-prefix"||child.getAttribute("slot")==="start")},this.onEndSlotChange=()=>{this.hasEndSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="end")},this.addEventListener("invalid",()=>{this.touched=!0})}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get country(){return this.resolveCountry(this.availableCountries)}set country(next){const old=this.country;this.explicitCountry=normalizeCountry(next??""),this.requestUpdate("country",old)}get input(){return this.inputElement}get inputValue(){return this.editableValue}get phoneStatus(){return this.status}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){this.inputElement&&(this.inputElement.selectionStart=value??0)}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){this.inputElement&&(this.inputElement.selectionEnd=value??0)}get selectionDirection(){return this.inputElement?.selectionDirection}set selectionDirection(value){this.inputElement&&(this.inputElement.selectionDirection=value??"none")}[VALIDITY_ANCHOR](){return this.inputElement??null}get value(){return super.value}set value(next){const raw=next??"",parsed=this.parse(raw);this.applyParsed(raw,parsed)}get availableCountries(){return this.countries??this.adapterCountries}resolveCountry(rows){this.countryCodes?.rows!==rows&&(this.countryCodes={rows,codes:new Set(rows.map(row=>row.code))});const{codes}=this.countryCodes,explicit=normalizeCountry(this.explicitCountry),preferred=normalizeCountry(this.defaultCountry??"");return codes.has(explicit)?explicit:codes.has(preferred)?preferred:rows[0]?.code??""}parse(input){if(!this.adapter)return fallbackParse(input);try{const parse=this.adapter.parse;return typeof parse!="function"?{status:"invalid",formatted:input}:normalizeParseResult(parse.call(this.adapter,input,this.country||void 0),input)}catch{return{status:"invalid",formatted:input}}}reconcileCountryCatalog(){this.explicitCountry=this.resolveCountry(this.availableCountries)}applyParsed(raw,parsed){this.editableValue=parsed.formatted??raw,this.status=parsed.status,parsed.country&&(this.country=normalizeCountry(parsed.country)),super.value=parsed.status==="valid"?parsed.e164:"",this.setAttribute("data-phone-status",parsed.status)}syncFormattedValue(input,digitsBeforeCaret){if(input.value!==this.editableValue&&(input.value=this.editableValue,digitsBeforeCaret!=null)){const position=indexAfterDigits(this.editableValue,digitsBeforeCaret);input.setSelectionRange(position,position)}}get eventDetail(){return{value:super.value,inputValue:this.editableValue,country:this.country,valid:this.internals.validity.valid,status:this.status}}static get observedAttributes(){const attributes=super.observedAttributes;return observeReactivePropertyWrites(this.prototype,["countryLabel","incompleteText","invalidText"],(instance,name,value)=>{const authored=value!=null;let ownershipChanged=!1;switch(name){case"countryLabel":if(instance.countryLabelAuthored===void 0)return;ownershipChanged=authored!==instance.countryLabelAuthored,instance.countryLabelAuthored=authored;break;case"incompleteText":if(instance.incompleteTextAuthored===void 0)return;ownershipChanged=authored!==instance.incompleteTextAuthored,instance.incompleteTextAuthored=authored;break;case"invalidText":if(instance.invalidTextAuthored===void 0)return;ownershipChanged=authored!==instance.invalidTextAuthored,instance.invalidTextAuthored=authored;break}ownershipChanged&&instance.requestUpdate(),name!=="countryLabel"&&instance.hasUpdated&&instance.updateValidity()}),attributes}attributeChangedCallback(name,oldValue,newValue){if(super.attributeChangedCallback(name,oldValue,newValue),newValue===null){if(name==="country-label")this.countryLabelAuthored=!1;else if(name==="incomplete-text")this.incompleteTextAuthored=!1;else if(name==="invalid-text")this.invalidTextAuthored=!1;else return;this.requestUpdate(),this.hasUpdated&&this.updateValidity()}}get effectiveCountryLabel(){return this.countryLabelAuthored?this.countryLabel:this.localize("countryPickerLabel")}effectivePhoneLabel(hasLabel){return this.accessibleLabel!==null?this.accessibleLabel:this.phoneLabel?this.phoneLabel:hasLabel?nothing:this.placeholder||this.localize("phoneInputLabel")}get incompleteMessage(){return(this.incompleteTextAuthored?this.incompleteText:"")||this.localize("phoneInputIncomplete")}get invalidMessage(){return(this.invalidTextAuthored?this.invalidText:"")||this.localize("valueInvalid")}countryName(row){if(row.label)return row.label;try{return getDisplayNames(this.effectiveLocale,{type:"region"}).of(row.code)??row.code}catch{return row.code}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.status==="empty"?(flags.valueMissing=!0,message=this.localize("fieldRequired")):this.status==="incomplete"?(flags.badInput=!0,message=this.incompleteMessage):this.status==="invalid"&&(flags.typeMismatch=!0,message=this.invalidMessage),this[SET_ANCHORED_VALIDITY](flags,message)}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}willUpdate(changed){super.willUpdate(changed),this.flags&&!LyraPhoneInput.flagRegistration&&(LyraPhoneInput.flagRegistration=import("../../media/flag/flag.js").catch(error=>{console.warn("<lr-phone-input> failed to register <lr-flag> for its flags option:",error)})),this.hasUpdated||this.seedFirstRenderState(()=>{this.hasCountryPrefixSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="country-prefix"||child.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="end")}),(!this.hasUpdated||changed.has("countries")||changed.has("adapter")||changed.has("country")||changed.has("defaultCountry"))&&this.reconcileCountryCatalog(),(changed.has("adapter")||changed.has("countries")||changed.has("country")||changed.has("defaultCountry"))&&this.editableValue&&this.applyParsed(this.editableValue,this.parse(this.editableValue))}updated(changed){super.updated(changed),changed.has("strings")&&this.updateValidity(),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("status"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}commitTypedText(input){const caret=input.selectionStart,digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value)),this.syncFormattedValue(input,digitsBeforeCaret)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this.inputElement?.click()}focus(options){this.liveDisabled||this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;if(!input)return;setNativeRangeText(input,replacement,start,end,selectMode);const caret=input.selectionStart,digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value)),this.syncFormattedValue(input,digitsBeforeCaret)}formResetCallback(){this.explicitCountry="",this.reconcileCountryCatalog(),super.formResetCallback(),this.touched=!1}render(){const hasLabel=!!(this.label||this.hasLabelSlot||this.withLabel),hasHint=!!(this.hint||this.hasHintSlot||this.withHint),hasError=!!(this.errorText||this.hasErrorSlot),describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" "),rows=this.availableCountries,country=this.country,current=rows.find(row=>row.code===country),locale=this.effectiveLocale;(this.countryNames?.rows!==rows||this.countryNames.locale!==locale)&&(this.countryNames={rows,locale,names:rows.map(row=>this.countryName(row))});const{names}=this.countryNames;return html`
1
+ import{__decorate}from"tslib";import{nativeAutocorrectAttribute,setNativeRangeText}from"../../../internal/native-text-control.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{observeReactivePropertyWrites}from"../../../internal/reactive-property-writes.js";import{HostDescriptionController}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./phone-input.styles.js";import{digitsBefore,fallbackParse,indexAfterDigits,normalizeCountry,normalizeCountryCatalog,normalizeParseResult}from"./phone-number-adapter.js";import{loadLibphonenumberAdapter}from"./phone-number-adapter.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{declaredDefaultConverter,autocorrectConverter,normalizeAutocorrect,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_countryPickerLabel,LYRA_DEFAULT_phoneInputIncomplete,LYRA_DEFAULT_phoneInputLabel}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings/shared.generated.js";class LyraPhoneInputBase extends LyraElement{}class LyraPhoneInput extends FormAssociated(LyraPhoneInputBase){static{this.defaultStrings={...super.defaultStrings,countryPickerLabel:LYRA_DEFAULT_countryPickerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,phoneInputIncomplete:LYRA_DEFAULT_phoneInputIncomplete,phoneInputLabel:LYRA_DEFAULT_phoneInputLabel,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={country:{noAccessor:!0}}}get adapter(){return this._adapter}set adapter(next){const previous=this._adapter;this._adapter=next,this.adapterCountries=normalizeCountryCatalog(next?.countries),this.requestUpdate("adapter",previous)}get countries(){return this._countries}set countries(next){const previous=this._countries;this._countries=next===void 0?void 0:normalizeCountryCatalog(next),this.requestUpdate("countries",previous)}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??"tel"}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(next),this.requestUpdate()}constructor(){super(),this.flags=!1,this.adapterCountries=Object.freeze([]),this.defaultCountry="",this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.placeholder="",this.size="m",this.pill=!1,this.appearance="outlined",this.accessibleLabel=null,this.countryLabel="Country",this.countryLabelAuthored=!1,this.phoneLabel="",this.incompleteText="This phone number is incomplete.",this.incompleteTextAuthored=!1,this.invalidText="The value is invalid.",this.invalidTextAuthored=!1,this.autocomplete="tel",this.inputMode="tel",this.enterKeyHint="",this.readonly=!1,this.autofocus=!1,this.spellcheck=!0,this.autocapitalize="",this.autocorrectValue=!0,this.editableValue="",this.status="empty",this.touched=!1,this.slotPresence=new SlotPresenceController(this),this.hasCountryPrefixSlot=!1,this.hasEndSlot=!1,this.inputId=nextId("phone-input"),this.hintId=nextId("phone-hint"),this.errorId=nextId("phone-error"),this.explicitCountry="",this.compositionPending=!1,this.compositionCommitted=!1,this.hostDescription=new HostDescriptionController(this,()=>this.inputElement??null),this.onInput=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}const input=event.currentTarget;if(event.isComposing){this.compositionPending=!0,relayNativeEvent(this,event);return}const alreadyCommitted=this.compositionCommitted&&input.value===this.editableValue;this.compositionCommitted=!1,this.compositionPending=!1,alreadyCommitted||this.commitTypedText(input),relayNativeEvent(this,event),alreadyCommitted||this.emit("lr-input",this.eventDetail)},this.onCompositionEnd=event=>{!this.compositionPending||this.liveDisabled||this.readonly||(this.compositionPending=!1,this.commitTypedText(event.currentTarget),this.compositionCommitted=!0,this.emit("lr-input",this.eventDetail))},this.onChange=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}this.touched=!0,relayNativeEvent(this,event),this.emit("lr-change",this.eventDetail)},this.onCountryChange=event=>{if(this.liveDisabled||this.readonly){event.stopPropagation();return}this.country=normalizeCountry(event.currentTarget.value),this.applyParsed(this.editableValue,this.parse(this.editableValue)),dispatchNativeInputEvent(this),this.emit("lr-input",this.eventDetail),relayNativeEvent(this,event),this.emit("lr-change",this.eventDetail)},this.onKeyDown=event=>{this.liveDisabled||submitOnEnter(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onCountryPrefixSlotChange=()=>{this.hasCountryPrefixSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="country-prefix"||child.getAttribute("slot")==="start")},this.onEndSlotChange=()=>{this.hasEndSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="end")},this.addEventListener("invalid",()=>{this.touched=!0})}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}get country(){return this.resolveCountry(this.availableCountries)}set country(next){const old=this.country;this.explicitCountry=normalizeCountry(next??""),this.requestUpdate("country",old)}get input(){return this.inputElement}get inputValue(){return this.editableValue}get phoneStatus(){return this.status}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){this.inputElement&&(this.inputElement.selectionStart=value??0)}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){this.inputElement&&(this.inputElement.selectionEnd=value??0)}get selectionDirection(){return this.inputElement?.selectionDirection}set selectionDirection(value){this.inputElement&&(this.inputElement.selectionDirection=value??"none")}[VALIDITY_ANCHOR](){return this.inputElement??null}get value(){return super.value}set value(next){const raw=next??"",parsed=this.parse(raw);this.applyParsed(raw,parsed)}get availableCountries(){return this.countries??this.adapterCountries}resolveCountry(rows){this.countryCodes?.rows!==rows&&(this.countryCodes={rows,codes:new Set(rows.map(row=>row.code))});const{codes}=this.countryCodes,explicit=normalizeCountry(this.explicitCountry),preferred=normalizeCountry(this.defaultCountry??"");return codes.has(explicit)?explicit:codes.has(preferred)?preferred:rows[0]?.code??""}parse(input){if(!this.adapter)return fallbackParse(input);try{const parse=this.adapter.parse;return typeof parse!="function"?{status:"invalid",formatted:input}:normalizeParseResult(parse.call(this.adapter,input,this.country||void 0),input)}catch{return{status:"invalid",formatted:input}}}reconcileCountryCatalog(){this.explicitCountry=this.resolveCountry(this.availableCountries)}applyParsed(raw,parsed){this.editableValue=parsed.formatted??raw,this.status=parsed.status,parsed.country&&(this.country=normalizeCountry(parsed.country)),super.value=parsed.status==="valid"?parsed.e164:"",this.setAttribute("data-phone-status",parsed.status)}syncFormattedValue(input,digitsBeforeCaret){if(input.value!==this.editableValue&&(input.value=this.editableValue,digitsBeforeCaret!=null)){const position=indexAfterDigits(this.editableValue,digitsBeforeCaret);input.setSelectionRange(position,position)}}get eventDetail(){return{value:super.value,inputValue:this.editableValue,country:this.country,valid:this.internals.validity.valid,status:this.status}}static get observedAttributes(){const attributes=super.observedAttributes;return observeReactivePropertyWrites(this.prototype,["countryLabel","incompleteText","invalidText"],(instance,name,value)=>{const authored=value!=null;let ownershipChanged=!1;switch(name){case"countryLabel":if(instance.countryLabelAuthored===void 0)return;ownershipChanged=authored!==instance.countryLabelAuthored,instance.countryLabelAuthored=authored;break;case"incompleteText":if(instance.incompleteTextAuthored===void 0)return;ownershipChanged=authored!==instance.incompleteTextAuthored,instance.incompleteTextAuthored=authored;break;case"invalidText":if(instance.invalidTextAuthored===void 0)return;ownershipChanged=authored!==instance.invalidTextAuthored,instance.invalidTextAuthored=authored;break}ownershipChanged&&instance.requestUpdate(),name!=="countryLabel"&&instance.hasUpdated&&instance.updateValidity()}),attributes}attributeChangedCallback(name,oldValue,newValue){if(super.attributeChangedCallback(name,oldValue,newValue),newValue===null){if(name==="country-label")this.countryLabelAuthored=!1;else if(name==="incomplete-text")this.incompleteTextAuthored=!1;else if(name==="invalid-text")this.invalidTextAuthored=!1;else return;this.requestUpdate(),this.hasUpdated&&this.updateValidity()}}get effectiveCountryLabel(){return this.countryLabelAuthored?this.countryLabel:this.localize("countryPickerLabel")}effectivePhoneLabel(hasLabel){return this.accessibleLabel!==null?this.accessibleLabel:this.phoneLabel?this.phoneLabel:hasLabel?nothing:this.placeholder||this.localize("phoneInputLabel")}get incompleteMessage(){return(this.incompleteTextAuthored?this.incompleteText:"")||this.localize("phoneInputIncomplete")}get invalidMessage(){return(this.invalidTextAuthored?this.invalidText:"")||this.localize("valueInvalid")}countryName(row){if(row.label)return row.label;try{return getDisplayNames(this.effectiveLocale,{type:"region"}).of(row.code)??row.code}catch{return row.code}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.status==="empty"?(flags.valueMissing=!0,message=this.localize("fieldRequired")):this.status==="incomplete"?(flags.badInput=!0,message=this.incompleteMessage):this.status==="invalid"&&(flags.typeMismatch=!0,message=this.invalidMessage),this[SET_ANCHORED_VALIDITY](flags,message)}adoptedCallback(){super.adoptedCallback(),this.hostDescription.adopted()}willUpdate(changed){super.willUpdate(changed),this.flags&&!LyraPhoneInput.flagRegistration&&(LyraPhoneInput.flagRegistration=import("../../media/flag/flag.js").catch(error=>{console.warn("<lr-phone-input> failed to register <lr-flag> for its flags option:",error)})),this.hasUpdated||this.seedFirstRenderState(()=>{this.hasCountryPrefixSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="country-prefix"||child.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(child=>child.getAttribute("slot")==="end")}),(!this.hasUpdated||changed.has("countries")||changed.has("adapter")||changed.has("country")||changed.has("defaultCountry"))&&this.reconcileCountryCatalog(),(changed.has("adapter")||changed.has("countries")||changed.has("country")||changed.has("defaultCountry"))&&this.editableValue&&this.applyParsed(this.editableValue,this.parse(this.editableValue))}updated(changed){super.updated(changed),changed.has("strings")&&this.updateValidity(),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("status"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}commitTypedText(input){const caret=input.selectionStart,digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value)),this.syncFormattedValue(input,digitsBeforeCaret)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this.inputElement?.click()}focus(options){this.liveDisabled||this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;if(!input)return;setNativeRangeText(input,replacement,start,end,selectMode);const caret=input.selectionStart,digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value)),this.syncFormattedValue(input,digitsBeforeCaret)}formResetCallback(){this.explicitCountry="",this.reconcileCountryCatalog(),super.formResetCallback(),this.touched=!1}render(){const hasLabel=!!(this.label||this.hasLabelSlot||this.withLabel),hasHint=!!(this.hint||this.hasHintSlot||this.withHint),hasError=!!(this.errorText||this.hasErrorSlot),describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" "),rows=this.availableCountries,country=this.country,current=rows.find(row=>row.code===country),locale=this.effectiveLocale;(this.countryNames?.rows!==rows||this.countryNames.locale!==locale)&&(this.countryNames={rows,locale,names:rows.map(row=>this.countryName(row))});const{names}=this.countryNames;return html`
2
2
  <div part="form-control">
3
3
  <label part="form-control-label" for=${this.inputId} ?hidden=${!hasLabel}>
4
4
  ${this.label}<slot name="label"></slot>
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent}from"../../../internal/native-event-relay.js";import{isStaticValidityCheckInProgress}from"../../../internal/invalid-event-alias.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{declaredDefaultConverter,literalSetConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{AdjacentRunScheduler,measureAdjacentRuns}from"../../../internal/adjacent-runs.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";installFormControlLabelSupport();const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")],RADIO_GROUP_ORIENTATION=literalSetConverter(["horizontal","vertical"],"vertical");class LyraRadioGroup extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-activate"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["option","radio"]),"lr-change":Object.freeze(["option","radio"]),"lr-activate":Object.freeze(["option","radio"])})}static get validators(){return[currentValidityValidator("required","disabled","value")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},orientation:{reflect:!0,converter:RADIO_GROUP_ORIENTATION},form:{noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasHelpTextSlot(){return this.slotPresence.has("help-text")}get hasErrorSlot(){return this.slotPresence.has("error")}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormState(),this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=!0,this.selectValue(next??"")}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||(this.selectValue(this._defaultValue),this._valueDirty=!1),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.syncRadios(),this.updateValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.syncRadios(),this.updateValidity(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}constructor(){super(),this.size="m",this.orientation="vertical",this.label="",this.hint="",this.helpText="",this.shoelaceDefaultValue="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("radio-group-label"),this.hintId=nextId("radio-group-hint"),this.errorId=nextId("radio-group-error"),this.managedRadios=new Set,this.syncingRadios=!1,this.membershipObserverGeneration=0,this.runs=new AdjacentRunScheduler(this,()=>this.projectButtonRuns()),this._name="",this._value="",this._defaultValue="",this._valueDirty=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this.hasInteracted=!1,this.hadShoelaceDefaultValue=!1,this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target)))return;isStaticValidityCheckInProgress(this)||(this.hasInteracted=!0),this.reflectValidityStates(),this.requestUpdate(),this.emit("lr-invalid",null,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onFocusOut=event=>{this.hasInteracted||this.effectiveDisabled||this.matches(":disabled")||event.target.matches(":disabled")||(this.hasInteracted=!0,this.reflectValidityStates(),this.requestUpdate())},this.onKeyDown=event=>{if(!["ArrowRight","ArrowLeft","ArrowDown","ArrowUp","Home","End"].includes(event.key)||this.effectiveDisabled)return;const radios=this.radios().filter(radio=>this.isRadioAvailable(radio)),current=event.target;if(!this.isRadioAvailable(current))return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;const nextIndex=resolveListMove(event,{count:radios.length,current:index,orientation:"both",direction:this.effectiveDirection});if(nextIndex===null)return;event.preventDefault();const next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument,generation=this.membershipObserverGeneration,ownerWindow=ownerDocument?.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument&&this.syncRadios()})},this.validityController=new FormControlController(this),this.internals=this.validityController.formInternals,this.addEventListener("invalid",this.onInvalid,!0),this.syncFormState(),this.updateValidity()}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot?.querySelector('[role="radiogroup"]')??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.syncRadios(),this.armMembershipObserver(),this.runs.schedule()}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}projectButtonRuns(){const radios=this.radios(),positions=this.orientation==="horizontal"?measureAdjacentRuns(radios,{direction:this.effectiveDirection,joinable:radio=>this.isButtonRadio(radio)}):radios.map(()=>"standalone");radios.forEach((radio,index)=>radio.setButtonRunPosition(positions[index]))}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument?.defaultView,MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||ownerWindow.queueMicrotask(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.syncRadios()})});this.membershipObserver=observer,this.membershipObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["slot","checked","disabled","value","size","appearance","hidden","inert","aria-hidden","aria-disabled","class","style"]})}disconnectedCallback(){this.releaseExternalDescription(),this.resetMembershipObserver(),this.runs.dispose(),this.releaseRadios(this.managedRadios),this.managedRadios.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)&&(this.defaultValue=this.shoelaceDefaultValue,this.hadShoelaceDefaultValue=this.hasAttribute("default-value"))}updated(changed){super.updated(changed),this.syncExternalDescription(),(changed.has("size")||changed.has("orientation"))&&this.syncRadios()}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner=="function")}isRadioAvailable(radio,blocked=new Map){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){let excluded=blocked.get(current);if(excluded===void 0&&(excluded=isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")),blocked.set(current,excluded)),excluded)return!1;if(current===this)break}return!0}selectValue(next){const desired=next??"",radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired,this.pendingSelection=desired,this.syncFormState(),this.updateValidity(),this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=!0;try{for(const radio of radios)radio.checked!==(radio===match)&&(radio.checked=radio===match)}finally{this.syncingRadios=!1}this.pendingSelection=void 0,this.syncRadios(match)}syncRadios(preferred){if(!this.syncingRadios){this.syncingRadios=!0;try{const radios=this.radios(),current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios)radio.setGroupOwner(this);const membershipChanged=current.size!==this.managedRadios.size||radios.some(radio=>!this.managedRadios.has(radio));this.managedRadios=current,membershipChanged&&this.runs.observe(radios);for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const availability=new Map,enabled=radios.filter(radio=>this.isRadioAvailable(radio,availability));let checked=radios.filter(radio=>radio.checked),checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked!==(radio===checkedRadio)&&(radio.checked=radio===checkedRadio);checked=checkedRadio?[checkedRadio]:[],this.pendingSelection=void 0}else checkedRadio=preferred?.checked&&current.has(preferred)?preferred:checked[checked.length-1];for(const radio of checked)radio!==checkedRadio&&(radio.checked=!1);const tabbableRadio=checkedRadio&&this.isRadioAvailable(checkedRadio,availability)?checkedRadio:enabled[0];for(const radio of radios)radio.setGroupSize(this.size),radio.setGroupRequired(this.required&&!this.effectiveDisabled),radio.setGroupTabbable(radio===tabbableRadio);const oldValue=this._value;this._value=checkedRadio?.value??"",this.syncFormState(),this.updateValidity(),oldValue!==this._value&&this.requestUpdate("value",oldValue),this.runs.schedule()}finally{this.syncingRadios=!1}}}releaseRadios(radios){for(const radio of radios)radio.releaseGroupOwner(this),radio.setButtonRunPosition("standalone")}reconcileRadio(radio){return this.ownsRadio(radio)?(this.syncRadios(radio.checked?radio:void 0),!0):!1}releaseRadio(radio){this.managedRadios.has(radio)&&(this.releaseRadios([radio]),this.managedRadios.delete(radio),this.syncRadios())}radioCheckedChanged(radio){this.syncingRadios||!this.ownsRadio(radio)||(this._valueDirty=!0,this.syncRadios(radio.checked?radio:void 0))}selectRadio(radio){if(this.effectiveDisabled||!this.ownsRadio(radio)||!this.isRadioAvailable(radio))return!1;const detail=Object.freeze({value:radio.value,option:radio,radio});if(!radio.checked){this._valueDirty=!0,this.hasInteracted=!0,this.syncingRadios=!0;try{for(const candidate of this.radios())candidate.checked!==(candidate===radio)&&(candidate.checked=candidate===radio)}finally{this.syncingRadios=!1}this.syncRadios(),dispatchNativeEvent(this,"input"),this.emit("lr-input",detail),dispatchNativeEvent(this,"change"),this.emit("lr-change",detail)}return this.emit("lr-activate",detail),!0}focus(options){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}blur(){this.radios().find(radio=>radio.matches(":focus-within"))?.blur()}click(){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){this.internals&&this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("radioRequired"):""),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.updateValidity(),this.requestUpdate(),this.internals.reportValidity()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.reflectValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message=""){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity()}formResetCallback(){this._valueDirty=!1,this.pendingSelection=void 0,this.syncingRadios=!0;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=!1}this.defaultValue&&(this.pendingSelection=this.defaultValue),this.hasInteracted=!1,this.syncRadios()}formStateRestoreCallback(state,reason){this._valueDirty=!0,this.hasInteracted=!1,this.pendingSelection=typeof state=="string"?state:"",this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.syncRadios(),this.updateValidity(),this.requestUpdate())}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasAccessibleLabel=this.hasAttribute("aria-label")||!!this.accessibleLabel,hasHint=this.hasHintSlot||this.hasHelpTextSlot||!!(this.hint||this.helpText)||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,ariaOrientation=RADIO_GROUP_ORIENTATION.normalize(this.orientation);return html`
1
+ import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent}from"../../../internal/native-event-relay.js";import{isStaticValidityCheckInProgress}from"../../../internal/invalid-event-alias.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{declaredDefaultConverter,literalSetConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{AdjacentRunScheduler,measureAdjacentRuns}from"../../../internal/adjacent-runs.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings/forms.generated.js";installFormControlLabelSupport();const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")],RADIO_GROUP_ORIENTATION=literalSetConverter(["horizontal","vertical"],"vertical");class LyraRadioGroup extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-activate"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["option","radio"]),"lr-change":Object.freeze(["option","radio"]),"lr-activate":Object.freeze(["option","radio"])})}static get validators(){return[currentValidityValidator("required","disabled","value")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},orientation:{reflect:!0,converter:RADIO_GROUP_ORIENTATION},form:{noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasHelpTextSlot(){return this.slotPresence.has("help-text")}get hasErrorSlot(){return this.slotPresence.has("error")}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormState(),this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=!0,this.selectValue(next??"")}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||(this.selectValue(this._defaultValue),this._valueDirty=!1),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.syncRadios(),this.updateValidity(),this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.syncRadios(),this.updateValidity(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}constructor(){super(),this.size="m",this.orientation="vertical",this.label="",this.hint="",this.helpText="",this.shoelaceDefaultValue="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.slotPresence=new SlotPresenceController(this),this.labelId=nextId("radio-group-label"),this.hintId=nextId("radio-group-hint"),this.errorId=nextId("radio-group-error"),this.managedRadios=new Set,this.syncingRadios=!1,this.membershipObserverGeneration=0,this.runs=new AdjacentRunScheduler(this,()=>this.projectButtonRuns()),this._name="",this._value="",this._defaultValue="",this._valueDirty=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this.hasInteracted=!1,this.hadShoelaceDefaultValue=!1,this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target)))return;isStaticValidityCheckInProgress(this)||(this.hasInteracted=!0),this.reflectValidityStates(),this.requestUpdate(),this.emit("lr-invalid",null,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onFocusOut=event=>{this.hasInteracted||this.effectiveDisabled||this.matches(":disabled")||event.target.matches(":disabled")||(this.hasInteracted=!0,this.reflectValidityStates(),this.requestUpdate())},this.onKeyDown=event=>{if(!["ArrowRight","ArrowLeft","ArrowDown","ArrowUp","Home","End"].includes(event.key)||this.effectiveDisabled)return;const radios=this.radios().filter(radio=>this.isRadioAvailable(radio)),current=event.target;if(!this.isRadioAvailable(current))return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;const nextIndex=resolveListMove(event,{count:radios.length,current:index,orientation:"both",direction:this.effectiveDirection});if(nextIndex===null)return;event.preventDefault();const next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument,generation=this.membershipObserverGeneration,ownerWindow=ownerDocument?.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument&&this.syncRadios()})},this.validityController=new FormControlController(this),this.internals=this.validityController.formInternals,this.addEventListener("invalid",this.onInvalid,!0),this.syncFormState(),this.updateValidity()}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot?.querySelector('[role="radiogroup"]')??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.syncRadios(),this.armMembershipObserver(),this.runs.schedule()}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}projectButtonRuns(){const radios=this.radios(),positions=this.orientation==="horizontal"?measureAdjacentRuns(radios,{direction:this.effectiveDirection,joinable:radio=>this.isButtonRadio(radio)}):radios.map(()=>"standalone");radios.forEach((radio,index)=>radio.setButtonRunPosition(positions[index]))}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument?.defaultView,MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||ownerWindow.queueMicrotask(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.syncRadios()})});this.membershipObserver=observer,this.membershipObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["slot","checked","disabled","value","size","appearance","hidden","inert","aria-hidden","aria-disabled","class","style"]})}disconnectedCallback(){this.releaseExternalDescription(),this.resetMembershipObserver(),this.runs.dispose(),this.releaseRadios(this.managedRadios),this.managedRadios.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed),changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)&&(this.defaultValue=this.shoelaceDefaultValue,this.hadShoelaceDefaultValue=this.hasAttribute("default-value"))}updated(changed){super.updated(changed),this.syncExternalDescription(),(changed.has("size")||changed.has("orientation"))&&this.syncRadios()}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;for(;topLevelChild.parentElement&&topLevelChild.parentElement!==group;)topLevelChild=topLevelChild.parentElement;if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner=="function")}isRadioAvailable(radio,blocked=new Map){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){let excluded=blocked.get(current);if(excluded===void 0&&(excluded=isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")),blocked.set(current,excluded)),excluded)return!1;if(current===this)break}return!0}selectValue(next){const desired=next??"",radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired,this.pendingSelection=desired,this.syncFormState(),this.updateValidity(),this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=!0;try{for(const radio of radios)radio.checked!==(radio===match)&&(radio.checked=radio===match)}finally{this.syncingRadios=!1}this.pendingSelection=void 0,this.syncRadios(match)}syncRadios(preferred){if(!this.syncingRadios){this.syncingRadios=!0;try{const radios=this.radios(),current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios)radio.setGroupOwner(this);const membershipChanged=current.size!==this.managedRadios.size||radios.some(radio=>!this.managedRadios.has(radio));this.managedRadios=current,membershipChanged&&this.runs.observe(radios);for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const availability=new Map,enabled=radios.filter(radio=>this.isRadioAvailable(radio,availability));let checked=radios.filter(radio=>radio.checked),checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked!==(radio===checkedRadio)&&(radio.checked=radio===checkedRadio);checked=checkedRadio?[checkedRadio]:[],this.pendingSelection=void 0}else checkedRadio=preferred?.checked&&current.has(preferred)?preferred:checked[checked.length-1];for(const radio of checked)radio!==checkedRadio&&(radio.checked=!1);const tabbableRadio=checkedRadio&&this.isRadioAvailable(checkedRadio,availability)?checkedRadio:enabled[0];for(const radio of radios)radio.setGroupSize(this.size),radio.setGroupRequired(this.required&&!this.effectiveDisabled),radio.setGroupTabbable(radio===tabbableRadio);const oldValue=this._value;this._value=checkedRadio?.value??"",this.syncFormState(),this.updateValidity(),oldValue!==this._value&&this.requestUpdate("value",oldValue),this.runs.schedule()}finally{this.syncingRadios=!1}}}releaseRadios(radios){for(const radio of radios)radio.releaseGroupOwner(this),radio.setButtonRunPosition("standalone")}reconcileRadio(radio){return this.ownsRadio(radio)?(this.syncRadios(radio.checked?radio:void 0),!0):!1}releaseRadio(radio){this.managedRadios.has(radio)&&(this.releaseRadios([radio]),this.managedRadios.delete(radio),this.syncRadios())}radioCheckedChanged(radio){this.syncingRadios||!this.ownsRadio(radio)||(this._valueDirty=!0,this.syncRadios(radio.checked?radio:void 0))}selectRadio(radio){if(this.effectiveDisabled||!this.ownsRadio(radio)||!this.isRadioAvailable(radio))return!1;const detail=Object.freeze({value:radio.value,option:radio,radio});if(!radio.checked){this._valueDirty=!0,this.hasInteracted=!0,this.syncingRadios=!0;try{for(const candidate of this.radios())candidate.checked!==(candidate===radio)&&(candidate.checked=candidate===radio)}finally{this.syncingRadios=!1}this.syncRadios(),dispatchNativeEvent(this,"input"),this.emit("lr-input",detail),dispatchNativeEvent(this,"change"),this.emit("lr-change",detail)}return this.emit("lr-activate",detail),!0}focus(options){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}blur(){this.radios().find(radio=>radio.matches(":focus-within"))?.blur()}click(){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){this.internals&&this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:!0}:{},missing?this.localize("radioRequired"):""),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.validityController.checkValidity()}reportValidity(){return this.validityController.syncConstraints(),this.hasInteracted=!0,this.updateValidity(),this.requestUpdate(),this.internals.reportValidity()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.reflectValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message=""){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity()}formResetCallback(){this._valueDirty=!1,this.pendingSelection=void 0,this.syncingRadios=!0;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=!1}this.defaultValue&&(this.pendingSelection=this.defaultValue),this.hasInteracted=!1,this.syncRadios()}formStateRestoreCallback(state,reason){this._valueDirty=!0,this.hasInteracted=!1,this.pendingSelection=typeof state=="string"?state:"",this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.syncRadios(),this.updateValidity(),this.requestUpdate())}render(){const hasLabel=this.hasLabelSlot||!!this.label||this.withLabel,hasAccessibleLabel=this.hasAttribute("aria-label")||!!this.accessibleLabel,hasHint=this.hasHintSlot||this.hasHelpTextSlot||!!(this.hint||this.helpText)||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing,ariaOrientation=RADIO_GROUP_ORIENTATION.normalize(this.orientation);return html`
2
2
  <div part="base" role="radiogroup"
3
3
  aria-label=${hasAccessibleLabel?this.accessibleLabel:nothing}
4
4
  aria-labelledby=${!hasAccessibleLabel&&hasLabel?this.labelId:nothing}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./radio.styles.js";import{appearanceStyles}from"./radio-button.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";installFormControlLabelSupport();class LyraRadioBase extends LyraElement{}class LyraRadio extends CheckedFormAssociated(LyraRadioBase){constructor(){super(...arguments),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.labelTextObserver=new AccessibleTextController(this,[],()=>{this.recomputeHasLabel(),this.recomputeButtonAdornments()},["slot"]),this.swappingControl=!1,this.committingCustomError=!1,this.resettingCustomError=!1,this._radioName="",this._radioValue="on",this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this.onClick=event=>{if(event&&this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.select()},this.onKeyDown=event=>{if(this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.effectiveDisabled||(event.key===" "||event.key==="Spacebar")&&(event.preventDefault(),this.select())},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{!this.effectiveDisabled&&!this.matches(":disabled")&&!this.swappingControl&&this.setInteracted(!0),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.labelTextObserver.bind(),this.recomputeButtonAdornments()}}static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles,appearanceStyles]}static{this.properties={appearance:{reflect:!0,converter:declaredDefaultConverter("default")},pill:{type:Boolean,reflect:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")}}}get name(){return this._radioName}set name(value){const old=this._radioName,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._radioName=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._radioValue}set value(value){const old=this._radioValue,next=value??"on";old!==next&&(this._radioValue=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}radioCustomMessage(){return this.currentGroup()?.customError??this.validityController.customValidityMessage}get customError(){return this.radioCustomMessage()||null}set customError(next){this.setCustomValidity(next??"")}acceptsCheckedWrite(previous,next){return previous!==next}checkedWritten(previous){this.isConnected&&this.group()?.radioCheckedChanged?.(this)}isDisabledByOwner(){return!!this.currentGroup()&&this._groupDisabled}reportsRequired(){return this.effectiveRequired}requiredMessage(){return this.localize("radioRequired")}commitFormValue(value){this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?value:null,this.checked?"checked":"unchecked")}updateValidity(){const owned=!!this.currentGroup(),violates=!this.isBarredFromValidation()&&!owned&&this.effectiveRequired&&!this.checked;this[SET_ANCHORED_VALIDITY](violates?{valueMissing:!0}:{},this.requiredMessage())}formResetCallback(){this.currentGroup()||super.formResetCallback()}formStateRestoreCallback(state2,reason){this.currentGroup()||(this.checked=state2==="checked")}get effectiveRequired(){return this.required||(this.currentGroup()?this._groupRequired:!1)}get effectiveName(){return this.currentGroup()?.name||this.name}get effectiveSize(){return this.currentGroup()?.size??this._groupSize??this.size}syncFormState(){this.commitFormValue(this.value),this.updateValidity()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}willUpdate(changed){super.willUpdate(changed),this.swappingControl=this.hasUpdated&&changed.has("appearance")}updated(changed){super.updated(changed),this.swappingControl=!1,this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),super.disconnectedCallback()}resetFromGroup(){this.setInteracted(!1),this.restoreCheckedFromDefault()}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}setGroupRequired(value){this._groupRequired!==value&&(this._groupRequired=value,this.updateValidity(),this.requestUpdate())}setGroupSize(value){this._groupSize!==value&&(this._groupSize=value,this.toggleAttribute("data-lr-group-size",value!==null),this.requestUpdate())}setGroupTabbable(value){this._tabbable!==value&&(this._tabbable=value,this.requestUpdate())}setButtonRunPosition(value){this._buttonRunPosition!==value&&(this._buttonRunPosition=value,this.requestUpdate())}setGroupOwner(owner){if(this.groupOwner===owner)return;this.groupOwner?.releaseRadio?.(this);const standaloneCustomError=this.validityController.customValidityMessage;this.groupOwner=owner,standaloneCustomError&&owner.setCustomValidity&&(owner.setCustomValidity(standaloneCustomError),this.validityController.setCustomValidity("")),this.syncFormState()}releaseGroupOwner(owner){if(this.groupOwner!==owner)return;this.groupOwner=null,this.setGroupRequired(!1),this.setGroupDisabled(!1),this.setGroupSize(null),this.setGroupTabbable(!0),this.setButtonRunPosition("standalone");const reflectedCustomError=this.getAttribute("custom-error")??"";reflectedCustomError&&this.validityController.setCustomValidity(reflectedCustomError),this.syncFormState()}setCustomValidity(message){if(this.committingCustomError){this.resettingCustomError&&this.applyCustomValidity(message??"");return}const old=this.radioCustomMessage()||null;this.committingCustomError=!0;try{this.applyCustomValidity(message??""),this.reflectCustomError(this.radioCustomMessage())}finally{this.committingCustomError=!1}this.requestUpdate("customError",old)}applyCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message);return}this.validityController.setCustomValidity(message),this.syncValidityStates(),this.requestUpdate()}reflectCustomError(message){message?this.getAttribute("custom-error")!==message&&this.setAttribute("custom-error",message):this.hasAttribute("custom-error")&&this.removeAttribute("custom-error")}resetValidity(){if(this.committingCustomError)return;const old=this.radioCustomMessage()||null;this.committingCustomError=!0,this.resettingCustomError=!0;try{this.applyCustomValidity(""),this.reflectCustomError(this.radioCustomMessage())}finally{this.resettingCustomError=!1,this.committingCustomError=!1}this.requestUpdate("customError",old)}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}currentGroup(){if(!this.isConnected)return null;const closest=this.closest;if(typeof closest!="function")return null;const group=closest.call(this,tag("radio-group"));return group?.isConnected&&group.ownsRadio?.(this)?group:null}group(){const group=this.currentGroup();return group?(this.setGroupOwner(group),group.reconcileRadio?.(this),group):(this.groupOwner?.releaseRadio?.(this),null)}activateFromGroup(){this.select()}select(){const group=this.group();if(!this.effectiveDisabled){if(this.checked||this.setInteracted(!0),group){group.selectRadio?.(this);return}this.checked||(this.checked=!0,this.uncheckSameNameRadios(),dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})),this.emit("lr-activate",{value:this.value})}}uncheckSameNameRadios(){if(this.name)for(const other of this.getRootNode().querySelectorAll(`${tag("radio")},${tag("radio-button")}`))other!==this&&other.name===this.name&&other.form===this.form&&!other.currentGroup()&&(other.checked=!1)}get buttonRunPosition(){return this._buttonRunPosition}isNestedInteractiveEvent(event){const currentTarget=event.currentTarget;for(const entry of event.composedPath()){if(entry===currentTarget)break;if(entry&&typeof entry=="object"&&entry.nodeType===1&&isActionableElement(entry))return!0}return!1}isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}recomputeHasLabel(){const slot=this.renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.childNodes??[]).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabel=hasRealContent(nodes)}assignedAdornmentNodes(names){const slots=names.map(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)).filter(slot=>!!slot);if(slots.length>0)return slots.flatMap(slot=>slot.assignedNodes({flatten:!0}));const children=this.children;return(children?Array.from(children):[]).filter(element=>names.includes(element.getAttribute("slot")??"")).flatMap(element=>{if(element.localName!=="slot")return[element];const forwardingSlot=element;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}recomputeButtonAdornments(){this.hasStart=hasRealContent(this.assignedAdornmentNodes(["start","prefix"])),this.hasEnd=hasRealContent(this.assignedAdornmentNodes(["end","suffix"]))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.labelTextObserver.bind(),this.recomputeHasLabel())}renderButtonContent(){return html`
1
+ import{__decorate}from"tslib";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./radio.styles.js";import{appearanceStyles}from"./radio-button.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings/forms.generated.js";installFormControlLabelSupport();class LyraRadioBase extends LyraElement{}class LyraRadio extends CheckedFormAssociated(LyraRadioBase){constructor(){super(...arguments),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.labelTextObserver=new AccessibleTextController(this,[],()=>{this.recomputeHasLabel(),this.recomputeButtonAdornments()},["slot"]),this.swappingControl=!1,this.committingCustomError=!1,this.resettingCustomError=!1,this._radioName="",this._radioValue="on",this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this.onClick=event=>{if(event&&this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.select()},this.onKeyDown=event=>{if(this.isNestedInteractiveEvent(event)){event.stopPropagation();return}this.effectiveDisabled||(event.key===" "||event.key==="Spacebar")&&(event.preventDefault(),this.select())},this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{!this.effectiveDisabled&&!this.matches(":disabled")&&!this.swappingControl&&this.setInteracted(!0),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.labelTextObserver.bind(),this.recomputeButtonAdornments()}}static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles,appearanceStyles]}static{this.properties={appearance:{reflect:!0,converter:declaredDefaultConverter("default")},pill:{type:Boolean,reflect:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")}}}get name(){return this._radioName}set name(value){const old=this._radioName,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._radioName=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._radioValue}set value(value){const old=this._radioValue,next=value??"on";old!==next&&(this._radioValue=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}radioCustomMessage(){return this.currentGroup()?.customError??this.validityController.customValidityMessage}get customError(){return this.radioCustomMessage()||null}set customError(next){this.setCustomValidity(next??"")}acceptsCheckedWrite(previous,next){return previous!==next}checkedWritten(previous){this.isConnected&&this.group()?.radioCheckedChanged?.(this)}isDisabledByOwner(){return!!this.currentGroup()&&this._groupDisabled}reportsRequired(){return this.effectiveRequired}requiredMessage(){return this.localize("radioRequired")}commitFormValue(value){this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?value:null,this.checked?"checked":"unchecked")}updateValidity(){const owned=!!this.currentGroup(),violates=!this.isBarredFromValidation()&&!owned&&this.effectiveRequired&&!this.checked;this[SET_ANCHORED_VALIDITY](violates?{valueMissing:!0}:{},this.requiredMessage())}formResetCallback(){this.currentGroup()||super.formResetCallback()}formStateRestoreCallback(state2,reason){this.currentGroup()||(this.checked=state2==="checked")}get effectiveRequired(){return this.required||(this.currentGroup()?this._groupRequired:!1)}get effectiveName(){return this.currentGroup()?.name||this.name}get effectiveSize(){return this.currentGroup()?.size??this._groupSize??this.size}syncFormState(){this.commitFormValue(this.value),this.updateValidity()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}willUpdate(changed){super.willUpdate(changed),this.swappingControl=this.hasUpdated&&changed.has("appearance")}updated(changed){super.updated(changed),this.swappingControl=!1,this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),super.disconnectedCallback()}resetFromGroup(){this.setInteracted(!1),this.restoreCheckedFromDefault()}setGroupDisabled(value){this._groupDisabled!==value&&(this._groupDisabled=value,this.updateValidity(),this.requestUpdate())}setGroupRequired(value){this._groupRequired!==value&&(this._groupRequired=value,this.updateValidity(),this.requestUpdate())}setGroupSize(value){this._groupSize!==value&&(this._groupSize=value,this.toggleAttribute("data-lr-group-size",value!==null),this.requestUpdate())}setGroupTabbable(value){this._tabbable!==value&&(this._tabbable=value,this.requestUpdate())}setButtonRunPosition(value){this._buttonRunPosition!==value&&(this._buttonRunPosition=value,this.requestUpdate())}setGroupOwner(owner){if(this.groupOwner===owner)return;this.groupOwner?.releaseRadio?.(this);const standaloneCustomError=this.validityController.customValidityMessage;this.groupOwner=owner,standaloneCustomError&&owner.setCustomValidity&&(owner.setCustomValidity(standaloneCustomError),this.validityController.setCustomValidity("")),this.syncFormState()}releaseGroupOwner(owner){if(this.groupOwner!==owner)return;this.groupOwner=null,this.setGroupRequired(!1),this.setGroupDisabled(!1),this.setGroupSize(null),this.setGroupTabbable(!0),this.setButtonRunPosition("standalone");const reflectedCustomError=this.getAttribute("custom-error")??"";reflectedCustomError&&this.validityController.setCustomValidity(reflectedCustomError),this.syncFormState()}setCustomValidity(message){if(this.committingCustomError){this.resettingCustomError&&this.applyCustomValidity(message??"");return}const old=this.radioCustomMessage()||null;this.committingCustomError=!0;try{this.applyCustomValidity(message??""),this.reflectCustomError(this.radioCustomMessage())}finally{this.committingCustomError=!1}this.requestUpdate("customError",old)}applyCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message);return}this.validityController.setCustomValidity(message),this.syncValidityStates(),this.requestUpdate()}reflectCustomError(message){message?this.getAttribute("custom-error")!==message&&this.setAttribute("custom-error",message):this.hasAttribute("custom-error")&&this.removeAttribute("custom-error")}resetValidity(){if(this.committingCustomError)return;const old=this.radioCustomMessage()||null;this.committingCustomError=!0,this.resettingCustomError=!0;try{this.applyCustomValidity(""),this.reflectCustomError(this.radioCustomMessage())}finally{this.resettingCustomError=!1,this.committingCustomError=!1}this.requestUpdate("customError",old)}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}currentGroup(){if(!this.isConnected)return null;const closest=this.closest;if(typeof closest!="function")return null;const group=closest.call(this,tag("radio-group"));return group?.isConnected&&group.ownsRadio?.(this)?group:null}group(){const group=this.currentGroup();return group?(this.setGroupOwner(group),group.reconcileRadio?.(this),group):(this.groupOwner?.releaseRadio?.(this),null)}activateFromGroup(){this.select()}select(){const group=this.group();if(!this.effectiveDisabled){if(this.checked||this.setInteracted(!0),group){group.selectRadio?.(this);return}this.checked||(this.checked=!0,this.uncheckSameNameRadios(),dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})),this.emit("lr-activate",{value:this.value})}}uncheckSameNameRadios(){if(this.name)for(const other of this.getRootNode().querySelectorAll(`${tag("radio")},${tag("radio-button")}`))other!==this&&other.name===this.name&&other.form===this.form&&!other.currentGroup()&&(other.checked=!1)}get buttonRunPosition(){return this._buttonRunPosition}isNestedInteractiveEvent(event){const currentTarget=event.currentTarget;for(const entry of event.composedPath()){if(entry===currentTarget)break;if(entry&&typeof entry=="object"&&entry.nodeType===1&&isActionableElement(entry))return!0}return!1}isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}recomputeHasLabel(){const slot=this.renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(this.childNodes??[]).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabel=hasRealContent(nodes)}assignedAdornmentNodes(names){const slots=names.map(name=>this.renderRoot.querySelector(`slot[name="${name}"]`)).filter(slot=>!!slot);if(slots.length>0)return slots.flatMap(slot=>slot.assignedNodes({flatten:!0}));const children=this.children;return(children?Array.from(children):[]).filter(element=>names.includes(element.getAttribute("slot")??"")).flatMap(element=>{if(element.localName!=="slot")return[element];const forwardingSlot=element;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)})}recomputeButtonAdornments(){this.hasStart=hasRealContent(this.assignedAdornmentNodes(["start","prefix"])),this.hasEnd=hasRealContent(this.assignedAdornmentNodes(["end","suffix"]))}handleLabelSlotChange(event){const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.labelTextObserver.bind(),this.recomputeHasLabel())}renderButtonContent(){return html`
2
2
  <span part="start prefix" ?hidden=${!this.hasStart}>
3
3
  <slot name="start" @slotchange=${this.onAdornmentSlotChange}></slot>
4
4
  <slot name="prefix" @slotchange=${this.onAdornmentSlotChange}></slot>
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{tag}from"../../../internal/prefix.js";import{nextId}from"../../../internal/a11y.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import{agentActionButtonStyles}from"../../agent-tools/agent-action-button.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings.generated.js";installFormControlLabelSupport();const EMPTY_KEYS=[],EMPTY_VALUE={},MAX_RUBRIC_COLLECTION_ENTRIES=1e4;function cloneRubricValue(value){return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,Array.isArray(entry)?Object.freeze([...entry]):entry])))}function projectRubricStringArray(value){try{if(!Array.isArray(value))return;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return;const values=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const entry=getOwnDataDescriptor(value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value=="string"&&values.push(entry.value)}return Object.freeze(values)}catch{return}}function projectRubricOptions(value){try{if(!Array.isArray(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const options=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const candidate=getOwnDataDescriptor(value,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR||candidate.value===null||typeof candidate.value!="object"||Array.isArray(candidate.value))continue;const optionValue=getOwnDataDescriptor(candidate.value,"value"),label=getOwnDataDescriptor(candidate.value,"label"),description=getOwnDataDescriptor(candidate.value,"description"),icon=getOwnDataDescriptor(candidate.value,"icon");if(optionValue===MISSING_OWN_DATA_DESCRIPTOR||optionValue===UNSAFE_OWN_DATA_DESCRIPTOR||typeof optionValue.value!="string")continue;const labelValue=label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:typeof label.value=="string"?label.value:void 0,descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:typeof description.value=="string"?description.value:void 0,iconValue=icon===MISSING_OWN_DATA_DESCRIPTOR||icon===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:icon.value;options.push(Object.freeze({value:optionValue.value,...labelValue===void 0?{}:{label:labelValue},...descriptionValue===void 0?{}:{description:descriptionValue},...iconValue===void 0?{}:{icon:iconValue}}))}return Object.freeze(options)}catch{return Object.freeze([])}}function projectRubricKey(candidate){try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))return;const key=getOwnDataDescriptor(candidate,"key"),type=getOwnDataDescriptor(candidate,"type"),label=getOwnDataDescriptor(candidate,"label"),description=getOwnDataDescriptor(candidate,"description"),required=getOwnDataDescriptor(candidate,"required");if(key===MISSING_OWN_DATA_DESCRIPTOR||key===UNSAFE_OWN_DATA_DESCRIPTOR||type===UNSAFE_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR||required===UNSAFE_OWN_DATA_DESCRIPTOR||typeof key.value!="string"||key.value.trim().length===0)return;const typeValue=type===MISSING_OWN_DATA_DESCRIPTOR?"":type.value;if(typeof typeValue!="string")return;const labelValue=label===MISSING_OWN_DATA_DESCRIPTOR?void 0:label.value,descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR?void 0:description.value,requiredValue=required===MISSING_OWN_DATA_DESCRIPTOR?void 0:required.value,common={key:key.value,...typeof labelValue=="string"?{label:labelValue}:{},...typeof descriptionValue=="string"?{description:descriptionValue}:{},...typeof requiredValue=="boolean"?{required:requiredValue}:{}};if(typeValue==="score"){const min=getOwnDataDescriptor(candidate,"min"),max=getOwnDataDescriptor(candidate,"max"),step=getOwnDataDescriptor(candidate,"step");return min===UNSAFE_OWN_DATA_DESCRIPTOR||max===UNSAFE_OWN_DATA_DESCRIPTOR||step===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"score",...min!==MISSING_OWN_DATA_DESCRIPTOR&&typeof min.value=="number"?{min:min.value}:{},...max!==MISSING_OWN_DATA_DESCRIPTOR&&typeof max.value=="number"?{max:max.value}:{},...step!==MISSING_OWN_DATA_DESCRIPTOR&&typeof step.value=="number"?{step:step.value}:{}})}if(typeValue==="category"){const options=getOwnDataDescriptor(candidate,"options"),multiple=getOwnDataDescriptor(candidate,"multiple");return options===UNSAFE_OWN_DATA_DESCRIPTOR||multiple===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"category",options:options===MISSING_OWN_DATA_DESCRIPTOR?Object.freeze([]):projectRubricOptions(options.value),...multiple!==MISSING_OWN_DATA_DESCRIPTOR&&typeof multiple.value=="boolean"?{multiple:multiple.value}:{}})}if(typeValue==="comment"){const placeholder=getOwnDataDescriptor(candidate,"placeholder");return placeholder===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"comment",...placeholder!==MISSING_OWN_DATA_DESCRIPTOR&&typeof placeholder.value=="string"?{placeholder:placeholder.value}:{}})}return Object.freeze({...common,type:typeValue})}catch{return}}function normalizeRubricKeys(next){try{if(!Array.isArray(next))return EMPTY_KEYS;const length=getOwnDataDescriptor(next,"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_KEYS;const seen=new Set,normalized=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const candidate=getOwnDataDescriptor(next,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const key=projectRubricKey(candidate.value);!key||seen.has(key.key)||(seen.add(key.key),normalized.push(key))}return Object.freeze(normalized)}catch{return EMPTY_KEYS}}function scoreDomain(key){const min=Number.isFinite(key.min)?key.min:0,rawMax=Number.isFinite(key.max)?key.max:5,max=Math.max(min,rawMax),step=Number.isFinite(key.step)&&key.step>0?key.step:1;return{min,max,step}}function isSegmentedScoreKey(key){if(key.step!==void 0&&(!Number.isFinite(key.step)||key.step<=0)||Number.isFinite(key.min)&&Number.isFinite(key.max)&&key.max<key.min)return!1;const{min,max,step}=scoreDomain(key);if(!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return!1;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}function canonicalScore(value,key){if(typeof value!="number"||!Number.isFinite(value))return;const{min,max,step}=scoreDomain(key),clamped=Math.min(max,Math.max(min,value)),snapped=Math.min(max,Math.max(min,min+Math.round((clamped-min)/step)*step));return Number(snapped.toPrecision(15))}function normalizeRubricValue(value,keys){const source=value!==null&&typeof value=="object"&&!Array.isArray(value)?value:EMPTY_VALUE,normalized={};for(const key of keys){const descriptor=getOwnDataDescriptor(source,key.key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const hasEntry=descriptor!==MISSING_OWN_DATA_DESCRIPTOR,entry=descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value;if(key.type==="score"){const{min,max}=scoreDomain(key),score=canonicalScore(hasEntry?entry:isSegmentedScoreKey(key)?void 0:min+(max-min)/2,key);score!==void 0&&(normalized[key.key]=score)}else if(key.type==="category"){if(!hasEntry)continue;const allowed=(key.options??[]).map(option=>option.value);if(key.multiple){const entries=projectRubricStringArray(entry);if(!entries)continue;const remaining=new Map;for(const option of allowed)remaining.set(option,(remaining.get(option)??0)+1);const selected=[];for(const candidate of entries){const count=remaining.get(candidate)??0;count<=0||(selected.push(candidate),remaining.set(candidate,count-1))}normalized[key.key]=selected}else typeof entry=="string"&&entry!==""&&allowed.includes(entry)&&(normalized[key.key]=entry)}else key.type==="comment"&&hasEntry&&typeof entry=="string"&&(normalized[key.key]=entry)}return normalized}class LyraRubricForm extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,agentActionButtonStyles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},keys:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:!1,noAccessor:!0},itemId:{attribute:"item-id",reflect:!0,noAccessor:!0},hasNext:{type:Boolean,attribute:"has-next",noAccessor:!0},skippable:{type:Boolean,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._errors={},this.touchedFields=new Set,this.slotPresence=new SlotPresenceController(this),this.baseId=nextId("rubric-form"),this.aggregateLabelId=`${this.baseId}-label`,this.aggregateHintId=`${this.baseId}-hint`,this.aggregateErrorId=`${this.baseId}-error`,this._fieldsetDisabled=!1,this._name="",this._keys=EMPTY_KEYS,this._value=EMPTY_VALUE,this._defaultValue=EMPTY_VALUE,this._rawValue=EMPTY_VALUE,this._rawDefaultValue=EMPTY_VALUE,this._valueDirty=!1,this._itemId="",this._hasNext=!1,this._skippable=!1,this._disabled=!1,this.pendingFocusFirst=!1,this.markInteracted=()=>{Object.keys(this._errors).length!==0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]),this.syncCustomStates())},this.onFormKeyDown=e=>{e.key==="Enter"&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.submit())},this.onValueCommit=event=>{event.stopPropagation(),this.effectiveDisabled||emitValueEvents(this,"change",Object.freeze({value:cloneRubricValue(this._value)}),detail=>this.emit("lr-change",detail))},this.stopChildEvent=event=>{event.stopPropagation()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.addEventListener("keydown",this.onFormKeyDown),this.syncFormState()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get keys(){return this._keys}set keys(next){if(next===this._boundKeys)return;this._boundKeys=next;const old=this._keys,recoverFromRaw=old.length===0;this._keys=normalizeRubricKeys(next??EMPTY_KEYS);const oldDefault=this._defaultValue,oldValue=this._value;this._defaultValue=normalizeRubricValue(recoverFromRaw?this._rawDefaultValue:this._defaultValue,this._keys),this._value=this._valueDirty?normalizeRubricValue(recoverFromRaw?this._rawValue:this._value,this._keys):cloneRubricValue(this._defaultValue),this.syncFormState(),this.requestUpdate("keys",old),this.requestUpdate("defaultValue",oldDefault),this.requestUpdate("value",oldValue)}get value(){return cloneRubricValue(this._value)}set value(next){next!==this._boundValue&&(this._boundValue=next,this.setLiveValue(next,!0))}get defaultValue(){return cloneRubricValue(this._defaultValue)}set defaultValue(next){if(next===this._rawDefaultValue)return;const old=this._defaultValue;this._rawDefaultValue=next??EMPTY_VALUE,this._defaultValue=normalizeRubricValue(this._rawDefaultValue,this._keys),this._valueDirty||this.setLiveValue(this._defaultValue,!1),this.requestUpdate("defaultValue",old)}setLiveValue(next,dirty){const old=this._value;this._rawValue=next??EMPTY_VALUE,this._value=normalizeRubricValue(this._rawValue,this._keys),this._valueDirty=dirty,this.syncFormState(),this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"",old!==this._itemId&&(this.touchedFields=new Set,this.syncCustomStates(),this.hasUpdated&&(this.pendingFocusFirst=!0)),this._itemId?this.setAttribute("item-id",this._itemId):this.removeAttribute("item-id"),this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=!!next,this.toggleAttribute("has-next",this._hasNext),this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=!!next,this.requestUpdate("skippable",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.validityController&&this.syncFormState(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&this.validityController.customValidityMessage&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}fieldElement(key){const root=this.renderRoot,ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];return!firstInvalidKey||!this.renderRoot?void 0:this.fieldElement(firstInvalidKey)?.querySelector(".control")??void 0}isSegmentedScore(k){return isSegmentedScoreKey(k)}scoreValues(k){if(!this.isSegmentedScore(k))return[];const{min,max,step}=scoreDomain(k),count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors={},flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){const unsupported=k;errors[unsupported.key]=this.localize("unsupportedFieldType",void 0,{type:unsupported.type}),flags.customError=!0;continue}if(!k.required)continue;const v=this._value[k.key];(k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="")||(errors[k.key]=this.localize("fieldRequired"),flags.valueMissing=!0)}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}if(this.internals.setFormValue(formValue,formValue),this.barredFromValidation||Object.keys(flags).length===0)this.validityController.setValidity({});else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates(),this.publishValiditySnapshot()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>!!key.required),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){return this.validityController.checkValidity(()=>this.syncFormState())}reportValidity(){return this.validityController.syncConstraints(),this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]),this.syncCustomStates()),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.setLiveValue(this._defaultValue,!1),this.touchedFields=new Set,this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.setLiveValue(restored,!0)}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.syncFormState(),this.requestUpdate())}setFieldValue(key,val,committed=!0){if(this.effectiveDisabled)return;this.setLiveValue({...this._value,[key]:val},!0);const detail=Object.freeze({value:cloneRubricValue(this._value)});emitValueEvents(this,"input",detail,detail2=>this.emit("lr-input",detail2)),committed&&emitValueEvents(this,"change",detail,detail2=>this.emit("lr-change",detail2))}markTouched(key){this.effectiveDisabled||this.touchedFields.has(key)||(this.touchedFields=new Set(this.touchedFields).add(key),this.syncCustomStates())}submit(){this.effectiveDisabled||this.reportValidity()&&this.emit("lr-submit",Object.freeze({value:cloneRubricValue(this._value),itemId:this.itemId}))}skip(){this.effectiveDisabled||this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(options){const firstKey=this._keys[0];if(!firstKey)return;const control=this.fieldElement(firstKey.key)?.querySelector(".control");control&&(firstKey.type==="score"&&this.isSegmentedScore(firstKey)?control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus(options):firstKey.type==="score"?control.shadowRoot?.querySelector('[part="thumb"]')?.focus(options):firstKey.type==="category"&&firstKey.multiple?control.querySelector(tag("checkbox"))?.focus(options):control.focus(options))}focus(options){this.effectiveDisabled||this.focusFirstControl(options)}click(){this.effectiveDisabled||this.focusFirstControl()}syncExternalDescription(){const target=this.isConnected?this.renderRoot.querySelector('[part="base"][role="group"]'):null;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription(),this.publishValiditySnapshot(),this.pendingFocusFirst&&(this.pendingFocusFirst=!1,this.focusFirstControl())}renderScoreControl(k,fieldId,current,hasError){const{min,max,step}=scoreDomain(k),disabled=this.effectiveDisabled,accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>!!value).join(". ");if(this.isSegmentedScore(k)){const numberFormat=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:20}),items=this.scoreValues(k).map(score=>({value:String(score),label:numberFormat.format(score),disabled})),value=typeof current=="number"?String(current):"";return html`<lr-segmented
1
+ import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/value-events.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{tag}from"../../../internal/prefix.js";import{nextId}from"../../../internal/a11y.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import{agentActionButtonStyles}from"../../agent-tools/agent-action-button.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{finiteMidpoint}from"../../../internal/numbers.js";import{clampSteppedValue}from"../../../internal/step-value.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noData,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();const EMPTY_KEYS=[],EMPTY_VALUE={},MAX_RUBRIC_COLLECTION_ENTRIES=1e4;function cloneRubricValue(value){return Object.freeze(Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,Array.isArray(entry)?Object.freeze([...entry]):entry])))}function projectRubricStringArray(value){try{if(!Array.isArray(value))return;const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return;const values=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const entry=getOwnDataDescriptor(value,String(index));entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR||typeof entry.value=="string"&&values.push(entry.value)}return Object.freeze(values)}catch{return}}function projectRubricOptions(value){try{if(!Array.isArray(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const options=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const candidate=getOwnDataDescriptor(value,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR||candidate.value===null||typeof candidate.value!="object"||Array.isArray(candidate.value))continue;const optionValue=getOwnDataDescriptor(candidate.value,"value"),label=getOwnDataDescriptor(candidate.value,"label"),description=getOwnDataDescriptor(candidate.value,"description"),icon=getOwnDataDescriptor(candidate.value,"icon");if(optionValue===MISSING_OWN_DATA_DESCRIPTOR||optionValue===UNSAFE_OWN_DATA_DESCRIPTOR||typeof optionValue.value!="string")continue;const labelValue=label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:typeof label.value=="string"?label.value:void 0,descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:typeof description.value=="string"?description.value:void 0,iconValue=icon===MISSING_OWN_DATA_DESCRIPTOR||icon===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:icon.value;options.push(Object.freeze({value:optionValue.value,...labelValue===void 0?{}:{label:labelValue},...descriptionValue===void 0?{}:{description:descriptionValue},...iconValue===void 0?{}:{icon:iconValue}}))}return Object.freeze(options)}catch{return Object.freeze([])}}function projectRubricKey(candidate){try{if(candidate===null||typeof candidate!="object"||Array.isArray(candidate))return;const key=getOwnDataDescriptor(candidate,"key"),type=getOwnDataDescriptor(candidate,"type"),label=getOwnDataDescriptor(candidate,"label"),description=getOwnDataDescriptor(candidate,"description"),required=getOwnDataDescriptor(candidate,"required");if(key===MISSING_OWN_DATA_DESCRIPTOR||key===UNSAFE_OWN_DATA_DESCRIPTOR||type===UNSAFE_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||description===UNSAFE_OWN_DATA_DESCRIPTOR||required===UNSAFE_OWN_DATA_DESCRIPTOR||typeof key.value!="string"||key.value.trim().length===0)return;const typeValue=type===MISSING_OWN_DATA_DESCRIPTOR?"":type.value;if(typeof typeValue!="string")return;const labelValue=label===MISSING_OWN_DATA_DESCRIPTOR?void 0:label.value,descriptionValue=description===MISSING_OWN_DATA_DESCRIPTOR?void 0:description.value,requiredValue=required===MISSING_OWN_DATA_DESCRIPTOR?void 0:required.value,common={key:key.value,...typeof labelValue=="string"?{label:labelValue}:{},...typeof descriptionValue=="string"?{description:descriptionValue}:{},...typeof requiredValue=="boolean"?{required:requiredValue}:{}};if(typeValue==="score"){const min=getOwnDataDescriptor(candidate,"min"),max=getOwnDataDescriptor(candidate,"max"),step=getOwnDataDescriptor(candidate,"step");return min===UNSAFE_OWN_DATA_DESCRIPTOR||max===UNSAFE_OWN_DATA_DESCRIPTOR||step===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"score",...min!==MISSING_OWN_DATA_DESCRIPTOR&&typeof min.value=="number"?{min:min.value}:{},...max!==MISSING_OWN_DATA_DESCRIPTOR&&typeof max.value=="number"?{max:max.value}:{},...step!==MISSING_OWN_DATA_DESCRIPTOR&&typeof step.value=="number"?{step:step.value}:{}})}if(typeValue==="category"){const options=getOwnDataDescriptor(candidate,"options"),multiple=getOwnDataDescriptor(candidate,"multiple");return options===UNSAFE_OWN_DATA_DESCRIPTOR||multiple===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"category",options:options===MISSING_OWN_DATA_DESCRIPTOR?Object.freeze([]):projectRubricOptions(options.value),...multiple!==MISSING_OWN_DATA_DESCRIPTOR&&typeof multiple.value=="boolean"?{multiple:multiple.value}:{}})}if(typeValue==="comment"){const placeholder=getOwnDataDescriptor(candidate,"placeholder");return placeholder===UNSAFE_OWN_DATA_DESCRIPTOR?void 0:Object.freeze({...common,type:"comment",...placeholder!==MISSING_OWN_DATA_DESCRIPTOR&&typeof placeholder.value=="string"?{placeholder:placeholder.value}:{}})}return Object.freeze({...common,type:typeValue})}catch{return}}function normalizeRubricKeys(next){try{if(!Array.isArray(next))return EMPTY_KEYS;const length=getOwnDataDescriptor(next,"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_KEYS;const seen=new Set,normalized=[];for(let index=0;index<Math.min(length.value,MAX_RUBRIC_COLLECTION_ENTRIES);index+=1){const candidate=getOwnDataDescriptor(next,String(index));if(candidate===MISSING_OWN_DATA_DESCRIPTOR||candidate===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const key=projectRubricKey(candidate.value);!key||seen.has(key.key)||(seen.add(key.key),normalized.push(key))}return Object.freeze(normalized)}catch{return EMPTY_KEYS}}function scoreDomain(key){const min=Number.isFinite(key.min)?key.min:0,rawMax=Number.isFinite(key.max)?key.max:5,max=Math.max(min,rawMax),step=Number.isFinite(key.step)&&key.step>0?key.step:1;return{min,max,step}}function isSegmentedScoreKey(key){if(key.step!==void 0&&(!Number.isFinite(key.step)||key.step<=0)||Number.isFinite(key.min)&&Number.isFinite(key.max)&&key.max<key.min)return!1;const{min,max,step}=scoreDomain(key);if(!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return!1;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}function canonicalScore(value,key){if(typeof value!="number"||!Number.isFinite(value))return;const{min,max,step}=scoreDomain(key);return clampSteppedValue(value,min,max,step)}function normalizeRubricValue(value,keys){const source=value!==null&&typeof value=="object"&&!Array.isArray(value)?value:EMPTY_VALUE,normalized=Object.create(null);for(const key of keys){const descriptor=getOwnDataDescriptor(source,key.key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const hasEntry=descriptor!==MISSING_OWN_DATA_DESCRIPTOR,entry=descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value;if(key.type==="score"){const{min,max}=scoreDomain(key),score=canonicalScore(hasEntry?entry:isSegmentedScoreKey(key)?void 0:finiteMidpoint(min,max),key);score!==void 0&&(normalized[key.key]=score)}else if(key.type==="category"){if(!hasEntry)continue;const allowed=(key.options??[]).map(option=>option.value);if(key.multiple){const entries=projectRubricStringArray(entry);if(!entries)continue;const remaining=new Map;for(const option of allowed)remaining.set(option,(remaining.get(option)??0)+1);const selected=[];for(const candidate of entries){const count=remaining.get(candidate)??0;count<=0||(selected.push(candidate),remaining.set(candidate,count-1))}normalized[key.key]=selected}else typeof entry=="string"&&entry!==""&&allowed.includes(entry)&&(normalized[key.key]=entry)}else key.type==="comment"&&hasEntry&&typeof entry=="string"&&(normalized[key.key]=entry)}return normalized}class LyraRubricForm extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,agentActionButtonStyles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},keys:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:!1,noAccessor:!0},itemId:{attribute:"item-id",reflect:!0,noAccessor:!0},hasNext:{type:Boolean,attribute:"has-next",noAccessor:!0},skippable:{type:Boolean,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get hasLabelSlot(){return this.slotPresence.has("label")}get hasHintSlot(){return this.slotPresence.has("hint")}get hasErrorSlot(){return this.slotPresence.has("error")}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._errors={},this.touchedFields=new Set,this.slotPresence=new SlotPresenceController(this),this.baseId=nextId("rubric-form"),this.aggregateLabelId=`${this.baseId}-label`,this.aggregateHintId=`${this.baseId}-hint`,this.aggregateErrorId=`${this.baseId}-error`,this._fieldsetDisabled=!1,this._name="",this._keys=EMPTY_KEYS,this._value=EMPTY_VALUE,this._defaultValue=EMPTY_VALUE,this._rawValue=EMPTY_VALUE,this._rawDefaultValue=EMPTY_VALUE,this._valueDirty=!1,this._itemId="",this._hasNext=!1,this._skippable=!1,this._disabled=!1,this.pendingFocusFirst=!1,this.markInteracted=()=>{Object.keys(this._errors).length!==0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]),this.syncCustomStates())},this.onFormKeyDown=e=>{e.key==="Enter"&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.submit())},this.onValueCommit=event=>{event.stopPropagation(),this.effectiveDisabled||emitValueEvents(this,"change",Object.freeze({value:cloneRubricValue(this._value)}),detail=>this.emit("lr-change",detail))},this.stopChildEvent=event=>{event.stopPropagation()},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,this.addEventListener("keydown",this.onFormKeyDown),this.syncFormState()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}get keys(){return this._keys}set keys(next){if(next===this._boundKeys)return;this._boundKeys=next;const old=this._keys,recoverFromRaw=old.length===0;this._keys=normalizeRubricKeys(next??EMPTY_KEYS);const oldDefault=this._defaultValue,oldValue=this._value;this._defaultValue=normalizeRubricValue(recoverFromRaw?this._rawDefaultValue:this._defaultValue,this._keys),this._value=this._valueDirty?normalizeRubricValue(recoverFromRaw?this._rawValue:this._value,this._keys):cloneRubricValue(this._defaultValue),this.syncFormState(),this.requestUpdate("keys",old),this.requestUpdate("defaultValue",oldDefault),this.requestUpdate("value",oldValue)}get value(){return cloneRubricValue(this._value)}set value(next){next!==this._boundValue&&(this._boundValue=next,this.setLiveValue(next,!0))}get defaultValue(){return cloneRubricValue(this._defaultValue)}set defaultValue(next){if(next===this._rawDefaultValue)return;const old=this._defaultValue;this._rawDefaultValue=next??EMPTY_VALUE,this._defaultValue=normalizeRubricValue(this._rawDefaultValue,this._keys),this._valueDirty||this.setLiveValue(this._defaultValue,!1),this.requestUpdate("defaultValue",old)}setLiveValue(next,dirty){const old=this._value;this._rawValue=next??EMPTY_VALUE,this._value=normalizeRubricValue(this._rawValue,this._keys),this._valueDirty=dirty,this.syncFormState(),this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"",old!==this._itemId&&(this.touchedFields=new Set,this.syncCustomStates(),this.hasUpdated&&(this.pendingFocusFirst=!0)),this._itemId?this.setAttribute("item-id",this._itemId):this.removeAttribute("item-id"),this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=!!next,this.toggleAttribute("has-next",this._hasNext),this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=!!next,this.requestUpdate("skippable",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this.validityController&&this.syncFormState(),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return this.publicValidityErrors()}publicValidityErrors(){const errors={...this._errors};return this.willValidate&&this.validityController.customValidityMessage&&(errors.base=this.validationMessage),Object.freeze(errors)}publishValiditySnapshot(){if(!this.isConnected)return;const valid=!this.willValidate||this.validity.valid,errors=valid?Object.freeze({}):this.publicValidityErrors(),key=JSON.stringify({valid,errors});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,errors})))}fieldElement(key){const root=this.renderRoot,ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];return!firstInvalidKey||!this.renderRoot?void 0:this.fieldElement(firstInvalidKey)?.querySelector(".control")??void 0}isSegmentedScore(k){return isSegmentedScoreKey(k)}scoreValues(k){if(!this.isSegmentedScore(k))return[];const{min,max,step}=scoreDomain(k),count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors=Object.create(null),flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){const unsupported=k;errors[unsupported.key]=this.localize("unsupportedFieldType",void 0,{type:unsupported.type}),flags.customError=!0;continue}if(!k.required)continue;const v=Object.hasOwn(this._value,k.key)?this._value[k.key]:void 0;(k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="")||(errors[k.key]=this.localize("fieldRequired"),flags.valueMissing=!0)}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}if(this.internals.setFormValue(formValue,formValue),this.barredFromValidation||Object.keys(flags).length===0)this.validityController.setValidity({});else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates(),this.publishValiditySnapshot()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>!!key.required),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){return this.validityController.checkValidity(()=>this.syncFormState())}reportValidity(){return this.validityController.syncConstraints(),this.syncFormState(),Object.keys(this._errors).length>0&&(this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]),this.syncCustomStates()),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.publishValiditySnapshot(),this.requestUpdate()}formResetCallback(){this.setLiveValue(this._defaultValue,!1),this.touchedFields=new Set,this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2=="string")try{const parsed=JSON.parse(state2);parsed!==null&&typeof parsed=="object"&&!Array.isArray(parsed)&&(restored=parsed)}catch{}this.setLiveValue(restored,!0)}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(this.syncFormState(),this.requestUpdate())}setFieldValue(key,val,committed=!0){if(this.effectiveDisabled)return;this.setLiveValue({...this._value,[key]:val},!0);const detail=Object.freeze({value:cloneRubricValue(this._value)});emitValueEvents(this,"input",detail,detail2=>this.emit("lr-input",detail2)),committed&&emitValueEvents(this,"change",detail,detail2=>this.emit("lr-change",detail2))}markTouched(key){this.effectiveDisabled||this.touchedFields.has(key)||(this.touchedFields=new Set(this.touchedFields).add(key),this.syncCustomStates())}submit(){this.effectiveDisabled||this.reportValidity()&&this.emit("lr-submit",Object.freeze({value:cloneRubricValue(this._value),itemId:this.itemId}))}skip(){this.effectiveDisabled||this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(options){const firstKey=this._keys[0];if(!firstKey)return;const control=this.fieldElement(firstKey.key)?.querySelector(".control");control&&(firstKey.type==="score"&&this.isSegmentedScore(firstKey)?control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus(options):firstKey.type==="score"?control.shadowRoot?.querySelector('[part="thumb"]')?.focus(options):firstKey.type==="category"&&firstKey.multiple?control.querySelector(tag("checkbox"))?.focus(options):control.focus(options))}focus(options){this.effectiveDisabled||this.focusFirstControl(options)}click(){this.effectiveDisabled||this.focusFirstControl()}syncExternalDescription(){const target=this.isConnected?this.renderRoot.querySelector('[part="base"][role="group"]'):null;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription(),this.publishValiditySnapshot(),this.pendingFocusFirst&&(this.pendingFocusFirst=!1,this.focusFirstControl())}renderScoreControl(k,fieldId,current,hasError){const{min,max,step}=scoreDomain(k),disabled=this.effectiveDisabled,accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>!!value).join(". ");if(this.isSegmentedScore(k)){const numberFormat=getNumberFormat(this.effectiveLocale,{maximumFractionDigits:20}),items=this.scoreValues(k).map(score=>({value:String(score),label:numberFormat.format(score),disabled})),value=typeof current=="number"?String(current):"";return html`<lr-segmented
2
2
  @lr-activate=${this.stopChildEvent}
3
3
  id=${fieldId}
4
4
  class="control"
@@ -9,7 +9,7 @@ import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/valu
9
9
  label=${accessibleLabel}
10
10
  @lr-input=${this.stopChildEvent}
11
11
  @lr-change=${e=>{e.stopPropagation(),this.setFieldValue(k.key,Number(e.detail.value))}}
12
- ></lr-segmented>`}const numeric=typeof current=="number"?current:min+(max-min)/2;return html`<lr-slider
12
+ ></lr-segmented>`}const numeric=typeof current=="number"?current:finiteMidpoint(min,max);return html`<lr-slider
13
13
  id=${fieldId}
14
14
  class="control"
15
15
  part="scale"
@@ -24,7 +24,7 @@ import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/valu
24
24
  @change=${this.stopChildEvent}
25
25
  @lr-input=${this.stopChildEvent}
26
26
  @lr-change=${e=>{e.stopPropagation(),this.setFieldValue(k.key,e.detail.value)}}
27
- ></lr-slider>`}renderCategoryControl(k,fieldId,current,hasError){const options=k.options??[],disabled=this.effectiveDisabled,label=k.label??k.key,description=k.description?html`<span slot="hint" part="description">${k.description}</span>`:nothing,error=hasError?html`<span slot="error" part="error">${this._errors[k.key]}</span>`:nothing;if(k.multiple){const selected=Array.isArray(current)?current:[];return html`<lr-checkbox-group
27
+ ></lr-slider>`}renderCategoryControl(k,fieldId,current,hasError){const options=k.options??[],disabled=this.effectiveDisabled,label=k.label??k.key,description=k.description?html`<span slot="hint" part="description">${k.description}</span>`:nothing,error=hasError?html`<span slot="error" part="error">${this._errors[k.key]}</span>`:nothing;if(k.multiple){const selected=Array.isArray(current)?current:[],remaining=new Map;for(const value2 of selected)remaining.set(value2,(remaining.get(value2)??0)+1);const checked=value2=>{const count=remaining.get(value2)??0;return count===0?!1:(remaining.set(value2,count-1),!0)};return html`<lr-checkbox-group
28
28
  id=${fieldId}
29
29
  class="control"
30
30
  part="scale"
@@ -38,7 +38,7 @@ import{__decorate}from"tslib";import{emitValueEvents}from"../../../internal/valu
38
38
  >
39
39
  <span slot="label" part="label">${label}</span>
40
40
  ${description} ${error}
41
- ${options.map(opt=>html`<lr-checkbox value=${opt.value} .checked=${live(selected.includes(opt.value))} ?disabled=${disabled}
41
+ ${options.map(opt=>html`<lr-checkbox value=${opt.value} .checked=${live(checked(opt.value))} ?disabled=${disabled}
42
42
  >${opt.icon==null?nothing:renderInertPresentation(opt.icon)}<span
43
43
  >${opt.label??opt.value}${opt.description?html`<small class="option-description">${opt.description}</small>`:nothing}</span
44
44
  ></lr-checkbox
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_loading,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select,LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,loading:LYRA_DEFAULT_loading,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-change-request"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"]),"lr-change-request":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.optionsObserved=!1,this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this.listboxHidden=!0,this.listboxRendered=!1,this.listboxPositioned=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.previousValue="",this.openStateGeneration=0,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeBuffer=new TypeAheadBuffer(this),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isLyraOptionElement(option)&&this.options.includes(option)&&isOptionSelectedWrite(e)){markVetoGuardWrite(this.selectionWriteGuard),this._valueDirty=!0,this._restoredStateActive=!1;const selected=this._selectedOptions.includes(option);if(option.selected===selected&&(!selected||this._selectedValuesByOption.get(option)===option.value))return;if(option.selected&&!this.multiple){this.setSelection([option.value],[option]);return}const remaining=[...this._selectedOptions],preferred=this._selected.map(value=>{const index2=remaining.findIndex(candidate=>this._selectedValuesByOption.get(candidate)===value);return index2<0?void 0:remaining.splice(index2,1)[0]}),values=[...this._selected],index=preferred.indexOf(option);if(option.selected)index<0?(values.push(option.value),preferred.push(option)):values[index]=option.value;else{if(index<0)return;values.splice(index,1),preferred.splice(index,1)}this.setSelection(values,preferred);return}if(isLyraOptionElement(option)&&this.adornmentClones.get(option)?.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option),this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.selectionWriteGuard=new VetoWriteGuard,this.selectionRequestDispatching=!1,this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229)return;const navigable=this.navigableOptions(),move=()=>resolveListMove(e,{count:navigable.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0||this._pendingInitialSelectedOptions!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0,this.selectedOptions=pending}}finally{this._resolvingPendingInitialSelection=!1}}if(this.announceOpenTransition(changed),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1,this.listboxRendered=!0),changed.has("open")&&!this.openVetoed){const navigable=this.navigableOptions();this.setActiveIndex(this.open?navigable.findIndex(option=>this._selectedOptions.includes(option)):-1,navigable)}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{const assigned=s.assignedElements({flatten:!0});this.optionsObserved=!0,assigned.some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){this.listboxHidden=!0;const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.popupController.cancel(),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!(!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)){if(!this.isConnected){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialValue=next),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialSelectedOptions=next),this._restoredStateActive=!1,this._valueDirty=!0;const candidates=Array.isArray(next)?next:[],live=candidates.filter((option,index)=>isLyraOptionElement(option)&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){markVetoGuardWrite(this.selectionWriteGuard);const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this.previousValue=old,this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){const claimed=new Set;return values.map((value,index)=>{const hint=preferred.length===values.length?preferred[index]:preferred.find(option=>option?.value===value&&!claimed.has(option)),match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0)}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;markVetoGuardWrite(this.selectionWriteGuard);const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.updateValidity(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){markVetoGuardWrite(this.selectionWriteGuard),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.typeBuffer.clear(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}adoptedCallback(){markVetoGuardWrite(this.selectionWriteGuard),super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.typeBuffer.clear(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.optionsObserved=!0,this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(!(this.selectionRequestDispatching||this.effectiveDisabled)){if(this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.requestSelection(values,this.resolveOccurrenceSlots(values,this._selectedOptions),()=>{this.emitValueEvents(),this.emit("lr-activate",{value})});return}this.hide(),this.emit("lr-activate",{value})}}resolvedLabelFor(value,occurrenceIndex=0){const option=(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]:void 0)??this._selectedOptions.find(candidate=>candidate.value===value)??this.options.find(candidate=>candidate.value===value);return option&&(option.label||option.value)}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;if(this.loading)return this.localize("loading");const override=this.optionsObserved?this.getUnknownLabel?.(value):void 0;return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return!this.optionsObserved||this.loading||value===""?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return options.filter(option=>this.isOptionAvailable(option))}get unknownValues(){return this.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get listboxOptions(){const unknown=this.unknownOptions;return unknown.length===0?this.options:[...this.options,...unknown]}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.listboxOptions.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0,this.revealActiveOption()),positioned))}revealActiveOption(){if(!this.isConnected||!this.open||!this.listboxPositioned||!this.cleanup)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),activeId=this.triggerElement?.getAttribute("aria-activedescendant"),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&activeId&&row.id===activeId&&revealRow(listbox,row)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.popupController.bindPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("activeIndex")||changed.has("options")||changed.has("listboxPositioned"))&&this.revealActiveOption(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return this.forceCloseOpenState(),!1}return!0},conceal:()=>{this.listboxHidden=!0}})}emitValueEvents(){const self=this,data=this.selectedData,value=self.value,previousValue=this.previousValue;dispatchNativeInputEvent(this),self.emit("lr-input",{value,previousValue,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value,previousValue,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}requestSelection(values,preferred,afterCommit,available=()=>!0){if(this.selectionRequestDispatching||this.effectiveDisabled)return!1;const multiple=this.multiple,document=this.ownerDocument,connected=this.isConnected,open=this.open,slots=this.resolveOccurrenceSlots(values,preferred),data=slots.map(option=>option?.data),value=multiple?[...values]:values[0]??"",previousValue=this.value,self=this;let committed=!1;this.selectionRequestDispatching=!0;try{requestThenCommit({requestDetail:{value,previousValue,data},guard:this.selectionWriteGuard,emitRequest:(detail,init)=>self.emit("lr-change-request",detail,init),commit:()=>{const liveOptions=new Set(this.renderRoot.querySelector("slot:not([name])")?.assignedElements({flatten:!0})??[]);this.effectiveDisabled||this.multiple!==multiple||this.ownerDocument!==document||this.isConnected!==connected||this.open!==open||!available(liveOptions)||slots.some((option,index)=>option&&(!liveOptions.has(option)||option.value!==values[index]||!Object.is(option.data,data[index])))||(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(values,preferred),committed=!0,afterCommit())}})}finally{this.selectionRequestDispatching=!1}return committed}selectOption(option){if(this.selectionRequestDispatching||this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}const value=option.value,available=liveOptions=>liveOptions.has(option)&&option.value===value&&this.isOptionAvailable(option);if(this.multiple){const currentSlots=this.resolveOccurrenceSlots(this._selected,this._selectedOptions),selectedIndex=currentSlots.indexOf(option),selected=selectedIndex>=0,occurrences=selected?currentSlots.filter((_,index)=>index!==selectedIndex):[...currentSlots,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,value];this.requestSelection(values,occurrences,()=>{this.emitValueEvents(),this.emit("lr-activate",{value})},available);return}if(!(option!==this._selectedOptions[0]||value!==this._selected[0])){this.hide(),this.emit("lr-activate",{value});return}this.requestSelection([value],[option],()=>{this.hide(),this.emitValueEvents(),this.emit("lr-activate",{value})},available)}removeValueAt(index){return this.effectiveDisabled||index<0||index>=this._selected.length?!1:this.requestSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this.resolveOccurrenceSlots(this._selected,this._selectedOptions).filter((_,candidateIndex)=>candidateIndex!==index),()=>this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||this.requestSelection([],[],()=>{this.emitValueEvents(),this.emit("lr-clear")})}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&this.removeValueAt(index)&&this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),match=this.typeBuffer.match(navigable,currentIndex,option=>option.label,this.effectiveLocale,option=>this.open||!this.multiple||!this._selectedOptions.includes(option));if(match===null)return;const candidate=navigable[match];this.open?this.setActiveIndex(match,navigable):this.selectOption(candidate)}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
1
+ import{__decorate}from"tslib";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_loading,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,loading:LYRA_DEFAULT_loading,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-change-request"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"]),"lr-change-request":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.optionsObserved=!1,this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this.listboxHidden=!0,this.listboxRendered=!1,this.listboxPositioned=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.previousValue="",this.openStateGeneration=0,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeBuffer=new TypeAheadBuffer(this),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isLyraOptionElement(option)&&this.options.includes(option)&&isOptionSelectedWrite(e)){markVetoGuardWrite(this.selectionWriteGuard),this._valueDirty=!0,this._restoredStateActive=!1;const selected=this._selectedOptions.includes(option);if(option.selected===selected&&(!selected||this._selectedValuesByOption.get(option)===option.value))return;if(option.selected&&!this.multiple){this.setSelection([option.value],[option]);return}const remaining=[...this._selectedOptions],preferred=this._selected.map(value=>{const index2=remaining.findIndex(candidate=>this._selectedValuesByOption.get(candidate)===value);return index2<0?void 0:remaining.splice(index2,1)[0]}),values=[...this._selected],index=preferred.indexOf(option);if(option.selected)index<0?(values.push(option.value),preferred.push(option)):values[index]=option.value;else{if(index<0)return;values.splice(index,1),preferred.splice(index,1)}this.setSelection(values,preferred);return}if(isLyraOptionElement(option)&&this.adornmentClones.get(option)?.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option),this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.selectionWriteGuard=new VetoWriteGuard,this.selectionRequestDispatching=!1,this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229)return;const navigable=this.navigableOptions(),move=()=>resolveListMove(e,{count:navigable.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0||this._pendingInitialSelectedOptions!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0,this.selectedOptions=pending}}finally{this._resolvingPendingInitialSelection=!1}}if(this.announceOpenTransition(changed),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1,this.listboxRendered=!0),changed.has("open")&&!this.openVetoed){const navigable=this.navigableOptions();this.setActiveIndex(this.open?navigable.findIndex(option=>this._selectedOptions.includes(option)):-1,navigable)}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{const assigned=s.assignedElements({flatten:!0});this.optionsObserved=!0,assigned.some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){this.listboxHidden=!0;const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.popupController.cancel(),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!(!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)){if(!this.isConnected){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialValue=next),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialSelectedOptions=next),this._restoredStateActive=!1,this._valueDirty=!0;const candidates=Array.isArray(next)?next:[],live=candidates.filter((option,index)=>isLyraOptionElement(option)&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){markVetoGuardWrite(this.selectionWriteGuard);const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this.previousValue=old,this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){const claimed=new Set;return values.map((value,index)=>{const hint=preferred.length===values.length?preferred[index]:preferred.find(option=>option?.value===value&&!claimed.has(option)),match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0)}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;markVetoGuardWrite(this.selectionWriteGuard);const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.updateValidity(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){markVetoGuardWrite(this.selectionWriteGuard),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.typeBuffer.clear(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}adoptedCallback(){markVetoGuardWrite(this.selectionWriteGuard),super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.typeBuffer.clear(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.optionsObserved=!0,this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(!(this.selectionRequestDispatching||this.effectiveDisabled)){if(this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.requestSelection(values,this.resolveOccurrenceSlots(values,this._selectedOptions),()=>{this.emitValueEvents(),this.emit("lr-activate",{value})});return}this.hide(),this.emit("lr-activate",{value})}}resolvedLabelFor(value,occurrenceIndex=0){const option=(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]:void 0)??this._selectedOptions.find(candidate=>candidate.value===value)??this.options.find(candidate=>candidate.value===value);return option&&(option.label||option.value)}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;if(this.loading)return this.localize("loading");const override=this.optionsObserved?this.getUnknownLabel?.(value):void 0;return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return!this.optionsObserved||this.loading||value===""?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return options.filter(option=>this.isOptionAvailable(option))}get unknownValues(){return this.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get listboxOptions(){const unknown=this.unknownOptions;return unknown.length===0?this.options:[...this.options,...unknown]}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.listboxOptions.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0,this.revealActiveOption()),positioned))}revealActiveOption(){if(!this.isConnected||!this.open||!this.listboxPositioned||!this.cleanup)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),activeId=this.triggerElement?.getAttribute("aria-activedescendant"),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&activeId&&row.id===activeId&&revealRow(listbox,row)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.popupController.bindPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("activeIndex")||changed.has("options")||changed.has("listboxPositioned"))&&this.revealActiveOption(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return this.forceCloseOpenState(),!1}return!0},conceal:()=>{this.listboxHidden=!0}})}emitValueEvents(){const self=this,data=this.selectedData,value=self.value,previousValue=this.previousValue;dispatchNativeInputEvent(this),self.emit("lr-input",{value,previousValue,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value,previousValue,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}requestSelection(values,preferred,afterCommit,available=()=>!0){if(this.selectionRequestDispatching||this.effectiveDisabled)return!1;const multiple=this.multiple,document=this.ownerDocument,connected=this.isConnected,open=this.open,slots=this.resolveOccurrenceSlots(values,preferred),data=slots.map(option=>option?.data),value=multiple?[...values]:values[0]??"",previousValue=this.value,self=this;let committed=!1;this.selectionRequestDispatching=!0;try{requestThenCommit({requestDetail:{value,previousValue,data},guard:this.selectionWriteGuard,emitRequest:(detail,init)=>self.emit("lr-change-request",detail,init),commit:()=>{const liveOptions=new Set(this.renderRoot.querySelector("slot:not([name])")?.assignedElements({flatten:!0})??[]);this.effectiveDisabled||this.multiple!==multiple||this.ownerDocument!==document||this.isConnected!==connected||this.open!==open||!available(liveOptions)||slots.some((option,index)=>option&&(!liveOptions.has(option)||option.value!==values[index]||!Object.is(option.data,data[index])))||(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(values,preferred),committed=!0,afterCommit())}})}finally{this.selectionRequestDispatching=!1}return committed}selectOption(option){if(this.selectionRequestDispatching||this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}const value=option.value,available=liveOptions=>liveOptions.has(option)&&option.value===value&&this.isOptionAvailable(option);if(this.multiple){const currentSlots=this.resolveOccurrenceSlots(this._selected,this._selectedOptions),selectedIndex=currentSlots.indexOf(option),selected=selectedIndex>=0,occurrences=selected?currentSlots.filter((_,index)=>index!==selectedIndex):[...currentSlots,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,value];this.requestSelection(values,occurrences,()=>{this.emitValueEvents(),this.emit("lr-activate",{value})},available);return}if(!(option!==this._selectedOptions[0]||value!==this._selected[0])){this.hide(),this.emit("lr-activate",{value});return}this.requestSelection([value],[option],()=>{this.hide(),this.emitValueEvents(),this.emit("lr-activate",{value})},available)}removeValueAt(index){return this.effectiveDisabled||index<0||index>=this._selected.length?!1:this.requestSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this.resolveOccurrenceSlots(this._selected,this._selectedOptions).filter((_,candidateIndex)=>candidateIndex!==index),()=>this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||this.requestSelection([],[],()=>{this.emitValueEvents(),this.emit("lr-clear")})}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&this.removeValueAt(index)&&this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),match=this.typeBuffer.match(navigable,currentIndex,option=>option.label,this.effectiveLocale,option=>this.open||!this.multiple||!this._selectedOptions.includes(option));if(match===null)return;const candidate=navigable[match];this.open?this.setActiveIndex(match,navigable):this.selectOption(candidate)}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
2
2
  <div id=${labelId} class="group-label" part="group-label">${currentGroup}</div>
3
3
  ${groupRows}
4
4
  </div>`)}else out.push(...groupRows);groupRows=[]}};return options.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,unknown=this.unknownOptionCache.get(o.value)===o,selected=unknown||chosen.has(o),adornments=this.adornmentsFor(o);groupRows.push(html`<div