@aceshooting/lyra-ui 16.0.0 → 17.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (296) hide show
  1. package/CHANGELOG.md +504 -0
  2. package/custom-elements.json +1 -1
  3. package/dist/cli/migration-contract.json +1 -1
  4. package/dist/components/agent-tools/browser-frame/browser-frame.class.d.ts +3 -3
  5. package/dist/components/agent-tools/browser-frame/browser-frame.class.js +2 -2
  6. package/dist/components/agent-tools/compare-panel/compare-panel.class.d.ts +2 -2
  7. package/dist/components/agent-tools/compare-panel/compare-panel.class.js +3 -3
  8. package/dist/components/agent-tools/confirm-bar/confirm-bar.class.d.ts +37 -13
  9. package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
  10. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  11. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.d.ts +4 -0
  12. package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
  13. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +3 -3
  14. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  15. package/dist/components/charts/chart/chart.class.d.ts +117 -17
  16. package/dist/components/charts/chart/chart.class.js +3 -3
  17. package/dist/components/charts/chart/histogram-bin.d.ts +5 -1
  18. package/dist/components/charts/chart/histogram-bin.js +1 -1
  19. package/dist/components/charts/chart/lite-chart.class.d.ts +9 -0
  20. package/dist/components/conversation/code-block/code-block.styles.js +1 -1
  21. package/dist/components/conversation/message-actions/message-actions.styles.js +1 -1
  22. package/dist/components/conversation/model-select/model-select.class.d.ts +13 -4
  23. package/dist/components/conversation/model-select/model-select.class.js +2 -1
  24. package/dist/components/conversation/model-select/model-select.styles.js +1 -1
  25. package/dist/components/conversation/streaming-text/streaming-text-base.class.d.ts +40 -2
  26. package/dist/components/conversation/streaming-text/streaming-text-base.class.js +2 -2
  27. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +5 -3
  28. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +10 -0
  29. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +9 -3
  30. package/dist/components/conversation/streaming-text/streaming-text.class.js +10 -0
  31. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.d.ts +30 -2
  32. package/dist/components/conversation/suggestion-chips/suggestion-chips.class.js +4 -3
  33. package/dist/components/conversation/suggestion-chips/suggestion-chips.styles.js +1 -1
  34. package/dist/components/conversation/transcript-feed/transcript-feed.class.js +1 -1
  35. package/dist/components/conversation/usage-badge/usage-badge-overlay-runtime.js +1 -1
  36. package/dist/components/conversation/usage-badge/usage-badge.class.d.ts +4 -0
  37. package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +16 -4
  38. package/dist/components/conversation/voice-picker/voice-picker.class.js +2 -1
  39. package/dist/components/conversation/voice-picker/voice-picker.styles.js +1 -1
  40. package/dist/components/data/context-meter/context-meter.class.d.ts +23 -4
  41. package/dist/components/data/context-meter/context-meter.class.js +10 -7
  42. package/dist/components/data/context-meter/context-meter.styles.js +1 -1
  43. package/dist/components/data/data-grid/data-grid.class.d.ts +5 -2
  44. package/dist/components/data/data-grid/data-grid.class.js +1 -1
  45. package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +32 -5
  46. package/dist/components/data/flow-canvas/flow-canvas.class.js +3 -1
  47. package/dist/components/data/flow-canvas/flow-canvas.styles.js +1 -1
  48. package/dist/components/data/flow-canvas/flow-model.js +1 -1
  49. package/dist/components/data/flow-canvas/flow-types.d.ts +10 -1
  50. package/dist/components/data/gauge/gauge.class.d.ts +15 -2
  51. package/dist/components/data/gauge/gauge.class.js +20 -20
  52. package/dist/components/data/gauge/gauge.styles.js +1 -1
  53. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +14 -5
  54. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +2 -2
  55. package/dist/components/data/sequence-strip/sequence-strip.class.d.ts +28 -2
  56. package/dist/components/data/sequence-strip/sequence-strip.class.js +3 -2
  57. package/dist/components/data/sequence-strip/sequence-strip.styles.js +1 -1
  58. package/dist/components/data/table/table.class.d.ts +155 -30
  59. package/dist/components/data/table/table.class.js +6 -4
  60. package/dist/components/data/table/table.styles.js +1 -1
  61. package/dist/components/data/timeline/timeline-item.class.d.ts +9 -1
  62. package/dist/components/data/timeline/timeline-item.class.js +2 -2
  63. package/dist/components/data/word-cloud/word-cloud.class.js +1 -1
  64. package/dist/components/data/word-cloud/word-cloud.styles.js +1 -1
  65. package/dist/components/forms/button/button.class.d.ts +30 -1
  66. package/dist/components/forms/button/button.class.js +2 -2
  67. package/dist/components/forms/checkbox/checkbox.class.d.ts +8 -6
  68. package/dist/components/forms/checkbox/checkbox.class.js +2 -2
  69. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +7 -5
  70. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  71. package/dist/components/forms/color-picker/color-picker.class.d.ts +16 -2
  72. package/dist/components/forms/color-picker/color-picker.class.js +2 -2
  73. package/dist/components/forms/color-picker/color-picker.styles.js +1 -1
  74. package/dist/components/forms/combobox/combobox.class.d.ts +43 -8
  75. package/dist/components/forms/combobox/combobox.class.js +2 -2
  76. package/dist/components/forms/date-picker/date-input.class.d.ts +4 -0
  77. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  78. package/dist/components/forms/icon-button/icon-button.class.d.ts +20 -3
  79. package/dist/components/forms/icon-button/icon-button.class.js +1 -1
  80. package/dist/components/forms/icon-button/icon-button.styles.js +1 -1
  81. package/dist/components/forms/input/input.class.d.ts +5 -2
  82. package/dist/components/forms/input/input.class.js +1 -1
  83. package/dist/components/forms/input/time-input.class.d.ts +4 -0
  84. package/dist/components/forms/input/time-input.class.js +1 -1
  85. package/dist/components/forms/locale-picker/locale-picker.class.d.ts +11 -5
  86. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  87. package/dist/components/forms/otp-input/otp-input.class.d.ts +7 -2
  88. package/dist/components/forms/otp-input/otp-input.class.js +2 -2
  89. package/dist/components/forms/radio/radio-button.class.d.ts +2 -1
  90. package/dist/components/forms/radio/radio-group.class.d.ts +9 -4
  91. package/dist/components/forms/radio/radio-group.class.js +1 -1
  92. package/dist/components/forms/radio/radio.class.d.ts +13 -7
  93. package/dist/components/forms/radio/radio.class.js +1 -1
  94. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +16 -6
  95. package/dist/components/forms/rubric-form/rubric-form.class.js +2 -2
  96. package/dist/components/forms/select/select.class.d.ts +19 -8
  97. package/dist/components/forms/select/select.class.js +2 -2
  98. package/dist/components/forms/slider/slider.class.d.ts +4 -2
  99. package/dist/components/forms/slider/slider.class.js +1 -1
  100. package/dist/components/forms/switch/switch.class.d.ts +8 -6
  101. package/dist/components/forms/switch/switch.class.js +1 -1
  102. package/dist/components/forms/textarea/textarea.class.d.ts +5 -3
  103. package/dist/components/forms/textarea/textarea.class.js +1 -1
  104. package/dist/components/forms/time-range/time-range.class.d.ts +12 -7
  105. package/dist/components/forms/time-range/time-range.class.js +1 -1
  106. package/dist/components/forms/time-range/time-range.styles.js +1 -1
  107. package/dist/components/forms/token-input/token-input.class.d.ts +6 -4
  108. package/dist/components/forms/token-input/token-input.class.js +1 -1
  109. package/dist/components/layout/app-rail/app-rail-item.class.d.ts +109 -4
  110. package/dist/components/layout/app-rail/app-rail-item.class.js +34 -29
  111. package/dist/components/layout/app-rail/app-rail-item.styles.js +1 -1
  112. package/dist/components/layout/app-rail/app-rail.class.d.ts +25 -3
  113. package/dist/components/layout/app-rail/app-rail.styles.js +1 -1
  114. package/dist/components/layout/app-rail-group/app-rail-group.class.d.ts +2 -2
  115. package/dist/components/layout/app-rail-group/app-rail-group.class.js +2 -2
  116. package/dist/components/layout/carousel/carousel.class.d.ts +1 -1
  117. package/dist/components/layout/carousel/carousel.class.js +1 -1
  118. package/dist/components/layout/details/accordion.class.d.ts +2 -2
  119. package/dist/components/layout/details/accordion.class.js +2 -2
  120. package/dist/components/layout/filter-bar/filter-bar-register.d.ts +1 -0
  121. package/dist/components/layout/filter-bar/filter-bar-register.js +1 -0
  122. package/dist/components/layout/filter-bar/filter-bar.class.d.ts +85 -10
  123. package/dist/components/layout/filter-bar/filter-bar.class.js +7 -4
  124. package/dist/components/layout/menu/menu-item.class.d.ts +3 -3
  125. package/dist/components/layout/menu/menu-item.class.js +3 -3
  126. package/dist/components/layout/menu/menu.class.d.ts +5 -1
  127. package/dist/components/layout/menu/menu.class.js +2 -2
  128. package/dist/components/layout/reorder-list/reorder-item.styles.js +1 -1
  129. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  130. package/dist/components/media/attachment-trigger/attachment-trigger.styles.js +1 -1
  131. package/dist/components/media/avatar-group/avatar-group.class.d.ts +12 -1
  132. package/dist/components/media/avatar-group/avatar-group.class.js +2 -2
  133. package/dist/components/media/drop-zone/drop-zone.class.d.ts +32 -11
  134. package/dist/components/media/drop-zone/drop-zone.class.js +2 -2
  135. package/dist/components/media/file-input/file-input.class.d.ts +40 -19
  136. package/dist/components/media/file-input/file-input.class.js +2 -2
  137. package/dist/components/overlays/callout/callout.styles.js +1 -1
  138. package/dist/components/overlays/dialog/dialog.styles.js +1 -1
  139. package/dist/components/overlays/overlay/dropdown.class.d.ts +13 -3
  140. package/dist/components/overlays/overlay/dropdown.class.js +2 -2
  141. package/dist/components/overlays/overlay/popover.class.d.ts +12 -3
  142. package/dist/components/overlays/overlay/popover.class.js +2 -2
  143. package/dist/components/overlays/rating/rating.class.d.ts +9 -7
  144. package/dist/components/overlays/rating/rating.class.js +1 -1
  145. package/dist/components/retrieval/citation-badge/citation-badge.class.d.ts +5 -1
  146. package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
  147. package/dist/components/retrieval/embedding-explorer/embedding-explorer.styles.js +1 -1
  148. package/dist/components/retrieval/entity-chip/entity-chip.class.d.ts +5 -1
  149. package/dist/components/retrieval/entity-chip/entity-chip.class.js +1 -1
  150. package/dist/components/retrieval/graph-legend/graph-legend.styles.js +1 -1
  151. package/dist/components/retrieval/retrieval-value-format.js +1 -1
  152. package/dist/components/retrieval/source-list/source-list.styles.js +1 -1
  153. package/dist/components/utility/copy-button/copy-button.class.d.ts +23 -11
  154. package/dist/components/utility/copy-button/copy-button.class.js +2 -2
  155. package/dist/components/utility/copy-button/copy-button.styles.js +1 -1
  156. package/dist/components/utility/diff-view/diff-view.styles.js +1 -1
  157. package/dist/components/utility/export-button/export-button.class.d.ts +4 -0
  158. package/dist/components/utility/export-button/export-button.class.js +1 -1
  159. package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
  160. package/dist/components/utility/known-date/known-date.class.js +1 -1
  161. package/dist/components/utility/mention-popover/mention-popover.class.d.ts +38 -3
  162. package/dist/components/utility/mention-popover/mention-popover.class.js +2 -1
  163. package/dist/components/utility/mention-popover/mention-popover.styles.js +1 -1
  164. package/dist/components/utility/poll-status/poll-status.styles.js +1 -1
  165. package/dist/components/utility/tour/tour.class.d.ts +4 -0
  166. package/dist/components/utility/tour/tour.class.js +1 -1
  167. package/dist/components/utility/tour/tour.styles.js +1 -1
  168. package/dist/components/viewers/document-preview/document-preview.class.js +2 -2
  169. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +2 -2
  170. package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +2 -2
  171. package/dist/components/viewers/highlight-layer/highlight-layer.class.js +2 -2
  172. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
  173. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
  174. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +2 -2
  175. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
  176. package/dist/custom-elements-jsx.d.ts +2 -2
  177. package/dist/events.d.ts +13 -12
  178. package/dist/internal/aggregate-file-limits.d.ts +33 -0
  179. package/dist/internal/aggregate-file-limits.js +1 -0
  180. package/dist/internal/catalog-picker.d.ts +15 -2
  181. package/dist/internal/catalog-picker.js +1 -1
  182. package/dist/internal/debounce-controller.d.ts +14 -0
  183. package/dist/internal/debounce-controller.js +1 -1
  184. package/dist/internal/default-strings.generated.d.ts +1 -1
  185. package/dist/internal/default-strings.generated.js +2 -2
  186. package/dist/internal/focus-navigation.d.ts +45 -0
  187. package/dist/internal/focus-navigation.js +1 -1
  188. package/dist/internal/form-associated.js +1 -1
  189. package/dist/internal/initial-slot-collection.d.ts +30 -0
  190. package/dist/internal/initial-slot-collection.js +1 -0
  191. package/dist/internal/intl-cache.js +1 -1
  192. package/dist/internal/invalid-event-alias.d.ts +46 -0
  193. package/dist/internal/invalid-event-alias.js +1 -1
  194. package/dist/internal/localization-runtime.d.ts +24 -0
  195. package/dist/internal/localization-runtime.js +1 -1
  196. package/dist/internal/localization-types.d.ts +1 -1
  197. package/dist/internal/localization.js +1 -1
  198. package/dist/internal/package-metadata.d.ts +1 -1
  199. package/dist/internal/package-metadata.js +1 -1
  200. package/dist/internal/positioning-strategy.d.ts +3 -1
  201. package/dist/internal/state-part.d.ts +49 -0
  202. package/dist/internal/state-part.js +1 -0
  203. package/dist/internal/variants.styles.js +1 -1
  204. package/dist/lyra.d.ts +1 -1
  205. package/dist/svelte.d.ts +2 -2
  206. package/dist/testing/index.d.ts +1 -1
  207. package/dist/testing/index.js +1 -1
  208. package/dist/testing/lyra-tag-event-map.d.ts +2 -2
  209. package/dist/testing/lyra-tag-event-map.js +1 -1
  210. package/dist/testing/wait-for-mount.d.ts +46 -0
  211. package/dist/testing/wait-for-mount.js +1 -0
  212. package/dist/theme/theme-bootstrap.js +1 -1
  213. package/dist/theme/theme.d.ts +11 -2
  214. package/dist/theme/theme.js +1 -1
  215. package/dist/translations/ar/layout.js +1 -1
  216. package/dist/translations/de/layout.js +1 -1
  217. package/dist/translations/es/layout.js +1 -1
  218. package/dist/translations/fa/layout.js +1 -1
  219. package/dist/translations/fr/layout.js +1 -1
  220. package/dist/translations/he/layout.js +1 -1
  221. package/dist/translations/it/layout.js +1 -1
  222. package/dist/translations/ja/layout.js +1 -1
  223. package/dist/translations/pt-BR/layout.js +1 -1
  224. package/dist/translations/ru/layout.js +1 -1
  225. package/dist/translations/zh-CN/layout.js +1 -1
  226. package/dist/utilities/format.d.ts +17 -0
  227. package/dist/utilities/format.js +1 -1
  228. package/dist/vue.d.ts +2 -2
  229. package/llms/components/lr-app-rail-group.md +87 -10
  230. package/llms/components/lr-app-rail-item.md +88 -11
  231. package/llms/components/lr-app-rail.md +88 -11
  232. package/llms/components/lr-attachment-trigger.md +21 -0
  233. package/llms/components/lr-bar-chart.md +3 -2
  234. package/llms/components/lr-bubble-chart.md +3 -2
  235. package/llms/components/lr-callout.md +10 -0
  236. package/llms/components/lr-chart.md +43 -12
  237. package/llms/components/lr-citation-badge.md +7 -1
  238. package/llms/components/lr-code-block.md +21 -0
  239. package/llms/components/lr-color-picker.md +12 -7
  240. package/llms/components/lr-combobox.md +13 -1
  241. package/llms/components/lr-confirm-bar.md +36 -7
  242. package/llms/components/lr-context-meter.md +17 -4
  243. package/llms/components/lr-date-input.md +7 -1
  244. package/llms/components/lr-date-picker.md +6 -0
  245. package/llms/components/lr-dialog.md +21 -0
  246. package/llms/components/lr-doughnut-chart.md +3 -2
  247. package/llms/components/lr-drawer.md +10 -0
  248. package/llms/components/lr-drop-zone.md +16 -7
  249. package/llms/components/lr-dropdown-item.md +7 -0
  250. package/llms/components/lr-entity-chip.md +7 -1
  251. package/llms/components/lr-export-button.md +7 -1
  252. package/llms/components/lr-file-input.md +21 -10
  253. package/llms/components/lr-filter-bar.md +91 -15
  254. package/llms/components/lr-flow-canvas.md +16 -9
  255. package/llms/components/lr-gauge.md +22 -2
  256. package/llms/components/lr-histogram.md +7 -2
  257. package/llms/components/lr-icon-button.md +15 -7
  258. package/llms/components/lr-input.md +3 -1
  259. package/llms/components/lr-line-chart.md +3 -2
  260. package/llms/components/lr-lite-chart.md +13 -0
  261. package/llms/components/lr-locale-picker.md +7 -1
  262. package/llms/components/lr-mention-popover.md +16 -3
  263. package/llms/components/lr-menu-item.md +7 -0
  264. package/llms/components/lr-menu.md +8 -1
  265. package/llms/components/lr-message-actions.md +10 -0
  266. package/llms/components/lr-model-select.md +8 -3
  267. package/llms/components/lr-native-time-input.md +8 -1
  268. package/llms/components/lr-number-input.md +8 -1
  269. package/llms/components/lr-option.md +12 -0
  270. package/llms/components/lr-otp-input.md +6 -0
  271. package/llms/components/lr-pie-chart.md +3 -2
  272. package/llms/components/lr-polar-area-chart.md +3 -2
  273. package/llms/components/lr-prompt-input.md +2 -2
  274. package/llms/components/lr-radar-chart.md +3 -2
  275. package/llms/components/lr-reorder-item.md +12 -0
  276. package/llms/components/lr-reorder-list.md +12 -0
  277. package/llms/components/lr-scatter-chart.md +3 -2
  278. package/llms/components/lr-sequence-strip.md +10 -4
  279. package/llms/components/lr-streaming-text-core.md +21 -8
  280. package/llms/components/lr-streaming-text.md +34 -4
  281. package/llms/components/lr-suggestion-chips.md +8 -4
  282. package/llms/components/lr-table.md +47 -10
  283. package/llms/components/lr-textarea.md +1 -1
  284. package/llms/components/lr-time-input.md +7 -1
  285. package/llms/components/lr-tool-call-chip.md +7 -1
  286. package/llms/components/lr-tour.md +7 -1
  287. package/llms/components/lr-usage-badge.md +7 -1
  288. package/llms/components/lr-voice-picker.md +7 -3
  289. package/llms/shared.md +169 -16
  290. package/llms/tokens.md +17 -1
  291. package/llms-full.txt +941 -147
  292. package/package.json +16 -2
  293. package/registrations.json +1 -1
  294. package/vscode-css-data.json +1 -1
  295. package/vscode-html-data.json +1 -1
  296. package/web-types.json +1 -1
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{findImplicitSubmitter,isNativeSubmitter,submitOnEnter}from"../../../internal/submit-on-enter.js";import{styles}from"./otp-input.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{currentValidityValidator}from"../form-validator.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel}from"../../../internal/default-strings.generated.js";const ACCEPTED={numeric:/[0-9]/,alpha:/[a-zA-Z]/,alphanumeric:/[a-zA-Z0-9]/},DEFAULT_LENGTH=6,MAX_LENGTH=32,MAX_FORMAT_SOURCE_LENGTH=4096,MAX_VALUE_SOURCE_LENGTH=4096;class LyraOtpInputBase extends LyraElement{static{this.styles=[LyraElement.styles,contextualSizes,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){constructor(){super(...arguments),this.label="",this.hint="",this.errorText="",this.appearance="outlined",this.autofocus=!1,this.autosubmit=!1,this.size="m",this.length=DEFAULT_LENGTH,this.format="",this.type="numeric",this.case="preserve",this.mask=!1,this.withMask=!1,this.readonly=!1,this.autocomplete="one-time-code",this.focused=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.touched=!1,this.labelId=nextId("otp-input-label"),this.hintId=nextId("otp-input-hint"),this.errorId=nextId("otp-input-error"),this.activeSegmentIndex=0,this.segmentValues=[],this.rawValue="",this.segmentEditPendingChange=!1,this.autosubmitToken=0,this.onInput=event=>{if(event.isComposing===!0){event.stopPropagation();return}const raw=event.target.value,next=this.sanitize(raw),previous=this.value,previousFilled=this.filledSegmentCount,layoutChanged=Array.from({length:this.renderedSegmentCount},(_,index)=>next[index]??"").some((value,index)=>value!==this.segmentValues[index]);if(this.control&&this.control.value!==next&&(this.control.value=next),next===this.value&&!layoutChanged){event.stopImmediatePropagation();return}this.touched=!0,this.value=next,relayNativeEvent(this,event),previous&&!next&&this.emit("lr-clear"),this.completeIfTransition(previousFilled)},this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1,delta=this.effectiveDirection==="rtl"?-physical:physical;this.setActiveSegment(this.activeSegmentIndex+delta);return}if(event.key==="Enter"){this.readonly||submitOnEnter(this,event,{beforeSubmit:()=>this.flushPendingChange()});return}if(this.readonly||event.isComposing)return;const selection=this.selectedSegmentRange;if(event.key==="Backspace"||event.key==="Delete"){event.preventDefault();const values2=this.normalizedSegmentValues();if(selection){for(const index of selection.indices)values2[index]="";this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),this.setActiveSegment(selection.first);return}const changed=!!values2[this.activeSegmentIndex];values2[this.activeSegmentIndex]="",changed&&this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),event.key==="Backspace"&&this.setActiveSegment(this.activeSegmentIndex-1);return}if(event.ctrlKey||event.metaKey||event.altKey||event.key.length!==1)return;event.preventDefault();const accepted=this.sanitize(event.key).slice(0,1);if(!accepted)return;const values=this.normalizedSegmentValues(),targetIndex=selection?.first??this.activeSegmentIndex;if(selection)for(const index of selection.indices)values[index]="";values[targetIndex]=accepted,this.commitSegmentEdit(values,"insertText",accepted),this.setActiveSegment(targetIndex+1)},this.onPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=this.sanitize(event.clipboardData?.getData("text")??"");if(event.preventDefault(),!pasted)return;const values=Array.from({length:this.renderedSegmentCount},(_,index)=>pasted[index]??"");this.commitSegmentEdit(values,"insertFromPaste",pasted),this.setActiveSegment(Math.min(pasted.length,this.renderedSegmentCount-1))},this.onChange=event=>{this.segmentEditPendingChange=!1,relayNativeEvent(this,event)},this.onFocus=event=>{this.focused=!0,relayNativeEvent(this,event)},this.onBlur=event=>{this.focused=!1,this.effectiveDisabled||(this.touched=!0),this.flushPendingChange(),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedNodes({flatten:!0}).length>0}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,otpInputIncomplete:LYRA_DEFAULT_otpInputIncomplete,otpInputLabel:LYRA_DEFAULT_otpInputLabel}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","length","pattern")]}get input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){this.autosubmitToken+=1,this.rawValue=next??"";const normalized=this.sanitize(this.rawValue);this.packSegmentValues(normalized),super.value=normalized}get defaultValue(){return super.defaultValue}set defaultValue(next){this.autosubmitToken+=1,super.defaultValue=next}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;if(this.parsedFormatSource=this.format,!this.format)return this.parsedFormatCells=null,null;const cells=[];let segments=0,literal="";const flushLiteral=()=>{literal&&(cells.push({kind:"separator",text:literal}),literal="")};for(const char of this.format.slice(0,MAX_FORMAT_SOURCE_LENGTH)){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral(),cells.push({kind:"segment"}),segments+=1}return flushLiteral(),this.parsedFormatCells=segments>0?cells:null,this.parsedFormatCells}get renderedSegmentCount(){const formatted=this.formattedCells;return formatted?formatted.filter(cell=>cell.kind==="segment").length:Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.renderedSegmentCount}get cells(){return this.formattedCells??Array.from({length:this.renderedSegmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric,limit=this.renderedSegmentCount;let out="";for(const char of(raw??"").slice(0,MAX_VALUE_SOURCE_LENGTH))if(accepted.test(char)&&(out+=char),out.length>=limit)break;return this.case==="upper"?out=out.toUpperCase():this.case==="lower"&&(out=out.toLowerCase()),out.slice(0,limit)}packSegmentValues(value){const count=this.renderedSegmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??""),this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){return Array.isArray(this.segmentValues)?this.segmentValues.reduce((count,value)=>count+(value?1:0),0):this.value.length}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.renderedSegmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.renderedSegmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret),this.updateComplete.then(()=>{this.renderRoot.querySelectorAll('[part~="segment"]')[next]?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();if(!form)return;const submitter=findImplicitSubmitter(form);submitter?isNativeSubmitter(submitter)?form.requestSubmit(submitter):submitter.click():form.requestSubmit()}completeIfTransition(previousFilled){if(previousFilled>=this.renderedSegmentCount||this.filledSegmentCount!==this.renderedSegmentCount)return;const completionValue=this.value,token=this.autosubmitToken,completeEvent=this.emit("lr-complete",{value:completionValue},{cancelable:!0});this.autosubmit&&setTimeout(()=>{token!==this.autosubmitToken||completeEvent.defaultPrevented||!this.isConnected||!this.autosubmit||this.value!==completionValue||this.filledSegmentCount!==this.renderedSegmentCount||this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){this.autosubmitToken+=1;const previousValue=this.value,previousFilled=this.filledSegmentCount;this.segmentValues=this.normalizedSegmentValues(values);const nextValue=this.segmentValues.join("");super.value=nextValue,this.control&&(this.control.value=nextValue),this.touched=!0,dispatchNativeInputEvent(this,{data,inputType}),this.segmentEditPendingChange=!0,previousValue&&!nextValue&&this.emit("lr-clear"),this.completeIfTransition(previousFilled),this.requestUpdate()}get selectedSegmentRange(){const start=this.control?.selectionStart,end=this.control?.selectionEnd;if(start==null||end===void 0||end===null||start===end)return null;const indices=this.normalizedSegmentValues().map((value,index)=>value?index:-1).filter(index=>index>=0).slice(start,end),first=indices[0];return first===void 0?null:{indices,first}}segmentIndexAtCompactOffset(offset){const values=this.normalizedSegmentValues();let occupied=0;for(let index=0;index<values.length;index+=1){if(occupied>=offset)return index;values[index]&&(occupied+=1)}return Math.max(0,values.length-1)}syncActiveSegmentFromSelection(){const control=this.control;if(!control||control.selectionStart===null)return;const selected=this.selectedSegmentRange;this.activeSegmentIndex=selected?.first??this.segmentIndexAtCompactOffset(control.selectionStart)}get selectionStart(){return this.control?.selectionStart??null}set selectionStart(value){this.control&&(this.control.selectionStart=value,this.syncActiveSegmentFromSelection())}get selectionEnd(){return this.control?.selectionEnd??null}set selectionEnd(value){this.control&&(this.control.selectionEnd=value,this.syncActiveSegmentFromSelection())}get selectionDirection(){return this.control?.selectionDirection??null}set selectionDirection(value){this.control&&(this.control.selectionDirection=value)}focus(options){this.effectiveDisabled||this.control?.focus(options)}blur(){this.control?.blur()}click(){this.effectiveDisabled||this.control?.click()}select(){this.control?.select()}setSelectionRange(start,end,direction){this.control&&(this.control.setSelectionRange(start,end,direction),this.syncActiveSegmentFromSelection())}setRangeText(replacement,start,end,selectMode){const control=this.control;if(!control)return;const selectionPrefixLength=(value,offset)=>{if(offset===null)return null;const boundedOffset=Math.min(MAX_VALUE_SOURCE_LENGTH,Math.max(0,offset));return this.sanitize(value.slice(0,boundedOffset)).length},currentRaw=control.value,currentSelectionStart=selectionPrefixLength(currentRaw,control.selectionStart),currentSelectionEnd=selectionPrefixLength(currentRaw,control.selectionEnd),currentSelectionDirection=control.selectionDirection,boundedCurrent=this.sanitize(currentRaw);currentRaw!==boundedCurrent&&(control.value=boundedCurrent,currentSelectionStart!==null&&currentSelectionEnd!==null&&control.setSelectionRange(currentSelectionStart,currentSelectionEnd,currentSelectionDirection??void 0));const boundedReplacement=this.sanitize(replacement);start===void 0||end===void 0?control.setRangeText(boundedReplacement):control.setRangeText(boundedReplacement,start,end,selectMode);const raw=control.value,selectionStart=selectionPrefixLength(raw,control.selectionStart),selectionEnd=selectionPrefixLength(raw,control.selectionEnd),selectionDirection=control.selectionDirection,normalized=this.sanitize(raw);this.value=normalized,control.value=normalized,selectionStart!==null&&selectionEnd!==null&&control.setSelectionRange(selectionStart,selectionEnd,selectionDirection??void 0),this.syncActiveSegmentFromSelection()}clear(){const hadValue=this.value.length>0;this.value="",this.control&&(this.control.value=""),this.focus(),hadValue&&this.emit("lr-clear")}formResetCallback(){this.autosubmitToken+=1,super.formResetCallback(),this.touched=!1,this.segmentEditPendingChange=!1}formStateRestoreCallback(state2,reason){this.autosubmitToken+=1,super.formStateRestoreCallback(state2,reason)}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback(),this.autosubmitToken+=1}reportValidity(){return this.touched=!0,super.reportValidity()}firstUpdated(changed){super.firstUpdated(changed),this.autofocus&&this.scheduleAfterUpdate(()=>this.focus(),"otp-autofocus")}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const target=this.control??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()}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.rawValue);next!==this.value?this.value=next:this.packSegmentValues(next)}(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format"))&&this.updateValidity(),this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"--blank",this.value.length===0),setCustomState(this.internals,"--filled",this.filledSegmentCount===this.renderedSegmentCount),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"readonly",this.readonly)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const total=this.renderedSegmentCount,filled=this.filledSegmentCount,complete=filled===total;if(this.required&&filled===0){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}if(filled>0&&!complete){this[SET_ANCHORED_VALIDITY]({tooShort:!0},this.localize("otpInputIncomplete",void 0,{total}));return}this[SET_ANCHORED_VALIDITY]({})}flushPendingChange(){this.segmentEditPendingChange&&(this.segmentEditPendingChange=!1,dispatchNativeEvent(this,"change"))}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&index===this.activeSegmentIndex,masked=filled&&this.mask,placeholderMask=!filled&&this.withMask,parts=["segment"];return active&&parts.push("active"),masked&&parts.push("masked"),placeholderMask&&parts.push("placeholder-mask"),invalid&&parts.push("invalid"),html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=!!this.label||this.hasLabelSlot,hasHint=!!this.hint||this.hasHintSlot,hasError=!!this.errorText||this.hasErrorSlot,intrinsicInvalid=this.touched&&!this.validity.valid,ariaInvalid=hasError||intrinsicInvalid,describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" "),labelledBy=hasLabel&&!this.getAttribute("aria-label")?this.labelId:nothing;let segmentIndex=-1;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{findImplicitSubmitter,isNativeSubmitter,submitOnEnter}from"../../../internal/submit-on-enter.js";import{styles}from"./otp-input.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{currentValidityValidator}from"../form-validator.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel}from"../../../internal/default-strings.generated.js";const ACCEPTED={numeric:/[0-9]/,alpha:/[a-zA-Z]/,alphanumeric:/[a-zA-Z0-9]/},DEFAULT_LENGTH=6,MAX_LENGTH=32,MAX_FORMAT_SOURCE_LENGTH=4096,MAX_VALUE_SOURCE_LENGTH=4096;class LyraOtpInputBase extends LyraElement{static{this.styles=[LyraElement.styles,contextualSizes,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){constructor(){super(...arguments),this.label="",this.hint="",this.errorText="",this.appearance="outlined",this.autofocus=!1,this.autosubmit=!1,this.size="m",this.length=DEFAULT_LENGTH,this.format="",this.type="numeric",this.case="preserve",this.mask=!1,this.withMask=!1,this.readonly=!1,this.autocomplete="one-time-code",this.focused=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.touched=!1,this.labelId=nextId("otp-input-label"),this.hintId=nextId("otp-input-hint"),this.errorId=nextId("otp-input-error"),this.activeSegmentIndex=0,this.segmentValues=[],this.rawValue="",this.segmentEditPendingChange=!1,this.autosubmitToken=0,this.onInput=event=>{if(event.isComposing===!0){event.stopPropagation();return}const raw=event.target.value,next=this.sanitize(raw),previous=this.value,previousFilled=this.filledSegmentCount,layoutChanged=Array.from({length:this.renderedSegmentCount},(_,index)=>next[index]??"").some((value,index)=>value!==this.segmentValues[index]);if(this.control&&this.control.value!==next&&(this.control.value=next),next===this.value&&!layoutChanged){event.stopImmediatePropagation();return}this.touched=!0,this.value=next,relayNativeEvent(this,event),previous&&!next&&this.emit("lr-clear"),this.completeIfTransition(previousFilled)},this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1,delta=this.effectiveDirection==="rtl"?-physical:physical;this.setActiveSegment(this.activeSegmentIndex+delta);return}if(event.key==="Enter"){this.readonly||submitOnEnter(this,event,{beforeSubmit:()=>this.flushPendingChange()});return}if(this.readonly||event.isComposing)return;const selection=this.selectedSegmentRange;if(event.key==="Backspace"||event.key==="Delete"){event.preventDefault();const values2=this.normalizedSegmentValues();if(selection){for(const index of selection.indices)values2[index]="";this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),this.setActiveSegment(selection.first);return}const changed=!!values2[this.activeSegmentIndex];values2[this.activeSegmentIndex]="",changed&&this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),event.key==="Backspace"&&this.setActiveSegment(this.activeSegmentIndex-1);return}if(event.ctrlKey||event.metaKey||event.altKey||event.key.length!==1)return;event.preventDefault();const accepted=this.sanitize(event.key).slice(0,1);if(!accepted)return;const values=this.normalizedSegmentValues(),targetIndex=selection?.first??this.activeSegmentIndex;if(selection)for(const index of selection.indices)values[index]="";values[targetIndex]=accepted,this.commitSegmentEdit(values,"insertText",accepted),this.setActiveSegment(targetIndex+1)},this.onPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=this.sanitize(event.clipboardData?.getData("text")??"");if(event.preventDefault(),!pasted)return;const values=Array.from({length:this.renderedSegmentCount},(_,index)=>pasted[index]??"");this.commitSegmentEdit(values,"insertFromPaste",pasted),this.setActiveSegment(Math.min(pasted.length,this.renderedSegmentCount-1))},this.onChange=event=>{this.segmentEditPendingChange=!1,relayNativeEvent(this,event)},this.onFocus=event=>{this.focused=!0,relayNativeEvent(this,event)},this.onBlur=event=>{this.focused=!1,this.effectiveDisabled||(this.touched=!0),this.flushPendingChange(),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>{this.applyLabelSlotAssignment(event.target)},this.onHintSlotChange=event=>{this.applyHintSlotAssignment(event.target)},this.onErrorSlotChange=event=>{this.applyErrorSlotAssignment(event.target)}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,otpInputIncomplete:LYRA_DEFAULT_otpInputIncomplete,otpInputLabel:LYRA_DEFAULT_otpInputLabel}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","length","pattern")]}get input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){this.autosubmitToken+=1,this.rawValue=next??"";const normalized=this.sanitize(this.rawValue);this.packSegmentValues(normalized),super.value=normalized}get defaultValue(){return super.defaultValue}set defaultValue(next){this.autosubmitToken+=1,super.defaultValue=next}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;if(this.parsedFormatSource=this.format,!this.format)return this.parsedFormatCells=null,null;const cells=[];let segments=0,literal="";const flushLiteral=()=>{literal&&(cells.push({kind:"separator",text:literal}),literal="")};for(const char of this.format.slice(0,MAX_FORMAT_SOURCE_LENGTH)){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral(),cells.push({kind:"segment"}),segments+=1}return flushLiteral(),this.parsedFormatCells=segments>0?cells:null,this.parsedFormatCells}get renderedSegmentCount(){const formatted=this.formattedCells;return formatted?formatted.filter(cell=>cell.kind==="segment").length:Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.renderedSegmentCount}get cells(){return this.formattedCells??Array.from({length:this.renderedSegmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric,limit=this.renderedSegmentCount;let out="";for(const char of(raw??"").slice(0,MAX_VALUE_SOURCE_LENGTH))if(accepted.test(char)&&(out+=char),out.length>=limit)break;return this.case==="upper"?out=out.toUpperCase():this.case==="lower"&&(out=out.toLowerCase()),out.slice(0,limit)}packSegmentValues(value){const count=this.renderedSegmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??""),this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){return Array.isArray(this.segmentValues)?this.segmentValues.reduce((count,value)=>count+(value?1:0),0):this.value.length}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.renderedSegmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.renderedSegmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret),this.updateComplete.then(()=>{this.renderRoot.querySelectorAll('[part~="segment"]')[next]?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();if(!form)return;const submitter=findImplicitSubmitter(form);submitter?isNativeSubmitter(submitter)?form.requestSubmit(submitter):submitter.click():form.requestSubmit()}completeIfTransition(previousFilled){if(previousFilled>=this.renderedSegmentCount||this.filledSegmentCount!==this.renderedSegmentCount)return;const completionValue=this.value,token=this.autosubmitToken,completeEvent=this.emit("lr-complete",{value:completionValue},{cancelable:!0});this.autosubmit&&setTimeout(()=>{token!==this.autosubmitToken||completeEvent.defaultPrevented||!this.isConnected||!this.autosubmit||this.value!==completionValue||this.filledSegmentCount!==this.renderedSegmentCount||this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){this.autosubmitToken+=1;const previousValue=this.value,previousFilled=this.filledSegmentCount;this.segmentValues=this.normalizedSegmentValues(values);const nextValue=this.segmentValues.join("");super.value=nextValue,this.control&&(this.control.value=nextValue),this.touched=!0,dispatchNativeInputEvent(this,{data,inputType}),this.segmentEditPendingChange=!0,previousValue&&!nextValue&&this.emit("lr-clear"),this.completeIfTransition(previousFilled),this.requestUpdate()}get selectedSegmentRange(){const start=this.control?.selectionStart,end=this.control?.selectionEnd;if(start==null||end===void 0||end===null||start===end)return null;const indices=this.normalizedSegmentValues().map((value,index)=>value?index:-1).filter(index=>index>=0).slice(start,end),first=indices[0];return first===void 0?null:{indices,first}}segmentIndexAtCompactOffset(offset){const values=this.normalizedSegmentValues();let occupied=0;for(let index=0;index<values.length;index+=1){if(occupied>=offset)return index;values[index]&&(occupied+=1)}return Math.max(0,values.length-1)}syncActiveSegmentFromSelection(){const control=this.control;if(!control||control.selectionStart===null)return;const selected=this.selectedSegmentRange;this.activeSegmentIndex=selected?.first??this.segmentIndexAtCompactOffset(control.selectionStart)}get selectionStart(){return this.control?.selectionStart??null}set selectionStart(value){this.control&&(this.control.selectionStart=value,this.syncActiveSegmentFromSelection())}get selectionEnd(){return this.control?.selectionEnd??null}set selectionEnd(value){this.control&&(this.control.selectionEnd=value,this.syncActiveSegmentFromSelection())}get selectionDirection(){return this.control?.selectionDirection??null}set selectionDirection(value){this.control&&(this.control.selectionDirection=value)}focus(options){this.effectiveDisabled||this.control?.focus(options)}blur(){this.control?.blur()}click(){this.effectiveDisabled||this.control?.click()}select(){this.control?.select()}setSelectionRange(start,end,direction){this.control&&(this.control.setSelectionRange(start,end,direction),this.syncActiveSegmentFromSelection())}setRangeText(replacement,start,end,selectMode){const control=this.control;if(!control)return;const selectionPrefixLength=(value,offset)=>{if(offset===null)return null;const boundedOffset=Math.min(MAX_VALUE_SOURCE_LENGTH,Math.max(0,offset));return this.sanitize(value.slice(0,boundedOffset)).length},currentRaw=control.value,currentSelectionStart=selectionPrefixLength(currentRaw,control.selectionStart),currentSelectionEnd=selectionPrefixLength(currentRaw,control.selectionEnd),currentSelectionDirection=control.selectionDirection,boundedCurrent=this.sanitize(currentRaw);currentRaw!==boundedCurrent&&(control.value=boundedCurrent,currentSelectionStart!==null&&currentSelectionEnd!==null&&control.setSelectionRange(currentSelectionStart,currentSelectionEnd,currentSelectionDirection??void 0));const boundedReplacement=this.sanitize(replacement);start===void 0||end===void 0?control.setRangeText(boundedReplacement):control.setRangeText(boundedReplacement,start,end,selectMode);const raw=control.value,selectionStart=selectionPrefixLength(raw,control.selectionStart),selectionEnd=selectionPrefixLength(raw,control.selectionEnd),selectionDirection=control.selectionDirection,normalized=this.sanitize(raw);this.value=normalized,control.value=normalized,selectionStart!==null&&selectionEnd!==null&&control.setSelectionRange(selectionStart,selectionEnd,selectionDirection??void 0),this.syncActiveSegmentFromSelection()}clear(){const hadValue=this.value.length>0;this.value="",this.control&&(this.control.value=""),this.focus(),hadValue&&this.emit("lr-clear")}formResetCallback(){this.autosubmitToken+=1,super.formResetCallback(),this.touched=!1,this.segmentEditPendingChange=!1}formStateRestoreCallback(state2,reason){this.autosubmitToken+=1,super.formStateRestoreCallback(state2,reason)}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback(),this.autosubmitToken+=1}reportValidity(){return this.touched=!0,super.reportValidity()}firstUpdated(changed){super.firstUpdated(changed),this.autofocus&&this.scheduleAfterUpdate(()=>this.focus(),"otp-autofocus");const labelSlot=this.labelSlotEl,hintSlot=this.hintSlotEl,errorSlot=this.errorSlotEl;queueMicrotask(()=>{collectInitialSlotAssignment(labelSlot,slot=>this.applyLabelSlotAssignment(slot)),collectInitialSlotAssignment(hintSlot,slot=>this.applyHintSlotAssignment(slot)),collectInitialSlotAssignment(errorSlot,slot=>this.applyErrorSlotAssignment(slot))})}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const target=this.control??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()}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.rawValue);next!==this.value?this.value=next:this.packSegmentValues(next)}(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format"))&&this.updateValidity(),this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"--blank",this.value.length===0),setCustomState(this.internals,"--filled",this.filledSegmentCount===this.renderedSegmentCount),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"readonly",this.readonly)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const total=this.renderedSegmentCount,filled=this.filledSegmentCount,complete=filled===total;if(this.required&&filled===0){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}if(filled>0&&!complete){this[SET_ANCHORED_VALIDITY]({tooShort:!0},this.localize("otpInputIncomplete",void 0,{total}));return}this[SET_ANCHORED_VALIDITY]({})}flushPendingChange(){this.segmentEditPendingChange&&(this.segmentEditPendingChange=!1,dispatchNativeEvent(this,"change"))}applyLabelSlotAssignment(slot){this.hasLabelSlot=slot.assignedNodes({flatten:!0}).length>0}applyHintSlotAssignment(slot){this.hasHintSlot=slot.assignedNodes({flatten:!0}).length>0}applyErrorSlotAssignment(slot){this.hasErrorSlot=slot.assignedNodes({flatten:!0}).length>0}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&index===this.activeSegmentIndex,masked=filled&&this.mask,placeholderMask=!filled&&this.withMask,parts=["segment"];return active&&parts.push("active"),masked&&parts.push("masked"),placeholderMask&&parts.push("placeholder-mask"),invalid&&parts.push("invalid"),html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=!!this.label||this.hasLabelSlot,hasHint=!!this.hint||this.hasHintSlot,hasError=!!this.errorText||this.hasErrorSlot,intrinsicInvalid=this.touched&&!this.validity.valid,ariaInvalid=hasError||intrinsicInvalid,describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" "),labelledBy=hasLabel&&!this.getAttribute("aria-label")?this.labelId:nothing;let segmentIndex=-1;return html`
2
2
  <div part="base form-control">
3
3
  <label part="label form-control-label" id=${this.labelId} for="control" ?hidden=${!hasLabel}>
4
4
  ${this.label}<slot name="label" ?hidden=${!!this.label} @slotchange=${this.onLabelSlotChange}></slot>
@@ -46,4 +46,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
46
46
  ${this.hint}<slot name="hint" ?hidden=${!!this.hint} @slotchange=${this.onHintSlotChange}></slot>
47
47
  </div>
48
48
  </div>
49
- `}}__decorate([property()],LyraOtpInput.prototype,"label",void 0),__decorate([property()],LyraOtpInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraOtpInput.prototype,"errorText",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("outlined")})],LyraOtpInput.prototype,"appearance",void 0),__decorate([property({type:Boolean})],LyraOtpInput.prototype,"autofocus",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraOtpInput.prototype,"autosubmit",void 0),__decorate([property({reflect:!0,useDefault:!0})],LyraOtpInput.prototype,"size",void 0),__decorate([property({type:Number,reflect:!0,converter:declaredDefaultConverter(DEFAULT_LENGTH)})],LyraOtpInput.prototype,"length",void 0),__decorate([property()],LyraOtpInput.prototype,"format",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("numeric")})],LyraOtpInput.prototype,"type",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("preserve")})],LyraOtpInput.prototype,"case",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraOtpInput.prototype,"mask",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"with-mask"})],LyraOtpInput.prototype,"withMask",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraOtpInput.prototype,"readonly",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("one-time-code")})],LyraOtpInput.prototype,"autocomplete",void 0),__decorate([state()],LyraOtpInput.prototype,"focused",void 0),__decorate([state()],LyraOtpInput.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraOtpInput.prototype,"hasHintSlot",void 0),__decorate([state()],LyraOtpInput.prototype,"hasErrorSlot",void 0),__decorate([state()],LyraOtpInput.prototype,"touched",void 0),__decorate([query('[part="control"]')],LyraOtpInput.prototype,"control",void 0),__decorate([state()],LyraOtpInput.prototype,"activeSegmentIndex",void 0);export{LyraOtpInput};
49
+ `}}__decorate([property()],LyraOtpInput.prototype,"label",void 0),__decorate([property()],LyraOtpInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraOtpInput.prototype,"errorText",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("outlined")})],LyraOtpInput.prototype,"appearance",void 0),__decorate([property({type:Boolean})],LyraOtpInput.prototype,"autofocus",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraOtpInput.prototype,"autosubmit",void 0),__decorate([property({reflect:!0,useDefault:!0})],LyraOtpInput.prototype,"size",void 0),__decorate([property({type:Number,reflect:!0,converter:declaredDefaultConverter(DEFAULT_LENGTH)})],LyraOtpInput.prototype,"length",void 0),__decorate([property()],LyraOtpInput.prototype,"format",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("numeric")})],LyraOtpInput.prototype,"type",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("preserve")})],LyraOtpInput.prototype,"case",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraOtpInput.prototype,"mask",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"with-mask"})],LyraOtpInput.prototype,"withMask",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraOtpInput.prototype,"readonly",void 0),__decorate([property({reflect:!0,converter:declaredDefaultConverter("one-time-code")})],LyraOtpInput.prototype,"autocomplete",void 0),__decorate([state()],LyraOtpInput.prototype,"focused",void 0),__decorate([state()],LyraOtpInput.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraOtpInput.prototype,"hasHintSlot",void 0),__decorate([state()],LyraOtpInput.prototype,"hasErrorSlot",void 0),__decorate([state()],LyraOtpInput.prototype,"touched",void 0),__decorate([query('[part="control"]')],LyraOtpInput.prototype,"control",void 0),__decorate([query('slot[name="label"]')],LyraOtpInput.prototype,"labelSlotEl",void 0),__decorate([query('slot[name="hint"]')],LyraOtpInput.prototype,"hintSlotEl",void 0),__decorate([query('slot[name="error"]')],LyraOtpInput.prototype,"errorSlotEl",void 0),__decorate([state()],LyraOtpInput.prototype,"activeSegmentIndex",void 0);export{LyraOtpInput};
@@ -47,7 +47,8 @@ import{type TemplateResult}from'lit';import{LyraRadio}from'./radio.class.js';
47
47
  * @cssstate invalid - Matches while it does not — from the very first render, before the user has
48
48
  * touched anything.
49
49
  * @cssstate user-valid - `valid`, but only after the user has interacted with this control:
50
- * selecting it, blurring it, or a `reportValidity()` call (which is what a submit attempt runs).
50
+ * selecting it, blurring it, `reportValidity()`, or a submission attempt. Not after a silent
51
+ * `checkValidity()` alone.
51
52
  * @cssstate user-invalid - `invalid` after that same interaction. Style validation errors with this
52
53
  * rather than `invalid`: a pristine required control is genuinely invalid, but colouring it red
53
54
  * before the user has done anything is hostile.
@@ -2,8 +2,10 @@ import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from
2
2
  /**
3
3
  * `<lr-radio-group>` — a labeled, keyboard-navigable group of radios.
4
4
  * A required but pristine group exposes `aria-invalid="false"`; intrinsic invalidity is projected
5
- * to the radiogroup only after user interaction or a native validity check (`checkValidity()`,
6
- * `reportValidity()`, or form-level validation), while explicit error chrome remains immediate.
5
+ * to the radiogroup only after user interaction (selecting a radio, blurring the group) or
6
+ * interactive validation (`reportValidity()`, or a submission attempt), while explicit error
7
+ * chrome remains immediate. `checkValidity()` alone is a silent query and never marks a pristine
8
+ * group interacted.
7
9
  *
8
10
  * Host `aria-describedby` references resolve onto the internal radiogroup before local hint/error
9
11
  * guidance. References track target replacement/removal, reconnect and document adoption.
@@ -25,8 +27,11 @@ import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from
25
27
  * @cssstate optional - Matches while `required` is not set.
26
28
  * @cssstate valid - Matches while the aggregate value satisfies every constraint.
27
29
  * @cssstate invalid - Matches while the aggregate value fails a constraint.
28
- * @cssstate user-valid - Matches `valid` after user interaction or a native validity check.
29
- * @cssstate user-invalid - Matches `invalid` after user interaction or a native validity check.
30
+ * @cssstate user-valid - Matches `valid` after user interaction (selecting a radio, blurring the
31
+ * group) or interactive validation (`reportValidity()`, or a submission attempt); not after a
32
+ * silent `checkValidity()` alone.
33
+ * @cssstate user-invalid - Matches `invalid` after that same interaction or interactive validation;
34
+ * not after a silent `checkValidity()` alone.
30
35
  * @csspart base - The radiogroup wrapper.
31
36
  * @csspart form-control - Mapped form-control wrapper.
32
37
  * @csspart label - The group label.
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();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,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{declaredDefaultConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["radio"]),"lr-change":Object.freeze(["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:declaredDefaultConverter("vertical")},form:{noAccessor:!0}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("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.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)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}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.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,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._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;this.hasInteracted=!0,this.reflectValidityStates(),this.requestUpdate(),this.emit("lr-invalid",null,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onKeyDown=event=>{if(![...this.orientation==="horizontal"?["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;event.preventDefault();const rtl=this.effectiveDirection==="rtl",forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight",backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft",nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index,next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onSlotChange=event=>{const slot=event.target,elements=slot.assignedElements({flatten:!0});slot.name==="label"&&(this.hasLabelSlot=elements.length>0),slot.name==="hint"&&(this.hasHintSlot=elements.length>0),slot.name==="help-text"&&(this.hasHelpTextSlot=elements.length>0),slot.name==="error"&&(this.hasErrorSlot=elements.length>0)},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.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),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.syncSupportSlots(),this.syncRadios(),this.armMembershipObserver(),this.armRunResizeObserver(),this.scheduleRunProjection()}armRunResizeObserver(){this.runResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerDocument?.defaultView?.ResizeObserver;if(!(!ResizeObserverCtor||!this.isConnected)){this.runResizeObserver=new ResizeObserverCtor(()=>this.scheduleRunProjection()),this.runResizeObserver.observe(this);for(const radio of this.radios())this.runResizeObserver.observe(radio)}}scheduleRunProjection(){const ownerWindow=this.ownerDocument?.defaultView;!ownerWindow||!this.isConnected||this.runProjectionFrame!==void 0||(this.runProjectionFrame=ownerWindow.requestAnimationFrame(()=>{this.runProjectionFrame=void 0,this.isConnected&&this.projectButtonRuns()}))}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}areActuallyAdjacent(first,second){const firstRect=first.getBoundingClientRect(),secondRect=second.getBoundingClientRect();if(firstRect.width<=0||firstRect.height<=0||secondRect.width<=0||secondRect.height<=0||!(Math.abs(firstRect.top-secondRect.top)<=1&&Math.abs(firstRect.bottom-secondRect.bottom)<=1))return!1;const gap=getComputedStyle(this).direction==="rtl"?firstRect.left-secondRect.right:secondRect.left-firstRect.right;return gap>=-2&&gap<=1}projectButtonRuns(){const radios=this.radios(),joinsPrevious=radios.map(()=>!1);if(this.orientation==="horizontal")for(let index=1;index<radios.length;index+=1){const previous=radios[index-1],current=radios[index];joinsPrevious[index]=this.isButtonRadio(previous)&&this.isButtonRadio(current)&&this.areActuallyAdjacent(previous,current)}for(let index=0;index<radios.length;index+=1){const joinsBefore=joinsPrevious[index]??!1,joinsAfter=joinsPrevious[index+1]??!1,position=joinsBefore?joinsAfter?"middle":"end":joinsAfter?"start":"standalone";radios[index].setButtonRunPosition(position)}}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.runResizeObserver?.disconnect(),this.runResizeObserver=void 0;const ownerWindow=this.ownerDocument?.defaultView;ownerWindow&&this.runProjectionFrame!==void 0&&ownerWindow.cancelAnimationFrame(this.runProjectionFrame),this.runProjectionFrame=void 0,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(),this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="hint"),this.hasHelpTextSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="help-text"),this.hasErrorSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="error")}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){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))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);this.managedRadios=current,this.armRunResizeObserver();for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>this.isRadioAvailable(radio));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)?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.scheduleRunProjection()}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;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}return this.syncRadios(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:radio.value,radio}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:radio.value,radio}),!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.internals.checkValidity()}reportValidity(){return 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(state2,reason){this._valueDirty=!0,this.hasInteracted=!1,this.pendingSelection=typeof state2=="string"?state2:"",this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,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;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();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,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{isStaticValidityCheckInProgress,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{declaredDefaultConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["radio"]),"lr-change":Object.freeze(["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:declaredDefaultConverter("vertical")},form:{noAccessor:!0}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("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.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)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}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.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,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._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.onKeyDown=event=>{if(![...this.orientation==="horizontal"?["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;event.preventDefault();const rtl=this.effectiveDirection==="rtl",forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight",backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft",nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index,next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onSlotChange=event=>{const slot=event.target,elements=slot.assignedElements({flatten:!0});slot.name==="label"&&(this.hasLabelSlot=elements.length>0),slot.name==="hint"&&(this.hasHintSlot=elements.length>0),slot.name==="help-text"&&(this.hasHelpTextSlot=elements.length>0),slot.name==="error"&&(this.hasErrorSlot=elements.length>0)},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.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),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.syncSupportSlots(),this.syncRadios(),this.armMembershipObserver(),this.armRunResizeObserver(),this.scheduleRunProjection()}armRunResizeObserver(){this.runResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerDocument?.defaultView?.ResizeObserver;if(!(!ResizeObserverCtor||!this.isConnected)){this.runResizeObserver=new ResizeObserverCtor(()=>this.scheduleRunProjection()),this.runResizeObserver.observe(this);for(const radio of this.radios())this.runResizeObserver.observe(radio)}}scheduleRunProjection(){const ownerWindow=this.ownerDocument?.defaultView;!ownerWindow||!this.isConnected||this.runProjectionFrame!==void 0||(this.runProjectionFrame=ownerWindow.requestAnimationFrame(()=>{this.runProjectionFrame=void 0,this.isConnected&&this.projectButtonRuns()}))}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}areActuallyAdjacent(first,second){const firstRect=first.getBoundingClientRect(),secondRect=second.getBoundingClientRect();if(firstRect.width<=0||firstRect.height<=0||secondRect.width<=0||secondRect.height<=0||!(Math.abs(firstRect.top-secondRect.top)<=1&&Math.abs(firstRect.bottom-secondRect.bottom)<=1))return!1;const gap=getComputedStyle(this).direction==="rtl"?firstRect.left-secondRect.right:secondRect.left-firstRect.right;return gap>=-2&&gap<=1}projectButtonRuns(){const radios=this.radios(),joinsPrevious=radios.map(()=>!1);if(this.orientation==="horizontal")for(let index=1;index<radios.length;index+=1){const previous=radios[index-1],current=radios[index];joinsPrevious[index]=this.isButtonRadio(previous)&&this.isButtonRadio(current)&&this.areActuallyAdjacent(previous,current)}for(let index=0;index<radios.length;index+=1){const joinsBefore=joinsPrevious[index]??!1,joinsAfter=joinsPrevious[index+1]??!1,position=joinsBefore?joinsAfter?"middle":"end":joinsAfter?"start":"standalone";radios[index].setButtonRunPosition(position)}}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.runResizeObserver?.disconnect(),this.runResizeObserver=void 0;const ownerWindow=this.ownerDocument?.defaultView;ownerWindow&&this.runProjectionFrame!==void 0&&ownerWindow.cancelAnimationFrame(this.runProjectionFrame),this.runProjectionFrame=void 0,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(),this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="label"),this.hasHintSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="hint"),this.hasHelpTextSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="help-text"),this.hasErrorSlot=Array.from(this.children??[]).some(element=>element.getAttribute("slot")==="error")}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){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))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);this.managedRadios=current,this.armRunResizeObserver();for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>this.isRadioAvailable(radio));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)?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.scheduleRunProjection()}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;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}return this.syncRadios(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:radio.value,radio}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:radio.value,radio}),!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 withStaticValidityCheck(this,()=>this.internals.checkValidity())}reportValidity(){return 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(state2,reason){this._valueDirty=!0,this.hasInteracted=!1,this.pendingSelection=typeof state2=="string"?state2:"",this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,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;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}
@@ -48,8 +48,9 @@ import{type TemplateResult,type PropertyValues}from'lit';import{LyraElement}from
48
48
  * `setCustomValidity()` error.
49
49
  * @cssstate invalid - Matches while it does not — from the very first render, before the user has
50
50
  * touched anything.
51
- * @cssstate user-valid - `valid`, but only after the user has interacted with this radio: selecting
52
- * it, blurring it, or a `reportValidity()` call (which is what a submit attempt runs).
51
+ * @cssstate user-valid - `valid`, but only after the user has interacted with this radio:
52
+ * selecting it, blurring it, `reportValidity()`, or a submission attempt. Not after a silent
53
+ * `checkValidity()` alone.
53
54
  * @cssstate user-invalid - `invalid` after that same interaction. Style validation errors with this
54
55
  * rather than `invalid`: a pristine required radio is genuinely invalid, but colouring it red
55
56
  * before the user has done anything is hostile.
@@ -129,9 +130,11 @@ appearance:RadioAppearance;
129
130
  */
130
131
  pill:boolean;private hasLabel;private hasStart;private hasEnd;private labelObserver?;
131
132
  /** Whether the user has acted on this radio yet, which is what gates the `user-valid`/
132
- * `user-invalid` custom states: a selection or a blur. A pristine required radio is genuinely
133
- * invalid, but styling it as an error before the user has done anything is hostile, which is the
134
- * entire reason the `user-*` pair exists. Not `@state`: nothing in `render()` reads it. */
133
+ * `user-invalid` custom states: a selection, a blur, or interactive validation
134
+ * (`reportValidity()` or a submission attempt, via `installInteractionOnInvalid()`). A silent
135
+ * `checkValidity()` alone never counts. A pristine required radio is genuinely invalid, but
136
+ * styling it as an error before the user has done anything is hostile, which is the entire
137
+ * reason the `user-*` pair exists. Not `@state`: nothing in `render()` reads it. */
135
138
  private hasInteracted;private internals;private validityController;
136
139
  /** Consumer-supplied validation message reflected through `custom-error`. */
137
140
  customError:string|null;private _checked;private _disabled;private _required;private _name;private _value;private _fieldsetDisabled;private _groupDisabled;private _groupRequired;private _groupSize;private _tabbable;private _buttonRunPosition;private groupOwner;private _defaultChecked;private _checkedDirty;private settingDefaultChecked;private reflectingDefaultChecked;get checked():boolean;set checked(value:boolean);
@@ -154,9 +157,12 @@ private get barredFromValidation();private updateValidity;
154
157
  * `user-valid`/`user-invalid`) from whatever `ElementInternals` currently holds. `required`
155
158
  * here is the EFFECTIVE one -- a radio inside a `required` `<lr-radio-group>` is required even
156
159
  * with no attribute of its own, and that is what its validity is already computed from. */
157
- private reflectValidityStates;
160
+ private reflectValidityStates;private markInteracted;
158
161
  /** Whether the radio currently satisfies its constraints — the silent query, so it deliberately
159
- * does not count as interaction for the `user-*` custom states. */
162
+ * does not count as interaction for the `user-*` custom states.
163
+ * `withStaticValidityCheck()` tells the `installInteractionOnInvalid()` listener above that
164
+ * whatever `invalid` event fires synchronously inside this call is this call, not a
165
+ * submission attempt. */
160
166
  checkValidity():boolean;
161
167
  /** `checkValidity()`, plus the browser's own validation UI on failure. */
162
168
  reportValidity():boolean;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.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{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{declaredDefaultConverter,omittedEmptyStringConverter}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";class LyraRadio extends LyraElement{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.formAssociated=!0}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},checked:{attribute:!1,noAccessor:!0},defaultChecked:{attribute:"checked",type:Boolean,reflect:!0,useDefault:!0,noAccessor:!0},appearance:{reflect:!0,converter:declaredDefaultConverter("default")},disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},pill:{type:Boolean,reflect:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")},value:{reflect:!0,noAccessor:!0}}}get checked(){return this._checked}set checked(value){const old=this._checked,next=!!value;this.settingDefaultChecked||(this._checkedDirty=!0),old!==next&&(this._checked=next,this.syncFormState(),this.requestUpdate("checked",old),this.isConnected&&this.group()?.radioCheckedChanged?.(this))}get defaultChecked(){return this._defaultChecked}set defaultChecked(value){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=!!value,this.reflectingDefaultChecked=!0;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=!1}this._checkedDirty||this.restoreCheckedFromDefault(),this.requestUpdate("defaultChecked",old)}get disabled(){return this._disabled}set disabled(value){const old=this._disabled;this._disabled=!!value,this.toggleAttribute("disabled",this._disabled),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(value){const old=this._required;this._required=!!value,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get name(){return this._name}set name(value){const old=this._name,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._name=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._value}set value(value){const old=this._value,next=value??"on";old!==next&&(this._value=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled||!!this.currentGroup()&&this._groupDisabled}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}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}constructor(){super(),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.hasInteracted=!1,this._checked=!1,this._disabled=!1,this._required=!1,this._name="",this._value="on",this._fieldsetDisabled=!1,this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this._defaultChecked=!1,this._checkedDirty=!1,this.settingDefaultChecked=!1,this.reflectingDefaultChecked=!1,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.hasInteracted=!0,this.reflectValidityStates()),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.bindLabelObserverTargets(),this.recomputeButtonAdornments()},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.currentGroup()?.customError??this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}[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"))}updated(changed){super.updated(changed),this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.recomputeHasLabel(),this.recomputeButtonAdornments()}):void 0,this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.bindLabelObserverTargets(),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,super.disconnectedCallback()}formResetCallback(){this.currentGroup()||(this.hasInteracted=!1,this.restoreCheckedFromDefault(),this.reflectValidityStates())}resetFromGroup(){this.hasInteracted=!1,this.restoreCheckedFromDefault()}restoreCheckedFromDefault(){this.settingDefaultChecked=!0;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=!1}this._checkedDirty=!1}formStateRestoreCallback(state2,reason){if(this.currentGroup())return;const old=this._checked;this._checked=state2==="checked",this._checkedDirty=!0,this.syncFormState(),this.requestUpdate("checked",old),this.isConnected&&this.group()?.radioCheckedChanged?.(this)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.updateValidity(),this.requestUpdate()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){const owned=!!this.currentGroup(),violates=!this.barredFromValidation&&!owned&&this.effectiveRequired&&!this.checked;this.validityController.setValidity(violates?{valueMissing:!0}:{},this.localize("radioRequired")),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.effectiveRequired,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"checked",this.checked),setCustomState(this.internals,"disabled",this.effectiveDisabled)}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()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message??"");return}this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}resetValidity(){this.setCustomValidity("")}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}syncFormState(){!!this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked"),this.updateValidity()}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||this.checked)){if(this.hasInteracted=!0,group)return group.selectRadio?.(this),void 0;this.checked=!0,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})}}get groupTabbable(){return this._tabbable}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)})}adornmentForwardingSlots(){const names=["start","prefix","end","suffix"];return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top===slot&&top.parentNode===this&&names.includes(slot.getAttribute("slot")??"")})}observeLabelNode(node){if(this.labelObserver){if(node.nodeType===3){this.labelObserver.observe(node,{characterData:!0});return}node.nodeType===1&&this.labelObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:!0,characterData:!0,subtree:!0})}}bindLabelObserverTargets(){if(this.labelObserver){this.labelObserver.disconnect(),this.observeLabelNode(this);for(const slot of this.labelForwardingSlots())if(slot.assignedNodes().length!==0)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeLabelNode(assigned);for(const slot of this.adornmentForwardingSlots())if(slot.assignedNodes().length!==0)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeLabelNode(assigned)}}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.bindLabelObserverTargets(),this.recomputeHasLabel())}renderButtonContent(){return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.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{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{declaredDefaultConverter,omittedEmptyStringConverter}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";class LyraRadio extends LyraElement{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.formAssociated=!0}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},checked:{attribute:!1,noAccessor:!0},defaultChecked:{attribute:"checked",type:Boolean,reflect:!0,useDefault:!0,noAccessor:!0},appearance:{reflect:!0,converter:declaredDefaultConverter("default")},disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},pill:{type:Boolean,reflect:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},size:{reflect:!0,converter:declaredDefaultConverter("m")},value:{reflect:!0,noAccessor:!0}}}get checked(){return this._checked}set checked(value){const old=this._checked,next=!!value;this.settingDefaultChecked||(this._checkedDirty=!0),old!==next&&(this._checked=next,this.syncFormState(),this.requestUpdate("checked",old),this.isConnected&&this.group()?.radioCheckedChanged?.(this))}get defaultChecked(){return this._defaultChecked}set defaultChecked(value){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=!!value,this.reflectingDefaultChecked=!0;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=!1}this._checkedDirty||this.restoreCheckedFromDefault(),this.requestUpdate("defaultChecked",old)}get disabled(){return this._disabled}set disabled(value){const old=this._disabled;this._disabled=!!value,this.toggleAttribute("disabled",this._disabled),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(value){const old=this._required;this._required=!!value,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get name(){return this._name}set name(value){const old=this._name,next=value??"";if(old===next){!next&&this.hasAttribute("name")&&this.removeAttribute("name");return}this._name=next,next?this.getAttribute("name")!==next&&this.setAttribute("name",next):this.hasAttribute("name")&&this.removeAttribute("name"),this.requestUpdate("name",old)}get value(){return this._value}set value(value){const old=this._value,next=value??"on";old!==next&&(this._value=next,value==null?this.hasAttribute("value")&&this.removeAttribute("value"):this.getAttribute("value")!==next&&this.setAttribute("value",next),this.syncFormState(),this.requestUpdate("value",old))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled||!!this.currentGroup()&&this._groupDisabled}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}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}constructor(){super(),this.size="m",this.appearance="default",this.pill=!1,this.hasLabel=!1,this.hasStart=!1,this.hasEnd=!1,this.hasInteracted=!1,this._checked=!1,this._disabled=!1,this._required=!1,this._name="",this._value="on",this._fieldsetDisabled=!1,this._groupDisabled=!1,this._groupRequired=!1,this._groupSize=null,this._tabbable=!0,this._buttonRunPosition="standalone",this.groupOwner=null,this._defaultChecked=!1,this._checkedDirty=!1,this.settingDefaultChecked=!1,this.reflectingDefaultChecked=!1,this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},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.hasInteracted=!0,this.reflectValidityStates()),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event),this.onAdornmentSlotChange=()=>{this.bindLabelObserverTargets(),this.recomputeButtonAdornments()},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.currentGroup()?.customError??this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),installInteractionOnInvalid(this,this.markInteracted),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}[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"))}updated(changed){super.updated(changed),this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets(),this.recomputeHasLabel(),this.recomputeButtonAdornments()}):void 0,this.addEventListener("slotchange",this.onLabelSlotChange),this.addEventListener("slotchange",this.onAdornmentSlotChange),this.bindLabelObserverTargets(),this.recomputeHasLabel(),this.recomputeButtonAdornments(),this.updateValidity(),this.group()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),this.removeEventListener("slotchange",this.onAdornmentSlotChange),this.labelObserver?.disconnect(),this.labelObserver=void 0,super.disconnectedCallback()}formResetCallback(){this.currentGroup()||(this.hasInteracted=!1,this.restoreCheckedFromDefault(),this.reflectValidityStates())}resetFromGroup(){this.hasInteracted=!1,this.restoreCheckedFromDefault()}restoreCheckedFromDefault(){this.settingDefaultChecked=!0;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=!1}this._checkedDirty=!1}formStateRestoreCallback(state2,reason){if(this.currentGroup())return;const old=this._checked;this._checked=state2==="checked",this._checkedDirty=!0,this.syncFormState(),this.requestUpdate("checked",old),this.isConnected&&this.group()?.radioCheckedChanged?.(this)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.updateValidity(),this.requestUpdate()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){const owned=!!this.currentGroup(),violates=!this.barredFromValidation&&!owned&&this.effectiveRequired&&!this.checked;this.validityController.setValidity(violates?{valueMissing:!0}:{},this.localize("radioRequired")),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.effectiveRequired,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"checked",this.checked),setCustomState(this.internals,"disabled",this.effectiveDisabled)}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()}checkValidity(){return withStaticValidityCheck(this,()=>this.internals.checkValidity())}reportValidity(){return this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){const group=this.currentGroup();if(group?.setCustomValidity){group.setCustomValidity(message??"");return}this.validityController.setCustomValidity(message??""),this.reflectValidityStates(),this.requestUpdate()}resetValidity(){this.setCustomValidity("")}click(){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.effectiveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}syncFormState(){!!this.currentGroup()?this.internals.setFormValue(null):this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked"),this.updateValidity()}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||this.checked)){if(this.hasInteracted=!0,group)return group.selectRadio?.(this),void 0;this.checked=!0,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:!0,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:!0,value:this.value})}}get groupTabbable(){return this._tabbable}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)})}adornmentForwardingSlots(){const names=["start","prefix","end","suffix"];return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top===slot&&top.parentNode===this&&names.includes(slot.getAttribute("slot")??"")})}observeLabelNode(node){if(this.labelObserver){if(node.nodeType===3){this.labelObserver.observe(node,{characterData:!0});return}node.nodeType===1&&this.labelObserver.observe(node,{attributes:!0,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:!0,characterData:!0,subtree:!0})}}bindLabelObserverTargets(){if(this.labelObserver){this.labelObserver.disconnect(),this.observeLabelNode(this);for(const slot of this.labelForwardingSlots())if(slot.assignedNodes().length!==0)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeLabelNode(assigned);for(const slot of this.adornmentForwardingSlots())if(slot.assignedNodes().length!==0)for(const assigned of slot.assignedNodes({flatten:!0}))this.observeLabelNode(assigned)}}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.bindLabelObserverTargets(),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>
@@ -104,8 +104,9 @@ export type RubricKey=ScoreRubricKey|CategoryRubricKey|CommentRubricKey;export t
104
104
  * `type`.
105
105
  * @cssstate invalid - Matches while it does not — including a pristine rubric with unanswered
106
106
  * required keys, exactly like native `:invalid`.
107
- * @cssstate user-valid - `valid`, but only after the user has interacted (visited a field, or been
108
- * through a `reportValidity()`/Submit attempt, which reveals every outstanding error).
107
+ * @cssstate user-valid - `valid`, but only after the user has interacted: visited a field, been
108
+ * through a `reportValidity()`/Submit attempt (which reveals every outstanding error), or a
109
+ * form submission attempt. Not after a silent `checkValidity()` alone.
109
110
  * @cssstate user-invalid - `invalid`, but only after that same interaction — a rubric nobody has
110
111
  * touched yet is invalid without being styled as an error.
111
112
  * @status stable
@@ -121,7 +122,7 @@ errorText:string;
121
122
  /** SSR label-presence hint; hydrated instances also discover populated slots. */
122
123
  withLabel:boolean;
123
124
  /** SSR hint-presence hint; hydrated instances also discover populated hint/help-text slots. */
124
- withHint:boolean;private _errors;private touchedFields;private hasLabelSlot;private hasHintSlot;private hasErrorSlot;private internals;private validityController;
125
+ withHint:boolean;private _errors;private touchedFields;private hasLabelSlot;private hasHintSlot;private hasErrorSlot;private aggregateLabelSlotEl?;private aggregateHintSlotEl?;private aggregateErrorSlotEl?;private internals;private validityController;
125
126
  /** Consumer-supplied validation message reflected through `custom-error`. */
126
127
  customError:string|null;private baseId;private aggregateLabelId;private aggregateHintId;private aggregateErrorId;private _fieldsetDisabled;private _name;private _keys;private _value;private _defaultValue;private _rawValue;private _rawDefaultValue;private _valueDirty;private _itemId;private _hasNext;private _skippable;private _disabled;private lastValidityKey;private pendingFocusFirst;constructor();
127
128
  /** `attachInternals()` throws in any environment without a real `ElementInternals`
@@ -162,7 +163,7 @@ private get barredFromValidation();
162
163
  * `touchedFields` being non-empty: any field visited, or a `reportValidity()`/submit attempt,
163
164
  * which reveals every outstanding error at once.
164
165
  */
165
- private syncCustomStates;
166
+ private syncCustomStates;private markInteracted;
166
167
  /** Resynchronizes validity without revealing inline errors. */
167
168
  checkValidity():boolean;
168
169
  /**
@@ -187,7 +188,16 @@ reportValidity():boolean;
187
188
  * The message is form-level and is exposed as `errors.base`, keyed to this control's `base`
188
189
  * part. It is caller-supplied content, so it is used verbatim and never localized here.
189
190
  */
190
- setCustomValidity(message:string):void;formResetCallback():void;formStateRestoreCallback(state:string|File|FormData|null,_mode?:'restore'|'autocomplete'):void;formDisabledCallback(disabled:boolean):void;private onFormKeyDown;private setFieldValue;private stopChildEvent;private onAggregateSlotChange;private markTouched;private submit;private skip;private focusFirstControl;
191
+ setCustomValidity(message:string):void;formResetCallback():void;formStateRestoreCallback(state:string|File|FormData|null,_mode?:'restore'|'autocomplete'):void;formDisabledCallback(disabled:boolean):void;private onFormKeyDown;private setFieldValue;private stopChildEvent;private onAggregateSlotChange;
192
+ /**
193
+ * Reads one aggregate label/hint/error slot's currently assigned content and applies it --
194
+ * wired as the `slotchange` handler (via `onAggregateSlotChange`) for every later mutation, and
195
+ * called once more from `firstUpdated()` (see `collectInitialSlotAssignment`) to cover an
196
+ * environment, or a real-browser timing race, where the slot's initial assignment never fires
197
+ * `slotchange`. Idempotent: re-deriving the same boolean from the same assigned-node set
198
+ * produces the same result on a second call.
199
+ */
200
+ private applyAggregateSlotAssignment;private markTouched;private submit;private skip;private focusFirstControl;
191
201
  /** Forwards host clicks to the first rendered field, so programmatic and `<label>`-driven
192
202
  * interactions target the active rubric field. */
193
- click():void;private externalDescriptionLease?;private syncExternalDescription;private releaseExternalDescription;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected updated(changed:PropertyValues):void;private renderScoreControl;private renderCategoryControl;private renderCommentControl;private renderField;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-rubric-form':LyraRubricForm;}}export{};
203
+ click():void;private externalDescriptionLease?;private syncExternalDescription;private releaseExternalDescription;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected firstUpdated(changed:PropertyValues):void;protected updated(changed:PropertyValues):void;private renderScoreControl;private renderCategoryControl;private renderCommentControl;private renderField;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-rubric-form':LyraRubricForm;}}export{};
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.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,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.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";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");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;options.push(Object.freeze({value:optionValue.value,...labelValue===void 0?{}:{label:labelValue},...descriptionValue===void 0?{}:{description:descriptionValue}}))}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 LyraElement{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,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}}}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._errors={},this.touchedFields=new Set,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,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.onFormKeyDown=e=>{e.key==="Enter"&&(e.ctrlKey||e.metaKey)&&(e.preventDefault(),this.submit())},this.stopChildEvent=event=>{event.stopPropagation()},this.onAggregateSlotChange=event=>{const slot=event.target,populated=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||!!node.textContent?.trim());slot.name==="label"?this.hasLabelSlot=populated:slot.name==="hint"?this.hasHintSlot=populated:slot.name==="error"&&(this.hasErrorSlot=populated)},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.addEventListener("keydown",this.onFormKeyDown),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get keys(){return this._keys}set keys(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){this.setLiveValue(next,!0)}get defaultValue(){return cloneRubricValue(this._defaultValue)}set defaultValue(next){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??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("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.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.syncFormState(),this.internals.checkValidity()}reportValidity(){return 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){this._fieldsetDisabled=disabled,this.syncFormState(),this.requestUpdate()}setFieldValue(key,val){this.effectiveDisabled||(this.value={...this._value,[key]:val},this.emit("lr-input",Object.freeze({value:cloneRubricValue(this._value)})))}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(){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():firstKey.type==="score"?control.shadowRoot?.querySelector('[part="thumb"]')?.focus():firstKey.type==="category"&&firstKey.multiple?control.querySelector("lr-checkbox")?.focus():control.focus())}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
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{nextId}from"../../../internal/a11y.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./rubric-form.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,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.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";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");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;options.push(Object.freeze({value:optionValue.value,...labelValue===void 0?{}:{label:labelValue},...descriptionValue===void 0?{}:{description:descriptionValue}}))}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 LyraElement{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,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}}}constructor(){super(),this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this._errors={},this.touchedFields=new Set,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,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.stopChildEvent=event=>{event.stopPropagation()},this.onAggregateSlotChange=event=>{this.applyAggregateSlotAssignment(event.target)},this.internals=this.safeAttachInternals(),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),installInteractionOnInvalid(this,this.markInteracted),this.addEventListener("keydown",this.onFormKeyDown),this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals>"u")return this.inertInternals();try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:!1,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>!0,reportValidity:()=>!0,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get keys(){return this._keys}set keys(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){this.setLiveValue(next,!0)}get defaultValue(){return cloneRubricValue(this._defaultValue)}set defaultValue(next){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??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("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.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.syncFormState(),withStaticValidityCheck(this,()=>this.internals.checkValidity())}reportValidity(){return 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){this._fieldsetDisabled=disabled,this.syncFormState(),this.requestUpdate()}setFieldValue(key,val){this.effectiveDisabled||(this.value={...this._value,[key]:val},this.emit("lr-input",Object.freeze({value:cloneRubricValue(this._value)})))}applyAggregateSlotAssignment(slot){const populated=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||!!node.textContent?.trim());slot.name==="label"?this.hasLabelSlot=populated:slot.name==="hint"?this.hasHintSlot=populated:slot.name==="error"&&(this.hasErrorSlot=populated)}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(){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():firstKey.type==="score"?control.shadowRoot?.querySelector('[part="thumb"]')?.focus():firstKey.type==="category"&&firstKey.multiple?control.querySelector("lr-checkbox")?.focus():control.focus())}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()}firstUpdated(changed){super.firstUpdated(changed);const labelSlot=this.aggregateLabelSlotEl,hintSlot=this.aggregateHintSlotEl,errorSlot=this.aggregateErrorSlotEl;queueMicrotask(()=>{collectInitialSlotAssignment(labelSlot,slot=>this.applyAggregateSlotAssignment(slot)),collectInitialSlotAssignment(hintSlot,slot=>this.applyAggregateSlotAssignment(slot)),collectInitialSlotAssignment(errorSlot,slot=>this.applyAggregateSlotAssignment(slot))})}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"
@@ -131,4 +131,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
131
131
  </button>
132
132
  </div>`:nothing}
133
133
  </div>
134
- `}}__decorate([property()],LyraRubricForm.prototype,"label",void 0),__decorate([property()],LyraRubricForm.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraRubricForm.prototype,"errorText",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraRubricForm.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraRubricForm.prototype,"withHint",void 0),__decorate([state()],LyraRubricForm.prototype,"_errors",void 0),__decorate([state()],LyraRubricForm.prototype,"touchedFields",void 0),__decorate([state()],LyraRubricForm.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraRubricForm.prototype,"hasHintSlot",void 0),__decorate([state()],LyraRubricForm.prototype,"hasErrorSlot",void 0);export{LyraRubricForm};
134
+ `}}__decorate([property()],LyraRubricForm.prototype,"label",void 0),__decorate([property()],LyraRubricForm.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraRubricForm.prototype,"errorText",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraRubricForm.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraRubricForm.prototype,"withHint",void 0),__decorate([state()],LyraRubricForm.prototype,"_errors",void 0),__decorate([state()],LyraRubricForm.prototype,"touchedFields",void 0),__decorate([state()],LyraRubricForm.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraRubricForm.prototype,"hasHintSlot",void 0),__decorate([state()],LyraRubricForm.prototype,"hasErrorSlot",void 0),__decorate([query('slot[name="label"]')],LyraRubricForm.prototype,"aggregateLabelSlotEl",void 0),__decorate([query('slot[name="hint"]')],LyraRubricForm.prototype,"aggregateHintSlotEl",void 0),__decorate([query('slot[name="error"]')],LyraRubricForm.prototype,"aggregateErrorSlotEl",void 0);export{LyraRubricForm};