@aceshooting/lyra-ui 8.2.0 → 8.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  3. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  4. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  5. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  6. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  7. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  8. package/dist/components/forms/combobox/combobox.class.js +1 -1
  9. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  10. package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
  11. package/dist/components/forms/input/input.class.js +1 -1
  12. package/dist/components/forms/input/time-input.class.js +1 -1
  13. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  14. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  15. package/dist/components/forms/phone-input/phone-input.class.js +1 -1
  16. package/dist/components/forms/select/select.class.js +1 -1
  17. package/dist/components/forms/switch/switch.class.js +1 -1
  18. package/dist/components/forms/textarea/textarea.class.js +1 -1
  19. package/dist/components/forms/token-input/token-input.class.js +1 -1
  20. package/dist/components/media/file-input/file-input.class.js +1 -1
  21. package/dist/components/utility/known-date/known-date.class.js +1 -1
  22. package/dist/internal/form-associated.js +1 -1
  23. package/dist/internal/localization-runtime.d.ts +13 -0
  24. package/dist/internal/localization-runtime.js +1 -1
  25. package/dist/internal/lyra-element.d.ts +15 -0
  26. package/dist/internal/lyra-element.js +1 -1
  27. package/dist/internal/package-metadata.d.ts +1 -1
  28. package/dist/internal/package-metadata.js +1 -1
  29. package/dist/testing/happy-dom-shims.d.ts +1 -1
  30. package/dist/testing/happy-dom-shims.js +1 -1
  31. package/package.json +2 -2
  32. package/web-types.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # Changelog
2
2
 
3
+ ## 8.2.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 6c00bbc: Fix `<lr-chat-composer>` marking a field touched from a blur the platform forces when the control becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
8
+ - 3a942eb: Fix `<lr-checkbox>` marking a field touched/interacted from a blur the platform forces when the control (or an ancestor `<fieldset>`) becomes disabled while it is focused, which could leave the control primed to show as invalid immediately on re-enable, or trip a Lit dev-mode reentrancy warning.
9
+ - 842484a: Fix `<lr-model-select>` marking a field touched from a blur the platform forces when the trigger button or combobox input becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
10
+ - 9c69ed7: Fix `<lr-textarea>` marking a field touched from a blur the platform forces when the control becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
11
+ - 9476967: Fix `<lr-time-input>` marking a segment touched from a blur the platform forces when the focused segment becomes disabled (its tabindex drops below zero while it still holds focus), which could trip a Lit dev-mode reentrancy warning.
12
+ - 823b395: `@aceshooting/lyra-ui/testing`'s `installHappyDomFormAssociatedShims()` now resolves the stub `ElementInternals.form` live via `host.closest('form')` instead of always `null` — a form-associated component that calls `attachInternals()` from its constructor (before it's inserted anywhere) previously got a permanently-`null` form owner even after being placed inside a real `<form>`, silently breaking anything (like `<lr-button>`) that resolves its submit target through `internals.form`.
13
+ - de626e7: Fix `<lr-input>` marking a field touched from a blur the platform forces when the control becomes disabled while focused (fr_asxOgk4UhNB07xevCWwFVQ), and stop `formDisabledCallback()` redoing validity/render work that a same-tick `disabled` write already performed — together these could trip Lit's dev-mode "scheduled an update after an update completed" warning inside a real `<lr-dialog>` for a re-render nothing observable needed.
14
+ - 340d39b: Fix `<lr-known-date>` marking a field touched from a blur the platform forces when the field becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
15
+ - db19f3e: `LyraElement`'s ancestor `class`/`style` observer (kept for CSS-only direction/locale context changes) now only calls `requestUpdate()` when the resolved direction or locale actually changes, instead of on every ancestor `class`/`style` mutation regardless of relevance — an unrelated ancestor style write (e.g. an overlay's own stacking-index custom property) could otherwise schedule a spurious re-render.
16
+ - 6ef43b1: Fix `LyraElement`'s ancestor `class`/`style` observer (introduced in the previous release to stop spurious re-renders) forcing a `getComputedStyle()` read on _every_ ancestor `class`/`style`/`locale`/`lang` mutation, even ones with nothing to do with direction. That forced read — from a sibling's own unrelated `MutationObserver` reacting to an ancestor's inline-style write — could permanently break a completely unrelated host's own shadow-DOM CSS custom-property resolution in Chromium (observed with `<lr-chip-group>`'s `--lr-chip-group-overflow-expanded-color`), and forced an extra synchronous style read on every reconnect/adoption regardless of whether anything direction-relevant changed. The observer now only calls `getComputedStyle()` when the mutation could plausibly affect direction (an explicit `dir`/`class` change, or a `style` change that actually declares `direction`), and seeds its baseline from whatever the host's own render already resolved instead of forcing an extra read at connect time.
17
+ - 0eb1de0: Fix `<lr-token-input>` marking a field touched (and committing a pending draft) from a blur the platform forces when the control becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
18
+ - e849075: Fix `<lr-code-editor>` marking a field touched from a blur the platform forces when the control becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
19
+ - f4b8304: Fix `<lr-phone-input>` marking a field touched from a blur the platform forces when the control becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
20
+ - a9cd82e: Fix `<lr-file-input>` marking its dropzone touched from a blur the platform forces when the focused `[part="base"]` button becomes disabled, which could trip a Lit dev-mode reentrancy warning.
21
+ - 9c35472: Fix `<lr-emoji-picker>` marking a field touched from a blur the platform forces when the control becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
22
+ - 5b96432: Fix `<lr-checkbox-group>` marking the group touched from a blur the platform forces when a focused child `<lr-checkbox>` becomes disabled -- either directly or via an ancestor `<fieldset disabled>` cascading down -- which could trip a Lit dev-mode reentrancy warning.
23
+ - 3d5b695: Fix `<lr-date-input>` marking the field touched from a blur the platform forces when the internal date text input becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
24
+ - 8e1eb54: Fix `<lr-otp-input>` marking a field touched from a blur the platform forces when the control becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
25
+ - 530c30b: Fix `<lr-voice-picker>` marking a field touched from a blur the platform forces when the trigger button or free-text combobox input becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
26
+ - 614ee6a: Fix `<lr-switch>` marking a field touched from a blur the browser forces when the control (a form-associated custom element) becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning and could flash `user-invalid` styling on a later re-enable for an interaction the user never had.
27
+ - 6149517: Fix `<lr-select>` marking a field touched from a blur the platform forces when the trigger becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
28
+ - 1c58af5: Fix `<lr-combobox>` marking its field touched from a blur the platform forces when the internal input becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
29
+ - aa345d8: Fix `<lr-locale-picker>` marking a field touched from a blur the platform forces when the control becomes disabled while focused, which could trip a Lit dev-mode reentrancy warning.
30
+
3
31
  ## 8.2.0
4
32
 
5
33
  ### Minor Changes
@@ -21,7 +21,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
21
21
  aria-hidden="true"
22
22
  focusable="false"
23
23
  ><rect x="6" y="6" width="12" height="12" rx="1.5"></rect></svg>
24
- `}class LyraChatComposerBase extends LyraElement{}class LyraChatComposer extends FormAssociated(LyraChatComposerBase){static{this.defaultStrings={...super.defaultStrings,composerLabel:LYRA_DEFAULT_composerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,restore:LYRA_DEFAULT_restore,sendMessage:LYRA_DEFAULT_sendMessage,stopGenerating:LYRA_DEFAULT_stopGenerating}}static{this.styles=[LyraElement.styles,styles]}get effectiveMinRows(){return finiteInteger(this.minRows,1,1)}get effectiveMaxRows(){return Math.max(this.effectiveMinRows,finiteInteger(this.maxRows,this.effectiveMinRows,1))}constructor(){super();this.placeholder="";this.minRows=1;this.maxRows=8;this.status="idle";this.frame="card";this.submitOnEnter=true;this.submitDisabled=false;this.stoppable=true;this.accessibleLabel=null;this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.wrap="soft";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.hasLeadingSlot=false;this.hasChipsSlot=false;this.hasTrailingSlot=false;this.touched=false;this.textareaResizeGeneration=0;this.onTextareaInput=e=>{this.value=e.target.value;this.emit("lr-input",{value:this.value})};this.onTextareaKeyDown=e=>{if(e.key!=="Enter")return;if(e.shiftKey)return;if(!this.submitOnEnter)return;if(e.isComposing||e.keyCode===229)return;if(this.status!=="idle")return;e.preventDefault();this.submit()};this.onActionClick=()=>{if(this.effectiveDisabled)return;if(this.status==="idle"){this.submit()}else if(this.stoppable){this.emit("lr-stop")}};this.onLeadingSlotChange=e=>{this.hasLeadingSlot=e.target.assignedElements({flatten:true}).length>0};this.onChipsSlotChange=e=>{this.hasChipsSlot=e.target.assignedElements({flatten:true}).length>0};this.onTrailingSlotChange=e=>{this.hasTrailingSlot=e.target.assignedElements({flatten:true}).length>0};this.onTextareaBlur=()=>{this.touched=true;this.emit("blur")};this.onTextareaFocus=()=>{this.emit("focus")};this.addEventListener("invalid",()=>{this.touched=true})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){if(this.textareaEl)this.textareaEl.selectionStart=value??0}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){if(this.textareaEl)this.textareaEl.selectionEnd=value??0}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){if(this.textareaEl)this.textareaEl.selectionDirection=value??"none"}focus(options){this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}click(){if(!this.effectiveDisabled)this.textareaEl?.focus()}select(){this.textareaEl?.select()}setSelectionRange(start,end,direction){this.textareaEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const textarea=this.textareaEl;if(!textarea)return;if(start===void 0||end===void 0){textarea.setRangeText(replacement)}else{textarea.setRangeText(replacement,start,end,selectMode)}this.value=textarea.value;this.resizeTextarea()}willUpdate(changed){super.willUpdate(changed);this.seedFirstRenderState(()=>{this.hasLeadingSlot=this.hasSlotted("leading");this.hasChipsSlot=this.hasSlotted("chips");this.hasTrailingSlot=this.hasSlotted("trailing")})}firstUpdated(changed){super.firstUpdated(changed);this.resizeTextarea();this.armTextareaResizeObserver()}connectedCallback(){super.connectedCallback();if(this.hasUpdated){this.armTextareaResizeObserver();this.resizeTextarea()}}disconnectedCallback(){super.disconnectedCallback();this.resetTextareaResizeWork()}adoptedCallback(){this.resetTextareaResizeWork()}updated(changed){super.updated(changed);if(changed.has("value")||changed.has("minRows")||changed.has("maxRows")){this.resizeTextarea()}}formResetCallback(){super.formResetCallback();this.touched=false}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}resizeTextarea(){const ta=this.textareaEl;if(!ta)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(ta)??ta.style;const lineHeight=parseFloat(cs.lineHeight)||parseFloat(cs.fontSize)*1.2;const paddingBlock=parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom);const borderBlock=parseFloat(cs.borderTopWidth)+parseFloat(cs.borderBottomWidth);const minRows=this.effectiveMinRows;const maxRows=this.effectiveMaxRows;const minHeight=lineHeight*minRows+paddingBlock+borderBlock;const maxHeight=lineHeight*maxRows+paddingBlock+borderBlock;ta.style.height="auto";const contentHeight=ta.scrollHeight+borderBlock;const next=Math.min(Math.max(contentHeight,minHeight),maxHeight);ta.style.height=`${next}px`;ta.style.overflowY=contentHeight>maxHeight?"auto":"hidden"}armTextareaResizeObserver(){const ta=this.textareaEl;const ownerDocument=this.ownerDocument;const ownerWindow=ownerDocument.defaultView;if(!ta||!this.isConnected||!ownerWindow?.ResizeObserver)return;if(this.textareaResizeObserver&&this.textareaResizeObserverDocument===ownerDocument&&this.textareaResizeObserverTarget===ta){return}this.resetTextareaResizeWork();const generation=this.textareaResizeGeneration;let lastWidth=ta.getBoundingClientRect().width;const observer=new ownerWindow.ResizeObserver(entries=>{if(this.textareaResizeObserver!==observer||this.textareaResizeObserverDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}const box=entries[0]?.contentBoxSize?.[0];const width=box?box.inlineSize:entries[0]?.contentRect.width??lastWidth;if(Math.abs(width-lastWidth)<.5)return;lastWidth=width;if(this.textareaResizeRaf!==void 0){this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf)}const handle=ownerWindow.requestAnimationFrame(()=>{if(this.textareaResizeRaf!==handle||this.textareaResizeRafOwner!==ownerWindow||this.textareaResizeRafDocument!==ownerDocument||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta){return}this.textareaResizeRaf=void 0;this.textareaResizeRafOwner=void 0;this.textareaResizeRafDocument=void 0;this.resizeTextarea()});this.textareaResizeRaf=handle;this.textareaResizeRafOwner=ownerWindow;this.textareaResizeRafDocument=ownerDocument});this.textareaResizeObserver=observer;this.textareaResizeObserverDocument=ownerDocument;this.textareaResizeObserverTarget=ta;observer.observe(ta)}resetTextareaResizeWork(){this.textareaResizeGeneration+=1;this.textareaResizeObserver?.disconnect();this.textareaResizeObserver=void 0;this.textareaResizeObserverDocument=void 0;this.textareaResizeObserverTarget=void 0;if(this.textareaResizeRaf!==void 0){this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf)}this.textareaResizeRaf=void 0;this.textareaResizeRafOwner=void 0;this.textareaResizeRafDocument=void 0}submit(){if(this.submitDisabled||this.effectiveDisabled||this.status!=="idle")return;this.emit("lr-submit",{value:this.value})}renderActionButton(){const busy=this.status!=="idle";const showStop=busy&&this.stoppable;return html`
24
+ `}class LyraChatComposerBase extends LyraElement{}class LyraChatComposer extends FormAssociated(LyraChatComposerBase){static{this.defaultStrings={...super.defaultStrings,composerLabel:LYRA_DEFAULT_composerLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,restore:LYRA_DEFAULT_restore,sendMessage:LYRA_DEFAULT_sendMessage,stopGenerating:LYRA_DEFAULT_stopGenerating}}static{this.styles=[LyraElement.styles,styles]}get effectiveMinRows(){return finiteInteger(this.minRows,1,1)}get effectiveMaxRows(){return Math.max(this.effectiveMinRows,finiteInteger(this.maxRows,this.effectiveMinRows,1))}constructor(){super();this.placeholder="";this.minRows=1;this.maxRows=8;this.status="idle";this.frame="card";this.submitOnEnter=true;this.submitDisabled=false;this.stoppable=true;this.accessibleLabel=null;this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.wrap="soft";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.hasLeadingSlot=false;this.hasChipsSlot=false;this.hasTrailingSlot=false;this.touched=false;this.textareaResizeGeneration=0;this.onTextareaInput=e=>{this.value=e.target.value;this.emit("lr-input",{value:this.value})};this.onTextareaKeyDown=e=>{if(e.key!=="Enter")return;if(e.shiftKey)return;if(!this.submitOnEnter)return;if(e.isComposing||e.keyCode===229)return;if(this.status!=="idle")return;e.preventDefault();this.submit()};this.onActionClick=()=>{if(this.effectiveDisabled)return;if(this.status==="idle"){this.submit()}else if(this.stoppable){this.emit("lr-stop")}};this.onLeadingSlotChange=e=>{this.hasLeadingSlot=e.target.assignedElements({flatten:true}).length>0};this.onChipsSlotChange=e=>{this.hasChipsSlot=e.target.assignedElements({flatten:true}).length>0};this.onTrailingSlotChange=e=>{this.hasTrailingSlot=e.target.assignedElements({flatten:true}).length>0};this.onTextareaBlur=()=>{if(!this.effectiveDisabled)this.touched=true;this.emit("blur")};this.onTextareaFocus=()=>{this.emit("focus")};this.addEventListener("invalid",()=>{this.touched=true})}get input(){return this.textareaEl??null}get selectionStart(){return this.textareaEl?.selectionStart??null}set selectionStart(value){if(this.textareaEl)this.textareaEl.selectionStart=value??0}get selectionEnd(){return this.textareaEl?.selectionEnd??null}set selectionEnd(value){if(this.textareaEl)this.textareaEl.selectionEnd=value??0}get selectionDirection(){return this.textareaEl?.selectionDirection}set selectionDirection(value){if(this.textareaEl)this.textareaEl.selectionDirection=value??"none"}focus(options){this.textareaEl?.focus(options)}blur(){this.textareaEl?.blur()}click(){if(!this.effectiveDisabled)this.textareaEl?.focus()}select(){this.textareaEl?.select()}setSelectionRange(start,end,direction){this.textareaEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const textarea=this.textareaEl;if(!textarea)return;if(start===void 0||end===void 0){textarea.setRangeText(replacement)}else{textarea.setRangeText(replacement,start,end,selectMode)}this.value=textarea.value;this.resizeTextarea()}willUpdate(changed){super.willUpdate(changed);this.seedFirstRenderState(()=>{this.hasLeadingSlot=this.hasSlotted("leading");this.hasChipsSlot=this.hasSlotted("chips");this.hasTrailingSlot=this.hasSlotted("trailing")})}firstUpdated(changed){super.firstUpdated(changed);this.resizeTextarea();this.armTextareaResizeObserver()}connectedCallback(){super.connectedCallback();if(this.hasUpdated){this.armTextareaResizeObserver();this.resizeTextarea()}}disconnectedCallback(){super.disconnectedCallback();this.resetTextareaResizeWork()}adoptedCallback(){this.resetTextareaResizeWork()}updated(changed){super.updated(changed);if(changed.has("value")||changed.has("minRows")||changed.has("maxRows")){this.resizeTextarea()}}formResetCallback(){super.formResetCallback();this.touched=false}hasSlotted(name){return Array.from(this.children).some(el=>el.getAttribute("slot")===name)}resizeTextarea(){const ta=this.textareaEl;if(!ta)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(ta)??ta.style;const lineHeight=parseFloat(cs.lineHeight)||parseFloat(cs.fontSize)*1.2;const paddingBlock=parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom);const borderBlock=parseFloat(cs.borderTopWidth)+parseFloat(cs.borderBottomWidth);const minRows=this.effectiveMinRows;const maxRows=this.effectiveMaxRows;const minHeight=lineHeight*minRows+paddingBlock+borderBlock;const maxHeight=lineHeight*maxRows+paddingBlock+borderBlock;ta.style.height="auto";const contentHeight=ta.scrollHeight+borderBlock;const next=Math.min(Math.max(contentHeight,minHeight),maxHeight);ta.style.height=`${next}px`;ta.style.overflowY=contentHeight>maxHeight?"auto":"hidden"}armTextareaResizeObserver(){const ta=this.textareaEl;const ownerDocument=this.ownerDocument;const ownerWindow=ownerDocument.defaultView;if(!ta||!this.isConnected||!ownerWindow?.ResizeObserver)return;if(this.textareaResizeObserver&&this.textareaResizeObserverDocument===ownerDocument&&this.textareaResizeObserverTarget===ta){return}this.resetTextareaResizeWork();const generation=this.textareaResizeGeneration;let lastWidth=ta.getBoundingClientRect().width;const observer=new ownerWindow.ResizeObserver(entries=>{if(this.textareaResizeObserver!==observer||this.textareaResizeObserverDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}const box=entries[0]?.contentBoxSize?.[0];const width=box?box.inlineSize:entries[0]?.contentRect.width??lastWidth;if(Math.abs(width-lastWidth)<.5)return;lastWidth=width;if(this.textareaResizeRaf!==void 0){this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf)}const handle=ownerWindow.requestAnimationFrame(()=>{if(this.textareaResizeRaf!==handle||this.textareaResizeRafOwner!==ownerWindow||this.textareaResizeRafDocument!==ownerDocument||this.textareaResizeGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.textareaResizeObserverTarget!==ta){return}this.textareaResizeRaf=void 0;this.textareaResizeRafOwner=void 0;this.textareaResizeRafDocument=void 0;this.resizeTextarea()});this.textareaResizeRaf=handle;this.textareaResizeRafOwner=ownerWindow;this.textareaResizeRafDocument=ownerDocument});this.textareaResizeObserver=observer;this.textareaResizeObserverDocument=ownerDocument;this.textareaResizeObserverTarget=ta;observer.observe(ta)}resetTextareaResizeWork(){this.textareaResizeGeneration+=1;this.textareaResizeObserver?.disconnect();this.textareaResizeObserver=void 0;this.textareaResizeObserverDocument=void 0;this.textareaResizeObserverTarget=void 0;if(this.textareaResizeRaf!==void 0){this.textareaResizeRafOwner?.cancelAnimationFrame(this.textareaResizeRaf)}this.textareaResizeRaf=void 0;this.textareaResizeRafOwner=void 0;this.textareaResizeRafDocument=void 0}submit(){if(this.submitDisabled||this.effectiveDisabled||this.status!=="idle")return;this.emit("lr-submit",{value:this.value})}renderActionButton(){const busy=this.status!=="idle";const showStop=busy&&this.stoppable;return html`
25
25
  <button
26
26
  part="action-button"
27
27
  type="button"
@@ -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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{AnchoredPopoverController}from"../../../internal/anchored-popover-controller.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./model-select.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue}from"../../../internal/catalog-picker.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_model,LYRA_DEFAULT_modelSelectNoModels,LYRA_DEFAULT_modelSelectRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraModelSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,model:LYRA_DEFAULT_model,modelSelectNoModels:LYRA_DEFAULT_modelSelectNoModels,modelSelectRequired:LYRA_DEFAULT_modelSelectRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.provider="";this.allowCustom=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.open=false;this.size="m";this.activeIndex=-1;this.query="";this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.listId=nextId("model-select-list");this.controlId=nextId("model-select-control");this.popupPosition=new AnchoredPopoverController;this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this.suppressControlBlur=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{if(this.suppressControlBlur){event.stopImmediatePropagation();return}this.touched=true;this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onTriggerFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onTriggerKeyDown=e=>{const rows=this.effectiveEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=rows[this.activeIndex];if(this.activeIndex>=0&&active){this.selectEntry(active)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus()};this.onInputFocus=event=>{if(!this.open)this.query=this.labelFor(this.value);this.show();relayNativeEvent(this,event);this.emit("lr-focus")};this.onInput=e=>{this.query=e.target.value;this.activeIndex=-1;this.show();relayNativeEvent(this,e)};this.onInputBlur=event=>{if(this.suppressControlBlur){event.stopImmediatePropagation();return}this.touched=true;this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onInputKeyDown=e=>{const rows=this.filteredEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":if(this.open){e.preventDefault();this.commitFreeText()}break;case"Escape":if(this.open){e.preventDefault();this.query=this.labelFor(this.value);this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const entry=(this.closedMode?this.effectiveEntries:this.filteredEntries).find(e2=>e2.id===value);if(entry)this.selectEntry(entry)};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals.setFormValue("")}click(){if(this.effectiveDisabled)return;const trigger=this.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}const input=this.renderRoot?.querySelector('[part="combobox-input"]');input?.click();input?.focus()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}willUpdate(changed){let modeChanged=false;if(this.hasUpdated){const renderedClosedMode=this.renderRoot.querySelector('[part="trigger"]')!==null;modeChanged=renderedClosedMode!==this.closedMode;this.suppressControlBlur=modeChanged}if(this.open&&(changed.has("catalog")||changed.has("value")||changed.has("allowCustom"))){this.activeIndex=-1;if(changed.has("value")||changed.has("allowCustom")||modeChanged){this.query=this.labelFor(this._value)}}if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}disconnectedCallback(){super.disconnectedCallback();this.popupPosition.disconnect();this.unbindDocumentPointer();this.open=false}adoptedCallback(){this.popupPosition.disconnect();this.unbindDocumentPointer()}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("modelSelectRequired"))}else{this.validityController.setValidity({})}this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishValidityStates()}get normalizedCatalog(){return normalizeCatalog(this.catalog)}get closedMode(){return this.normalizedCatalog.length>0&&!this.allowCustom}get effectiveEntries(){return withSyntheticCatalogValue(this.normalizedCatalog,this._value)}get filteredEntries(){return filterCatalogEntries(this.effectiveEntries,this.query,this.effectiveLocale,entry=>[entry.id,entry.label])}labelFor(id){if(!id)return"";return this.effectiveEntries.find(e=>e.id===id)?.label??id}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.popupPosition.disconnect();if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.popupPosition.reposition(anchor,listbox)}updated(changed){const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));if(reposition){this.syncPopup()}if(changed.has("required")||changed.has("touched")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}this.publishValidityStates();this.suppressControlBlur=false}commitValue(next){const inCatalog=this.normalizedCatalog.some(e=>e.id===next);this.value=next;this.hide();this.emit("lr-change",{value:next,inCatalog});this.emitValueEvents()}emitValueEvents(){dispatchNativeEvent(this,"input");dispatchNativeEvent(this,"change")}selectEntry(entry){this.commitValue(entry.id)}commitFreeText(){const rows=this.filteredEntries;const active=rows[this.activeIndex];if(this.activeIndex>=0&&active){this.commitValue(active.id);return}this.commitValue(this.query.trim())}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.id===this._value;return html`<div
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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{AnchoredPopoverController}from"../../../internal/anchored-popover-controller.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./model-select.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue}from"../../../internal/catalog-picker.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_model,LYRA_DEFAULT_modelSelectNoModels,LYRA_DEFAULT_modelSelectRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraModelSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,model:LYRA_DEFAULT_model,modelSelectNoModels:LYRA_DEFAULT_modelSelectNoModels,modelSelectRequired:LYRA_DEFAULT_modelSelectRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.provider="";this.allowCustom=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.open=false;this.size="m";this.activeIndex=-1;this.query="";this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.listId=nextId("model-select-list");this.controlId=nextId("model-select-control");this.popupPosition=new AnchoredPopoverController;this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this.suppressControlBlur=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{if(this.suppressControlBlur){event.stopImmediatePropagation();return}if(!this.effectiveDisabled)this.touched=true;this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onTriggerFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onTriggerKeyDown=e=>{const rows=this.effectiveEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=rows[this.activeIndex];if(this.activeIndex>=0&&active){this.selectEntry(active)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus()};this.onInputFocus=event=>{if(!this.open)this.query=this.labelFor(this.value);this.show();relayNativeEvent(this,event);this.emit("lr-focus")};this.onInput=e=>{this.query=e.target.value;this.activeIndex=-1;this.show();relayNativeEvent(this,e)};this.onInputBlur=event=>{if(this.suppressControlBlur){event.stopImmediatePropagation();return}if(!this.effectiveDisabled)this.touched=true;this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onInputKeyDown=e=>{const rows=this.filteredEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":if(this.open){e.preventDefault();this.commitFreeText()}break;case"Escape":if(this.open){e.preventDefault();this.query=this.labelFor(this.value);this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const entry=(this.closedMode?this.effectiveEntries:this.filteredEntries).find(e2=>e2.id===value);if(entry)this.selectEntry(entry)};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals.setFormValue("")}click(){if(this.effectiveDisabled)return;const trigger=this.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}const input=this.renderRoot?.querySelector('[part="combobox-input"]');input?.click();input?.focus()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}willUpdate(changed){let modeChanged=false;if(this.hasUpdated){const renderedClosedMode=this.renderRoot.querySelector('[part="trigger"]')!==null;modeChanged=renderedClosedMode!==this.closedMode;this.suppressControlBlur=modeChanged}if(this.open&&(changed.has("catalog")||changed.has("value")||changed.has("allowCustom"))){this.activeIndex=-1;if(changed.has("value")||changed.has("allowCustom")||modeChanged){this.query=this.labelFor(this._value)}}if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}disconnectedCallback(){super.disconnectedCallback();this.popupPosition.disconnect();this.unbindDocumentPointer();this.open=false}adoptedCallback(){this.popupPosition.disconnect();this.unbindDocumentPointer()}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("modelSelectRequired"))}else{this.validityController.setValidity({})}this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishValidityStates()}get normalizedCatalog(){return normalizeCatalog(this.catalog)}get closedMode(){return this.normalizedCatalog.length>0&&!this.allowCustom}get effectiveEntries(){return withSyntheticCatalogValue(this.normalizedCatalog,this._value)}get filteredEntries(){return filterCatalogEntries(this.effectiveEntries,this.query,this.effectiveLocale,entry=>[entry.id,entry.label])}labelFor(id){if(!id)return"";return this.effectiveEntries.find(e=>e.id===id)?.label??id}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.popupPosition.disconnect();if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.popupPosition.reposition(anchor,listbox)}updated(changed){const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));if(reposition){this.syncPopup()}if(changed.has("required")||changed.has("touched")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}this.publishValidityStates();this.suppressControlBlur=false}commitValue(next){const inCatalog=this.normalizedCatalog.some(e=>e.id===next);this.value=next;this.hide();this.emit("lr-change",{value:next,inCatalog});this.emitValueEvents()}emitValueEvents(){dispatchNativeEvent(this,"input");dispatchNativeEvent(this,"change")}selectEntry(entry){this.commitValue(entry.id)}commitFreeText(){const rows=this.filteredEntries;const active=rows[this.activeIndex];if(this.activeIndex>=0&&active){this.commitValue(active.id);return}this.commitValue(this.query.trim())}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.id===this._value;return html`<div
2
2
  part="option"
3
3
  id=${id}
4
4
  role="option"
@@ -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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredPopoverController}from"../../../internal/anchored-popover-controller.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,playIcon,pauseIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{trueDefaultBooleanConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue}from"../../../internal/catalog-picker.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings.generated.js";class LyraVoicePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.provider="";this.allowCustom=false;this.preview=true;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.open=false;this.activeIndex=-1;this.query="";this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.previewingId=null;this.listId=nextId("voice-picker-list");this.controlId=nextId("voice-picker-control");this.popupPosition=new AnchoredPopoverController;this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.suppressControlEvents=false;this.transferControlFocus=false;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onAudioEnded=event=>{if(event.currentTarget!==this.audioEl)return;this.stopInternalPreview()};this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio;const candidate=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget;const audioLike=candidate;const failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause==="function"&&typeof audioLike.removeEventListener==="function"?audioLike:void 0;if(!failedAudio)return;failedAudio.removeEventListener("ended",this.onAudioEnded);failedAudio.removeEventListener("error",this.onAudioLoadFailure);failedAudio.pause();if(failedAudio!==this.audioEl)return;this.audioEl=void 0;if(this.previewingId!==null){this.previewingId=null;this.emit("lr-preview-change",{voiceId:null})}};this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;if(!candidate)return;if(this.previewingId===candidate)this.stopInternalPreview();else this.requestPreview(candidate)};this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation();if(this.previewingId===entry.id)this.stopInternalPreview();else this.requestPreview(entry.id)};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=()=>{if(this.suppressControlEvents)return;this.touched=true;this.hide();this.emit("blur")};this.onTriggerFocus=()=>{if(!this.suppressControlEvents)this.emit("focus")};this.onTriggerKeyDown=e=>{const rows=this.effectiveEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow)this.selectEntry(activeRow);else this.hide()}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus()};this.onInputFocus=()=>{if(!this.open)this.query=this.labelFor(this.value);this.show();if(!this.suppressControlEvents)this.emit("focus")};this.onInput=e=>{this.query=e.target.value;this.activeIndex=-1;this.show()};this.onInputBlur=()=>{if(this.suppressControlEvents)return;this.touched=true;this.hide();this.emit("blur")};this.onInputKeyDown=e=>{const rows=this.filteredEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":if(this.open){e.preventDefault();this.commitFreeText()}break;case"Escape":if(this.open){e.preventDefault();this.query=this.labelFor(this.value);this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const entry=(this.closedMode?this.effectiveEntries:this.filteredEntries).find(e2=>e2.id===value);if(entry)this.selectEntry(entry)};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.internals=attachInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals.setFormValue("")}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}click(){const trigger=this.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}this.renderRoot?.querySelector('[part="combobox-input"]')?.focus()}focus(options){this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus(options)}blur(){this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.blur()}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}willUpdate(changed){if(this.hasUpdated){const renderedClosedMode=this.renderRoot.querySelector('[part="trigger"]')!==null;const switchingMode=renderedClosedMode!==this.closedMode;const focused=activeElementIn(this.shadowRoot??this.ownerDocument);this.suppressControlEvents=switchingMode;this.transferControlFocus=switchingMode&&focused?.nodeType===1&&focused.matches('[part="trigger"], [part="combobox-input"]')}if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}if(this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset["value"];const rows=this.closedMode?this.effectiveEntries:this.filteredEntries;const remapped=activeValue?rows.findIndex(entry=>entry.id===activeValue):-1;this.activeIndex=remapped>=0?remapped:Math.min(this.activeIndex,Math.max(-1,rows.length-1))}if(changed.has("preview")&&!this.preview)this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback();this.popupPosition.disconnect();this.unbindDocumentPointer();this.stopInternalPreview();this.open=false}adoptedCallback(){this.popupPosition.disconnect();this.unbindDocumentPointer();this.stopInternalPreview()}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled){this.hide();this.stopInternalPreview()}this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("voicePickerRequired"))}else{this.validityController.setValidity({})}this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled){this.hide();this.stopInternalPreview()}this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishValidityStates()}get normalizedCatalog(){return normalizeCatalog(this.catalog)}get closedMode(){return this.normalizedCatalog.length>0&&!this.allowCustom}get effectiveEntries(){return withSyntheticCatalogValue(this.normalizedCatalog,this._value)}get filteredEntries(){return filterCatalogEntries(this.effectiveEntries,this.query,this.effectiveLocale,entry=>[entry.id,entry.label,entry.language??"",entry.description??""])}labelFor(id){if(!id)return"";return this.effectiveEntries.find(e=>e.id===id)?.label??id}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.popupPosition.disconnect();if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.popupPosition.reposition(anchor,listbox)}updated(changed){const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));if(reposition){this.syncPopup()}if(changed.has("required")||changed.has("touched")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}this.publishValidityStates();if(this.transferControlFocus){this.transferControlFocus=false;this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus()}this.suppressControlEvents=false}commitValue(next){const inCatalog=this.normalizedCatalog.some(e=>e.id===next);this.value=next;this.hide();this.emit("lr-change",{value:next,inCatalog});this.emitValueEvents()}emitValueEvents(){const EventConstructor=this.ownerDocument.defaultView?.Event??Event;const init={bubbles:true,composed:true};this.dispatchEvent(new EventConstructor("input",init));this.dispatchEvent(new EventConstructor("change",init))}selectEntry(entry){this.commitValue(entry.id)}commitFreeText(){const rows=this.filteredEntries;const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commitValue(activeRow.id);return}this.commitValue(this.query.trim())}get previewCandidateId(){if(this.open&&this.activeIndex>=0){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries;return rows[this.activeIndex]?.id??this._value}return this._value}requestPreview(voiceId){if(!voiceId)return;const entry=this.effectiveEntries.find(e=>e.id===voiceId);const previewUrl=entry?.previewUrl;const event=this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:true});if(!event.defaultPrevented&&previewUrl)this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe;audio.addEventListener("ended",this.onAudioEnded);audio.addEventListener("error",this.onAudioLoadFailure);this.audioEl=audio;this.previewingId=voiceId;void audio.play().catch(()=>this.onAudioLoadFailure(audio));this.emit("lr-preview-change",{voiceId})}stopInternalPreview(){if(this.audioEl){this.audioEl.removeEventListener("ended",this.onAudioEnded);this.audioEl.removeEventListener("error",this.onAudioLoadFailure);this.audioEl.pause();this.audioEl=void 0}if(this.previewingId!==null){this.previewingId=null;this.emit("lr-preview-change",{voiceId:null})}}get previewButtonLabel(){const candidate=this.previewCandidateId;const playing=this.previewingId!==null&&this.previewingId===candidate;const name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.id===this._value;const meta=[entry.language,entry.description].filter(Boolean).join(" \xB7 ");return html`<div
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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredPopoverController}from"../../../internal/anchored-popover-controller.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,playIcon,pauseIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./voice-picker.styles.js";import{trueDefaultBooleanConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{filterCatalogEntries,normalizeCatalog,withSyntheticCatalogValue}from"../../../internal/catalog-picker.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_voice,LYRA_DEFAULT_voicePickerNoVoices,LYRA_DEFAULT_voicePickerPreview,LYRA_DEFAULT_voicePickerRequired,LYRA_DEFAULT_voicePickerStopPreview}from"../../../internal/default-strings.generated.js";class LyraVoicePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,noMatches:LYRA_DEFAULT_noMatches,notInCatalog:LYRA_DEFAULT_notInCatalog,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,voice:LYRA_DEFAULT_voice,voicePickerNoVoices:LYRA_DEFAULT_voicePickerNoVoices,voicePickerPreview:LYRA_DEFAULT_voicePickerPreview,voicePickerRequired:LYRA_DEFAULT_voicePickerRequired,voicePickerStopPreview:LYRA_DEFAULT_voicePickerStopPreview}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.provider="";this.allowCustom=false;this.preview=true;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.open=false;this.activeIndex=-1;this.query="";this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.previewingId=null;this.listId=nextId("voice-picker-list");this.controlId=nextId("voice-picker-control");this.popupPosition=new AnchoredPopoverController;this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.suppressControlEvents=false;this.transferControlFocus=false;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onAudioEnded=event=>{if(event.currentTarget!==this.audioEl)return;this.stopInternalPreview()};this.onAudioLoadFailure=eventOrAudio=>{const direct=eventOrAudio;const candidate=direct.localName==="audio"?eventOrAudio:eventOrAudio.currentTarget;const audioLike=candidate;const failedAudio=audioLike?.localName==="audio"&&typeof audioLike.pause==="function"&&typeof audioLike.removeEventListener==="function"?audioLike:void 0;if(!failedAudio)return;failedAudio.removeEventListener("ended",this.onAudioEnded);failedAudio.removeEventListener("error",this.onAudioLoadFailure);failedAudio.pause();if(failedAudio!==this.audioEl)return;this.audioEl=void 0;if(this.previewingId!==null){this.previewingId=null;this.emit("lr-preview-change",{voiceId:null})}};this.onPreviewButtonClick=()=>{const candidate=this.previewCandidateId;if(!candidate)return;if(this.previewingId===candidate)this.stopInternalPreview();else this.requestPreview(candidate)};this.onOptionPreviewClick=(e,entry)=>{e.stopPropagation();if(this.previewingId===entry.id)this.stopInternalPreview();else this.requestPreview(entry.id)};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=()=>{if(this.suppressControlEvents)return;if(!this.effectiveDisabled)this.touched=true;this.hide();this.emit("blur")};this.onTriggerFocus=()=>{if(!this.suppressControlEvents)this.emit("focus")};this.onTriggerKeyDown=e=>{const rows=this.effectiveEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow)this.selectEntry(activeRow);else this.hide()}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus()};this.onInputFocus=()=>{if(!this.open)this.query=this.labelFor(this.value);this.show();if(!this.suppressControlEvents)this.emit("focus")};this.onInput=e=>{this.query=e.target.value;this.activeIndex=-1;this.show()};this.onInputBlur=()=>{if(this.suppressControlEvents)return;if(!this.effectiveDisabled)this.touched=true;this.hide();this.emit("blur")};this.onInputKeyDown=e=>{const rows=this.filteredEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":if(this.open){e.preventDefault();this.commitFreeText()}break;case"Escape":if(this.open){e.preventDefault();this.query=this.labelFor(this.value);this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const entry=(this.closedMode?this.effectiveEntries:this.filteredEntries).find(e2=>e2.id===value);if(entry)this.selectEntry(entry)};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.internals=attachInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals.setFormValue("")}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"], [part="combobox-input"]')??null}click(){const trigger=this.renderRoot?.querySelector('[part="trigger"]');if(trigger){trigger.click();return}this.renderRoot?.querySelector('[part="combobox-input"]')?.focus()}focus(options){this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus(options)}blur(){this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.blur()}connectedCallback(){super.connectedCallback();this.updateValidity();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}willUpdate(changed){if(this.hasUpdated){const renderedClosedMode=this.renderRoot.querySelector('[part="trigger"]')!==null;const switchingMode=renderedClosedMode!==this.closedMode;const focused=activeElementIn(this.shadowRoot??this.ownerDocument);this.suppressControlEvents=switchingMode;this.transferControlFocus=switchingMode&&focused?.nodeType===1&&focused.matches('[part="trigger"], [part="combobox-input"]')}if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}if(this.hasUpdated&&(changed.has("catalog")||changed.has("allowCustom")||changed.has("value"))){const activeValue=this.renderRoot.querySelector('[part="option"][data-active]')?.dataset["value"];const rows=this.closedMode?this.effectiveEntries:this.filteredEntries;const remapped=activeValue?rows.findIndex(entry=>entry.id===activeValue):-1;this.activeIndex=remapped>=0?remapped:Math.min(this.activeIndex,Math.max(-1,rows.length-1))}if(changed.has("preview")&&!this.preview)this.stopInternalPreview()}disconnectedCallback(){super.disconnectedCallback();this.popupPosition.disconnect();this.unbindDocumentPointer();this.stopInternalPreview();this.open=false}adoptedCallback(){this.popupPosition.disconnect();this.unbindDocumentPointer();this.stopInternalPreview()}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled){this.hide();this.stopInternalPreview()}this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("voicePickerRequired"))}else{this.validityController.setValidity({})}this.publishValidityStates()}publishValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled){this.hide();this.stopInternalPreview()}this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.publishValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.publishValidityStates()}get normalizedCatalog(){return normalizeCatalog(this.catalog)}get closedMode(){return this.normalizedCatalog.length>0&&!this.allowCustom}get effectiveEntries(){return withSyntheticCatalogValue(this.normalizedCatalog,this._value)}get filteredEntries(){return filterCatalogEntries(this.effectiveEntries,this.query,this.effectiveLocale,entry=>[entry.id,entry.label,entry.language??"",entry.description??""])}labelFor(id){if(!id)return"";return this.effectiveEntries.find(e=>e.id===id)?.label??id}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.popupPosition.disconnect();if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.closedMode?'[part="trigger"]':'[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.popupPosition.reposition(anchor,listbox)}updated(changed){const reposition=changed.has("open")||this.open&&(changed.has("catalog")||changed.has("allowCustom"));if(reposition){this.syncPopup()}if(changed.has("required")||changed.has("touched")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}this.publishValidityStates();if(this.transferControlFocus){this.transferControlFocus=false;this.renderRoot.querySelector('[part="trigger"], [part="combobox-input"]')?.focus()}this.suppressControlEvents=false}commitValue(next){const inCatalog=this.normalizedCatalog.some(e=>e.id===next);this.value=next;this.hide();this.emit("lr-change",{value:next,inCatalog});this.emitValueEvents()}emitValueEvents(){const EventConstructor=this.ownerDocument.defaultView?.Event??Event;const init={bubbles:true,composed:true};this.dispatchEvent(new EventConstructor("input",init));this.dispatchEvent(new EventConstructor("change",init))}selectEntry(entry){this.commitValue(entry.id)}commitFreeText(){const rows=this.filteredEntries;const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commitValue(activeRow.id);return}this.commitValue(this.query.trim())}get previewCandidateId(){if(this.open&&this.activeIndex>=0){const rows=this.closedMode?this.effectiveEntries:this.filteredEntries;return rows[this.activeIndex]?.id??this._value}return this._value}requestPreview(voiceId){if(!voiceId)return;const entry=this.effectiveEntries.find(e=>e.id===voiceId);const previewUrl=entry?.previewUrl;const event=this.emit("lr-preview-request",{voiceId,previewUrl},{cancelable:true});if(!event.defaultPrevented&&previewUrl)this.playInternal(voiceId,previewUrl)}playInternal(voiceId,url){const safe=safeMediaSrc(url);if(!safe)return;this.stopInternalPreview();const audio=this.ownerDocument.createElement("audio");audio.src=safe;audio.addEventListener("ended",this.onAudioEnded);audio.addEventListener("error",this.onAudioLoadFailure);this.audioEl=audio;this.previewingId=voiceId;void audio.play().catch(()=>this.onAudioLoadFailure(audio));this.emit("lr-preview-change",{voiceId})}stopInternalPreview(){if(this.audioEl){this.audioEl.removeEventListener("ended",this.onAudioEnded);this.audioEl.removeEventListener("error",this.onAudioLoadFailure);this.audioEl.pause();this.audioEl=void 0}if(this.previewingId!==null){this.previewingId=null;this.emit("lr-preview-change",{voiceId:null})}}get previewButtonLabel(){const candidate=this.previewCandidateId;const playing=this.previewingId!==null&&this.previewingId===candidate;const name=this.labelFor(candidate)||candidate;return playing?this.localize("voicePickerStopPreview"):this.localize("voicePickerPreview",void 0,{name})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.id===this._value;const meta=[entry.language,entry.description].filter(Boolean).join(" \xB7 ");return html`<div
2
2
  part="option"
3
3
  id=${id}
4
4
  role="option"
@@ -26,7 +26,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
26
26
  aria-hidden="true"
27
27
  focusable="false"
28
28
  ><line x1="5" y1="12" x2="19" y2="12"></line></svg>
29
- `}class LyraCheckbox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxRequired:LYRA_DEFAULT_checkboxRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.formAssociated=true}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},checked:{attribute:false,noAccessor:true},defaultChecked:{attribute:"checked",type:Boolean,reflect:true,useDefault:true,noAccessor:true},indeterminate:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},value:{reflect:true,noAccessor:true}}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled||this._groupDisabled}get checked(){return this._checked}set checked(next){const old=this._checked;if(!this.settingDefaultChecked)this._checkedDirty=true;this._checked=Boolean(next);this.syncFormState();this.requestUpdate("checked",old)}get defaultChecked(){return this._defaultChecked}set defaultChecked(next){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=Boolean(next);this.reflectingDefaultChecked=true;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=false}if(!this._checkedDirty)this.restoreCheckedFromDefault();this.requestUpdate("defaultChecked",old)}get indeterminate(){return this._indeterminate}set indeterminate(next){const old=this._indeterminate;this._indeterminate=Boolean(next);this.syncFormState();this.requestUpdate("indeterminate",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.updateValidity();this.requestUpdate("disabled",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??"on";if(next==null){if(this.hasAttribute("value"))this.removeAttribute("value")}else if(this.getAttribute("value")!==this._value){this.setAttribute("value",this._value)}this.syncFormState();this.requestUpdate("value",old,{reflect:false})}constructor(){super();this.size="m";this.hint="";this.helpText="";this.shoelaceDefaultChecked=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.touched=false;this.hasInteracted=false;this.hasSyncedDescribedByElements=false;this._defaultChecked=false;this._checkedDirty=false;this.settingDefaultChecked=false;this.reflectingDefaultChecked=false;this.hadShoelaceDefaultChecked=false;this._fieldsetDisabled=false;this._groupDisabled=false;this._name="";this._checked=false;this._indeterminate=false;this._disabled=false;this._required=false;this._value="on";this.onClick=()=>{this.toggle()};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key===" "||e.key==="Spacebar"){e.preventDefault();this.toggle()}};this.onSlotChange=event=>this.handleLabelSlotChange(event);this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:true}).length>0};this.onHelpTextSlotChange=event=>{this.hasHelpTextSlot=event.target.assignedElements({flatten:true}).length>0};this.onLabelSlotChange=event=>this.handleLabelSlotChange(event);this.onBlur=event=>{this.touched=true;this.hasInteracted=true;this.reflectInvalid();relayNativeEvent(this,event);this.emit("lr-blur")};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormState()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}):void 0;this.addEventListener("slotchange",this.onLabelSlotChange);this.bindLabelObserverTargets();if(this.hasUpdated){this.recomputeHasLabelSlot()}else{this.seedFirstRenderState(()=>{this.recomputeHasLabelSlot();const children=this.children;if(!children)return;this.hasHintSlot=Array.from(children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(children).some(element=>element.getAttribute("slot")==="help-text")})}}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange);this.labelObserver?.disconnect();this.labelObserver=void 0;super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultChecked")&&(this.hasAttribute("default-checked")||this.hadShoelaceDefaultChecked)){this.defaultChecked=this.shoelaceDefaultChecked;this.hadShoelaceDefaultChecked=this.hasAttribute("default-checked")}}updated(changed){super.updated(changed);const describedBy=this.getAttribute("aria-describedby");const hint=this.renderRoot.querySelector("#checkbox-hint");if(!describedBy&&!this.hasSyncedDescribedByElements&&(!hint||hint.hidden))return;const control=this.renderRoot.querySelector('[part~="base"]')??void 0;this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,control,describedBy);if(hint&&!hint.hidden&&control&&"ariaDescribedByElements"in control){const reflected=control;const current=reflected.ariaDescribedByElements??[];reflected.ariaDescribedByElements=[...current.filter(element=>element!==hint),hint]}}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this.checked){this.validityController.setValidity({valueMissing:true},this.localize("checkboxRequired"))}else{this.validityController.setValidity({})}this.reflectInvalid()}reflectInvalid(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred});setCustomState(this.internals,"checked",this.checked);setCustomState(this.internals,"indeterminate",this.indeterminate);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){const state2=`${this.checked?"checked":"unchecked"}${this.indeterminate?"/indeterminate":""}`;this.internals.setFormValue(this.checked?this.value:null,state2);this.updateValidity()}formResetCallback(){this.restoreCheckedFromDefault();this.touched=false;this.hasInteracted=false;this.reflectInvalid()}formStateRestoreCallback(state2,reason){void reason;const oldChecked=this._checked;const oldIndeterminate=this._indeterminate;this._checked=state2==="checked"||state2==="checked/indeterminate";this._checkedDirty=true;this._indeterminate=state2==="checked/indeterminate"||state2==="unchecked/indeterminate";this.syncFormState();this.requestUpdate("checked",oldChecked);this.requestUpdate("indeterminate",oldIndeterminate)}resetFromGroup(){this.restoreCheckedFromDefault()}restoreCheckedFromDefault(){this.settingDefaultChecked=true;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=false}this._checkedDirty=false}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.updateValidity();this.requestUpdate()}setGroupDisabled(value){if(this._groupDisabled===value)return;this._groupDisabled=value;this.updateValidity();this.requestUpdate()}checkValidity(){this.updateValidity();return this.internals.checkValidity()}reportValidity(){this.updateValidity();this.hasInteracted=true;this.reflectInvalid();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectInvalid();this.requestUpdate()}resetValidity(){this.setCustomValidity("")}click(){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.click()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}toggle(){if(this.effectiveDisabled)return;this.hasInteracted=true;this.checked=!this.checked;this.indeterminate=false;dispatchNativeEvent(this,"input");this.emit("lr-input",{checked:this.checked});dispatchNativeEvent(this,"change");this.emit("lr-change",{checked:this.checked})}isDefaultLabelNode(node){if(node.nodeType!==1)return true;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;while(top.parentNode&&top.parentNode!==this)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}observeLabelNode(node){if(!this.labelObserver)return;if(node.nodeType===3){this.labelObserver.observe(node,{characterData:true});return}if(node.nodeType!==1)return;this.labelObserver.observe(node,{attributes:true,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:true,characterData:true,subtree:true})}bindLabelObserverTargets(){if(!this.labelObserver)return;this.labelObserver.disconnect();this.observeLabelNode(this);for(const slot of this.labelForwardingSlots()){if(slot.assignedNodes().length===0)continue;for(const assigned of slot.assignedNodes({flatten:true}))this.observeLabelNode(assigned)}}handleLabelSlotChange(event){const target=event.target;if(target?.nodeType!==1||target.localName!=="slot")return;if(target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target))return;this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}recomputeHasLabelSlot(){const renderRoot=this.renderRoot;const childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])");const nodes=slot?slot.assignedNodes({flatten:true}):Array.from(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:true}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}render(){const mixed=this.indeterminate;const hasHint=this.hasHintSlot||this.hasHelpTextSlot||Boolean(this.hint||this.helpText);const controlParts=["box","control",this.checked?"checked control--checked":"",mixed?"indeterminate control--indeterminate":""].filter(Boolean).join(" ");const describedBy=[this.getAttribute("aria-describedby")??"",hasHint?"checkbox-hint":""].filter(Boolean).join(" ");return html`
29
+ `}class LyraCheckbox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxRequired:LYRA_DEFAULT_checkboxRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.formAssociated=true}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},checked:{attribute:false,noAccessor:true},defaultChecked:{attribute:"checked",type:Boolean,reflect:true,useDefault:true,noAccessor:true},indeterminate:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},value:{reflect:true,noAccessor:true}}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled||this._groupDisabled}get checked(){return this._checked}set checked(next){const old=this._checked;if(!this.settingDefaultChecked)this._checkedDirty=true;this._checked=Boolean(next);this.syncFormState();this.requestUpdate("checked",old)}get defaultChecked(){return this._defaultChecked}set defaultChecked(next){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=Boolean(next);this.reflectingDefaultChecked=true;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=false}if(!this._checkedDirty)this.restoreCheckedFromDefault();this.requestUpdate("defaultChecked",old)}get indeterminate(){return this._indeterminate}set indeterminate(next){const old=this._indeterminate;this._indeterminate=Boolean(next);this.syncFormState();this.requestUpdate("indeterminate",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.updateValidity();this.requestUpdate("disabled",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??"on";if(next==null){if(this.hasAttribute("value"))this.removeAttribute("value")}else if(this.getAttribute("value")!==this._value){this.setAttribute("value",this._value)}this.syncFormState();this.requestUpdate("value",old,{reflect:false})}constructor(){super();this.size="m";this.hint="";this.helpText="";this.shoelaceDefaultChecked=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.touched=false;this.hasInteracted=false;this.hasSyncedDescribedByElements=false;this._defaultChecked=false;this._checkedDirty=false;this.settingDefaultChecked=false;this.reflectingDefaultChecked=false;this.hadShoelaceDefaultChecked=false;this._fieldsetDisabled=false;this._groupDisabled=false;this._name="";this._checked=false;this._indeterminate=false;this._disabled=false;this._required=false;this._value="on";this.onClick=()=>{this.toggle()};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key===" "||e.key==="Spacebar"){e.preventDefault();this.toggle()}};this.onSlotChange=event=>this.handleLabelSlotChange(event);this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:true}).length>0};this.onHelpTextSlotChange=event=>{this.hasHelpTextSlot=event.target.assignedElements({flatten:true}).length>0};this.onLabelSlotChange=event=>this.handleLabelSlotChange(event);this.onBlur=event=>{if(!this.effectiveDisabled&&!this.matches(":disabled")){this.touched=true;this.hasInteracted=true;this.reflectInvalid()}relayNativeEvent(this,event);this.emit("lr-blur")};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormState()}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}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}):void 0;this.addEventListener("slotchange",this.onLabelSlotChange);this.bindLabelObserverTargets();if(this.hasUpdated){this.recomputeHasLabelSlot()}else{this.seedFirstRenderState(()=>{this.recomputeHasLabelSlot();const children=this.children;if(!children)return;this.hasHintSlot=Array.from(children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(children).some(element=>element.getAttribute("slot")==="help-text")})}}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange);this.labelObserver?.disconnect();this.labelObserver=void 0;super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultChecked")&&(this.hasAttribute("default-checked")||this.hadShoelaceDefaultChecked)){this.defaultChecked=this.shoelaceDefaultChecked;this.hadShoelaceDefaultChecked=this.hasAttribute("default-checked")}}updated(changed){super.updated(changed);const describedBy=this.getAttribute("aria-describedby");const hint=this.renderRoot.querySelector("#checkbox-hint");if(!describedBy&&!this.hasSyncedDescribedByElements&&(!hint||hint.hidden))return;const control=this.renderRoot.querySelector('[part~="base"]')??void 0;this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,control,describedBy);if(hint&&!hint.hidden&&control&&"ariaDescribedByElements"in control){const reflected=control;const current=reflected.ariaDescribedByElements??[];reflected.ariaDescribedByElements=[...current.filter(element=>element!==hint),hint]}}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this.checked){this.validityController.setValidity({valueMissing:true},this.localize("checkboxRequired"))}else{this.validityController.setValidity({})}this.reflectInvalid()}reflectInvalid(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred});setCustomState(this.internals,"checked",this.checked);setCustomState(this.internals,"indeterminate",this.indeterminate);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){const state2=`${this.checked?"checked":"unchecked"}${this.indeterminate?"/indeterminate":""}`;this.internals.setFormValue(this.checked?this.value:null,state2);this.updateValidity()}formResetCallback(){this.restoreCheckedFromDefault();this.touched=false;this.hasInteracted=false;this.reflectInvalid()}formStateRestoreCallback(state2,reason){void reason;const oldChecked=this._checked;const oldIndeterminate=this._indeterminate;this._checked=state2==="checked"||state2==="checked/indeterminate";this._checkedDirty=true;this._indeterminate=state2==="checked/indeterminate"||state2==="unchecked/indeterminate";this.syncFormState();this.requestUpdate("checked",oldChecked);this.requestUpdate("indeterminate",oldIndeterminate)}resetFromGroup(){this.restoreCheckedFromDefault()}restoreCheckedFromDefault(){this.settingDefaultChecked=true;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=false}this._checkedDirty=false}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.updateValidity();this.requestUpdate()}setGroupDisabled(value){if(this._groupDisabled===value)return;this._groupDisabled=value;this.updateValidity();this.requestUpdate()}checkValidity(){this.updateValidity();return this.internals.checkValidity()}reportValidity(){this.updateValidity();this.hasInteracted=true;this.reflectInvalid();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectInvalid();this.requestUpdate()}resetValidity(){this.setCustomValidity("")}click(){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.click()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}toggle(){if(this.effectiveDisabled)return;this.hasInteracted=true;this.checked=!this.checked;this.indeterminate=false;dispatchNativeEvent(this,"input");this.emit("lr-input",{checked:this.checked});dispatchNativeEvent(this,"change");this.emit("lr-change",{checked:this.checked})}isDefaultLabelNode(node){if(node.nodeType!==1)return true;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;while(top.parentNode&&top.parentNode!==this)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}observeLabelNode(node){if(!this.labelObserver)return;if(node.nodeType===3){this.labelObserver.observe(node,{characterData:true});return}if(node.nodeType!==1)return;this.labelObserver.observe(node,{attributes:true,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:true,characterData:true,subtree:true})}bindLabelObserverTargets(){if(!this.labelObserver)return;this.labelObserver.disconnect();this.observeLabelNode(this);for(const slot of this.labelForwardingSlots()){if(slot.assignedNodes().length===0)continue;for(const assigned of slot.assignedNodes({flatten:true}))this.observeLabelNode(assigned)}}handleLabelSlotChange(event){const target=event.target;if(target?.nodeType!==1||target.localName!=="slot")return;if(target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target))return;this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}recomputeHasLabelSlot(){const renderRoot=this.renderRoot;const childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])");const nodes=slot?slot.assignedNodes({flatten:true}):Array.from(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:true}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}render(){const mixed=this.indeterminate;const hasHint=this.hasHintSlot||this.hasHelpTextSlot||Boolean(this.hint||this.helpText);const controlParts=["box","control",this.checked?"checked control--checked":"",mixed?"indeterminate control--indeterminate":""].filter(Boolean).join(" ");const describedBy=[this.getAttribute("aria-describedby")??"",hasHint?"checkbox-hint":""].filter(Boolean).join(" ");return html`
30
30
  <div>
31
31
  <span
32
32
  part="base checkbox"
@@ -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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_checkboxGroupRequired,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}function warnValueAssigned(group){console.warn(`<lr-checkbox-group> \`value\` is derived from its <lr-checkbox> children and is overwritten by the next sync (any child toggle, a slot change, a \`name\`/\`required\` change, blur, or form reset), so assigning it has no lasting effect${group.name?` (name="${group.name}")`:""}. Set \`checked\` on the children instead.`)}function warnDuplicateValue(group,value){console.warn(`<lr-checkbox-group> has more than one <lr-checkbox> child with value="${value}"${group.name?` (name="${group.name}")`:""}; every checked one contributes an identical FormData entry, so the submitted data cannot say which was checked. Give each child a distinct \`value\`.`)}class LyraCheckboxGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},orientation:{reflect:true},value:{attribute:false,noAccessor:true}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.sync();this.requestUpdate("name",old)}get value(){return this._value}set value(next){if(!this._writingValue&&!this._warnedValueAssigned){this._warnedValueAssigned=true;warnValueAssigned(this)}const old=this._value;this._value=Array.isArray(next)?next:[];this.requestUpdate("value",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.sync();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.propagateDisabled();this.sync();this.requestUpdate("disabled",old)}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.touched=false;this.hasInteracted=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("checkbox-group-label");this.hintId=nextId("checkbox-group-hint");this.errorId=nextId("checkbox-group-error");this._fieldsetDisabled=false;this._name="";this._required=false;this._disabled=false;this._value=[];this._writingValue=false;this._warnedValueAssigned=false;this._warnedDuplicateValues=new Set;this.childObserverGeneration=0;this.childControllers=new Map;this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target))return;event.stopImmediatePropagation();if(event.type!=="change"||this.effectiveDisabled)return;this.hasInteracted=true;this.sync();this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})};this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}if(records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))){this.propagateSize()}if(records.some(record=>this.isOwnedCheckbox(record.target)))this.sync()};this.onSlotChange=()=>{this.hasLabelSlot=this.hasDirectSupportSlot("label");this.hasHintSlot=this.hasDirectSupportSlot("hint");this.hasErrorSlot=this.hasDirectSupportSlot("error");this.reconcileChildControllers();if(!this.applyPendingRestore())this.sync();this.propagateDisabled();this.propagateSize()};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init))}checkboxGroupOwner(element){const group=element.closest("lr-checkbox-group");if(!group)return null;let topLevelChild=element;while(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==="error"?null:group}ownsCheckbox(element){return element.localName==="lr-checkbox"&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){this.boxes.forEach(box=>{box.size=this.size})}readValue(){return this.boxes.filter(box=>box.checked).map(box=>box.value??"on")}warnOnDuplicateValues(){const seen=new Set;for(const box of this.boxes){const value=box.value??box.getAttribute("value")??"on";if(!seen.has(value)){seen.add(value);continue}if(this._warnedDuplicateValues.has(value))continue;this._warnedDuplicateValues.add(value);warnDuplicateValue(this,value)}}sync(){const next=this.readValue();this.warnOnDuplicateValues();this._writingValue=true;try{this.value=next}finally{this._writingValue=false}const data=new FormData;if(this.name)next.forEach(value=>data.append(this.name,value));this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next));if(!this.barredFromValidation&&this.required&&next.length===0)this.validityController.setValidity({valueMissing:true},this.localize("checkboxGroupRequired"));else this.validityController.setValidity({});this.reflectValidityStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller);this.childControllers.delete(box);const nextOwner=this.checkboxGroupOwner(box);if(!nextOwner||nextOwner===this)box.setGroupDisabled?.(false)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!=="function")continue;const controller={hostUpdated:()=>{if(this.isConnected&&this.ownsCheckbox(box))this.sync()}};box.addController(controller);this.childControllers.set(box,controller)}}hasDirectSupportSlot(name){return Array.from(this.children).some(child=>child.getAttribute("slot")===name)}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return false;const remaining=[...this.pendingRestoreValues];this.pendingRestoreValues=void 0;for(const box of this.boxes){const value=box.value??"on";const index=remaining.indexOf(value);box.checked=index>=0;if(index>=0)remaining.splice(index,1)}this.touched=false;this.hasInteracted=false;this.sync();return true}connectedCallback(){super.connectedCallback();this.addEventListener("input",this.onChildEvent);this.addEventListener("change",this.onChildEvent);this.addEventListener("lr-change",this.onChildEvent);this.onSlotChange();this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration;const observer=new MutationObserverCtor(records=>{if(this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onChildMutations(records)});this.childObserver=observer;this.childObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.removeEventListener("input",this.onChildEvent);this.removeEventListener("change",this.onChildEvent);this.removeEventListener("lr-change",this.onChildEvent);this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller);box.setGroupDisabled?.(false)}this.childControllers.clear();super.disconnectedCallback()}adoptedCallback(){this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1;this.childObserver?.disconnect();this.childObserver=void 0;this.childObserverDocument=void 0}firstUpdated(){this.addEventListener("blur",()=>{this.touched=true;this.hasInteracted=true;this.sync()},true)}updated(changed){super.updated(changed);if(changed.has("size"))this.propagateSize()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="options"]')??null}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}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}focusFirstControl(){const first=this.boxes.find(box=>!box.effectiveDisabled);first?.focus()}click(){this.focusFirstControl()}formResetCallback(){this.boxes.forEach(box=>box.resetFromGroup());this.touched=false;this.hasInteracted=false;this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2);this.applyPendingRestore()}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.propagateDisabled();this.sync();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||Boolean(this.hint)||this.withHint;const described=[hasHint?this.hintId:"",this.hasErrorSlot||this.errorText?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`<fieldset
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--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{nextId}from"../../../internal/a11y.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./checkbox-group.styles.js";import{createStringArrayFormDataState,getFormOwner,installCustomErrorProperty,isBarredFromValidation,readStringArrayFormDataState,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_checkboxGroupRequired,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}function warnValueAssigned(group){console.warn(`<lr-checkbox-group> \`value\` is derived from its <lr-checkbox> children and is overwritten by the next sync (any child toggle, a slot change, a \`name\`/\`required\` change, blur, or form reset), so assigning it has no lasting effect${group.name?` (name="${group.name}")`:""}. Set \`checked\` on the children instead.`)}function warnDuplicateValue(group,value){console.warn(`<lr-checkbox-group> has more than one <lr-checkbox> child with value="${value}"${group.name?` (name="${group.name}")`:""}; every checked one contributes an identical FormData entry, so the submitted data cannot say which was checked. Give each child a distinct \`value\`.`)}class LyraCheckboxGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,checkboxGroupRequired:LYRA_DEFAULT_checkboxGroupRequired,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},orientation:{reflect:true},value:{attribute:false,noAccessor:true}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name)this.setAttribute("name",this._name);else this.removeAttribute("name");this.sync();this.requestUpdate("name",old)}get value(){return this._value}set value(next){if(!this._writingValue&&!this._warnedValueAssigned){this._warnedValueAssigned=true;warnValueAssigned(this)}const old=this._value;this._value=Array.isArray(next)?next:[];this.requestUpdate("value",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.sync();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.propagateDisabled();this.sync();this.requestUpdate("disabled",old)}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.touched=false;this.hasInteracted=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.labelId=nextId("checkbox-group-label");this.hintId=nextId("checkbox-group-hint");this.errorId=nextId("checkbox-group-error");this._fieldsetDisabled=false;this._name="";this._required=false;this._disabled=false;this._value=[];this._writingValue=false;this._warnedValueAssigned=false;this._warnedDuplicateValues=new Set;this.childObserverGeneration=0;this.childControllers=new Map;this.onChildEvent=event=>{if(!this.isOwnedCheckbox(event.target))return;event.stopImmediatePropagation();if(event.type!=="change"||this.effectiveDisabled)return;this.hasInteracted=true;this.sync();this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})};this.onChildMutations=records=>{if(records.some(record=>record.type==="childList"||record.attributeName==="slot")){this.onSlotChange();return}if(records.some(record=>record.attributeName==="size"&&this.isOwnedCheckbox(record.target))){this.propagateSize()}if(records.some(record=>this.isOwnedCheckbox(record.target)))this.sync()};this.onSlotChange=()=>{this.hasLabelSlot=this.hasDirectSupportSlot("label");this.hasHintSlot=this.hasDirectSupportSlot("hint");this.hasErrorSlot=this.hasDirectSupportSlot("error");this.reconcileChildControllers();if(!this.applyPendingRestore())this.sync();this.propagateDisabled();this.propagateSize()};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init))}checkboxGroupOwner(element){const group=element.closest("lr-checkbox-group");if(!group)return null;let topLevelChild=element;while(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==="error"?null:group}ownsCheckbox(element){return element.localName==="lr-checkbox"&&this.checkboxGroupOwner(element)===this}get boxes(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return Array.from(querySelectorAll.call(this,"lr-checkbox")).filter(box=>this.ownsCheckbox(box))}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}propagateDisabled(){const effective=this.effectiveDisabled;this.boxes.forEach(box=>box.setGroupDisabled?.(effective))}propagateSize(){this.boxes.forEach(box=>{box.size=this.size})}readValue(){return this.boxes.filter(box=>box.checked).map(box=>box.value??"on")}warnOnDuplicateValues(){const seen=new Set;for(const box of this.boxes){const value=box.value??box.getAttribute("value")??"on";if(!seen.has(value)){seen.add(value);continue}if(this._warnedDuplicateValues.has(value))continue;this._warnedDuplicateValues.add(value);warnDuplicateValue(this,value)}}sync(){const next=this.readValue();this.warnOnDuplicateValues();this._writingValue=true;try{this.value=next}finally{this._writingValue=false}const data=new FormData;if(this.name)next.forEach(value=>data.append(this.name,value));this.internals.setFormValue(this.name?data:null,createStringArrayFormDataState(this.name,next));if(!this.barredFromValidation&&this.required&&next.length===0)this.validityController.setValidity({valueMissing:true},this.localize("checkboxGroupRequired"));else this.validityController.setValidity({});this.reflectValidityStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}reflectValidityStates(){const barred=this.barredFromValidation;this.toggleAttribute("data-invalid",!barred&&this.touched&&!this.internals.validity.valid);syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred})}isOwnedCheckbox(target){return target?.nodeType===1&&this.ownsCheckbox(target)}reconcileChildControllers(){const current=new Set(this.boxes);for(const[box,controller]of this.childControllers){if(current.has(box))continue;box.removeController(controller);this.childControllers.delete(box);const nextOwner=this.checkboxGroupOwner(box);if(!nextOwner||nextOwner===this)box.setGroupDisabled?.(false)}for(const box of current){if(this.childControllers.has(box)||typeof box.addController!=="function")continue;const controller={hostUpdated:()=>{if(this.isConnected&&this.ownsCheckbox(box))this.sync()}};box.addController(controller);this.childControllers.set(box,controller)}}hasDirectSupportSlot(name){return Array.from(this.children).some(child=>child.getAttribute("slot")===name)}applyPendingRestore(){if(this.pendingRestoreValues===void 0||this.boxes.length===0)return false;const remaining=[...this.pendingRestoreValues];this.pendingRestoreValues=void 0;for(const box of this.boxes){const value=box.value??"on";const index=remaining.indexOf(value);box.checked=index>=0;if(index>=0)remaining.splice(index,1)}this.touched=false;this.hasInteracted=false;this.sync();return true}connectedCallback(){super.connectedCallback();this.addEventListener("input",this.onChildEvent);this.addEventListener("change",this.onChildEvent);this.addEventListener("lr-change",this.onChildEvent);this.onSlotChange();this.armChildObserver()}armChildObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.childObserver&&this.childObserverDocument===ownerDocument)return;this.resetChildObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.childObserverGeneration;const observer=new MutationObserverCtor(records=>{if(this.childObserver!==observer||this.childObserverDocument!==ownerDocument||this.childObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onChildMutations(records)});this.childObserver=observer;this.childObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["checked","value","disabled","size","slot"]})}disconnectedCallback(){this.removeEventListener("input",this.onChildEvent);this.removeEventListener("change",this.onChildEvent);this.removeEventListener("lr-change",this.onChildEvent);this.resetChildObserver();for(const[box,controller]of this.childControllers){box.removeController(controller);box.setGroupDisabled?.(false)}this.childControllers.clear();super.disconnectedCallback()}adoptedCallback(){this.resetChildObserver()}resetChildObserver(){this.childObserverGeneration+=1;this.childObserver?.disconnect();this.childObserver=void 0;this.childObserverDocument=void 0}firstUpdated(){this.addEventListener("blur",event=>{const blurredControl=event.target;const disabled=typeof blurredControl?.matches==="function"?blurredControl.matches(":disabled"):this.effectiveDisabled;if(!disabled){this.touched=true;this.hasInteracted=true}this.sync()},true)}updated(changed){super.updated(changed);if(changed.has("size"))this.propagateSize()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="options"]')??null}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}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}focusFirstControl(){const first=this.boxes.find(box=>!box.effectiveDisabled);first?.focus()}click(){this.focusFirstControl()}formResetCallback(){this.boxes.forEach(box=>box.resetFromGroup());this.touched=false;this.hasInteracted=false;this.sync()}formStateRestoreCallback(state2,_mode){this.pendingRestoreValues=readStringArrayFormDataState(state2);this.applyPendingRestore()}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.propagateDisabled();this.sync();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||Boolean(this.hint)||this.withHint;const described=[hasHint?this.hintId:"",this.hasErrorSlot||this.errorText?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`<fieldset
2
2
  part="form-control"
3
3
  ?disabled=${this.effectiveDisabled}
4
4
  aria-label=${this.accessibleLabel||nothing}
@@ -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--)if(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{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{finiteInteger}from"../../../internal/numbers.js";import{styles}from"./code-editor.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_codeEditorLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";class LyraCodeEditorBase extends LyraElement{}class LyraCodeEditor extends FormAssociated(LyraCodeEditorBase){constructor(){super(...arguments);this.language="";this.lineNumbers=true;this._tabSize=2;this.tabSizeAssigned=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.readonly=false;this.resize="both";this.wrap="off";this.spellcheck=false;this.autocapitalize="off";this.autoCorrect="off";this.accessibleLabel="";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.onInput=event=>{this.value=event.target.value;this.emit("input",{value:this.value})};this.onChange=()=>{this.emit("change",{value:this.value})};this.onFocus=()=>{this.emit("focus")};this.onBlur=()=>{this.touched=true;this.tabBypassArmed=false;this.emit("blur")};this.tabBypassArmed=false;this.onKeyDown=event=>{if(event.key==="Escape"){this.tabBypassArmed=true;return}if(event.key==="Tab"){if(event.shiftKey)return;if(this.tabBypassArmed){this.tabBypassArmed=false;return}if(this.readonly)return;event.preventDefault();const target=event.target;const start=target.selectionStart;target.setRangeText(" ".repeat(this.indentWidth),start,target.selectionEnd,"end");this.value=target.value;this.emit("input",{value:this.value});return}this.tabBypassArmed=false};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0}}static{this.defaultStrings={...super.defaultStrings,codeEditorLabel:LYRA_DEFAULT_codeEditorLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,styles]}get tabSize(){return this._tabSize}set tabSize(value){const old=this._tabSize;this.tabSizeAssigned=value!=null;this._tabSize=finiteInteger(value,2,1,16);this.requestUpdate("tabSize",old)}get indentWidth(){if(this.tabSizeAssigned||!this.textarea)return this._tabSize;const resolved=getComputedStyle(this.textarea).tabSize.trim();if(!/^\d+(?:\.\d+)?$/.test(resolved))return this._tabSize;return finiteInteger(Number(resolved),this._tabSize,1,16)}click(){if(!this.effectiveDisabled)this.textarea?.click()}focus(options){this.textarea?.focus(options)}blur(){this.textarea?.blur()}select(){this.textarea?.select()}get selectionStart(){return this.textarea?.selectionStart??0}set selectionStart(value){if(this.textarea)this.textarea.selectionStart=value}get selectionEnd(){return this.textarea?.selectionEnd??0}set selectionEnd(value){if(this.textarea)this.textarea.selectionEnd=value}get selectionDirection(){return this.textarea?.selectionDirection??"none"}set selectionDirection(value){if(this.textarea)this.textarea.selectionDirection=value}setSelectionRange(start,end,direction){this.textarea?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectionMode){const textarea=this.textarea;if(!textarea)return;textarea.setRangeText(replacement,start??textarea.selectionStart,end??textarea.selectionEnd,selectionMode);this.value=textarea.value}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}updated(changed){super.updated(changed);if(this.textarea&&this.textarea.value!==this.value)this.textarea.value=this.value;if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}render(){const lineCount=Math.max(1,this.value.split("\n").length);const textareaStyle={resize:sanitizeCssResize(this.resize,"both"),...this.tabSizeAssigned?{"--lr-code-editor-tab-size":String(this._tabSize)}:{}};const hasLabel=this.hasLabelSlot||this.label.length>0;const hasHint=this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" ");const label=this.accessibleLabel||(hasLabel?nothing:this.localize("codeEditorLabel"));return html`<div part="form-control">
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--)if(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{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{finiteInteger}from"../../../internal/numbers.js";import{styles}from"./code-editor.styles.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssResize}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_codeEditorLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";class LyraCodeEditorBase extends LyraElement{}class LyraCodeEditor extends FormAssociated(LyraCodeEditorBase){constructor(){super(...arguments);this.language="";this.lineNumbers=true;this._tabSize=2;this.tabSizeAssigned=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.readonly=false;this.resize="both";this.wrap="off";this.spellcheck=false;this.autocapitalize="off";this.autoCorrect="off";this.accessibleLabel="";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.onInput=event=>{this.value=event.target.value;this.emit("input",{value:this.value})};this.onChange=()=>{this.emit("change",{value:this.value})};this.onFocus=()=>{this.emit("focus")};this.onBlur=()=>{if(!this.effectiveDisabled)this.touched=true;this.tabBypassArmed=false;this.emit("blur")};this.tabBypassArmed=false;this.onKeyDown=event=>{if(event.key==="Escape"){this.tabBypassArmed=true;return}if(event.key==="Tab"){if(event.shiftKey)return;if(this.tabBypassArmed){this.tabBypassArmed=false;return}if(this.readonly)return;event.preventDefault();const target=event.target;const start=target.selectionStart;target.setRangeText(" ".repeat(this.indentWidth),start,target.selectionEnd,"end");this.value=target.value;this.emit("input",{value:this.value});return}this.tabBypassArmed=false};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0}}static{this.defaultStrings={...super.defaultStrings,codeEditorLabel:LYRA_DEFAULT_codeEditorLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,styles]}get tabSize(){return this._tabSize}set tabSize(value){const old=this._tabSize;this.tabSizeAssigned=value!=null;this._tabSize=finiteInteger(value,2,1,16);this.requestUpdate("tabSize",old)}get indentWidth(){if(this.tabSizeAssigned||!this.textarea)return this._tabSize;const resolved=getComputedStyle(this.textarea).tabSize.trim();if(!/^\d+(?:\.\d+)?$/.test(resolved))return this._tabSize;return finiteInteger(Number(resolved),this._tabSize,1,16)}click(){if(!this.effectiveDisabled)this.textarea?.click()}focus(options){this.textarea?.focus(options)}blur(){this.textarea?.blur()}select(){this.textarea?.select()}get selectionStart(){return this.textarea?.selectionStart??0}set selectionStart(value){if(this.textarea)this.textarea.selectionStart=value}get selectionEnd(){return this.textarea?.selectionEnd??0}set selectionEnd(value){if(this.textarea)this.textarea.selectionEnd=value}get selectionDirection(){return this.textarea?.selectionDirection??"none"}set selectionDirection(value){if(this.textarea)this.textarea.selectionDirection=value}setSelectionRange(start,end,direction){this.textarea?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectionMode){const textarea=this.textarea;if(!textarea)return;textarea.setRangeText(replacement,start??textarea.selectionStart,end??textarea.selectionEnd,selectionMode);this.value=textarea.value}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}updated(changed){super.updated(changed);if(this.textarea&&this.textarea.value!==this.value)this.textarea.value=this.value;if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}render(){const lineCount=Math.max(1,this.value.split("\n").length);const textareaStyle={resize:sanitizeCssResize(this.resize,"both"),...this.tabSizeAssigned?{"--lr-code-editor-tab-size":String(this._tabSize)}:{}};const hasLabel=this.hasLabelSlot||this.label.length>0;const hasHint=this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"textarea-error":"",hasHint?"textarea-hint":""].filter(Boolean).join(" ");const label=this.accessibleLabel||(hasLabel?nothing:this.localize("codeEditorLabel"));return html`<div part="form-control">
2
2
  <label part="label form-control-label" for="textarea" ?hidden=${!hasLabel}>${this.label}<slot name="label" @slotchange=${this.onLabelSlotChange}></slot></label>
3
3
  <div part="editor" data-language=${this.language}>
4
4
  ${this.lineNumbers?html`<div part="gutter" aria-hidden="true">${lineCount<=1e3?Array.from({length:lineCount},(_v,i)=>html`<div>${i+1}</div>`):html`<span>${Array.from({length:lineCount},(_v,i)=>i+1).join("\n")}</span>`}</div>`:nothing}
@@ -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--)if(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{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import{LyraOption}from"./option.class.js";import"./option.class.js";import{autocorrectConverter,omittedEmptyStringConverter,spellcheckConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{tag}from"../../../internal/prefix.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraCombobox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},multiple:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:true},maxRender:{type:Number,attribute:"max-render",noAccessor:true},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:true}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=Boolean(next);this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=true;this.query=next??"";this.activeIndex=-1;if(this.source)this.runSource(this.query);this.requestUpdate()}constructor(){super();this.placeholder="";this.label="";this.hint="";this.errorText="";this.open=false;this.allowCreate=false;this.allowCustomValue=false;this.appearance="outlined";this.placement="bottom";this.size="m";this.pill=false;this.clearable=false;this.withClear=false;this.withLabel=false;this.withHint=false;this.validators=[];this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.spellcheck=false;this.autocapitalize="";this.autocorrectValue=true;this.emptyText="";this.loadingText="";this.overflowText="";this.filter=null;this.source=null;this.query="";this.explicitInputValue=false;this.activeIndex=-1;this.options=[];this.touched=false;this.slotPresence=new SlotPresenceController(this);this.loading=false;this.sourceFailed=false;this.asyncRows=[];this.sourceToken=0;this._sourceWarmed=false;this._selectedLabelCache=new Map;this._selectedRowCache=new Map;this._rowsByValue=new Map;this._fieldsetDisabled=false;this.listId=nextId("combobox-list");this.inputId=nextId("combobox-input");this._isFirstUpdate=true;this.openVetoed=false;this.transitionToken=0;this.transitionWaiters=new Map;this._selected=[];this._valueDirty=false;this._multiple=false;this._disabled=false;this._required=false;this._defaultSelected=[];this._defaultCaptured=false;this._restoredStateActive=false;this._name="";this._maxOptionsVisible=3;this._maxRender=200;this._sourceDelay=200;this.collectOptions=e=>{const slot=e.target;const previous=new Set(this.options);this.options=slot.assignedElements({flatten:true}).filter(el=>el instanceof LyraOption);if(!this._defaultCaptured){this._defaultCaptured=true;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value);const allLive=this.options.filter(option=>option.selected).map(option=>option.value);const defaults=this.multiple?allDefaults:allDefaults.slice(0,1);const live=this.multiple?allLive:allLive.slice(0,1);const initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);const optionDirty=this.options.some(option=>isOptionSelectedDirty(option));const dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);const dirtyValues=dirtySelected.map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0;const initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];if(fromDefaults&&!optionDirty)this.setValue(next,false);else this.value=next;return}if(optionDirty)this._valueDirty=true}else{const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected);const newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...!this._restoredStateActive?newLive:[]];if(eligible.length){const values=eligible.map(option=>option.value);const next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];if(newLive.length>0)this.value=next;else this.setValue(next,false);return}}this.reflectSelected()};this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults();this.reflectSelected();this.options=[...this.options]})};this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onInput=e=>{this.explicitInputValue=false;this.query=e.target.value;this.activeIndex=-1;this.show();if(this.source)this.runSource(this.query);this.emit("lr-filter",{value:this.query})};this.onInputBlur=()=>{this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onInputFocus=()=>{this.show();this.emit("focus")};this.onKeyDown=e=>{const navigable=this.renderedRows.rows.filter(r=>!r.disabled);switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open){void this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open){void this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault();this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault();this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault();this.commitCustomValue(this.query.trim());break}if(this.effectiveDisabled)break;submitOnEnter(this,e);break}case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=navigable.length-1}break;case"Backspace":if(this.multiple&&!this.query&&this._selected.length){this.removeValue(this._selected[this._selected.length-1])}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;if(e.target.closest("button"))return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus();this.show()};this.onListboxMouseDown=e=>{e.preventDefault()};this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const row=this._rowsByValue.get(value);if(row)this.pickRow(row)};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init))}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 validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0;this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){if(this.inputEl)this.inputEl.selectionStart=value}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){if(this.inputEl)this.inputEl.selectionEnd=value}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){if(this.inputEl)this.inputEl.selectionDirection=value}focus(options){this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){if(this.effectiveDisabled)return;this.inputEl?.focus();this.show()}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.explicitInputValue=true;this.query=input.value;this.activeIndex=-1;if(this.source)this.runSource(this.query)}[VALIDITY_ANCHOR](){return this.validationTarget}connectedCallback(){super.connectedCallback();this.syncSourceErrorAnnouncementSink();this.updateValidity();if(this.hasUpdated){queueMicrotask(()=>{if(this.open)this.reconnectOpenPopup();else if(this.source&&this._selected.length&&this.asyncRows.length===0){this.runSource("")}})}}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearSourceTimer();this.sourceToken+=1;this.sourceAbort?.abort();this.sourceAbort=void 0;this.releaseSourceErrorAnnouncementSink();this.syncSourceErrorAnnouncementSink()}syncSourceErrorAnnouncementSink(){if(!this.isConnected)return;if(this.sourceErrorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;this.releaseSourceErrorAnnouncementSink();this.sourceErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseSourceErrorAnnouncementSink(){this.sourceErrorAnnouncementSink?.release();this.sourceErrorAnnouncementSink=void 0}willUpdate(changed){super.willUpdate(changed);this._isFirstUpdate=!this.hasUpdated;this.announceOpenTransition(changed);if(changed.has("source")){this.clearSourceTimer();this.sourceAbort?.abort();this.sourceAbort=void 0;this.sourceToken++;this.loading=false;this.sourceFailed=false;this.asyncRows=[];this.activeIndex=-1;this._sourceWarmed=false;if(this.source&&this.open)this.runSource(this.query)}if(!this._sourceWarmed&&this.source&&this._selected.length&&this.asyncRows.length===0){this._sourceWarmed=true;this.runSource("")}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.syncFormValue();this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=Boolean(next);this.toggleAttribute("multiple",this._multiple);this.syncFormValue();this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,true)}setValue(next,dirty){const old=this._selected;if(dirty){this._restoredStateActive=false;this._valueDirty=true}this._selected=Array.isArray(next)?[...next]:next?[next]:[];const selected=new Set(this._selected);for(const value of selected){const row=this.effectiveRows.find(candidate=>candidate.value===value)??this.asyncRows.find(candidate=>candidate.value===value);if(row)this._selectedRowCache.set(value,row)}for(const value of this._selectedRowCache.keys()){if(!selected.has(value))this._selectedRowCache.delete(value)}for(const value of this._selectedLabelCache.keys()){if(!selected.has(value))this._selectedLabelCache.delete(value)}this.syncFormValue();this.reflectSelected();this.updateValidity();this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3);this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200);this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=finiteCount(next,200);this.requestUpdate("maxRender",old)}get selectedRows(){return this._selected.map(value=>this._selectedRowCache.get(value)??this.effectiveRows.find(row=>row.value===value)??this.asyncRows.find(row=>row.value===value)).filter(row=>row!=null)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&this._selected.length===0){this.validityController.setValidity({valueMissing:true},this.localize("comboboxRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation});setCustomState(this.internals,"blank",this._selected.length===0);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else{this.internals.setFormValue(this._selected[0]??"",state2)}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=false;this._restoredStateActive=false;this._valueDirty=false;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);if(this._defaultSelected.length===0&&resetValues.length>0)this._defaultSelected=[...resetValues];const defaults=new Set(resetValues);for(const option of this.options){option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value))}this.setValue(this.multiple?[...resetValues]:resetValues[0]??"",false);this.query="";this.explicitInputValue=false}formStateRestoreCallback(state2,reason){void reason;let selected=[];if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(Array.isArray(parsed)&&parsed.every(value=>typeof value==="string"))selected=parsed}catch{}}this.value=this.multiple?selected:selected[0]??"";this._restoredStateActive=true}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates()}disconnectedCallback(){this.transitionToken++;this.releaseSourceErrorAnnouncementSink();super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.clearSourceTimer();this.sourceToken+=1;this.sourceAbort?.abort();this.sourceAbort=void 0;this.unbindDocumentPointer();this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");this.open=false}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1);if(!this._valueDirty&&!this._restoredStateActive){this.setValue(this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",false)}}reflectSelected(){const sel=new Set(this._selected);for(const option of this.options){option[SET_OPTION_SELECTED_FROM_OWNER](sel.has(option.value))}}labelFor(value){return this._selectedLabelCache.get(value)??this.options.find(o=>o.value===value)?.label??this.asyncRows.find(r=>r.value===value)?.label??value}get effectiveRows(){if(this.source)return this.asyncRows;return this.filtered.map(o=>({value:o.value,label:o.label,sub:o.sub||void 0,dotColor:o.dotColor||void 0,group:o.group||void 0,disabled:o.disabled}))}get createRow(){if(!this.allowCreate)return void 0;const inputValue=this.query.trim();if(!inputValue)return void 0;const locale=this.effectiveLocale;const folded=inputValue.toLocaleLowerCase(locale);const rows=this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}));if(rows.some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded)){return void 0}return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}get renderedRows(){const all=this.effectiveRows;const create=this.createRow;if(all.length<=this.maxRender)return{rows:create?[...all,create]:all,overflow:0};const originalIndex=new Map(all.map((r,i)=>[r,i]));const capped=all.slice(0,this.maxRender);const cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=false;for(const v of this._selected){if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);if(selectedRow){capped.push(selectedRow);appendedOutOfCap=true}}}if(appendedOutOfCap){capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b))}if(create)capped.push(create);return{rows:capped,overflow:all.length-capped.length+(create?1:0)}}get filtered(){const locale=this.effectiveLocale;const q=this.query.trim().toLocaleLowerCase(locale);const selectedLabel=!this.multiple?this.labelFor(this._selected[0]??"")??"":"";const effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){if(this.multiple||this.open||this.explicitInputValue)return this.query;return this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){this.openVetoed=false;if(!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}if(!this.emit(name,void 0,{cancelable:true}).defaultPrevented)return;this.openVetoed=true;this.open=!this.open;this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show")}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;return settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.open=false;this.activeIndex=-1;if(!this.multiple){const queryChanged=this.query!=="";this.query="";this.explicitInputValue=false;if(queryChanged&&this.source){this.asyncRows=[];this.sourceFailed=false}}return settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.cleanup?.();this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`})}if(this.source&&this.asyncRows.length===0)this.runSource(this.query)}updated(changed){super.updated(changed);if(changed.has("open")&&!this.openVetoed){this.cleanup?.();this.cleanup=void 0;if(this.open&&this.isConnected){this.bindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-show")}const anchor=this.renderRoot.querySelector('[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`})}if(this.source&&this.asyncRows.length===0)this.runSource(this.query)}else if(!this.open){this.unbindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-hide")}}else{this.unbindDocumentPointer()}}if(changed.has("name"))this.syncFormValue();if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}if(changed.has("activeIndex")){this.renderRoot.querySelector('[part="option"][data-active]')?.scrollIntoView({block:"nearest"})}}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const listbox=this.renderRoot.querySelector('[part="listbox"]');const animations=listbox?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(this.transitionToken!==token)return}this.emit(event);this.resolveTransitionWaiters(event)}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve);this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(!waiters)return;this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}emitValueEvents(){this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})}createOption(inputValue){if(this.effectiveDisabled)return;const event=this.emit("lr-create",{inputValue},{cancelable:true});if(event.defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue);option.textContent=inputValue;this.append(option);this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.effectiveDisabled||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this._selectedLabelCache.set(inputValue,inputValue);this.value=inputValue;this.query="";this.explicitInputValue=false;void this.hide();if(selectionChanged)this.emitValueEvents()}pickRow(row){if(this.effectiveDisabled||row.disabled)return;if(row.createInput!==void 0){this.createOption(row.createInput);return}const selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);if(set.has(row.value)){set.delete(row.value);this._selectedRowCache.delete(row.value)}else{set.add(row.value);this._selectedLabelCache.set(row.value,row.label);this._selectedRowCache.set(row.value,row)}this.value=[...set];this.query="";this.explicitInputValue=false}else{this._selectedLabelCache.set(row.value,row.label);this._selectedRowCache.clear();this._selectedRowCache.set(row.value,row);this.value=row.value;this.query="";this.explicitInputValue=false;this.hide()}if(this.source)this.runSource(this.query);if(selectionChanged)this.emitValueEvents()}removeValue(value){const next=this._selected.filter(v=>v!==value);if(next.length===this._selected.length)return;this.value=next;this.emitValueEvents()}clear(){const hadSelection=this._selected.length>0;const queryChanged=this.query!=="";if(!hadSelection&&!queryChanged)return;if(hadSelection)this.value=[];this.query="";this.explicitInputValue=false;if(this.source)this.runSource(this.query);if(hadSelection){this.emitValueEvents();this.emit("lr-clear")}if(queryChanged)this.emit("lr-filter",{value:this.query})}runSource(query2){const source=this.source;if(!source)return;this.clearSourceTimer();this.sourceAbort?.abort();this.sourceAbort=void 0;const token=++this.sourceToken;const ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const timer={owner:ownerWindow,handle:0,token};timer.handle=ownerWindow.setTimeout(()=>{if(this.sourceTimer!==timer||token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.sourceTimer=void 0;const controller=new ownerWindow.AbortController;this.sourceAbort=controller;this.loading=true;this.sourceFailed=false;Promise.resolve().then(()=>source(query2,{signal:controller.signal})).then(rows=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.asyncRows=rows;this.sourceFailed=false;const navigableCount=rows.filter(row=>!row.disabled).length;if(this.activeIndex>=navigableCount){this.activeIndex=navigableCount?navigableCount-1:-1}const selected=new Set(this._selected);for(const row of rows){if(selected.has(row.value))this._selectedRowCache.set(row.value,row)}}).catch(err=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}if(typeof err==="object"&&err!==null&&"name"in err&&err.name==="AbortError"){return}this.asyncRows=[];this.activeIndex=-1;this.sourceFailed=true;this.sourceErrorAnnouncementSink?.announce(this.localize("comboboxLoadError"));console.warn("<lr-combobox> source() rejected:",err)}).finally(()=>{if(token===this.sourceToken)this.loading=false})},this._sourceDelay);this.sourceTimer=timer}clearSourceTimer(){const timer=this.sourceTimer;this.sourceTimer=void 0;if(timer)timer.owner.clearTimeout(timer.handle)}renderRows(rows,activeId){const out=[];let currentGroup;let currentGroupRows=[];let groupIndex=0;const selectedSet=new Set(this._selected);const flushGroup=()=>{if(!currentGroupRows.length)return;if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
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--)if(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{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import{LyraOption}from"./option.class.js";import"./option.class.js";import{autocorrectConverter,omittedEmptyStringConverter,spellcheckConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{tag}from"../../../internal/prefix.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraCombobox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},multiple:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:true},maxRender:{type:Number,attribute:"max-render",noAccessor:true},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:true}}}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=Boolean(next);this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=true;this.query=next??"";this.activeIndex=-1;if(this.source)this.runSource(this.query);this.requestUpdate()}constructor(){super();this.placeholder="";this.label="";this.hint="";this.errorText="";this.open=false;this.allowCreate=false;this.allowCustomValue=false;this.appearance="outlined";this.placement="bottom";this.size="m";this.pill=false;this.clearable=false;this.withClear=false;this.withLabel=false;this.withHint=false;this.validators=[];this.autocomplete="off";this.inputMode="";this.enterKeyHint="";this.spellcheck=false;this.autocapitalize="";this.autocorrectValue=true;this.emptyText="";this.loadingText="";this.overflowText="";this.filter=null;this.source=null;this.query="";this.explicitInputValue=false;this.activeIndex=-1;this.options=[];this.touched=false;this.slotPresence=new SlotPresenceController(this);this.loading=false;this.sourceFailed=false;this.asyncRows=[];this.sourceToken=0;this._sourceWarmed=false;this._selectedLabelCache=new Map;this._selectedRowCache=new Map;this._rowsByValue=new Map;this._fieldsetDisabled=false;this.listId=nextId("combobox-list");this.inputId=nextId("combobox-input");this._isFirstUpdate=true;this.openVetoed=false;this.transitionToken=0;this.transitionWaiters=new Map;this._selected=[];this._valueDirty=false;this._multiple=false;this._disabled=false;this._required=false;this._defaultSelected=[];this._defaultCaptured=false;this._restoredStateActive=false;this._name="";this._maxOptionsVisible=3;this._maxRender=200;this._sourceDelay=200;this.collectOptions=e=>{const slot=e.target;const previous=new Set(this.options);this.options=slot.assignedElements({flatten:true}).filter(el=>el instanceof LyraOption);if(!this._defaultCaptured){this._defaultCaptured=true;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value);const allLive=this.options.filter(option=>option.selected).map(option=>option.value);const defaults=this.multiple?allDefaults:allDefaults.slice(0,1);const live=this.multiple?allLive:allLive.slice(0,1);const initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);const optionDirty=this.options.some(option=>isOptionSelectedDirty(option));const dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);const dirtyValues=dirtySelected.map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0;const initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];if(fromDefaults&&!optionDirty)this.setValue(next,false);else this.value=next;return}if(optionDirty)this._valueDirty=true}else{const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected);const newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...!this._restoredStateActive?newLive:[]];if(eligible.length){const values=eligible.map(option=>option.value);const next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];if(newLive.length>0)this.value=next;else this.setValue(next,false);return}}this.reflectSelected()};this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults();this.reflectSelected();this.options=[...this.options]})};this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onInput=e=>{this.explicitInputValue=false;this.query=e.target.value;this.activeIndex=-1;this.show();if(this.source)this.runSource(this.query);this.emit("lr-filter",{value:this.query})};this.onInputBlur=()=>{if(!this.effectiveDisabled)this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onInputFocus=()=>{this.show();this.emit("focus")};this.onKeyDown=e=>{const navigable=this.renderedRows.rows.filter(r=>!r.disabled);switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open){void this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open){void this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault();this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault();this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault();this.commitCustomValue(this.query.trim());break}if(this.effectiveDisabled)break;submitOnEnter(this,e);break}case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=navigable.length-1}break;case"Backspace":if(this.multiple&&!this.query&&this._selected.length){this.removeValue(this._selected[this._selected.length-1])}break}};this.onComboMouseDown=e=>{if(this.effectiveDisabled)return;if(e.target.closest("button"))return;e.preventDefault();this.renderRoot.querySelector('[part="combobox-input"]')?.focus();this.show()};this.onListboxMouseDown=e=>{e.preventDefault()};this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]');const value=optionEl?.dataset["value"];if(value===void 0)return;const row=this._rowsByValue.get(value);if(row)this.pickRow(row)};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init))}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 validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0;this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){if(this.inputEl)this.inputEl.selectionStart=value}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){if(this.inputEl)this.inputEl.selectionEnd=value}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){if(this.inputEl)this.inputEl.selectionDirection=value}focus(options){this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){if(this.effectiveDisabled)return;this.inputEl?.focus();this.show()}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.explicitInputValue=true;this.query=input.value;this.activeIndex=-1;if(this.source)this.runSource(this.query)}[VALIDITY_ANCHOR](){return this.validationTarget}connectedCallback(){super.connectedCallback();this.syncSourceErrorAnnouncementSink();this.updateValidity();if(this.hasUpdated){queueMicrotask(()=>{if(this.open)this.reconnectOpenPopup();else if(this.source&&this._selected.length&&this.asyncRows.length===0){this.runSource("")}})}}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearSourceTimer();this.sourceToken+=1;this.sourceAbort?.abort();this.sourceAbort=void 0;this.releaseSourceErrorAnnouncementSink();this.syncSourceErrorAnnouncementSink()}syncSourceErrorAnnouncementSink(){if(!this.isConnected)return;if(this.sourceErrorAnnouncementSink?.element.ownerDocument===this.ownerDocument)return;this.releaseSourceErrorAnnouncementSink();this.sourceErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}releaseSourceErrorAnnouncementSink(){this.sourceErrorAnnouncementSink?.release();this.sourceErrorAnnouncementSink=void 0}willUpdate(changed){super.willUpdate(changed);this._isFirstUpdate=!this.hasUpdated;this.announceOpenTransition(changed);if(changed.has("source")){this.clearSourceTimer();this.sourceAbort?.abort();this.sourceAbort=void 0;this.sourceToken++;this.loading=false;this.sourceFailed=false;this.asyncRows=[];this.activeIndex=-1;this._sourceWarmed=false;if(this.source&&this.open)this.runSource(this.query)}if(!this._sourceWarmed&&this.source&&this._selected.length&&this.asyncRows.length===0){this._sourceWarmed=true;this.runSource("")}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.syncFormValue();this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=Boolean(next);this.toggleAttribute("multiple",this._multiple);this.syncFormValue();this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,true)}setValue(next,dirty){const old=this._selected;if(dirty){this._restoredStateActive=false;this._valueDirty=true}this._selected=Array.isArray(next)?[...next]:next?[next]:[];const selected=new Set(this._selected);for(const value of selected){const row=this.effectiveRows.find(candidate=>candidate.value===value)??this.asyncRows.find(candidate=>candidate.value===value);if(row)this._selectedRowCache.set(value,row)}for(const value of this._selectedRowCache.keys()){if(!selected.has(value))this._selectedRowCache.delete(value)}for(const value of this._selectedLabelCache.keys()){if(!selected.has(value))this._selectedLabelCache.delete(value)}this.syncFormValue();this.reflectSelected();this.updateValidity();this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3);this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200);this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=finiteCount(next,200);this.requestUpdate("maxRender",old)}get selectedRows(){return this._selected.map(value=>this._selectedRowCache.get(value)??this.effectiveRows.find(row=>row.value===value)??this.asyncRows.find(row=>row.value===value)).filter(row=>row!=null)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&this._selected.length===0){this.validityController.setValidity({valueMissing:true},this.localize("comboboxRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation});setCustomState(this.internals,"blank",this._selected.length===0);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else{this.internals.setFormValue(this._selected[0]??"",state2)}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=false;this._restoredStateActive=false;this._valueDirty=false;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);if(this._defaultSelected.length===0&&resetValues.length>0)this._defaultSelected=[...resetValues];const defaults=new Set(resetValues);for(const option of this.options){option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value))}this.setValue(this.multiple?[...resetValues]:resetValues[0]??"",false);this.query="";this.explicitInputValue=false}formStateRestoreCallback(state2,reason){void reason;let selected=[];if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(Array.isArray(parsed)&&parsed.every(value=>typeof value==="string"))selected=parsed}catch{}}this.value=this.multiple?selected:selected[0]??"";this._restoredStateActive=true}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates()}disconnectedCallback(){this.transitionToken++;this.releaseSourceErrorAnnouncementSink();super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.clearSourceTimer();this.sourceToken+=1;this.sourceAbort?.abort();this.sourceAbort=void 0;this.unbindDocumentPointer();this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");this.open=false}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1);if(!this._valueDirty&&!this._restoredStateActive){this.setValue(this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",false)}}reflectSelected(){const sel=new Set(this._selected);for(const option of this.options){option[SET_OPTION_SELECTED_FROM_OWNER](sel.has(option.value))}}labelFor(value){return this._selectedLabelCache.get(value)??this.options.find(o=>o.value===value)?.label??this.asyncRows.find(r=>r.value===value)?.label??value}get effectiveRows(){if(this.source)return this.asyncRows;return this.filtered.map(o=>({value:o.value,label:o.label,sub:o.sub||void 0,dotColor:o.dotColor||void 0,group:o.group||void 0,disabled:o.disabled}))}get createRow(){if(!this.allowCreate)return void 0;const inputValue=this.query.trim();if(!inputValue)return void 0;const locale=this.effectiveLocale;const folded=inputValue.toLocaleLowerCase(locale);const rows=this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}));if(rows.some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded)){return void 0}return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}get renderedRows(){const all=this.effectiveRows;const create=this.createRow;if(all.length<=this.maxRender)return{rows:create?[...all,create]:all,overflow:0};const originalIndex=new Map(all.map((r,i)=>[r,i]));const capped=all.slice(0,this.maxRender);const cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=false;for(const v of this._selected){if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);if(selectedRow){capped.push(selectedRow);appendedOutOfCap=true}}}if(appendedOutOfCap){capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b))}if(create)capped.push(create);return{rows:capped,overflow:all.length-capped.length+(create?1:0)}}get filtered(){const locale=this.effectiveLocale;const q=this.query.trim().toLocaleLowerCase(locale);const selectedLabel=!this.multiple?this.labelFor(this._selected[0]??"")??"":"";const effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){if(this.multiple||this.open||this.explicitInputValue)return this.query;return this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){this.openVetoed=false;if(!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}if(!this.emit(name,void 0,{cancelable:true}).defaultPrevented)return;this.openVetoed=true;this.open=!this.open;this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show")}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;return settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.open=false;this.activeIndex=-1;if(!this.multiple){const queryChanged=this.query!=="";this.query="";this.explicitInputValue=false;if(queryChanged&&this.source){this.asyncRows=[];this.sourceFailed=false}}return settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.cleanup?.();this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`})}if(this.source&&this.asyncRows.length===0)this.runSource(this.query)}updated(changed){super.updated(changed);if(changed.has("open")&&!this.openVetoed){this.cleanup?.();this.cleanup=void 0;if(this.open&&this.isConnected){this.bindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-show")}const anchor=this.renderRoot.querySelector('[part="combobox"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`})}if(this.source&&this.asyncRows.length===0)this.runSource(this.query)}else if(!this.open){this.unbindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-hide")}}else{this.unbindDocumentPointer()}}if(changed.has("name"))this.syncFormValue();if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}if(changed.has("activeIndex")){this.renderRoot.querySelector('[part="option"][data-active]')?.scrollIntoView({block:"nearest"})}}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const listbox=this.renderRoot.querySelector('[part="listbox"]');const animations=listbox?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(this.transitionToken!==token)return}this.emit(event);this.resolveTransitionWaiters(event)}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve);this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(!waiters)return;this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}emitValueEvents(){this.emit("input",{value:this.value});this.emit("change",{value:this.value});this.emit("lr-change",{value:this.value})}createOption(inputValue){if(this.effectiveDisabled)return;const event=this.emit("lr-create",{inputValue},{cancelable:true});if(event.defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue);option.textContent=inputValue;this.append(option);this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.effectiveDisabled||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this._selectedLabelCache.set(inputValue,inputValue);this.value=inputValue;this.query="";this.explicitInputValue=false;void this.hide();if(selectionChanged)this.emitValueEvents()}pickRow(row){if(this.effectiveDisabled||row.disabled)return;if(row.createInput!==void 0){this.createOption(row.createInput);return}const selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);if(set.has(row.value)){set.delete(row.value);this._selectedRowCache.delete(row.value)}else{set.add(row.value);this._selectedLabelCache.set(row.value,row.label);this._selectedRowCache.set(row.value,row)}this.value=[...set];this.query="";this.explicitInputValue=false}else{this._selectedLabelCache.set(row.value,row.label);this._selectedRowCache.clear();this._selectedRowCache.set(row.value,row);this.value=row.value;this.query="";this.explicitInputValue=false;this.hide()}if(this.source)this.runSource(this.query);if(selectionChanged)this.emitValueEvents()}removeValue(value){const next=this._selected.filter(v=>v!==value);if(next.length===this._selected.length)return;this.value=next;this.emitValueEvents()}clear(){const hadSelection=this._selected.length>0;const queryChanged=this.query!=="";if(!hadSelection&&!queryChanged)return;if(hadSelection)this.value=[];this.query="";this.explicitInputValue=false;if(this.source)this.runSource(this.query);if(hadSelection){this.emitValueEvents();this.emit("lr-clear")}if(queryChanged)this.emit("lr-filter",{value:this.query})}runSource(query2){const source=this.source;if(!source)return;this.clearSourceTimer();this.sourceAbort?.abort();this.sourceAbort=void 0;const token=++this.sourceToken;const ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const timer={owner:ownerWindow,handle:0,token};timer.handle=ownerWindow.setTimeout(()=>{if(this.sourceTimer!==timer||token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.sourceTimer=void 0;const controller=new ownerWindow.AbortController;this.sourceAbort=controller;this.loading=true;this.sourceFailed=false;Promise.resolve().then(()=>source(query2,{signal:controller.signal})).then(rows=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.asyncRows=rows;this.sourceFailed=false;const navigableCount=rows.filter(row=>!row.disabled).length;if(this.activeIndex>=navigableCount){this.activeIndex=navigableCount?navigableCount-1:-1}const selected=new Set(this._selected);for(const row of rows){if(selected.has(row.value))this._selectedRowCache.set(row.value,row)}}).catch(err=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}if(typeof err==="object"&&err!==null&&"name"in err&&err.name==="AbortError"){return}this.asyncRows=[];this.activeIndex=-1;this.sourceFailed=true;this.sourceErrorAnnouncementSink?.announce(this.localize("comboboxLoadError"));console.warn("<lr-combobox> source() rejected:",err)}).finally(()=>{if(token===this.sourceToken)this.loading=false})},this._sourceDelay);this.sourceTimer=timer}clearSourceTimer(){const timer=this.sourceTimer;this.sourceTimer=void 0;if(timer)timer.owner.clearTimeout(timer.handle)}renderRows(rows,activeId){const out=[];let currentGroup;let currentGroupRows=[];let groupIndex=0;const selectedSet=new Set(this._selected);const flushGroup=()=>{if(!currentGroupRows.length)return;if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
2
2
  <div id=${labelId} class="group-label">${currentGroup}</div>
3
3
  ${currentGroupRows}
4
4
  </div>`)}else{out.push(...currentGroupRows)}currentGroupRows=[]};rows.forEach((o,i)=>{if(o.group!==currentGroup){flushGroup();currentGroup=o.group}const id=`${this.listId}-opt-${i}`;const selected=selectedSet.has(o.value);currentGroupRows.push(html`<div