@aceshooting/lyra-ui 17.0.0 → 18.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/CHANGELOG.md +254 -0
  2. package/README.md +2 -2
  3. package/custom-elements.json +1 -1
  4. package/dist/cli/migration-contract.json +1 -1
  5. package/dist/components/conversation/streaming-text/streaming-text-core.class.d.ts +22 -0
  6. package/dist/components/conversation/streaming-text/streaming-text-core.class.js +1 -0
  7. package/dist/components/conversation/streaming-text/streaming-text.class.d.ts +22 -0
  8. package/dist/components/conversation/streaming-text/streaming-text.class.js +1 -0
  9. package/dist/components/conversation/thread-list/thread-list.class.js +1 -1
  10. package/dist/components/data/table/table.styles.js +1 -1
  11. package/dist/components/forms/combobox/combobox.class.d.ts +12 -2
  12. package/dist/components/forms/combobox/combobox.class.js +2 -2
  13. package/dist/components/forms/combobox/combobox.styles.js +1 -1
  14. package/dist/components/forms/select/select.class.d.ts +31 -5
  15. package/dist/components/forms/select/select.class.js +2 -2
  16. package/dist/components/layout/filter-bar/filter-bar.class.d.ts +68 -6
  17. package/dist/components/layout/filter-bar/filter-bar.class.js +2 -2
  18. package/dist/components/layout/reorder-list/reorder-list.class.js +1 -1
  19. package/dist/components/layout/virtual-list/virtual-list.class.d.ts +107 -2
  20. package/dist/components/layout/virtual-list/virtual-list.class.js +12 -7
  21. package/dist/components/media/map/map.class.d.ts +138 -12
  22. package/dist/components/media/map/map.class.js +25 -20
  23. package/dist/components/media/map/map.styles.js +1 -1
  24. package/dist/custom-elements-jsx.d.ts +1 -1
  25. package/dist/events.d.ts +7 -1
  26. package/dist/internal/package-metadata.d.ts +1 -1
  27. package/dist/internal/package-metadata.js +1 -1
  28. package/dist/lyra.d.ts +1 -1
  29. package/dist/lyra.js +1 -1
  30. package/dist/svelte.d.ts +1 -1
  31. package/dist/testing/lyra-tag-event-map.js +1 -1
  32. package/dist/translations/ar/retrieval.js +1 -1
  33. package/dist/translations/ar/shared.js +1 -1
  34. package/dist/translations/de/retrieval.js +1 -1
  35. package/dist/translations/de/shared.js +1 -1
  36. package/dist/translations/es/retrieval.js +1 -1
  37. package/dist/translations/es/shared.js +1 -1
  38. package/dist/translations/fa/retrieval.js +1 -1
  39. package/dist/translations/fa/shared.js +1 -1
  40. package/dist/translations/fr/retrieval.js +1 -1
  41. package/dist/translations/fr/shared.js +1 -1
  42. package/dist/translations/he/retrieval.js +1 -1
  43. package/dist/translations/he/shared.js +1 -1
  44. package/dist/translations/it/retrieval.js +1 -1
  45. package/dist/translations/it/shared.js +1 -1
  46. package/dist/translations/ja/retrieval.js +1 -1
  47. package/dist/translations/ja/shared.js +1 -1
  48. package/dist/translations/pt-BR/retrieval.js +1 -1
  49. package/dist/translations/pt-BR/shared.js +1 -1
  50. package/dist/translations/ro/agent-tools.d.ts +1 -0
  51. package/dist/translations/ro/agent-tools.js +1 -0
  52. package/dist/translations/ro/charts.d.ts +1 -0
  53. package/dist/translations/ro/charts.js +1 -0
  54. package/dist/translations/ro/conversation.d.ts +1 -0
  55. package/dist/translations/ro/conversation.js +1 -0
  56. package/dist/translations/ro/data.d.ts +1 -0
  57. package/dist/translations/ro/data.js +1 -0
  58. package/dist/translations/ro/forms.d.ts +1 -0
  59. package/dist/translations/ro/forms.js +1 -0
  60. package/dist/translations/ro/layout.d.ts +1 -0
  61. package/dist/translations/ro/layout.js +1 -0
  62. package/dist/translations/ro/media.d.ts +1 -0
  63. package/dist/translations/ro/media.js +1 -0
  64. package/dist/translations/ro/overlays.d.ts +1 -0
  65. package/dist/translations/ro/overlays.js +1 -0
  66. package/dist/translations/ro/retrieval.d.ts +1 -0
  67. package/dist/translations/ro/retrieval.js +1 -0
  68. package/dist/translations/ro/shared.d.ts +1 -0
  69. package/dist/translations/ro/shared.js +1 -0
  70. package/dist/translations/ro/utility.d.ts +1 -0
  71. package/dist/translations/ro/utility.js +1 -0
  72. package/dist/translations/ro/viewers.d.ts +1 -0
  73. package/dist/translations/ro/viewers.js +5 -0
  74. package/dist/translations/ro.d.ts +1 -0
  75. package/dist/translations/ro.js +1 -0
  76. package/dist/translations/ru/retrieval.js +1 -1
  77. package/dist/translations/ru/shared.js +1 -1
  78. package/dist/translations/zh-CN/retrieval.js +1 -1
  79. package/dist/translations/zh-CN/shared.js +1 -1
  80. package/dist/vue.d.ts +1 -1
  81. package/llms/components/lr-button.md +5 -4
  82. package/llms/components/lr-card.md +2 -1
  83. package/llms/components/lr-combobox.md +7 -0
  84. package/llms/components/lr-filter-bar.md +86 -3
  85. package/llms/components/lr-icon-button.md +2 -1
  86. package/llms/components/lr-map.md +63 -6
  87. package/llms/components/lr-option.md +7 -0
  88. package/llms/components/lr-select.md +19 -2
  89. package/llms/components/lr-streaming-text-core.md +7 -3
  90. package/llms/components/lr-streaming-text.md +7 -2
  91. package/llms/components/lr-virtual-list.md +53 -0
  92. package/llms/shared.md +6 -3
  93. package/llms-full.txt +273 -22
  94. package/package.json +28 -2
  95. package/registrations.json +1 -1
  96. package/vscode-css-data.json +1 -1
  97. package/vscode-html-data.json +1 -1
  98. package/web-types.json +1 -1
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select,LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings.generated.js";const TYPE_AHEAD_RESET_MS=500;function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.filled=!1,this.withClear=!1,this.clearable=!1,this.showUnknownOption=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this._isFirstUpdate=!0,this.openVetoed=!1,this.openStateGeneration=0,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeAheadBuffer="",this.typeAheadReset=new DebounceController(TYPE_AHEAD_RESET_MS,armedIn=>{!this.isConnected||this.ownerDocument.defaultView!==armedIn||(this.typeAheadBuffer="")},()=>this.ownerDocument.defaultView),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isLyraOptionElement(option)&&this.options.includes(option)&&isOptionSelectedWrite(e)){this._valueDirty=!0,this._restoredStateActive=!1;const selected=this._selectedOptions.includes(option);if(option.selected===selected&&(!selected||this._selectedValuesByOption.get(option)===option.value))return;if(option.selected&&!this.multiple){this.setSelection([option.value],[option]);return}const remaining=[...this._selectedOptions],preferred=this._selected.map(value=>{const index2=remaining.findIndex(candidate=>this._selectedValuesByOption.get(candidate)===value);return index2<0?void 0:remaining.splice(index2,1)[0]}),values=[...this._selected],index=preferred.indexOf(option);if(option.selected)index<0?(values.push(option.value),preferred.push(option)):values[index]=option.value;else{if(index<0)return;values.splice(index,1),preferred.splice(index,1)}this.setSelection(values,preferred);return}isLyraOptionElement(option)&&this.adornmentClones.get(option)?.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option);const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{const navigable=this.navigableOptions();switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(Math.min(navigable.length-1,this.activeIndex+1),navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(Math.max(0,this.activeIndex-1),navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(navigable.length-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),installInteractionOnInvalid(this,this.markInteracted),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),this.syncFormValue()}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"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0||this._pendingInitialSelectedOptions!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0,this.selectedOptions=pending}}finally{this._resolvingPendingInitialSelection=!1}}this.announceOpenTransition(changed),changed.has("open")&&!this.open&&!this.openVetoed&&this.setActiveIndex(-1)}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{s.assignedElements({flatten:!0}).some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.transitionToken++,this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open,this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show"))}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialValue=next),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialSelectedOptions=next),this._restoredStateActive=!1,this._valueDirty=!0;const candidates=Array.isArray(next)?next:[],live=candidates.filter((option,index)=>isLyraOptionElement(option)&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){const claimed=new Set;return values.map((value,index)=>{const hint=preferred.length===values.length?preferred[index]:preferred.find(option=>option?.value===value&&!claimed.has(option)),match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),this._selected.length===0?this.internals.states?.add("blank"):this.internals.states?.delete("blank")}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.updateValidity(),withStaticValidityCheck(this,()=>this.internals.checkValidity())}reportValidity(){return this.updateValidity(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.releaseExternalDescription(),this.transitionToken++,super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.clearTypeAheadTimer(),this.typeAheadBuffer="",this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),this.open=!1}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.setSelection(values,this.resolveOccurrences(values,this._selectedOptions)),this.emitValueEvents(),this.emit("lr-activate",{value});return}this.hide(),this.emit("lr-activate",{value})}resolvedLabelFor(value,occurrenceIndex=0){return(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]?.label:void 0)??this._selectedOptions.find(option=>option.value===value)?.label??this.options.find(option=>option.value===value)?.label}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;const override=this.getUnknownLabel?.(value);return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return options.filter(option=>this.isOptionAvailable(option))}get unknownValues(){return this.showUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get listboxOptions(){const unknown=this.unknownOptions;return unknown.length===0?this.options:[...this.options,...unknown]}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.listboxOptions.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');!anchor||!listbox||(this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")}),this.positioningReady=this.cleanup.ready)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.bindDocumentPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.restoreFocusOnClose=!0}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener,!0)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener,!0),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(event==="lr-after-show"){for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(this.transitionToken!==token)return;if(positioned)break;if(readiness===this.positioningReady){this.forceCloseOpenState();return}}if(await this.updateComplete,this.transitionToken!==token)return}if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),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){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}emitValueEvents(){const self=this,data=this.selectedData;dispatchNativeInputEvent(this),self.emit("lr-input",{value:self.value,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value:self.value,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}selectOption(option){if(this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}if(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.multiple){const selectedIndex=this._selectedOptions.indexOf(option),selected=selectedIndex>=0,occurrences=selected?this._selectedOptions.filter((_,index)=>index!==selectedIndex):[...this._selectedOptions,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,option.value];this.setSelection(values,occurrences),this.emitValueEvents(),this.emit("lr-activate",{value:option.value});return}const changed=option!==this._selectedOptions[0]||option.value!==this._selected[0];this.setSelection([option.value],[option]),this.hide(),changed&&this.emitValueEvents(),this.emit("lr-activate",{value:option.value})}removeValueAt(index){this.effectiveDisabled||index<0||index>=this._selected.length||(this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this._selectedOptions.filter((_,candidateIndex)=>candidateIndex!==index)),this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||(this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection([],[]),this.emitValueEvents(),this.emit("lr-clear"))}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&(this.removeValueAt(index),this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()}))}typeAhead(char){this.clearTypeAheadTimer(),this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;this.isConnected&&ownerWindow&&this.typeAheadReset.push(ownerWindow);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),n=navigable.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,candidate=navigable[idx];if(candidate!==void 0&&candidate.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.setActiveIndex(idx,navigable);return}if(this.multiple&&this._selectedOptions.includes(candidate))continue;this.selectOption(candidate);return}}}clearTypeAheadTimer(){this.typeAheadReset.cancel()}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_loading,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select,LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings.generated.js";const TYPE_AHEAD_RESET_MS=500;function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,loading:LYRA_DEFAULT_loading,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.filled=!1,this.withClear=!1,this.clearable=!1,this.showUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this._isFirstUpdate=!0,this.openVetoed=!1,this.openStateGeneration=0,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeAheadBuffer="",this.typeAheadReset=new DebounceController(TYPE_AHEAD_RESET_MS,armedIn=>{!this.isConnected||this.ownerDocument.defaultView!==armedIn||(this.typeAheadBuffer="")},()=>this.ownerDocument.defaultView),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isLyraOptionElement(option)&&this.options.includes(option)&&isOptionSelectedWrite(e)){this._valueDirty=!0,this._restoredStateActive=!1;const selected=this._selectedOptions.includes(option);if(option.selected===selected&&(!selected||this._selectedValuesByOption.get(option)===option.value))return;if(option.selected&&!this.multiple){this.setSelection([option.value],[option]);return}const remaining=[...this._selectedOptions],preferred=this._selected.map(value=>{const index2=remaining.findIndex(candidate=>this._selectedValuesByOption.get(candidate)===value);return index2<0?void 0:remaining.splice(index2,1)[0]}),values=[...this._selected],index=preferred.indexOf(option);if(option.selected)index<0?(values.push(option.value),preferred.push(option)):values[index]=option.value;else{if(index<0)return;values.splice(index,1),preferred.splice(index,1)}this.setSelection(values,preferred);return}isLyraOptionElement(option)&&this.adornmentClones.get(option)?.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option);const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{const navigable=this.navigableOptions();switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(Math.min(navigable.length-1,this.activeIndex+1),navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(Math.max(0,this.activeIndex-1),navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(navigable.length-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),installInteractionOnInvalid(this,this.markInteracted),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),this.syncFormValue()}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"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0||this._pendingInitialSelectedOptions!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0,this.selectedOptions=pending}}finally{this._resolvingPendingInitialSelection=!1}}this.announceOpenTransition(changed),changed.has("open")&&!this.open&&!this.openVetoed&&this.setActiveIndex(-1)}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{s.assignedElements({flatten:!0}).some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.transitionToken++,this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open,this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show"))}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialValue=next),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialSelectedOptions=next),this._restoredStateActive=!1,this._valueDirty=!0;const candidates=Array.isArray(next)?next:[],live=candidates.filter((option,index)=>isLyraOptionElement(option)&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){const claimed=new Set;return values.map((value,index)=>{const hint=preferred.length===values.length?preferred[index]:preferred.find(option=>option?.value===value&&!claimed.has(option)),match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),this._selected.length===0?this.internals.states?.add("blank"):this.internals.states?.delete("blank")}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.updateValidity(),withStaticValidityCheck(this,()=>this.internals.checkValidity())}reportValidity(){return this.updateValidity(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.releaseExternalDescription(),this.transitionToken++,super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.clearTypeAheadTimer(),this.typeAheadBuffer="",this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),this.open=!1}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.setSelection(values,this.resolveOccurrences(values,this._selectedOptions)),this.emitValueEvents(),this.emit("lr-activate",{value});return}this.hide(),this.emit("lr-activate",{value})}resolvedLabelFor(value,occurrenceIndex=0){return(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]?.label:void 0)??this._selectedOptions.find(option=>option.value===value)?.label??this.options.find(option=>option.value===value)?.label}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;if(this.loading)return this.localize("loading");const override=this.getUnknownLabel?.(value);return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return this.loading?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return options.filter(option=>this.isOptionAvailable(option))}get unknownValues(){return this.showUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get listboxOptions(){const unknown=this.unknownOptions;return unknown.length===0?this.options:[...this.options,...unknown]}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.listboxOptions.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');!anchor||!listbox||(this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")}),this.positioningReady=this.cleanup.ready)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.bindDocumentPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.restoreFocusOnClose=!0}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener,!0)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener,!0),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(event==="lr-after-show"){for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(this.transitionToken!==token)return;if(positioned)break;if(readiness===this.positioningReady){this.forceCloseOpenState();return}}if(await this.updateComplete,this.transitionToken!==token)return}if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),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){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}emitValueEvents(){const self=this,data=this.selectedData;dispatchNativeInputEvent(this),self.emit("lr-input",{value:self.value,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value:self.value,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}selectOption(option){if(this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}if(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.multiple){const selectedIndex=this._selectedOptions.indexOf(option),selected=selectedIndex>=0,occurrences=selected?this._selectedOptions.filter((_,index)=>index!==selectedIndex):[...this._selectedOptions,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,option.value];this.setSelection(values,occurrences),this.emitValueEvents(),this.emit("lr-activate",{value:option.value});return}const changed=option!==this._selectedOptions[0]||option.value!==this._selected[0];this.setSelection([option.value],[option]),this.hide(),changed&&this.emitValueEvents(),this.emit("lr-activate",{value:option.value})}removeValueAt(index){this.effectiveDisabled||index<0||index>=this._selected.length||(this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this._selectedOptions.filter((_,candidateIndex)=>candidateIndex!==index)),this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||(this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection([],[]),this.emitValueEvents(),this.emit("lr-clear"))}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&(this.removeValueAt(index),this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()}))}typeAhead(char){this.clearTypeAheadTimer(),this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;this.isConnected&&ownerWindow&&this.typeAheadReset.push(ownerWindow);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),n=navigable.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,candidate=navigable[idx];if(candidate!==void 0&&candidate.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.setActiveIndex(idx,navigable);return}if(this.multiple&&this._selectedOptions.includes(candidate))continue;this.selectOption(candidate);return}}}clearTypeAheadTimer(){this.typeAheadReset.cancel()}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
2
2
  <div id=${labelId} class="group-label" part="group-label">${currentGroup}</div>
3
3
  ${groupRows}
4
4
  </div>`)}else out.push(...groupRows);groupRows=[]}};return options.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,unknown=this.unknownOptionCache.get(o.value)===o,selected=unknown||chosen.has(o),adornments=this.adornmentsFor(o);groupRows.push(html`<div
@@ -152,4 +152,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
152
152
  @lr-option-change=${this.onOptionChange}
153
153
  hidden
154
154
  ></slot>
155
- `}}__decorate([property()],LyraSelect.prototype,"placeholder",void 0),__decorate([property()],LyraSelect.prototype,"label",void 0),__decorate([property()],LyraSelect.prototype,"hint",void 0),__decorate([property({attribute:"help-text"})],LyraSelect.prototype,"helpText",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraSelect.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraSelect.prototype,"withHint",void 0),__decorate([property({attribute:"error-text"})],LyraSelect.prototype,"errorText",void 0),__decorate([property({type:Boolean})],LyraSelect.prototype,"autofocus",void 0),__decorate([property()],LyraSelect.prototype,"title",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraSelect.prototype,"open",null),__decorate([property({reflect:!0})],LyraSelect.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraSelect.prototype,"appearance",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraSelect.prototype,"pill",void 0),__decorate([property({reflect:!0})],LyraSelect.prototype,"placement",void 0),__decorate([property({attribute:"positioning-strategy",reflect:!0,converter:POSITIONING_STRATEGY})],LyraSelect.prototype,"positioningStrategy",null),__decorate([property({type:Boolean,reflect:!0})],LyraSelect.prototype,"hoist",null),__decorate([property({type:Boolean,reflect:!0})],LyraSelect.prototype,"filled",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"with-clear"})],LyraSelect.prototype,"withClear",void 0),__decorate([property({type:Boolean})],LyraSelect.prototype,"clearable",void 0),__decorate([property({attribute:!1})],LyraSelect.prototype,"getTag",void 0),__decorate([property({type:Boolean,attribute:"show-unknown-option",reflect:!0})],LyraSelect.prototype,"showUnknownOption",void 0),__decorate([property({attribute:!1})],LyraSelect.prototype,"getUnknownLabel",void 0),__decorate([property({type:Boolean,attribute:"auto-commit-single-option"})],LyraSelect.prototype,"autoCommitSingleOption",void 0),__decorate([state()],LyraSelect.prototype,"activeIndex",void 0),__decorate([state()],LyraSelect.prototype,"options",void 0),__decorate([state()],LyraSelect.prototype,"touched",void 0),__decorate([query('[part="trigger"]')],LyraSelect.prototype,"triggerElement",void 0),__decorate([query("slot:not([name])")],LyraSelect.prototype,"optionsSlot",void 0);export{LyraSelect};
155
+ `}}__decorate([property()],LyraSelect.prototype,"placeholder",void 0),__decorate([property()],LyraSelect.prototype,"label",void 0),__decorate([property()],LyraSelect.prototype,"hint",void 0),__decorate([property({attribute:"help-text"})],LyraSelect.prototype,"helpText",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraSelect.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraSelect.prototype,"withHint",void 0),__decorate([property({attribute:"error-text"})],LyraSelect.prototype,"errorText",void 0),__decorate([property({type:Boolean})],LyraSelect.prototype,"autofocus",void 0),__decorate([property()],LyraSelect.prototype,"title",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraSelect.prototype,"open",null),__decorate([property({reflect:!0})],LyraSelect.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraSelect.prototype,"appearance",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraSelect.prototype,"pill",void 0),__decorate([property({reflect:!0})],LyraSelect.prototype,"placement",void 0),__decorate([property({attribute:"positioning-strategy",reflect:!0,converter:POSITIONING_STRATEGY})],LyraSelect.prototype,"positioningStrategy",null),__decorate([property({type:Boolean,reflect:!0})],LyraSelect.prototype,"hoist",null),__decorate([property({type:Boolean,reflect:!0})],LyraSelect.prototype,"filled",void 0),__decorate([property({type:Boolean,reflect:!0,attribute:"with-clear"})],LyraSelect.prototype,"withClear",void 0),__decorate([property({type:Boolean})],LyraSelect.prototype,"clearable",void 0),__decorate([property({attribute:!1})],LyraSelect.prototype,"getTag",void 0),__decorate([property({type:Boolean,attribute:"show-unknown-option",reflect:!0})],LyraSelect.prototype,"showUnknownOption",void 0),__decorate([property({attribute:!1})],LyraSelect.prototype,"getUnknownLabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraSelect.prototype,"loading",void 0),__decorate([property({type:Boolean,attribute:"auto-commit-single-option"})],LyraSelect.prototype,"autoCommitSingleOption",void 0),__decorate([state()],LyraSelect.prototype,"activeIndex",void 0),__decorate([state()],LyraSelect.prototype,"options",void 0),__decorate([state()],LyraSelect.prototype,"touched",void 0),__decorate([query('[part="trigger"]')],LyraSelect.prototype,"triggerElement",void 0),__decorate([query("slot:not([name])")],LyraSelect.prototype,"optionsSlot",void 0);export{LyraSelect};
@@ -11,8 +11,10 @@ import type{LyraEventDetailSnapshot}from'../../../internal/lyra-element.js';impo
11
11
  * toolbar-button shape for a small fixed set of independently togglable categories, with the
12
12
  * same `string[]` value a `'combobox'` with `multiple` carries. `'custom'` delegates rendering
13
13
  * and event-to-value conversion to the definition's `custom` adapter, so an existing Lyra
14
- * control can participate without this component growing a branch for every control family. */
15
- export type LyraFilterBarControlType='select'|'combobox'|'checkbox-menu'|'date'|'date-range'|'text'|'custom';
14
+ * control can participate without this component growing a branch for every control family.
15
+ * `'chip'` is the one type that maps to no control at all: its value is owned by a widget
16
+ * elsewhere on the page, and this component renders only its active-filter chip. */
17
+ export type LyraFilterBarControlType='select'|'combobox'|'checkbox-menu'|'date'|'date-range'|'text'|'chip'|'custom';
16
18
  /** One closed-set choice for a `'select'`/`'combobox'` filter. */
17
19
  export interface LyraFilterBarOption{readonly value:string;readonly label:string;
18
20
  /** Optional decorative leading visual rendered into the `<lr-option>`'s `start` slot — a status
@@ -207,9 +209,46 @@ readonly presets?:readonly LyraDateRangePreset[];}export interface LyraFilterBar
207
209
  * debounce left: before this field existed, a custom free-text filter had to hand-roll the same
208
210
  * timer plus its flush/cancel lifecycle itself to get the same behaviour. */
209
211
  readonly debounce?:number;}
212
+ /** A control-less filter whose value is owned by a widget elsewhere on the page -- a calendar
213
+ * heatmap cell, a map selection, a chart brush. `<lr-filter-bar>` renders NO control for it and it
214
+ * occupies NO toolbar cell, but it is a filter in every other sense this component knows: it lives
215
+ * in `value` under its own `filterId`, rides every `lr-input`/`lr-reset` detail, counts toward
216
+ * `hasActiveFilters` (so it enables the reset button) and `invalidFilterIds`, renders a removable
217
+ * active-filter chip subject to `activeFiltersDisplay`, and is cleared by a chip removal and by
218
+ * `reset()` alongside every other filter.
219
+ *
220
+ * It extends the shared definition base rather than the composed one for the same reason
221
+ * `'custom'` does: `size`/`icon`/`labelVisibility`/`clearable` have no control to be forwarded to,
222
+ * so declaring them would be inert public API. The inherited `placeholder` is likewise inert here
223
+ * (there is no field to place it in), exactly as it already is for `'custom'`. The inherited
224
+ * `required` IS honoured, but only in bookkeeping: a required-but-empty chip filter appears in
225
+ * `invalidFilterIds` and fails `checkValidity()`, while rendering no inline error -- this component
226
+ * renders no element for that filter on which one could appear, so the widget that owns the value
227
+ * owns its error affordance too. The inherited `defaultValue` is
228
+ * restored by `reset()` and compared by `activeFiltersDisplay: 'changed'` like any other type's. */
229
+ export interface LyraFilterBarChipDefinition extends LyraFilterBarDefinitionBase{readonly type:'chip';
230
+ /** The chip's text for the current value. `locale` is `effectiveLocale` -- the same value every
231
+ * built-in type's own chip formatting (`getListFormat`/`getDateTimeFormat`) and a custom
232
+ * adapter's `formatValue` already receive -- because such a value is normally a formatted string
233
+ * (a localized date) rather than a label looked up in an options list. Caller-supplied copy, so
234
+ * (like `label`) this component does not route the result through `this.localize()`; passing the
235
+ * locale is what lets the caller do it. Omitted falls back to the same ladder a custom adapter's
236
+ * omitted `formatValue` uses: a string array formats as a localized conjunction list, any other
237
+ * value renders `String(value)`, and `undefined` renders `''`. */
238
+ readonly formatValue?:(value:LyraFilterBarFieldValue,locale:string)=>string;
239
+ /** The value written when this filter's chip is removed (or `clearFilter()` runs). Defaults to
240
+ * `''`, matching what every non-multi built-in type writes. Declare `[]` for a `string[]`-valued
241
+ * chip filter. A domain sentinel (`'all'`) must be paired with `isEmpty`, or the bar will treat
242
+ * the "cleared" value as still set and keep rendering a chip for it -- the identical pairing
243
+ * `LyraFilterBarCustomControlAdapter.clearValue`/`isEmpty` documents. */
244
+ readonly clearValue?:LyraFilterBarFieldValue;
245
+ /** Optional domain-specific empty predicate. Omitted, this filter uses the same built-in rule
246
+ * every non-`'custom'` type uses: absent, `false`, `''` and `[]` are empty, everything else is
247
+ * set. */
248
+ readonly isEmpty?:(value:LyraFilterBarFieldValue)=>boolean;}
210
249
  /** A host-declared filter. The discriminant makes choice options and custom adapters mandatory
211
250
  * exactly where runtime needs them, while excluding irrelevant fields from every other mode. */
212
- export type LyraFilterBarFilterDefinition=LyraFilterBarSelectDefinition|LyraFilterBarComboboxDefinition|LyraFilterBarCheckboxMenuDefinition|LyraFilterBarTextDefinition|LyraFilterBarDateDefinition|LyraFilterBarDateRangeDefinition|LyraFilterBarCustomDefinition;
251
+ export type LyraFilterBarFilterDefinition=LyraFilterBarSelectDefinition|LyraFilterBarComboboxDefinition|LyraFilterBarCheckboxMenuDefinition|LyraFilterBarTextDefinition|LyraFilterBarDateDefinition|LyraFilterBarDateRangeDefinition|LyraFilterBarChipDefinition|LyraFilterBarCustomDefinition;
213
252
  /**
214
253
  * The whole filter bar's current state: a plain, JSON-serializable object keyed by
215
254
  * `LyraFilterBarFilterDefinition.filterId`. This is the entire URL-querystring/app-state serialization
@@ -226,9 +265,10 @@ export type LyraFilterBarValue=Readonly<Record<string,LyraFilterBarFieldValue>>;
226
265
  * a `multiple` `'combobox'`) and a `'combobox'` with `multiple: true` narrow to `readonly
227
266
  * string[]`; every other `'combobox'` and every `'select'`/`'text'`/`'date'`/`'date-range'` narrow
228
267
  * to `string`; a `'custom'` definition keeps the full unconstrained `LyraFilterBarFieldValue`,
229
- * since its adapter is free to use either boolean meaning (see `LyraFilterBarCustomControlAdapter`).
268
+ * since its adapter is free to use either boolean meaning (see `LyraFilterBarCustomControlAdapter`),
269
+ * and so does a `'chip'` definition, whose value is owned by a widget this component never renders.
230
270
  */
231
- export type LyraFilterBarDefinitionValue<D extends LyraFilterBarFilterDefinition> =D extends LyraFilterBarCheckboxMenuDefinition?readonly string[]:D extends LyraFilterBarComboboxDefinition?D extends{multiple:true;}?readonly string[]:string:D extends LyraFilterBarCustomDefinition?LyraFilterBarFieldValue:string;
271
+ export type LyraFilterBarDefinitionValue<D extends LyraFilterBarFilterDefinition> =D extends LyraFilterBarCheckboxMenuDefinition?readonly string[]:D extends LyraFilterBarComboboxDefinition?D extends{multiple:true;}?readonly string[]:string:D extends LyraFilterBarCustomDefinition?LyraFilterBarFieldValue:D extends LyraFilterBarChipDefinition?LyraFilterBarFieldValue:string;
232
272
  /**
233
273
  * `LyraFilterBarValue` narrowed to a keyed record whose per-`filterId` value type follows the
234
274
  * matching entry in `Defs` -- the filter-bar analogue of `LyraPickerValue<Multiple>`.
@@ -324,6 +364,26 @@ export type LyraFilterBarInputEvent<Defs extends readonly LyraFilterBarFilterDef
324
364
  * button role, so writing one would be silently inert. A revealed `required` error still reaches
325
365
  * assistive technology, as a screen-reader-only run inside the trigger's accessible name.
326
366
  *
367
+ * A `'chip'` filter is the one type that composes no control at all. Its value is owned by a widget
368
+ * elsewhere on the page -- a calendar heatmap cell, a map selection, a chart brush -- so the bar
369
+ * renders no field for it and it claims no toolbar cell (no `field` wrapper, and therefore no blank
370
+ * column where an empty one's validation spacer would otherwise reserve a row of height). It is a
371
+ * filter in every other sense: it lives in `value` under its own `filterId`, rides every
372
+ * `lr-input`/`lr-reset` detail, counts toward `hasActiveFilters` (so it enables the reset button,
373
+ * which is exactly the "clear all" action an all-chip bar needs) and `invalidFilterIds`, renders a
374
+ * removable active-filter chip subject to `activeFiltersDisplay`, and is cleared by a chip removal
375
+ * and by `reset()` alongside every other filter. Its chip text comes from an optional
376
+ * `formatValue(value, locale)` receiving `effectiveLocale` -- the same locale every built-in type's
377
+ * own chip formatting and a custom adapter's `formatValue` already receive; omitted, a string array
378
+ * formats as a localized conjunction list and anything else renders `String(value)` verbatim, never
379
+ * through the date branch that would reformat an ISO day or mangle a value containing a slash.
380
+ * `clearValue` (default `''`) is what a chip removal writes; a domain sentinel must be paired with
381
+ * `isEmpty`, exactly as a custom adapter's own `clearValue`/`isEmpty` are. Its inherited
382
+ * `placeholder` is inert (there is no field to place it in), as it already is for `'custom'`, and
383
+ * its inherited `required` is honoured in bookkeeping only: a required-but-empty chip filter joins
384
+ * `invalidFilterIds`/`checkValidity()`/`lr-validity-change` but renders no inline error, since this
385
+ * component renders no element of its own on which one could appear.
386
+ *
327
387
  * Controlled, like every other Lyra data component: `value` is a plain, JSON-serializable object
328
388
  * (`LyraFilterBarValue`) the host reads/writes directly -- this component never touches
329
389
  * `location`/`history`/storage itself, so turning `value` into (and back out of) a URL
@@ -382,7 +442,9 @@ export type LyraFilterBarInputEvent<Defs extends readonly LyraFilterBarFilterDef
382
442
  * alone) when `filterId` is not a plain CSS ident (ASCII letters/digits/`-`/`_`, starting with a
383
443
  * letter) -- `part` is a space-separated token list like `class`, so an id containing whitespace
384
444
  * would otherwise silently fabricate an unrelated second token (including, in the worst case,
385
- * one colliding with a real part name like `active-filters`).
445
+ * one colliding with a real part name like `active-filters`). A `'chip'` filter renders no
446
+ * `field` wrapper at all, so neither `::part(field)` nor `::part(field-<filterId>)` ever matches
447
+ * one -- its only rendered surface is its active-filter `chip`.
386
448
  * @csspart end - Wrapper around the `end` slot; hidden while nothing is slotted.
387
449
  * @csspart filter-control - One filter's composed built-in control, or the wrapper around a
388
450
  * custom renderer's control (and around a `'checkbox-menu'`'s dropdown plus its error line).
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activeElementIn}from"../../../internal/active-element.js";import{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./filter-bar.styles.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({}),EMPTY_DATE_PRESETS=Object.freeze([]);function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}return isArray?snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0):EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","tags: filter-control-tags","tag: filter-control-tag","tag-label: filter-control-tag-label","tag__remove-button: filter-control-tag-remove-button","tag__remove-button__base: filter-control-tag-remove-button-base","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),CHECKBOX_MENU_EXPORT_PARTS=["base: filter-control-listbox"].join(", "),CHECKBOX_MENU_TRIGGER_EXPORT_PARTS=["base: filter-control-field","start: filter-control-start","label: filter-control-label-group","caret: filter-control-expand-icon"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", "),SAFE_FILTER_ID_PART=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fieldPartNames(filterId){return SAFE_FILTER_ID_PART.test(filterId)?`field field-${filterId}`:"field"}function isChoiceDefinition(definition){return definition.type==="select"||definition.type==="combobox"||definition.type==="checkbox-menu"}function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function filterValueEqualsDefault(value,defaultValue){const valueIsArray=Array.isArray(value),defaultIsArray=Array.isArray(defaultValue);return valueIsArray||defaultIsArray?!valueIsArray||!defaultIsArray?!1:value.length===defaultValue.length&&value.every((entry,index)=>entry===defaultValue[index]):Object.is(value,defaultValue)}function defineFilterValueEntry(record,key,value){Object.defineProperty(record,key,{value,enumerable:!0,configurable:!0,writable:!0})}function cloneFilterValueRecord(value){const clone={},descriptors=Object.getOwnPropertyDescriptors(value);let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&defineFilterValueEntry(clone,key,fieldValue)}return clone}function cloneFilterValue(value){return Object.freeze(cloneFilterValueRecord(value))}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.activeFiltersDisplay="all",this.touchedFilters=new Set,this.slotPresence=new SlotPresenceController(this),this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.rawValue=EMPTY_VALUE,this.debounceControllers=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(def,e)=>{const control=e.target;if(def.type==="combobox"&&this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,control.value,def.debounce);return}this.setFilterValue(def.filterId,control.value,control.appliedPreset)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation();const next=def.custom.adapter.valueFromEvent(e);if(this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,next,def.debounce,pending=>this.setCustomContextValue(def,generation,pending));return}this.setCustomContextValue(def,generation,next)}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,srOnly,styles]}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){const old=this._filters,widened=next;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(widened).filter(definition=>{try{return!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||typeof definition.label!="string"||definition.label.trim().length===0||seen.has(definition.filterId)||isChoiceDefinition(definition)&&!Array.isArray(definition.options)||definition.type==="custom"&&(!definition.custom?.adapter||typeof definition.custom.render!="function")?!1:(seen.add(definition.filterId),!0)}catch{return!1}}).map(definition=>{if(!isChoiceDefinition(definition))return definition;const options=definition.options.filter(option=>{try{return option!==null&&typeof option=="object"&&typeof Object.getOwnPropertyDescriptor(option,"value")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(option,"label")?.value=="string"}catch{return!1}});return Object.freeze({...definition,options:Object.freeze(options)})}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this.rawValue),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){const old=this._value,widened=next;try{this.rawValue=cloneFilterValue(widened??EMPTY_VALUE)}catch{this.rawValue=EMPTY_VALUE}this._value=this.normalizeValue(widened),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||defineFilterValueEntry(normalized,def.filterId,fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){if(this.disabled)return;this.cancelDebounce(),this.touchedFilters=new Set;const self=this;self.value=self.resetValue,self.emit("lr-input",Object.freeze({value:self.value,filterId:void 0,appliedPreset:void 0})),self.emit("lr-reset",Object.freeze({value:self.value}))}get resetValue(){const out={};for(const def of this._filters)if(def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)){const value=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue;defineFilterValueEntry(out,def.filterId,value)}return Object.freeze(out)}setFilterValue(id,value,appliedPreset){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:defineFilterValueEntry(next,id,value);const self=this;self.value=next,self.emit("lr-input",Object.freeze({value:self.value,filterId:id,appliedPreset}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}isDebounced(delay){return typeof delay=="number"&&Number.isFinite(delay)&&delay>0}scheduleDebounce(id,value,delay,commit=pending=>this.setFilterValue(id,pending)){let controller=this.debounceControllers.get(id);if(!controller){const created=new DebounceController(delay,pending=>{this.debounceControllers.get(id)===created&&this.debounceControllers.delete(id),pending!==void 0&&commit(pending)});controller=created,this.debounceControllers.set(id,created)}controller.delayMs=delay,controller.push(value)}hasPendingDebounce(id){return this.debounceControllers.get(id)?.pending??!1}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"";if(!this.isDebounced(def.debounce)){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.scheduleDebounce(def.filterId,next,def.debounce)}flushDebounce(id){this.debounceControllers.get(id)?.flush()}cancelDebounce(id){for(const[key,controller]of this.debounceControllers)id!==void 0&&key!==id||(controller.dispose(),this.debounceControllers.delete(key))}onFieldFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="checkbox-menu"||def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value,this.effectiveLocale);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(isChoiceDefinition(def)){const labels=(Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[]).map(v=>def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this.activeFiltersDisplay==="hidden"?[]:this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).filter(def=>this.activeFiltersDisplay!=="changed"||!filterValueEqualsDefault(this.valueFor(def),def.defaultValue)).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.closeCheckboxMenus(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}closeCheckboxMenus(){for(const menu of this.renderRoot?.querySelectorAll("lr-dropdown[data-filter-id]")??[])menu.open&&(menu.open=!1)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.closeCheckboxMenus(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll("lr-input[data-filter-id]")){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.hasPendingDebounce(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderStartAdornment(icon,slotName="start"){return icon==null?nothing:html`<span slot=${slotName} aria-hidden="true" inert>${icon}</span>`}renderOption(option){return html`<lr-option
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activeElementIn}from"../../../internal/active-element.js";import{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./filter-bar.styles.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({}),EMPTY_DATE_PRESETS=Object.freeze([]);function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}return isArray?snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0):EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","tags: filter-control-tags","tag: filter-control-tag","tag-label: filter-control-tag-label","tag__remove-button: filter-control-tag-remove-button","tag__remove-button__base: filter-control-tag-remove-button-base","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),CHECKBOX_MENU_EXPORT_PARTS=["base: filter-control-listbox"].join(", "),CHECKBOX_MENU_TRIGGER_EXPORT_PARTS=["base: filter-control-field","start: filter-control-start","label: filter-control-label-group","caret: filter-control-expand-icon"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", "),SAFE_FILTER_ID_PART=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fieldPartNames(filterId){return SAFE_FILTER_ID_PART.test(filterId)?`field field-${filterId}`:"field"}function isChoiceDefinition(definition){return definition.type==="select"||definition.type==="combobox"||definition.type==="checkbox-menu"}function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function filterValueEqualsDefault(value,defaultValue){const valueIsArray=Array.isArray(value),defaultIsArray=Array.isArray(defaultValue);return valueIsArray||defaultIsArray?!valueIsArray||!defaultIsArray?!1:value.length===defaultValue.length&&value.every((entry,index)=>entry===defaultValue[index]):Object.is(value,defaultValue)}function defineFilterValueEntry(record,key,value){Object.defineProperty(record,key,{value,enumerable:!0,configurable:!0,writable:!0})}function cloneFilterValueRecord(value){const clone={},descriptors=Object.getOwnPropertyDescriptors(value);let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&defineFilterValueEntry(clone,key,fieldValue)}return clone}function cloneFilterValue(value){return Object.freeze(cloneFilterValueRecord(value))}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.activeFiltersDisplay="all",this.touchedFilters=new Set,this.slotPresence=new SlotPresenceController(this),this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.rawValue=EMPTY_VALUE,this.debounceControllers=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(def,e)=>{const control=e.target;if(def.type==="combobox"&&this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,control.value,def.debounce);return}this.setFilterValue(def.filterId,control.value,control.appliedPreset)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation();const next=def.custom.adapter.valueFromEvent(e);if(this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,next,def.debounce,pending=>this.setCustomContextValue(def,generation,pending));return}this.setCustomContextValue(def,generation,next)}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,srOnly,styles]}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){const old=this._filters,widened=next;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(widened).filter(definition=>{try{return!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||typeof definition.label!="string"||definition.label.trim().length===0||seen.has(definition.filterId)||isChoiceDefinition(definition)&&!Array.isArray(definition.options)||definition.type==="custom"&&(!definition.custom?.adapter||typeof definition.custom.render!="function")?!1:(seen.add(definition.filterId),!0)}catch{return!1}}).map(definition=>{if(!isChoiceDefinition(definition))return definition;const options=definition.options.filter(option=>{try{return option!==null&&typeof option=="object"&&typeof Object.getOwnPropertyDescriptor(option,"value")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(option,"label")?.value=="string"}catch{return!1}});return Object.freeze({...definition,options:Object.freeze(options)})}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this.rawValue),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){const old=this._value,widened=next;try{this.rawValue=cloneFilterValue(widened??EMPTY_VALUE)}catch{this.rawValue=EMPTY_VALUE}this._value=this.normalizeValue(widened),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type==="chip")return typeof def.isEmpty=="function"?def.isEmpty(value):!isBuiltInSet(value);if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||defineFilterValueEntry(normalized,def.filterId,fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){if(this.disabled)return;this.cancelDebounce(),this.touchedFilters=new Set;const self=this;self.value=self.resetValue,self.emit("lr-input",Object.freeze({value:self.value,filterId:void 0,appliedPreset:void 0})),self.emit("lr-reset",Object.freeze({value:self.value}))}get resetValue(){const out={};for(const def of this._filters)if(def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)){const value=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue;defineFilterValueEntry(out,def.filterId,value)}return Object.freeze(out)}setFilterValue(id,value,appliedPreset){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:defineFilterValueEntry(next,id,value);const self=this;self.value=next,self.emit("lr-input",Object.freeze({value:self.value,filterId:id,appliedPreset}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}isDebounced(delay){return typeof delay=="number"&&Number.isFinite(delay)&&delay>0}scheduleDebounce(id,value,delay,commit=pending=>this.setFilterValue(id,pending)){let controller=this.debounceControllers.get(id);if(!controller){const created=new DebounceController(delay,pending=>{this.debounceControllers.get(id)===created&&this.debounceControllers.delete(id),pending!==void 0&&commit(pending)});controller=created,this.debounceControllers.set(id,created)}controller.delayMs=delay,controller.push(value)}hasPendingDebounce(id){return this.debounceControllers.get(id)?.pending??!1}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"";if(!this.isDebounced(def.debounce)){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.scheduleDebounce(def.filterId,next,def.debounce)}flushDebounce(id){this.debounceControllers.get(id)?.flush()}cancelDebounce(id){for(const[key,controller]of this.debounceControllers)id!==void 0&&key!==id||(controller.dispose(),this.debounceControllers.delete(key))}onFieldFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue??"":def.type==="checkbox-menu"||def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value,this.effectiveLocale);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(def.type==="chip"){const formatted=typeof def.formatValue=="function"?def.formatValue(value,this.effectiveLocale):void 0;return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(isChoiceDefinition(def)){const labels=(Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[]).map(v=>def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this.activeFiltersDisplay==="hidden"?[]:this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).filter(def=>this.activeFiltersDisplay!=="changed"||!filterValueEqualsDefault(this.valueFor(def),def.defaultValue)).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.closeCheckboxMenus(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}closeCheckboxMenus(){for(const menu of this.renderRoot?.querySelectorAll("lr-dropdown[data-filter-id]")??[])menu.open&&(menu.open=!1)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.closeCheckboxMenus(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll("lr-input[data-filter-id]")){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.hasPendingDebounce(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderStartAdornment(icon,slotName="start"){return icon==null?nothing:html`<span slot=${slotName} aria-hidden="true" inert>${icon}</span>`}renderOption(option){return html`<lr-option
2
2
  value=${option.value}
3
3
  search-text=${option.searchText??nothing}
4
4
  ?disabled=${option.disabled===!0}
@@ -125,7 +125,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
125
125
  >`}rendersValidationError(def){return!!def.required&&this.touchedFilters.has(def.filterId)&&this.isEmpty(def,this.valueFor(def))}render(){const accessibleLabel=this.hasAttribute("aria-label")?this.getAttribute("aria-label"):this.label||nothing,active=this.activeEntries;return html`
126
126
  <div part="base" role="group" aria-label=${accessibleLabel}>
127
127
  <div part="controls">
128
- ${this._filters.map(def=>html`<div part=${fieldPartNames(def.filterId)}>
128
+ ${this._filters.filter(def=>def.type!=="chip").map(def=>html`<div part=${fieldPartNames(def.filterId)}>
129
129
  ${this.renderControl(def)}
130
130
  <span
131
131
  class="validation-spacer"
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{releaseReorderOwnerState,reorderIdentityChange,updateReorderOwnerState}from"./reorder-owner.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./reorder-list.styles.js";import{LYRA_DEFAULT_reorderItemMoved,LYRA_DEFAULT_reorderMoveCancelled,LYRA_DEFAULT_reorderMovePending}from"../../../internal/default-strings.generated.js";class LyraReorderList extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.controlled=!1,this.pendingFocusTarget=null,this.focusRestoreGeneration=0,this.stateItems=new Set,this.moveToken=0,this.pendingMove=null,this.pendingReconciliation=null,this.onSlotChange=()=>{this.pendingMove&&this.pendingMove.phase==="held"&&!this.pendingMembershipIsCurrent()&&this.revertPendingMove(),this.pendingReconciliation&&this.tryCompleteControlledReconciliation(),this.syncBoundaryState()},this.onMoveRequest=e=>{const item=e.target?.closest?.(tag("reorder-item"));if(!item||item.parentElement!==this)return;const{direction}=e.detail;e.stopPropagation(),this.moveItem(item,direction)},this.onKeyDown=e=>{if(!(e.ctrlKey||e.metaKey)||e.altKey||e.shiftKey||e.key!=="ArrowUp"&&e.key!=="ArrowDown")return;const path=e.composedPath(),item=path.find(target=>target instanceof Element&&target.localName===tag("reorder-item")&&target.parentElement===this);if(!item)return;const itemIndex=path.indexOf(item);if(path.slice(0,itemIndex).some(target=>{if(!(target instanceof Element)||target.getRootNode()===item.shadowRoot)return!1;const name=target.localName;return name==="a"||name==="button"||name==="input"||name==="select"||name==="textarea"||target.hasAttribute("contenteditable")||name.includes("-")&&target!==item}))return;const items=this.itemElements,fromIndex=items.indexOf(item),toIndex=e.key==="ArrowDown"?fromIndex+1:fromIndex-1;this.disabled||this.pendingMove||this.pendingReconciliation||item.disabled||fromIndex<0||toIndex<0||toIndex>=items.length||(e.preventDefault(),this.moveItem(item,e.key==="ArrowDown"?"down":"up"))}}static{this.defaultStrings={...super.defaultStrings,reorderItemMoved:LYRA_DEFAULT_reorderItemMoved,reorderMoveCancelled:LYRA_DEFAULT_reorderMoveCancelled,reorderMovePending:LYRA_DEFAULT_reorderMovePending}}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-reorder"])}get directItemElements(){const itemTag=tag("reorder-item");return[...this.children].filter(element=>element.localName===itemTag)}get itemElements(){const seen=new Set;return this.directItemElements.filter(item=>{const value=item.value;return typeof value!="string"||value.trim()===""||seen.has(value)?!1:(seen.add(value),!0)})}syncBoundaryState(){const directItems=this.directItemElements,items=this.itemElements,validItems=new Set(items),heldMove=this.pendingMove?.phase==="held",reconciliation=this.pendingReconciliation,busy=heldMove||reconciliation!==null,nextStateItems=new Set(directItems);for(const item of this.stateItems)nextStateItems.has(item)||releaseReorderOwnerState(item,this);directItems.forEach(item=>{const i=items.indexOf(item);updateReorderOwnerState(item,this,{atStart:i===0,atEnd:i>=0&&i===items.length-1,listDisabled:this.disabled,pending:heldMove&&this.pendingMove?.item===item||reconciliation!==null&&item.value===reconciliation.value,busy,validIdentity:validItems.has(item)})}),this.stateItems=nextStateItems,this.requestUpdate()}tryCompleteControlledReconciliation(){const reconciliation=this.pendingReconciliation;if(!reconciliation)return;const items=this.itemElements,currentValues=items.map(entry=>entry.value);if(!(currentValues.length===reconciliation.expectedValues.length&&currentValues.every((value,index)=>value===reconciliation.expectedValues[index]))){currentValues.includes(reconciliation.value)||(this.pendingReconciliation=null);return}const movedItem=items[reconciliation.toIndex];this.pendingReconciliation=null,movedItem&&this.finishMove(movedItem,reconciliation.direction,reconciliation.toIndex)}[reorderIdentityChange](item){item.parentElement===this&&this.onSlotChange()}refreshItemObserver(){this.itemObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver;!Observer||!this.isConnected||(this.itemObserver=new Observer(()=>this.onSlotChange()),this.itemObserver.observe(this,{attributes:!0,childList:!0,attributeFilter:["disabled","value"]}))}pendingMembershipIsCurrent(){if(!this.pendingMove)return!1;const current=this.itemElements;return!this.disabled&&!this.pendingMove.item.disabled&&!this.pendingMove.target.disabled&&current.length===this.pendingMove.members.length&&current.every((item,index)=>item===this.pendingMove.members[index]&&item.value===this.pendingMove.values[index])&&current[this.pendingMove.toIndex]===this.pendingMove.target}connectedCallback(){super.connectedCallback(),this.refreshItemObserver(),this.syncBoundaryState()}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.syncBoundaryState(),changed.has("controlled")&&this.pendingReconciliation&&(this.pendingReconciliation=null,this.syncBoundaryState())}disconnectedCallback(){this.itemObserver?.disconnect(),this.itemObserver=void 0,this.pendingFocusTarget=null,this.focusRestoreGeneration+=1,this.pendingMove=null,this.pendingReconciliation=null,this.moveToken+=1;for(const item of this.stateItems)releaseReorderOwnerState(item,this);this.stateItems.clear(),super.disconnectedCallback()}orderValues(items){return Object.freeze(items.map(item=>item.value))}scheduleFocusRestore(){this.scheduleAfterUpdate(()=>{const focusTarget=this.pendingFocusTarget;focusTarget&&this.restoreFocusAfterItemUpdate(focusTarget,this.focusRestoreGeneration)},"reorder-focus")}async restoreFocusAfterItemUpdate(focusTarget,generation){await focusTarget.item.updateComplete,!(!this.isConnected||generation!==this.focusRestoreGeneration||this.pendingFocusTarget!==focusTarget)&&(this.pendingFocusTarget=null,focusTarget.item.focusMoveButton(focusTarget.direction))}applyMove(item,direction,_fromIndex,toIndex){const target=this.itemElements[toIndex];direction==="up"?this.insertBefore(item,target):this.insertBefore(item,target.nextElementSibling),this.finishMove(item,direction,toIndex)}finishMove(item,direction,toIndex){this.syncBoundaryState();const focusDirection=(direction==="up"?item.atStart:item.atEnd)?direction==="up"?"down":"up":direction;this.pendingFocusTarget={item,direction:focusDirection},this.focusRestoreGeneration+=1,this.scheduleFocusRestore();const newItems=this.itemElements,number=getNumberFormat(this.effectiveLocale);this.liveRegion?.announce(this.localize("reorderItemMoved",void 0,{index:number.format(toIndex+1),total:number.format(newItems.length)}),{force:!0})}commitMove(item,direction,fromIndex,toIndex,expectedValues){this.controlled?(this.pendingReconciliation={value:item.value,direction,toIndex,expectedValues},this.syncBoundaryState()):this.applyMove(item,direction,fromIndex,toIndex)}moveItem(item,direction){if(this.disabled||item.disabled||this.pendingMove||this.pendingReconciliation)return;const items=this.itemElements,fromIndex=items.indexOf(item);if(fromIndex<0)return;const toIndex=direction==="up"?fromIndex-1:fromIndex+1;if(toIndex<0||toIndex>=items.length)return;const reordered=items.slice();reordered.splice(fromIndex,1),reordered.splice(toIndex,0,item);const expectedValues=this.orderValues(reordered),transaction={token:++this.moveToken,phase:"dispatching",resolution:null,item,target:items[toIndex],direction,fromIndex,toIndex,members:[...items],values:items.map(member=>member.value),expectedValues};this.pendingMove=transaction;const event=this.emit("lr-reorder",Object.freeze({order:expectedValues,fromIndex,toIndex}),{cancelable:!0});if(!(this.pendingMove!==transaction||transaction.token!==this.moveToken)){if(!this.pendingMembershipIsCurrent()){this.pendingMove=null,this.syncBoundaryState();return}if(event.defaultPrevented){if(transaction.resolution==="revert"){this.pendingMove=null,this.syncBoundaryState();return}if(transaction.resolution==="finalize"){this.pendingMove=null,this.syncBoundaryState(),this.commitMove(item,direction,fromIndex,toIndex,expectedValues);return}this.pendingMove={...transaction,phase:"held"},this.syncBoundaryState(),this.liveRegion?.announce(this.localize("reorderMovePending"),{force:!0});return}this.pendingMove=null,this.syncBoundaryState(),this.commitMove(item,direction,fromIndex,toIndex,expectedValues)}}finalizePendingMove(){if(!this.pendingMove)return;if(this.pendingMove.phase==="dispatching"){this.pendingMove.resolution="finalize";return}if(!this.pendingMembershipIsCurrent()){this.revertPendingMove();return}const{item,direction,fromIndex,toIndex,expectedValues}=this.pendingMove;this.pendingMove=null,this.syncBoundaryState(),this.commitMove(item,direction,fromIndex,toIndex,expectedValues)}revertPendingMove(options){if(!this.pendingMove)return;if(this.pendingMove.phase==="dispatching"){this.pendingMove.resolution="revert";return}const wasHeld=this.pendingMove.phase==="held";this.pendingMove=null,this.syncBoundaryState(),wasHeld&&!(options?.silent??!1)&&this.liveRegion?.announce(this.localize("reorderMoveCancelled"),{force:!0})}render(){return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{tag}from"../../../internal/prefix.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{releaseReorderOwnerState,reorderIdentityChange,updateReorderOwnerState}from"./reorder-owner.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./reorder-list.styles.js";import{LYRA_DEFAULT_reorderItemMoved,LYRA_DEFAULT_reorderMoveCancelled,LYRA_DEFAULT_reorderMovePending}from"../../../internal/default-strings.generated.js";function isRowOwnChrome(node,item){let root=node.getRootNode();for(;root instanceof ShadowRoot;){if(root===item.shadowRoot)return!0;root=root.host.getRootNode()}return!1}function deepActiveElement(doc){let active=doc.activeElement;for(;active?.shadowRoot?.activeElement;)active=active.shadowRoot.activeElement;return active}function composedContains(root,node){let current=node;for(;current;){if(current instanceof Element&&root.contains(current))return!0;current=current instanceof ShadowRoot?current.host:current.parentNode}return!1}class LyraReorderList extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.controlled=!1,this.pendingFocusTarget=null,this.focusRestoreGeneration=0,this.stateItems=new Set,this.moveToken=0,this.pendingMove=null,this.pendingReconciliation=null,this.onSlotChange=()=>{this.pendingMove&&this.pendingMove.phase==="held"&&!this.pendingMembershipIsCurrent()&&this.revertPendingMove(),this.pendingReconciliation&&this.tryCompleteControlledReconciliation(),this.syncBoundaryState()},this.onMoveRequest=e=>{const item=e.target?.closest?.(tag("reorder-item"));if(!item||item.parentElement!==this)return;const{direction}=e.detail;e.stopPropagation(),this.moveItem(item,direction)},this.onKeyDown=e=>{if(!(e.ctrlKey||e.metaKey)||e.altKey||e.shiftKey||e.key!=="ArrowUp"&&e.key!=="ArrowDown")return;const path=e.composedPath(),item=path.find(target=>target instanceof Element&&target.localName===tag("reorder-item")&&target.parentElement===this);if(!item)return;const itemIndex=path.indexOf(item);if(path.slice(0,itemIndex).some(target=>{if(!(target instanceof Element)||isRowOwnChrome(target,item))return!1;const name=target.localName;return name==="a"||name==="button"||name==="input"||name==="select"||name==="textarea"||target.hasAttribute("contenteditable")||name.includes("-")&&target!==item}))return;const items=this.itemElements,fromIndex=items.indexOf(item),toIndex=e.key==="ArrowDown"?fromIndex+1:fromIndex-1;this.disabled||this.pendingMove||this.pendingReconciliation||item.disabled||fromIndex<0||toIndex<0||toIndex>=items.length||(e.preventDefault(),this.moveItem(item,e.key==="ArrowDown"?"down":"up"))}}static{this.defaultStrings={...super.defaultStrings,reorderItemMoved:LYRA_DEFAULT_reorderItemMoved,reorderMoveCancelled:LYRA_DEFAULT_reorderMoveCancelled,reorderMovePending:LYRA_DEFAULT_reorderMovePending}}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-reorder"])}get directItemElements(){const itemTag=tag("reorder-item");return[...this.children].filter(element=>element.localName===itemTag)}get itemElements(){const seen=new Set;return this.directItemElements.filter(item=>{const value=item.value;return typeof value!="string"||value.trim()===""||seen.has(value)?!1:(seen.add(value),!0)})}syncBoundaryState(){const directItems=this.directItemElements,items=this.itemElements,validItems=new Set(items),heldMove=this.pendingMove?.phase==="held",reconciliation=this.pendingReconciliation,busy=heldMove||reconciliation!==null,nextStateItems=new Set(directItems);for(const item of this.stateItems)nextStateItems.has(item)||releaseReorderOwnerState(item,this);directItems.forEach(item=>{const i=items.indexOf(item);updateReorderOwnerState(item,this,{atStart:i===0,atEnd:i>=0&&i===items.length-1,listDisabled:this.disabled,pending:heldMove&&this.pendingMove?.item===item||reconciliation!==null&&item.value===reconciliation.value,busy,validIdentity:validItems.has(item)})}),this.stateItems=nextStateItems,this.requestUpdate()}tryCompleteControlledReconciliation(){const reconciliation=this.pendingReconciliation;if(!reconciliation)return;const items=this.itemElements,currentValues=items.map(entry=>entry.value);if(!(currentValues.length===reconciliation.expectedValues.length&&currentValues.every((value,index)=>value===reconciliation.expectedValues[index]))){currentValues.includes(reconciliation.value)||(this.pendingReconciliation=null);return}const movedItem=items[reconciliation.toIndex];this.pendingReconciliation=null,movedItem&&this.finishMove(movedItem,reconciliation.direction,reconciliation.toIndex)}[reorderIdentityChange](item){item.parentElement===this&&this.onSlotChange()}refreshItemObserver(){this.itemObserver?.disconnect();const Observer=this.ownerDocument.defaultView?.MutationObserver;!Observer||!this.isConnected||(this.itemObserver=new Observer(()=>this.onSlotChange()),this.itemObserver.observe(this,{attributes:!0,childList:!0,attributeFilter:["disabled","value"]}))}pendingMembershipIsCurrent(){if(!this.pendingMove)return!1;const current=this.itemElements;return!this.disabled&&!this.pendingMove.item.disabled&&!this.pendingMove.target.disabled&&current.length===this.pendingMove.members.length&&current.every((item,index)=>item===this.pendingMove.members[index]&&item.value===this.pendingMove.values[index])&&current[this.pendingMove.toIndex]===this.pendingMove.target}connectedCallback(){super.connectedCallback(),this.refreshItemObserver(),this.syncBoundaryState()}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.syncBoundaryState(),changed.has("controlled")&&this.pendingReconciliation&&(this.pendingReconciliation=null,this.syncBoundaryState())}disconnectedCallback(){this.itemObserver?.disconnect(),this.itemObserver=void 0,this.pendingFocusTarget=null,this.focusRestoreGeneration+=1,this.pendingMove=null,this.pendingReconciliation=null,this.moveToken+=1;for(const item of this.stateItems)releaseReorderOwnerState(item,this);this.stateItems.clear(),super.disconnectedCallback()}orderValues(items){return Object.freeze(items.map(item=>item.value))}scheduleFocusRestore(){this.scheduleAfterUpdate(()=>{const focusTarget=this.pendingFocusTarget;focusTarget&&this.restoreFocusAfterItemUpdate(focusTarget,this.focusRestoreGeneration)},"reorder-focus")}async restoreFocusAfterItemUpdate(focusTarget,generation){if(await focusTarget.item.updateComplete,!this.isConnected||generation!==this.focusRestoreGeneration||this.pendingFocusTarget!==focusTarget)return;this.pendingFocusTarget=null;const captured=focusTarget.preScheduleFocus;captured!=null&&captured!==this.ownerDocument.body&&captured.isConnected&&!composedContains(this,captured)||focusTarget.item.focusMoveButton(focusTarget.direction)}applyMove(item,direction,_fromIndex,toIndex){const target=this.itemElements[toIndex];direction==="up"?this.insertBefore(item,target):this.insertBefore(item,target.nextElementSibling),this.finishMove(item,direction,toIndex)}finishMove(item,direction,toIndex){this.syncBoundaryState();const focusDirection=(direction==="up"?item.atStart:item.atEnd)?direction==="up"?"down":"up":direction;this.pendingFocusTarget={item,direction:focusDirection,preScheduleFocus:deepActiveElement(this.ownerDocument)},this.focusRestoreGeneration+=1,this.scheduleFocusRestore();const newItems=this.itemElements,number=getNumberFormat(this.effectiveLocale);this.liveRegion?.announce(this.localize("reorderItemMoved",void 0,{index:number.format(toIndex+1),total:number.format(newItems.length)}),{force:!0})}commitMove(item,direction,fromIndex,toIndex,expectedValues){this.controlled?(this.pendingReconciliation={value:item.value,direction,toIndex,expectedValues},this.syncBoundaryState()):this.applyMove(item,direction,fromIndex,toIndex)}moveItem(item,direction){if(this.disabled||item.disabled||this.pendingMove||this.pendingReconciliation)return;const items=this.itemElements,fromIndex=items.indexOf(item);if(fromIndex<0)return;const toIndex=direction==="up"?fromIndex-1:fromIndex+1;if(toIndex<0||toIndex>=items.length)return;const reordered=items.slice();reordered.splice(fromIndex,1),reordered.splice(toIndex,0,item);const expectedValues=this.orderValues(reordered),transaction={token:++this.moveToken,phase:"dispatching",resolution:null,item,target:items[toIndex],direction,fromIndex,toIndex,members:[...items],values:items.map(member=>member.value),expectedValues};this.pendingMove=transaction;const event=this.emit("lr-reorder",Object.freeze({order:expectedValues,fromIndex,toIndex}),{cancelable:!0});if(!(this.pendingMove!==transaction||transaction.token!==this.moveToken)){if(!this.pendingMembershipIsCurrent()){this.pendingMove=null,this.syncBoundaryState();return}if(event.defaultPrevented){if(transaction.resolution==="revert"){this.pendingMove=null,this.syncBoundaryState();return}if(transaction.resolution==="finalize"){this.pendingMove=null,this.syncBoundaryState(),this.commitMove(item,direction,fromIndex,toIndex,expectedValues);return}this.pendingMove={...transaction,phase:"held"},this.syncBoundaryState(),this.liveRegion?.announce(this.localize("reorderMovePending"),{force:!0});return}this.pendingMove=null,this.syncBoundaryState(),this.commitMove(item,direction,fromIndex,toIndex,expectedValues)}}finalizePendingMove(){if(!this.pendingMove)return;if(this.pendingMove.phase==="dispatching"){this.pendingMove.resolution="finalize";return}if(!this.pendingMembershipIsCurrent()){this.revertPendingMove();return}const{item,direction,fromIndex,toIndex,expectedValues}=this.pendingMove;this.pendingMove=null,this.syncBoundaryState(),this.commitMove(item,direction,fromIndex,toIndex,expectedValues)}revertPendingMove(options){if(!this.pendingMove)return;if(this.pendingMove.phase==="dispatching"){this.pendingMove.resolution="revert";return}const wasHeld=this.pendingMove.phase==="held";this.pendingMove=null,this.syncBoundaryState(),wasHeld&&!(options?.silent??!1)&&this.liveRegion?.announce(this.localize("reorderMoveCancelled"),{force:!0})}render(){return html`
2
2
  <div
3
3
  part="base"
4
4
  role="list"