@aceshooting/lyra-ui 25.4.0 → 25.6.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.
- package/CHANGELOG.md +36 -0
- package/README.md +15 -3
- package/custom-elements.json +1 -1
- package/dist/all.d.ts +1 -1
- package/dist/all.js +1 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/forms/button/button.class.d.ts +13 -3
- package/dist/components/forms/button/button.class.js +2 -2
- package/dist/components/forms/catalog-picker-base.d.ts +48 -0
- package/dist/components/forms/catalog-picker-base.js +29 -0
- package/dist/components/forms/catalog-picker-base.styles.d.ts +1 -0
- package/dist/components/forms/catalog-picker-base.styles.js +1 -0
- package/dist/components/forms/combobox/combobox.class.d.ts +4 -1
- package/dist/components/forms/combobox/combobox.class.js +2 -2
- package/dist/components/forms/country-picker/country-picker.class.d.ts +40 -0
- package/dist/components/forms/country-picker/country-picker.class.js +1 -0
- package/dist/components/forms/country-picker/country-picker.d.ts +1 -0
- package/dist/components/forms/country-picker/country-picker.js +1 -0
- package/dist/components/forms/country-picker/country-picker.styles.d.ts +1 -0
- package/dist/components/forms/country-picker/country-picker.styles.js +1 -0
- package/dist/components/forms/currency-picker/currency-catalog.d.ts +19 -0
- package/dist/components/forms/currency-picker/currency-catalog.js +1 -0
- package/dist/components/forms/currency-picker/currency-picker.class.d.ts +95 -0
- package/dist/components/forms/currency-picker/currency-picker.class.js +30 -0
- package/dist/components/forms/currency-picker/currency-picker.d.ts +1 -0
- package/dist/components/forms/currency-picker/currency-picker.js +1 -0
- package/dist/components/forms/currency-picker/currency-picker.styles.d.ts +1 -0
- package/dist/components/forms/currency-picker/currency-picker.styles.js +1 -0
- package/dist/components/forms/currency-picker/currency-presentation.d.ts +3 -0
- package/dist/components/forms/currency-picker/currency-presentation.js +1 -0
- package/dist/components/forms/currency-picker/currency-types.d.ts +3 -0
- package/dist/components/forms/index.d.ts +1 -1
- package/dist/components/forms/index.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +37 -11
- package/dist/components/forms/locale-picker/locale-picker.class.js +43 -8
- package/dist/components/forms/locale-picker/locale-picker.styles.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +9 -2
- package/dist/components/forms/select/select.class.js +2 -2
- package/dist/components/forms/select/select.styles.js +1 -1
- package/dist/components/forms/time-zone-picker/time-zone-picker.class.d.ts +40 -0
- package/dist/components/forms/time-zone-picker/time-zone-picker.class.js +1 -0
- package/dist/components/forms/time-zone-picker/time-zone-picker.d.ts +1 -0
- package/dist/components/forms/time-zone-picker/time-zone-picker.js +1 -0
- package/dist/components/forms/time-zone-picker/time-zone-picker.styles.d.ts +1 -0
- package/dist/components/forms/time-zone-picker/time-zone-picker.styles.js +1 -0
- package/dist/components/forms/unit-picker/unit-picker.class.d.ts +38 -0
- package/dist/components/forms/unit-picker/unit-picker.class.js +1 -0
- package/dist/components/forms/unit-picker/unit-picker.d.ts +1 -0
- package/dist/components/forms/unit-picker/unit-picker.js +1 -0
- package/dist/components/forms/unit-picker/unit-picker.styles.d.ts +1 -0
- package/dist/components/forms/unit-picker/unit-picker.styles.js +1 -0
- package/dist/components/lr-country-picker.js +1 -0
- package/dist/components/lr-currency-picker.js +1 -0
- package/dist/components/lr-time-zone-picker.js +1 -0
- package/dist/components/lr-unit-picker.js +1 -0
- package/dist/components/overlays/overlay/popover.class.d.ts +6 -5
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/countries.d.ts +7 -0
- package/dist/countries.js +1 -0
- package/dist/currency.d.ts +39 -0
- package/dist/currency.js +1 -0
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +28 -24
- package/dist/framework-types.d.ts +2 -2
- package/dist/internal/autoloader-manifest.js +1 -1
- package/dist/internal/autoloader-tags.d.ts +1 -1
- package/dist/internal/autoloader-tags.js +1 -1
- package/dist/internal/default-strings.generated.d.ts +1 -1
- package/dist/internal/default-strings.generated.js +1 -1
- package/dist/internal/form-associated.d.ts +3 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/root-registration-allowlist.d.ts +1 -1
- package/dist/internal/root-registration-allowlist.js +1 -1
- package/dist/internal/scoped-definitions.generated.js +1 -1
- package/dist/internal/selection-catalog.d.ts +4 -0
- package/dist/internal/selection-catalog.js +1 -0
- package/dist/lyra.d.ts +1 -1
- package/dist/lyra.js +1 -1
- package/dist/ssr/all.d.ts +1 -1
- package/dist/ssr/all.js +1 -1
- package/dist/ssr.d.ts +4 -4
- package/dist/ssr.js +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/testing/lyra-tag-event-map.d.ts +2 -2
- package/dist/testing/lyra-tag-event-map.js +1 -1
- package/dist/time-zones.d.ts +8 -0
- package/dist/time-zones.js +1 -0
- package/dist/translations/am/forms.js +1 -1
- package/dist/translations/ar/forms.js +1 -1
- package/dist/translations/bho/forms.js +1 -1
- package/dist/translations/bn/forms.js +1 -1
- package/dist/translations/cs/forms.js +1 -1
- package/dist/translations/da/forms.js +1 -1
- package/dist/translations/de/forms.js +1 -1
- package/dist/translations/el/forms.js +1 -1
- package/dist/translations/es/forms.js +1 -1
- package/dist/translations/fa/forms.js +1 -1
- package/dist/translations/fa-AF/forms.js +1 -1
- package/dist/translations/fi/forms.js +1 -1
- package/dist/translations/fr/forms.js +1 -1
- package/dist/translations/gu/forms.js +1 -1
- package/dist/translations/ha/forms.js +1 -1
- package/dist/translations/he/forms.js +1 -1
- package/dist/translations/hi/forms.js +1 -1
- package/dist/translations/hr/forms.js +1 -1
- package/dist/translations/hu/forms.js +1 -1
- package/dist/translations/id/forms.js +1 -1
- package/dist/translations/ig/forms.js +1 -1
- package/dist/translations/it/forms.js +1 -1
- package/dist/translations/ja/forms.js +1 -1
- package/dist/translations/jv/forms.js +1 -1
- package/dist/translations/kk/forms.js +1 -1
- package/dist/translations/kn/forms.js +1 -1
- package/dist/translations/ko/forms.js +1 -1
- package/dist/translations/ln/forms.js +1 -1
- package/dist/translations/ml/forms.js +1 -1
- package/dist/translations/mr/forms.js +1 -1
- package/dist/translations/ms/forms.js +1 -1
- package/dist/translations/my/forms.js +1 -1
- package/dist/translations/nb/forms.js +1 -1
- package/dist/translations/ne/forms.js +1 -1
- package/dist/translations/nl/forms.js +1 -1
- package/dist/translations/nn/forms.js +1 -1
- package/dist/translations/om/forms.js +1 -1
- package/dist/translations/or/forms.js +1 -1
- package/dist/translations/pa/forms.js +1 -1
- package/dist/translations/pcm/forms.js +1 -1
- package/dist/translations/pl/forms.js +1 -1
- package/dist/translations/pnb/forms.js +1 -1
- package/dist/translations/ps/forms.js +1 -1
- package/dist/translations/pt-BR/forms.js +1 -1
- package/dist/translations/pt-PT/forms.js +1 -1
- package/dist/translations/ro/forms.js +1 -1
- package/dist/translations/ru/forms.js +1 -1
- package/dist/translations/sd/forms.js +1 -1
- package/dist/translations/sl/forms.js +1 -1
- package/dist/translations/su/forms.js +1 -1
- package/dist/translations/sv/forms.js +1 -1
- package/dist/translations/sw/forms.js +1 -1
- package/dist/translations/ta/forms.js +1 -1
- package/dist/translations/te/forms.js +1 -1
- package/dist/translations/th/forms.js +1 -1
- package/dist/translations/tl/forms.js +1 -1
- package/dist/translations/tr/forms.js +1 -1
- package/dist/translations/uk/forms.js +1 -1
- package/dist/translations/ur/forms.js +1 -1
- package/dist/translations/uz/forms.js +1 -1
- package/dist/translations/vi/forms.js +1 -1
- package/dist/translations/yo/forms.js +1 -1
- package/dist/translations/zh-CN/forms.js +1 -1
- package/dist/translations/zh-TW/forms.js +1 -1
- package/dist/translations/zu/forms.js +1 -1
- package/dist/units.d.ts +5 -0
- package/dist/units.js +1 -0
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-button.md +9 -0
- package/llms/components/lr-combobox.md +5 -0
- package/llms/components/lr-country-picker.md +92 -0
- package/llms/components/lr-currency-picker.md +101 -0
- package/llms/components/lr-locale-picker.md +18 -4
- package/llms/components/lr-popover.md +10 -4
- package/llms/components/lr-select.md +29 -0
- package/llms/components/lr-time-zone-picker.md +56 -0
- package/llms/components/lr-unit-picker.md +54 -0
- package/llms/index.md +6 -2
- package/llms/shared/events-and-types.md +16 -0
- package/llms/shared/imports-and-registration.md +1 -1
- package/llms/shared/testing-and-utilities.md +4 -1
- package/llms/shared.md +21 -2
- package/llms.txt +1 -1
- package/locales.json +138 -138
- package/package.json +55 -3
- package/registrations.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{deferredPlace as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_retry,LYRA_DEFAULT_statusError}from"../../../internal/default-strings.generated.js";const TYPE_AHEAD_RESET_MS=500,MAX_LOCALE_ENTRIES=512;function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,retry:LYRA_DEFAULT_retry,statusError:LYRA_DEFAULT_statusError}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get localeLoader(){return this._localeLoader}set localeLoader(next){const previous=this._localeLoader;previous!==next&&(this.cancelLocaleLoad(),this._localeLoader=next,this.requestUpdate("localeLoader",previous))}get locales(){return this._locales}set locales(next){this.cancelLocaleLoad();const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1),this.requestUpdate("open",old)}constructor(){super(),this.withoutFlags=!1,this.topLayer=!1,this.triggerDisplay="flag-label",this.optionDisplay="label-tag",this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.registryTick=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this.listboxHidden=!0,this.closeSettleToken=0,this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeAheadBuffer="",this.typeAheadReset=new DebounceController(TYPE_AHEAD_RESET_MS,armedIn=>{!this.isConnected||this.ownerDocument.defaultView!==armedIn||(this.typeAheadBuffer="")},()=>this.ownerDocument.defaultView),this.activeScrollGeneration=0,this.localizedValidityLocale="",this.localizedIntrinsicMessage="",this.localDescriptionIds="",this.markInteracted=()=>{this.touched||(this.touched=!0,this.syncCustomStates())},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.hide()}},this.commitDispatching=!1,this.valueWriteVersion=0,this.loadGeneration=0,this.retryLocaleLoad=()=>{const restoreFocus=this.shadowRoot?.activeElement?.getAttribute("part")==="load-retry";this.loadFailureTag!==void 0&&this.commit(this.loadFailureTag),restoreFocus&&this.loadFailureTag===void 0&&this.isConnected&&this.shadowRoot?.activeElement?.getAttribute("part")==="load-retry"&&this.focus()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onLabelSlotChange=()=>{this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label")},this.onHintSlotChange=()=>{this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint")},this.onErrorSlotChange=()=>{this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error")},this.onKeyDown=e=>{if(this.liveDisabled)return;const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.min(rows.length-1,this.activeIndex+1));break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.max(0,this.activeIndex-1));break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.dismissFromEscape());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(rows.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),installInteractionOnInvalid(this,this.markInteracted),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}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.triggerElement??null;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.syncLocaleAttributeForLocalization(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.closeSettleToken++,this.listboxHidden=!0,this.releaseExternalDescription(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.deactivatePopupOverlay(!1),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.clearTypeAheadTimer(),this.activeScrollGeneration+=1,this.typeAheadBuffer="",this.open=!1}adoptedCallback(){this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.overlayHandle?.suspend(),this.clearTypeAheadTimer(),this.open&&queueMicrotask(()=>this.syncPopup())}willUpdate(changed){super.willUpdate(changed),changed.has("locale")&&this.syncLocaleAttributeForLocalization(),this.hasUpdated&&this.refreshLocalizedIntrinsicValidity(changed),this.open&&(changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.normalizedEntries.length-1),this.queueActiveScroll()),this.hasUpdated||this.seedFirstRenderState(()=>{this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label")}),this.open&&(this.listboxHidden=!1)}get value(){return this._value}set value(next){this.cancelLocaleLoad(),this.valueWriteVersion++;const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){next&&this.cancelLocaleLoad();const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.localizedValidityLocale=this.effectiveMessageLocale;const valueMissing=this.hasMissingRequiredValue(),message=valueMissing?this.localize("localePickerRequired"):"";this.localizedIntrinsicMessage=message,valueMissing?this.validityController.setValidity({valueMissing:!0},message):this.validityController.setValidity({}),this.syncCustomStates()}refreshLocalizedIntrinsicValidity(changed){const locale=this.effectiveMessageLocale,message=this.hasMissingRequiredValue()?this.localize("localePickerRequired"):"";(changed.has("strings")||locale!==this.localizedValidityLocale||message!==this.localizedIntrinsicMessage)&&this.updateValidity()}hasMissingRequiredValue(){return!this.isBarred()&&this.required&&!this._value}syncLocaleAttributeForLocalization(){this.locale?this.getAttribute("locale")!==this.locale&&this.setAttribute("locale",this.locale):this.hasAttribute("locale")&&this.removeAttribute("locale")}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){disabled&&this.cancelLocaleLoad(),this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return withStaticValidityCheck(this,()=>this.internals.checkValidity())}reportValidity(){return this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales;return raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label!==void 0&&entry.label.trim().length>0?entry.label:localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0)}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}dismissFromEscape(){this.open&&(this.deactivatePopupOverlay(!0),this.hide())}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)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}activatePopupOverlay(){if(this.overlayHandle?.isActive()){this.overlayHandle.resume();return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide(),restoreFocusTo:()=>this.renderRoot.querySelector('[part="trigger"]')})}deactivatePopupOverlay(restoreFocus){const overlay=this.overlayHandle;this.overlayHandle=void 0,overlay?.deactivate({restoreFocus}),this.unbindDocumentPointer()}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.deactivatePopupOverlay(!1);return}this.activatePopupOverlay(),this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.loadFailureTag!==void 0?'[part="form-control"]':'[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))))}async settleClosedLayout(){const token=++this.closeSettleToken;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.closeSettleToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.closeSettleToken!==token)return}this.listboxHidden=!0}updated(changed){super.updated(changed),this.syncExternalDescription(),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")||changed.has("locale")||changed.has("loadFailureTag")||changed.has("topLayer")))&&this.syncPopup(),changed.has("open")&&(this.open?this.closeSettleToken++:this.settleClosedLayout()),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}cancelLocaleLoad(){this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.loadGeneration++,this.loadingTag=void 0,this.loadFailureTag=void 0}announceLoad(key){this.loadAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.loadAnnouncements.announce(key==="loading"?this.localize("loading"):this.localize("statusError"))}commit(tag){if(!(this.commitDispatching||this.liveDisabled||!this.entryFor(tag))){this.commitDispatching=!0;try{const previousValue=this._value,version=this.valueWriteVersion,loader=this.localeLoader,generation=this.loadGeneration,detail=Object.freeze({value:tag,previousValue,direction:getLyraLocaleDirection(tag)});if(this.emit("lr-change-request",detail,{cancelable:!0}).defaultPrevented||this.liveDisabled||this.valueWriteVersion!==version||this.loadGeneration!==generation||this.localeLoader!==loader||!this.entryFor(tag))return;const commitValue=()=>{this.value=tag,this.hide(),setLyraLocale(tag),this.emit("lr-change",Object.freeze({...detail,direction:getLyraLocaleDirection(tag)}))};if(loader===void 0){commitValue();return}this.cancelLocaleLoad();const operation=this.loadGeneration,ownerDocument=this.ownerDocument;this.loadingTag=tag,this.announceLoad("loading");const ownsSelection=()=>this.isConnected&&this.ownerDocument===ownerDocument&&this.loadGeneration===operation&&this.valueWriteVersion===version&&this.localeLoader===loader&&!this.liveDisabled&&this.entryFor(tag)!==void 0;Promise.resolve().then(()=>{if(ownsSelection())return loader(tag)}).then(()=>{ownsSelection()&&commitValue()},()=>{ownsSelection()&&(this.loadingTag=void 0,this.loadFailureTag=tag,this.announceLoad("statusError"))})}finally{this.commitDispatching=!1}}}typeAhead(char){this.clearTypeAheadTimer(),this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;this.isConnected&&ownerWindow&&this.typeAheadReset.push(ownerWindow);const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){this.open?this.setActiveIndex(idx):this.commit(row.tag);return}}}clearTypeAheadTimer(){this.typeAheadReset.cancel()}setActiveIndex(index){const last=this.normalizedEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index||this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`)?.scrollIntoView({block:"nearest"})})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
1
|
+
import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{deferredPlace as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{getDisplayNames,resolveIntlLocale}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{autocorrectConverter,declaredDefaultConverter,spellcheckConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInteractionOnInvalid,installInvalidEventAlias,withStaticValidityCheck}from"../../../internal/invalid-event-alias.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_localePickerEmpty,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_localePickerSearchLabel,LYRA_DEFAULT_retry,LYRA_DEFAULT_statusError}from"../../../internal/default-strings.generated.js";const TYPE_AHEAD_RESET_MS=500,MAX_LOCALE_ENTRIES=512,localeSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,localePickerEmpty:LYRA_DEFAULT_localePickerEmpty,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,localePickerSearchLabel:LYRA_DEFAULT_localePickerSearchLabel,retry:LYRA_DEFAULT_retry,statusError:LYRA_DEFAULT_statusError}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get localeLoader(){return this._localeLoader}set localeLoader(next){const previous=this._localeLoader;previous!==next&&(this.cancelLocaleLoad(),this._localeLoader=next,this.requestUpdate("localeLoader",previous))}get locales(){return this._locales}set locales(next){this.cancelLocaleLoad();const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1,this.clearSearch()),this.requestUpdate("open",old)}constructor(){super(),this.withoutFlags=!1,this.topLayer=!1,this.triggerDisplay="flag-label",this.optionDisplay="label-tag",this.searchable=!1,this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.searchQuery="",this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.registryTick=0,this.searchFocusGeneration=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this.listboxHidden=!0,this.closeSettleToken=0,this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeAheadBuffer="",this.typeAheadReset=new DebounceController(TYPE_AHEAD_RESET_MS,armedIn=>{!this.isConnected||this.ownerDocument.defaultView!==armedIn||(this.typeAheadBuffer="")},()=>this.ownerDocument.defaultView),this.activeScrollGeneration=0,this.localizedValidityLocale="",this.localizedIntrinsicMessage="",this.localDescriptionIds="",this.markInteracted=()=>{this.touched||(this.touched=!0,this.syncCustomStates())},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.hide()}},this.commitDispatching=!1,this.valueWriteVersion=0,this.loadGeneration=0,this.retryLocaleLoad=()=>{const restoreFocus=activeElementIn(this.shadowRoot)?.getAttribute("part")==="load-retry";this.loadFailureTag!==void 0&&this.commit(this.loadFailureTag),restoreFocus&&this.loadFailureTag===void 0&&this.isConnected&&activeElementIn(this.shadowRoot)?.getAttribute("part")==="load-retry"&&this.focus()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.isSearchFocusTransfer(event)){event.stopPropagation();return}if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onSearchInput=event=>{event.stopPropagation(),!(!this.searchable||!this.open||this.liveDisabled)&&(this.searchQuery=event.currentTarget.value,this.setActiveIndex(this.visibleEntries.length?0:-1))},this.onSearchChange=event=>{event.stopPropagation()},this.onSearchKeyDown=event=>{if(this.liveDisabled||!this.open||event.isComposing||event.keyCode===229)return;const rows=this.visibleEntries;if(event.key==="ArrowDown"||event.key==="ArrowUp")event.preventDefault(),this.setActiveIndex(event.key==="ArrowDown"?Math.min(rows.length-1,this.activeIndex+1):Math.max(0,this.activeIndex-1));else if(event.key==="Enter"){event.preventDefault();const row=rows[this.activeIndex];row&&this.commit(row.tag)}else event.key==="Escape"&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(event.preventDefault(),this.dismissFromEscape())},this.onLabelSlotChange=()=>{this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label")},this.onHintSlotChange=()=>{this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint")},this.onErrorSlotChange=()=>{this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error")},this.onKeyDown=e=>{if(this.liveDisabled||e.isComposing||e.keyCode===229)return;const rows=this.visibleEntries;switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.min(rows.length-1,this.activeIndex+1)),this.queueSearchFocus();break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.max(0,this.activeIndex-1)),this.queueSearchFocus();break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.dismissFromEscape());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(rows.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&(this.searchable?(e.preventDefault(),this.show(),this.searchQuery+=e.key,this.setActiveIndex(this.visibleEntries.length?0:-1),this.queueSearchFocus()):this.typeAhead(e.key));break}},this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),installInteractionOnInvalid(this,this.markInteracted),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.searchElement&&activeElementIn(this.shadowRoot)===this.searchElement?this.searchElement.blur():this.triggerElement?.blur()}click(){this.liveDisabled||this.triggerElement?.click()}get input(){return this.searchable?this.searchElement??null:null}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.triggerElement??null;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.syncLocaleAttributeForLocalization(),this.updateValidity(),this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1}),this.hasUpdated&&this.open&&queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.closeSettleToken++,this.listboxHidden=!0,this.releaseExternalDescription(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.deactivatePopupOverlay(!1),this.stopRegistrySubscription?.(),this.stopRegistrySubscription=void 0,this.clearTypeAheadTimer(),this.activeScrollGeneration+=1,this.typeAheadBuffer="",this.open=!1}adoptedCallback(){this.clearSearch(),this.cancelLocaleLoad(),this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.overlayHandle?.suspend(),this.clearTypeAheadTimer(),this.open&&queueMicrotask(()=>this.syncPopup())}willUpdate(changed){super.willUpdate(changed),changed.has("locale")&&this.syncLocaleAttributeForLocalization(),this.hasUpdated&&this.refreshLocalizedIntrinsicValidity(changed),changed.has("searchable")&&!this.searchable&&(this.clearSearch(),this.searchElement&&activeElementIn(this.shadowRoot)===this.searchElement&&this.focus()),this.open&&(this.searchable||changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.visibleEntries.length-1),this.queueActiveScroll()),this.hasUpdated||this.seedFirstRenderState(()=>{this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label")}),this.open&&(this.listboxHidden=!1)}get value(){return this._value}set value(next){this.cancelLocaleLoad(),this.valueWriteVersion++;const old=this._value;this.settingDefaultValue||(this._valueDirty=!0),this._value=next??"",this.internals.setFormValue(this._value),this.updateValidity(),this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){next&&this.cancelLocaleLoad();const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),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 effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.localizedValidityLocale=this.effectiveMessageLocale;const valueMissing=this.hasMissingRequiredValue(),message=valueMissing?this.localize("localePickerRequired"):"";this.localizedIntrinsicMessage=message,valueMissing?this.validityController.setValidity({valueMissing:!0},message):this.validityController.setValidity({}),this.syncCustomStates()}refreshLocalizedIntrinsicValidity(changed){const locale=this.effectiveMessageLocale,message=this.hasMissingRequiredValue()?this.localize("localePickerRequired"):"";(changed.has("strings")||locale!==this.localizedValidityLocale||message!==this.localizedIntrinsicMessage)&&this.updateValidity()}hasMissingRequiredValue(){return!this.isBarred()&&this.required&&!this._value}syncLocaleAttributeForLocalization(){this.locale?this.getAttribute("locale")!==this.locale&&this.setAttribute("locale",this.locale):this.hasAttribute("locale")&&this.removeAttribute("locale")}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=!1,this.clearSearch(),this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){disabled&&this.cancelLocaleLoad(),this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return withStaticValidityCheck(this,()=>this.internals.checkValidity())}reportValidity(){return this.touched=!0,this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates(),this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),this.requestUpdate()}get normalizedEntries(){const raw=this.locales;return raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label!==void 0&&entry.label.trim().length>0?entry.label:localeNativeName(entry.tag),country:entry.country}):getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}normalizeSearch(text){return text.toLocaleLowerCase(resolveIntlLocale(this.effectiveLocale)).normalize("NFKD").replace(/\p{M}/gu,"").trim()}get visibleEntries(){const rows=this.normalizedEntries,query2=this.searchable?this.normalizeSearch(this.searchQuery):"";if(!query2)return rows;let names;try{names=getDisplayNames(this.effectiveLocale,{type:"language"})}catch{}return rows.filter(row=>{let localizedName="";try{localizedName=names?.of(row.tag)??""}catch{}return[row.tag,row.label,localeNativeName(row.tag),localizedName].some(text=>this.normalizeSearch(text).includes(query2))})}clearSearch(){this.searchQuery="",this.searchFocusGeneration++,this.searchAnnouncements?.release(),this.searchAnnouncements=void 0}queueSearchFocus(){if(!this.searchable||!this.open||this.liveDisabled)return;const generation=++this.searchFocusGeneration,ownerDocument=this.ownerDocument,outerFocus=activeElementIn(ownerDocument),innerFocus=activeElementIn(this.shadowRoot);this.updateComplete.then(()=>{generation!==this.searchFocusGeneration||!this.isConnected||!this.open||!this.searchable||this.liveDisabled||this.ownerDocument!==ownerDocument||activeElementIn(ownerDocument)!==outerFocus||activeElementIn(this.shadowRoot)!==innerFocus||this.searchElement?.focus()})}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){this.open||this.liveDisabled||(this.open=!0,this.queueSearchFocus())}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}dismissFromEscape(){this.open&&(this.deactivatePopupOverlay(!0),this.hide())}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)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}activatePopupOverlay(){if(this.overlayHandle?.isActive()){this.overlayHandle.resume();return}this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>this.dismissFromEscape(),onBackdrop:()=>this.hide(),restoreFocusTo:()=>this.renderRoot.querySelector('[part="trigger"]')})}deactivatePopupOverlay(restoreFocus){const overlay=this.overlayHandle;this.overlayHandle=void 0,overlay?.deactivate({restoreFocus}),this.unbindDocumentPointer()}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.deactivatePopupOverlay(!1);return}this.activatePopupOverlay(),this.bindDocumentPointer();const anchor=this.renderRoot.querySelector(this.loadFailureTag!==void 0?'[part="form-control"]':'[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,void 0,"fixed"))))}async settleClosedLayout(){const token=++this.closeSettleToken;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.closeSettleToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.closeSettleToken!==token)return}this.listboxHidden=!0}updated(changed){super.updated(changed),this.syncExternalDescription(),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")||changed.has("locale")||changed.has("searchQuery")||changed.has("searchable")||changed.has("loadFailureTag")||changed.has("topLayer")))&&this.syncPopup(),changed.has("open")&&(this.open?this.closeSettleToken++:this.settleClosedLayout()),this.open&&this.searchable&&changed.has("searchQuery")&&this.searchQuery.trim()&&this.visibleEntries.length===0&&(this.searchAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.searchAnnouncements.announce(this.localize("localePickerEmpty"))),changed.has("searchable")&&this.searchable&&activeElementIn(this.shadowRoot)===this.triggerElement&&this.queueSearchFocus(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}cancelLocaleLoad(){this.loadAnnouncements?.release(),this.loadAnnouncements=void 0,this.loadGeneration++,this.loadingTag=void 0,this.loadFailureTag=void 0}announceLoad(key){this.loadAnnouncements??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.loadAnnouncements.announce(key==="loading"?this.localize("loading"):this.localize("statusError"))}commit(tag){if(!(this.commitDispatching||this.liveDisabled||!this.entryFor(tag))){this.commitDispatching=!0;try{const previousValue=this._value,version=this.valueWriteVersion,loader=this.localeLoader,generation=this.loadGeneration,detail=Object.freeze({value:tag,previousValue,direction:getLyraLocaleDirection(tag)});if(this.emit("lr-change-request",detail,{cancelable:!0}).defaultPrevented||this.liveDisabled||this.valueWriteVersion!==version||this.loadGeneration!==generation||this.localeLoader!==loader||!this.entryFor(tag))return;const commitValue=()=>{const searchFocus=this.searchElement&&activeElementIn(this.shadowRoot)===this.searchElement?this.searchElement:void 0;this.value=tag,this.hide(),setLyraLocale(tag),this.emit("lr-change",Object.freeze({...detail,direction:getLyraLocaleDirection(tag)})),searchFocus&&this.isConnected&&this.searchable&&activeElementIn(this.shadowRoot)===searchFocus&&this.focus()};if(loader===void 0){commitValue();return}this.cancelLocaleLoad();const operation=this.loadGeneration,ownerDocument=this.ownerDocument;this.loadingTag=tag,this.announceLoad("loading");const ownsSelection=()=>this.isConnected&&this.ownerDocument===ownerDocument&&this.loadGeneration===operation&&this.valueWriteVersion===version&&this.localeLoader===loader&&!this.liveDisabled&&this.entryFor(tag)!==void 0;Promise.resolve().then(()=>{if(ownsSelection())return loader(tag)}).then(()=>{ownsSelection()&&commitValue()},()=>{ownsSelection()&&(this.loadingTag=void 0,this.loadFailureTag=tag,this.announceLoad("statusError"))})}finally{this.commitDispatching=!1}}}isSearchFocusTransfer(event){const related=event.relatedTarget;return(this.searchable||event.currentTarget===this.searchElement||related===this.searchElement)&&related!==null&&"nodeType"in related&&this.renderRoot.contains(related)}typeAhead(char){this.clearTypeAheadTimer(),this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;this.isConnected&&ownerWindow&&this.typeAheadReset.push(ownerWindow);const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag,currentIndex=rows.findIndex(r=>r.tag===currentTag),n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){this.open?this.setActiveIndex(idx):this.commit(row.tag);return}}}clearTypeAheadTimer(){this.typeAheadReset.cancel()}setActiveIndex(index){const last=this.visibleEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{if(generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index)return;const row=this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`);row?.scrollIntoView({block:"nearest"});const search=this.searchElement,popup=this.renderRoot.querySelector('[part="listbox"]');if(row&&search&&popup){const overlap=search.getBoundingClientRect().bottom-row.getBoundingClientRect().top;overlap>0&&(popup.scrollTop-=overlap)}})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/gla
|
|
|
11
11
|
<span>${entry.label}</span>
|
|
12
12
|
${this.optionDisplay==="label"?nothing:html`<span part="option-tag">${entry.tag}</span>`}
|
|
13
13
|
</span>
|
|
14
|
-
</div>`})}render(){const rows=this.
|
|
14
|
+
</div>`})}render(){const rows=this.visibleEntries,activeId=this.activeIndex>=0&&rows[this.activeIndex]?`${this.listId}-opt-${this.activeIndex}`:"",previewTag=this.previewTag,previewEntry=this.entryFor(previewTag),flagOnly=this.triggerDisplay==="flag"&&!this.withoutFlags,hasLabel=this.hasLabelSlot||(this.label??"").length>0,hasHint=this.hasHintSlot||(this.hint??"").length>0,hasError=this.hasErrorSlot||(this.errorText??"").length>0,describedBy=this.localDescriptionIds=[flagOnly?"locale-picker-value":"",hasError?"locale-picker-error":"",hasHint?"locale-picker-hint":"",this.loadingTag||this.loadFailureTag?"locale-picker-load-status":""].filter(Boolean).join(" ");return html`
|
|
15
15
|
<div part="form-control">
|
|
16
16
|
<label part="form-control-label" for=${this.controlId} ?hidden=${!hasLabel}>
|
|
17
17
|
${this.label}<slot name="label" @slotchange=${this.onLabelSlotChange}></slot>
|
|
@@ -22,11 +22,11 @@ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/gla
|
|
|
22
22
|
class=${flagOnly?"flag-only":nothing}
|
|
23
23
|
type="button"
|
|
24
24
|
role="combobox"
|
|
25
|
-
aria-haspopup
|
|
25
|
+
aria-haspopup=${this.searchable?"dialog":"listbox"}
|
|
26
26
|
aria-busy=${this.loadingTag!==void 0?"true":"false"}
|
|
27
27
|
aria-expanded=${this.open?"true":"false"}
|
|
28
28
|
aria-controls=${this.listId}
|
|
29
|
-
aria-activedescendant=${activeId}
|
|
29
|
+
aria-activedescendant=${this.searchable?nothing:activeId}
|
|
30
30
|
aria-label=${hostAriaLabel(this)??(hasLabel?nothing:this.localize("localePickerLabel"))}
|
|
31
31
|
aria-describedby=${describedBy||nothing}
|
|
32
32
|
aria-required=${this.required?"true":"false"}
|
|
@@ -45,17 +45,52 @@ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/gla
|
|
|
45
45
|
part="listbox"
|
|
46
46
|
?hidden=${this.listboxHidden}
|
|
47
47
|
id=${this.listId}
|
|
48
|
-
role
|
|
48
|
+
role=${this.searchable?"dialog":"listbox"}
|
|
49
|
+
aria-label=${this.searchable?this.localize("localePickerLabel"):nothing}
|
|
49
50
|
@mousedown=${this.onListboxMouseDown}
|
|
50
51
|
@click=${this.onListboxClick}
|
|
51
52
|
>
|
|
52
53
|
<span class="glass-scroll-layer" aria-hidden="true"></span>
|
|
53
|
-
${this.
|
|
54
|
+
${this.searchable?html`
|
|
55
|
+
<input
|
|
56
|
+
part="search-input"
|
|
57
|
+
type="search"
|
|
58
|
+
role="combobox"
|
|
59
|
+
aria-label=${this.localize("localePickerSearchLabel")}
|
|
60
|
+
placeholder=${this.localize("localePickerSearchLabel")}
|
|
61
|
+
aria-haspopup="listbox"
|
|
62
|
+
aria-autocomplete="list"
|
|
63
|
+
aria-expanded=${this.open?"true":"false"}
|
|
64
|
+
aria-controls=${`${this.listId}-matches`}
|
|
65
|
+
aria-activedescendant=${activeId||nothing}
|
|
66
|
+
aria-describedby=${rows.length?nothing:`${this.listId}-empty`}
|
|
67
|
+
autocomplete=${this.autocomplete}
|
|
68
|
+
inputmode=${this.inputMode||nothing}
|
|
69
|
+
enterkeyhint=${this.enterKeyHint||nothing}
|
|
70
|
+
spellcheck=${this.spellcheck?"true":"false"}
|
|
71
|
+
autocapitalize=${this.autocapitalize||nothing}
|
|
72
|
+
autocorrect=${this.autocorrect?"on":"off"}
|
|
73
|
+
tabindex=${this.open?"0":"-1"}
|
|
74
|
+
?disabled=${this.effectiveDisabled||!this.open}
|
|
75
|
+
.value=${this.searchQuery}
|
|
76
|
+
@input=${this.onSearchInput}
|
|
77
|
+
@change=${this.onSearchChange}
|
|
78
|
+
@keydown=${this.onSearchKeyDown}
|
|
79
|
+
@focus=${this.onTriggerFocus}
|
|
80
|
+
@blur=${this.onTriggerBlur}
|
|
81
|
+
>
|
|
82
|
+
<div id=${`${this.listId}-matches`} role="listbox" aria-label=${this.localize("localePickerLabel")}>
|
|
83
|
+
${this.renderRows(rows,activeId)}
|
|
84
|
+
</div>
|
|
85
|
+
${rows.length?nothing:html`<div part="empty" id=${`${this.listId}-empty`}>${this.localize("localePickerEmpty")}</div>`}
|
|
86
|
+
`:this.renderRows(rows,activeId)}
|
|
54
87
|
</div>
|
|
55
88
|
${this.loadingTag!==void 0||this.loadFailureTag!==void 0?html`
|
|
56
89
|
<div id="locale-picker-load-status" part="load-status">
|
|
57
90
|
${this.loadingTag!==void 0?this.localize("loading"):this.localize("statusError")}
|
|
58
|
-
${this.loadFailureTag!==void 0?html`<button part="load-retry" type="button" ?disabled=${this.effectiveDisabled} @click=${this.retryLocaleLoad}
|
|
91
|
+
${this.loadFailureTag!==void 0?html`<button part="load-retry" type="button" ?disabled=${this.effectiveDisabled} @click=${this.retryLocaleLoad}
|
|
92
|
+
@focus=${this.searchable?this.onTriggerFocus:nothing}
|
|
93
|
+
@blur=${this.searchable?this.onTriggerBlur:nothing}>${this.localize("retry")}</button>`:nothing}
|
|
59
94
|
</div>`:nothing}
|
|
60
95
|
<div id="locale-picker-error" part="error" ?hidden=${!hasError}>
|
|
61
96
|
${this.errorText}<slot name="error" @slotchange=${this.onErrorSlotChange}></slot>
|
|
@@ -64,4 +99,4 @@ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/gla
|
|
|
64
99
|
${this.hint}<slot name="hint" @slotchange=${this.onHintSlotChange}></slot>
|
|
65
100
|
</div>
|
|
66
101
|
</div>
|
|
67
|
-
`}}__decorate([property({attribute:!1})],LyraLocalePicker.prototype,"localeLoader",null),__decorate([property({attribute:!1})],LyraLocalePicker.prototype,"locales",null),__decorate([property({type:Boolean,attribute:"without-flags"})],LyraLocalePicker.prototype,"withoutFlags",void 0),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraLocalePicker.prototype,"topLayer",void 0),__decorate([property({attribute:"trigger-display",converter:declaredDefaultConverter("flag-label")})],LyraLocalePicker.prototype,"triggerDisplay",void 0),__decorate([property({attribute:"option-display",converter:declaredDefaultConverter("label-tag")})],LyraLocalePicker.prototype,"optionDisplay",void 0),__decorate([property()],LyraLocalePicker.prototype,"label",void 0),__decorate([property()],LyraLocalePicker.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraLocalePicker.prototype,"errorText",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraLocalePicker.prototype,"open",null),__decorate([property({reflect:!0,converter:declaredDefaultConverter("m")})],LyraLocalePicker.prototype,"size",void 0),__decorate([state()],LyraLocalePicker.prototype,"activeIndex",void 0),__decorate([state()],LyraLocalePicker.prototype,"touched",void 0),__decorate([state()],LyraLocalePicker.prototype,"hasHintSlot",void 0),__decorate([state()],LyraLocalePicker.prototype,"hasErrorSlot",void 0),__decorate([state()],LyraLocalePicker.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraLocalePicker.prototype,"registryTick",void 0),__decorate([query('[part="trigger"]')],LyraLocalePicker.prototype,"triggerElement",void 0),__decorate([state()],LyraLocalePicker.prototype,"listboxHidden",void 0),__decorate([state()],LyraLocalePicker.prototype,"loadingTag",void 0),__decorate([state()],LyraLocalePicker.prototype,"loadFailureTag",void 0);export{LyraLocalePicker};
|
|
102
|
+
`}}__decorate([property({attribute:!1})],LyraLocalePicker.prototype,"localeLoader",null),__decorate([property({attribute:!1})],LyraLocalePicker.prototype,"locales",null),__decorate([property({type:Boolean,attribute:"without-flags"})],LyraLocalePicker.prototype,"withoutFlags",void 0),__decorate([property({type:Boolean,attribute:"top-layer",reflect:!0})],LyraLocalePicker.prototype,"topLayer",void 0),__decorate([property({attribute:"trigger-display",converter:declaredDefaultConverter("flag-label")})],LyraLocalePicker.prototype,"triggerDisplay",void 0),__decorate([property({attribute:"option-display",converter:declaredDefaultConverter("label-tag")})],LyraLocalePicker.prototype,"optionDisplay",void 0),__decorate([property({type:Boolean})],LyraLocalePicker.prototype,"searchable",void 0),__decorate([property()],LyraLocalePicker.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraLocalePicker.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraLocalePicker.prototype,"enterKeyHint",void 0),__decorate([property({converter:localeSpellcheckConverter,useDefault:!0})],LyraLocalePicker.prototype,"spellcheck",void 0),__decorate([property()],LyraLocalePicker.prototype,"autocapitalize",void 0),__decorate([property({converter:autocorrectConverter})],LyraLocalePicker.prototype,"autocorrect",null),__decorate([property()],LyraLocalePicker.prototype,"label",void 0),__decorate([property()],LyraLocalePicker.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraLocalePicker.prototype,"errorText",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraLocalePicker.prototype,"open",null),__decorate([property({reflect:!0,converter:declaredDefaultConverter("m")})],LyraLocalePicker.prototype,"size",void 0),__decorate([state()],LyraLocalePicker.prototype,"activeIndex",void 0),__decorate([state()],LyraLocalePicker.prototype,"searchQuery",void 0),__decorate([state()],LyraLocalePicker.prototype,"touched",void 0),__decorate([state()],LyraLocalePicker.prototype,"hasHintSlot",void 0),__decorate([state()],LyraLocalePicker.prototype,"hasErrorSlot",void 0),__decorate([state()],LyraLocalePicker.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraLocalePicker.prototype,"registryTick",void 0),__decorate([query('[part="trigger"]')],LyraLocalePicker.prototype,"triggerElement",void 0),__decorate([query('[part="search-input"]')],LyraLocalePicker.prototype,"searchElement",void 0),__decorate([state()],LyraLocalePicker.prototype,"listboxHidden",void 0),__decorate([state()],LyraLocalePicker.prototype,"loadingTag",void 0),__decorate([state()],LyraLocalePicker.prototype,"loadFailureTag",void 0);export{LyraLocalePicker};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";import{glassSurface}from"../../../internal/glass-surface.styles.js";import{glassScrollLayerStyles}from"../../../internal/glass-scroll-layer.styles.js";import{glassIndependentRootStyles}from"../../../internal/glass-independent-root.styles.js";import{formControlFocusHalo,formControlRequiredMarker}from"../../../internal/form-control.styles.js";import{overlaySurfaceFill,overlaySurfaceControlEdge}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: block; --_lr-locale-picker-trigger-padding-default: var(--lr-space-xs) var(--lr-space-s); --_lr-locale-picker-trigger-min-height-default: var(--lr-form-control-height); --_lr-locale-picker-font-size-default: var(--lr-form-control-font-size); --_lr-locale-picker-expand-size-default: var(--lr-size-1-75rem); --_lr-locale-picker-gap-default: var(--lr-space-xs); --_lr-locale-picker-radius-default: var(--lr-form-control-radius); --_lr-form-control-focus-shadow: var(--lr-form-control-focus-shadow, none); } :host([size='2xs']) { --_lr-locale-picker-trigger-padding-default: var(--lr-size-0-0625rem) var(--lr-space-2xs); --_lr-locale-picker-expand-size-default: var(--lr-size-1rem); } :host([size='xs']) { --_lr-locale-picker-trigger-padding-default: var(--lr-size-0-125rem) var(--lr-space-xs); --_lr-locale-picker-expand-size-default: var(--lr-size-1rem); } :host([size='s']), :host([size='small']) { --_lr-locale-picker-trigger-padding-default: var(--lr-space-xs) var(--lr-space-xs); --_lr-locale-picker-expand-size-default: var(--lr-size-1-25rem); } :host([size='l']), :host([size='large']) { --_lr-locale-picker-trigger-padding-default: var(--lr-space-s) var(--lr-space-m); } :host([size='xl']) { --_lr-locale-picker-trigger-padding-default: var(--lr-space-m) var(--lr-space-l); } [part='form-control-label'] { display: block; margin-block-end: var(--lr-space-xs); font-size: var(--lr-font-size-md-sm); font-weight: var(--lr-font-weight-semibold); } [part='form-control-label'][hidden] { display: none; } ${formControlRequiredMarker} [part='trigger'] { position: relative; display: flex; align-items: center; justify-content: space-between; gap: var(--lr-locale-picker-gap, var(--_lr-locale-picker-gap-default)); inline-size: 100%; min-block-size: var(--lr-locale-picker-trigger-height, var(--lr-locale-picker-trigger-min-height, var(--_lr-locale-picker-trigger-min-height-default))); box-sizing: border-box; block-size: var(--lr-locale-picker-trigger-height, auto); padding: var(--lr-locale-picker-trigger-padding, var(--_lr-locale-picker-trigger-padding-default)); border: var(--lr-border-width-thin) solid var(--lr-locale-picker-trigger-border-color, var(--lr-color-border)); border-radius: var(--lr-locale-picker-radius, var(--_lr-locale-picker-radius-default)); background: var(--lr-locale-picker-trigger-fill, var(--lr-color-surface)); color: inherit; font: inherit; font-size: var(--lr-locale-picker-font-size, var(--_lr-locale-picker-font-size-default)); text-align: start; cursor: pointer; transition: background-color var(--lr-transition-fast), border-color var(--lr-transition-fast); } [part='trigger']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part='trigger']:focus { ${formControlFocusHalo} } [part='trigger']:where(.flag-only) { --_lr-locale-picker-compact-size: max(var(--lr-size-24px), var(--lr-locale-picker-trigger-height, var(--lr-locale-picker-trigger-min-height, var(--_lr-locale-picker-trigger-min-height-default)))); inline-size: var(--_lr-locale-picker-compact-size); block-size: var(--_lr-locale-picker-compact-size); min-inline-size: min(var(--lr-icon-button-size), var(--_lr-locale-picker-compact-size)); min-block-size: min(var(--lr-icon-button-size), var(--_lr-locale-picker-compact-size)); justify-content: center; padding: var(--lr-locale-picker-trigger-padding, 0); } :where([part='trigger']):hover:where(:not(:disabled)) { background: var(--lr-locale-picker-trigger-hover-bg, var(--lr-color-brand-quiet)); border-color: var( --lr-locale-picker-trigger-hover-border-color, var(--lr-locale-picker-trigger-border-color, var(--lr-color-border)) ); } :where([part='trigger']):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-locale-picker-trigger-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } :host([open]) [part='trigger'] { border-color: var(--lr-locale-picker-open-border-color, var(--lr-color-brand)); ${formControlFocusHalo} } :host(:disabled) [part='trigger'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='trigger-flag'] { flex: 0 0 auto; } .trigger-label { flex: 1 1 auto; min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='expand-icon'] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; color: var(--lr-color-text-quiet); min-inline-size: min(var(--lr-icon-button-size), var(--lr-locale-picker-expand-size, var(--_lr-locale-picker-expand-size-default))); min-block-size: min(var(--lr-icon-button-size), var(--lr-locale-picker-expand-size, var(--_lr-locale-picker-expand-size-default))); line-height: var(--lr-line-height-none); } [part='expand-icon'] svg { transform: rotate(90deg); } [part='listbox'][hidden] { display: none; } [part='listbox'] { position: fixed; z-index: var(--lr-overlay-stack-index, var(--lr-layer-dropdown)); box-sizing: border-box; max-block-size: var(--lr-size-18rem); overflow-y: auto; overflow-x: hidden; inline-size: max-content; min-inline-size: min(var(--lr-size-12rem), var(--lr-popover-viewport-clamp), var(--lr-size-28rem)); max-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-28rem)); padding: var(--lr-space-xs); ${overlaySurfaceFill} ${overlaySurfaceControlEdge} border-radius: var( --lr-locale-picker-radius, var(--lr-overlay-radius, var(--_lr-locale-picker-radius-default)) ); box-shadow: var(--lr-overlay-shadow-anchored, var(--lr-shadow-m)); visibility: hidden; opacity: 0; transform: translateY(var(--lr-size-neg-0-25rem)); transition: opacity var(--lr-transition-fast), transform var(--lr-transition-fast), visibility var(--lr-transition-fast); } :host([open]) [part='listbox'] { visibility: visible; opacity: 1; transform: translateY(0); } @media (prefers-reduced-motion: reduce) { [part='listbox'] { transition: none !important; } } [part='option'] { display: flex; align-items: center; gap: var(--lr-locale-picker-gap, var(--_lr-locale-picker-gap-default)); inline-size: 100%; box-sizing: border-box; min-block-size: max(var(--lr-size-3rem), var(--lr-form-control-height-m), var(--lr-form-control-height)); padding: var(--lr-space-s); border: var(--lr-border-width-thin) solid transparent; border-radius: var(--lr-locale-picker-radius, var(--_lr-locale-picker-radius-default)); background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; transition: background-color var(--lr-transition-fast); } [part='option']:hover { background: var( --lr-locale-picker-option-active-bg, var(--lr-color-brand-quiet) ); } [part='option'][data-active] { background: var(--lr-locale-picker-option-active-bg, var(--lr-color-brand-quiet)); } [part='option']:active { background: color-mix( in oklab, var(--lr-locale-picker-option-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part='option'][aria-selected='true'] { border-color: var(--lr-locale-picker-option-selected-border-color, var(--lr-color-brand)); color: var(--lr-locale-picker-option-selected-color, var(--lr-color-brand)); font-weight: var(--lr-locale-picker-option-selected-font-weight, var(--lr-font-weight-semibold)); } @media (forced-colors: active) { :where([part='trigger']):hover:where(:not(:disabled)) { outline: var(--lr-border-width-thin) dashed Highlight; outline-offset: calc(-1 * var(--lr-border-width-thin)); } :where([part="trigger"]):active:where(:not(:disabled)) { outline-style: double; outline-width: var(--lr-border-width-medium); } [part="option"][data-active] { outline: var(--lr-border-width-thin) dashed Highlight; outline-offset: calc(-1 * var(--lr-border-width-thin)); } [part="option"][aria-selected="true"] { border-color: Highlight; border-style: double; } } [part='option-flag'] { flex: 0 0 auto; } [part='option-label'] { display: flex; flex-direction: column; min-inline-size: 0; overflow: hidden; } [part='option-label'] span:first-child { overflow-wrap: anywhere; white-space: normal; } [part='option-tag'] { font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); } [part='load-status'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); margin-block-start: var(--lr-space-xs); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part='load-retry'] { min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); padding: var(--lr-space-xs) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-button); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; cursor: pointer; transition: background var(--lr-transition-fast), box-shadow var(--lr-transition-fast); } [part='load-retry']:where(:hover:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-surface), var(--lr-color-text) var(--lr-color-mix-hover)); } [part='load-retry']:where(:active:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-surface), var(--lr-color-text) var(--lr-color-mix-active)); } [part='load-retry']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part='load-retry']:where(:disabled) { cursor: default; opacity: var(--lr-opacity-disabled); } @media (prefers-reduced-motion: reduce) { [part='load-retry'] { transition: none; } } [part='hint'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-text-quiet); } [part='hint'][hidden] { display: none; } [part='error'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-danger); } [part='error'][hidden] { display: none; } [part='form-control'], [part='form-control-label'], [part='hint'], [part='error'] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } ${glassScrollLayerStyles} ${glassIndependentRootStyles} ${glassSurface('[part="listbox"]',css`var(--lr-overlay-surface, var(--_lr-overlay-surface, var(--lr-color-surface-container-high)))`,void 0,!0)} `;export{styles};
|
|
1
|
+
import{css}from"lit";import{glassSurface}from"../../../internal/glass-surface.styles.js";import{glassScrollLayerStyles}from"../../../internal/glass-scroll-layer.styles.js";import{glassIndependentRootStyles}from"../../../internal/glass-independent-root.styles.js";import{formControlFocusHalo,formControlRequiredMarker}from"../../../internal/form-control.styles.js";import{overlaySurfaceFill,overlaySurfaceControlEdge}from"../../../internal/overlay-surface.styles.js";const styles=css` :host { display: block; --_lr-locale-picker-trigger-padding-default: var(--lr-space-xs) var(--lr-space-s); --_lr-locale-picker-trigger-min-height-default: var(--lr-form-control-height); --_lr-locale-picker-font-size-default: var(--lr-form-control-font-size); --_lr-locale-picker-expand-size-default: var(--lr-size-1-75rem); --_lr-locale-picker-gap-default: var(--lr-space-xs); --_lr-locale-picker-radius-default: var(--lr-form-control-radius); --_lr-form-control-focus-shadow: var(--lr-form-control-focus-shadow, none); } :host([size='2xs']) { --_lr-locale-picker-trigger-padding-default: var(--lr-size-0-0625rem) var(--lr-space-2xs); --_lr-locale-picker-expand-size-default: var(--lr-size-1rem); } :host([size='xs']) { --_lr-locale-picker-trigger-padding-default: var(--lr-size-0-125rem) var(--lr-space-xs); --_lr-locale-picker-expand-size-default: var(--lr-size-1rem); } :host([size='s']), :host([size='small']) { --_lr-locale-picker-trigger-padding-default: var(--lr-space-xs) var(--lr-space-xs); --_lr-locale-picker-expand-size-default: var(--lr-size-1-25rem); } :host([size='l']), :host([size='large']) { --_lr-locale-picker-trigger-padding-default: var(--lr-space-s) var(--lr-space-m); } :host([size='xl']) { --_lr-locale-picker-trigger-padding-default: var(--lr-space-m) var(--lr-space-l); } [part='form-control-label'] { display: block; margin-block-end: var(--lr-space-xs); font-size: var(--lr-font-size-md-sm); font-weight: var(--lr-font-weight-semibold); } [part='form-control-label'][hidden] { display: none; } ${formControlRequiredMarker} [part='trigger'] { position: relative; display: flex; align-items: center; justify-content: space-between; gap: var(--lr-locale-picker-gap, var(--_lr-locale-picker-gap-default)); inline-size: 100%; min-block-size: var(--lr-locale-picker-trigger-height, var(--lr-locale-picker-trigger-min-height, var(--_lr-locale-picker-trigger-min-height-default))); box-sizing: border-box; block-size: var(--lr-locale-picker-trigger-height, auto); padding: var(--lr-locale-picker-trigger-padding, var(--_lr-locale-picker-trigger-padding-default)); border: var(--lr-border-width-thin) solid var(--lr-locale-picker-trigger-border-color, var(--lr-color-border)); border-radius: var(--lr-locale-picker-radius, var(--_lr-locale-picker-radius-default)); background: var(--lr-locale-picker-trigger-fill, var(--lr-color-surface)); color: inherit; font: inherit; font-size: var(--lr-locale-picker-font-size, var(--_lr-locale-picker-font-size-default)); text-align: start; cursor: pointer; transition: background-color var(--lr-transition-fast), border-color var(--lr-transition-fast); } [part='trigger']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part='trigger']:focus { ${formControlFocusHalo} } [part='trigger']:where(.flag-only) { --_lr-locale-picker-compact-size: max(var(--lr-size-24px), var(--lr-locale-picker-trigger-height, var(--lr-locale-picker-trigger-min-height, var(--_lr-locale-picker-trigger-min-height-default)))); inline-size: var(--_lr-locale-picker-compact-size); block-size: var(--_lr-locale-picker-compact-size); min-inline-size: min(var(--lr-icon-button-size), var(--_lr-locale-picker-compact-size)); min-block-size: min(var(--lr-icon-button-size), var(--_lr-locale-picker-compact-size)); justify-content: center; padding: var(--lr-locale-picker-trigger-padding, 0); } :where([part='trigger']):hover:where(:not(:disabled)) { background: var(--lr-locale-picker-trigger-hover-bg, var(--lr-color-brand-quiet)); border-color: var( --lr-locale-picker-trigger-hover-border-color, var(--lr-locale-picker-trigger-border-color, var(--lr-color-border)) ); } :where([part='trigger']):active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-locale-picker-trigger-hover-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } :host([open]) [part='trigger'] { border-color: var(--lr-locale-picker-open-border-color, var(--lr-color-brand)); ${formControlFocusHalo} } :host(:disabled) [part='trigger'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='trigger-flag'] { flex: 0 0 auto; } .trigger-label { flex: 1 1 auto; min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='expand-icon'] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; color: var(--lr-color-text-quiet); min-inline-size: min(var(--lr-icon-button-size), var(--lr-locale-picker-expand-size, var(--_lr-locale-picker-expand-size-default))); min-block-size: min(var(--lr-icon-button-size), var(--lr-locale-picker-expand-size, var(--_lr-locale-picker-expand-size-default))); line-height: var(--lr-line-height-none); } [part='expand-icon'] svg { transform: rotate(90deg); } [part='listbox'][hidden] { display: none; } [part='listbox'] { position: fixed; z-index: var(--lr-overlay-stack-index, var(--lr-layer-dropdown)); box-sizing: border-box; max-block-size: var(--lr-size-18rem); overflow-y: auto; overflow-x: hidden; inline-size: max-content; min-inline-size: min(var(--lr-size-12rem), var(--lr-popover-viewport-clamp), var(--lr-size-28rem)); max-inline-size: min(var(--lr-popover-viewport-clamp), var(--lr-size-28rem)); padding: var(--lr-space-xs); ${overlaySurfaceFill} ${overlaySurfaceControlEdge} border-radius: var( --lr-locale-picker-radius, var(--lr-overlay-radius, var(--_lr-locale-picker-radius-default)) ); box-shadow: var(--lr-overlay-shadow-anchored, var(--lr-shadow-m)); visibility: hidden; opacity: 0; transform: translateY(var(--lr-size-neg-0-25rem)); transition: opacity var(--lr-transition-fast), transform var(--lr-transition-fast), visibility var(--lr-transition-fast); } :host([open]) [part='listbox'] { visibility: visible; opacity: 1; transform: translateY(0); } @media (prefers-reduced-motion: reduce) { [part='listbox'] { transition: none !important; } } [part='search-input'] { position: sticky; inset-block-start: 0; z-index: var(--lr-layer-content); box-sizing: border-box; inline-size: 100%; min-inline-size: var(--lr-icon-button-size); min-block-size: max(var(--lr-icon-button-size), var(--lr-form-control-height)); margin-block-end: var(--lr-space-xs); padding: var(--lr-space-xs) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; text-align: start; transition: var(--lr-transition-interactive); } [part='search-input']:where(:hover:not(:disabled)) { border-color: var(--lr-color-brand); } [part='search-input']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: calc(-1 * var(--lr-focus-ring-width)); } [part='empty'] { padding: var(--lr-space-s); color: var(--lr-color-text-quiet); overflow-wrap: anywhere; } [part='option'] { display: flex; align-items: center; gap: var(--lr-locale-picker-gap, var(--_lr-locale-picker-gap-default)); inline-size: 100%; box-sizing: border-box; min-block-size: max(var(--lr-size-3rem), var(--lr-form-control-height-m), var(--lr-form-control-height)); padding: var(--lr-space-s); border: var(--lr-border-width-thin) solid transparent; border-radius: var(--lr-locale-picker-radius, var(--_lr-locale-picker-radius-default)); background: none; color: inherit; font: inherit; text-align: start; cursor: pointer; transition: background-color var(--lr-transition-fast); } [part='option']:hover { background: var( --lr-locale-picker-option-active-bg, var(--lr-color-brand-quiet) ); } [part='option'][data-active] { background: var(--lr-locale-picker-option-active-bg, var(--lr-color-brand-quiet)); } [part='option']:active { background: color-mix( in oklab, var(--lr-locale-picker-option-active-bg, var(--lr-color-brand-quiet)), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part='option'][aria-selected='true'] { border-color: var(--lr-locale-picker-option-selected-border-color, var(--lr-color-brand)); color: var(--lr-locale-picker-option-selected-color, var(--lr-color-brand)); font-weight: var(--lr-locale-picker-option-selected-font-weight, var(--lr-font-weight-semibold)); } @media (forced-colors: active) { :where([part='trigger']):hover:where(:not(:disabled)) { outline: var(--lr-border-width-thin) dashed Highlight; outline-offset: calc(-1 * var(--lr-border-width-thin)); } :where([part="trigger"]):active:where(:not(:disabled)) { outline-style: double; outline-width: var(--lr-border-width-medium); } [part="option"][data-active] { outline: var(--lr-border-width-thin) dashed Highlight; outline-offset: calc(-1 * var(--lr-border-width-thin)); } [part="option"][aria-selected="true"] { border-color: Highlight; border-style: double; } } [part='option-flag'] { flex: 0 0 auto; } [part='option-label'] { display: flex; flex-direction: column; min-inline-size: 0; overflow: hidden; } [part='option-label'] span:first-child { overflow-wrap: anywhere; white-space: normal; } [part='option-tag'] { font-size: var(--lr-font-size-xs); color: var(--lr-color-text-quiet); } [part='load-status'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); margin-block-start: var(--lr-space-xs); color: var(--lr-color-text-quiet); font-size: var(--lr-font-size-sm); overflow-wrap: anywhere; } [part='load-retry'] { min-inline-size: var(--lr-icon-button-size); min-block-size: var(--lr-icon-button-size); padding: var(--lr-space-xs) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border); border-radius: var(--lr-radius-button); background: var(--lr-color-surface); color: var(--lr-color-text); font: inherit; cursor: pointer; transition: background var(--lr-transition-fast), box-shadow var(--lr-transition-fast); } [part='load-retry']:where(:hover:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-surface), var(--lr-color-text) var(--lr-color-mix-hover)); } [part='load-retry']:where(:active:not(:disabled)) { background: color-mix(in oklab, var(--lr-color-surface), var(--lr-color-text) var(--lr-color-mix-active)); } [part='load-retry']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part='load-retry']:where(:disabled) { cursor: default; opacity: var(--lr-opacity-disabled); } @media (prefers-reduced-motion: reduce) { [part='load-retry'] { transition: none; } } [part='hint'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-text-quiet); } [part='hint'][hidden] { display: none; } [part='error'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-danger); } [part='error'][hidden] { display: none; } [part='form-control'], [part='form-control-label'], [part='hint'], [part='error'] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } ${glassScrollLayerStyles} ${glassIndependentRootStyles} ${glassSurface('[part="listbox"]',css`var(--lr-overlay-surface, var(--_lr-overlay-surface, var(--lr-color-surface-container-high)))`,void 0,!0)} `;export{styles};
|
|
@@ -100,6 +100,9 @@ export type LyraSelectChangeEvent<Multiple extends boolean=boolean> =LyraSelectE
|
|
|
100
100
|
* same flag covers an empty selection too -- with nothing selected the trigger shows that same
|
|
101
101
|
* localized text in place of `placeholder`, so both halves of a pending state read the same words
|
|
102
102
|
* without a consumer re-localizing them.
|
|
103
|
+
* When not loading, before the browser has observed the default option slot, including during
|
|
104
|
+
* server rendering, a committed value retains its raw code without an unavailable badge or custom unknown label.
|
|
105
|
+
* Once the slot is observed, real option labels and genuinely unmatched feedback resolve normally.
|
|
103
106
|
*
|
|
104
107
|
* A slotted `<lr-option>`'s `start`/`end` (and the Shoelace `prefix`/`suffix` aliases) adornments
|
|
105
108
|
* are cloned into the corresponding `[part='option-start']`/`[part='option-end']` listbox row,
|
|
@@ -470,7 +473,9 @@ loading:boolean;
|
|
|
470
473
|
autoCommitSingleOption:boolean;private activeIndex;
|
|
471
474
|
/** Stable identity behind `activeIndex`, retained across collection reorder/removal and option
|
|
472
475
|
* availability changes so the numeric index never silently points at a different row. */
|
|
473
|
-
private activeOption?;private options;
|
|
476
|
+
private activeOption?;private options;
|
|
477
|
+
/** An unobserved default slot is not an authoritative empty catalog. */
|
|
478
|
+
private optionsObserved;private touched;
|
|
474
479
|
/** Whether the user has acted on this control yet, which is what gates the `user-valid`/
|
|
475
480
|
* `user-invalid` custom states. Deliberately separate from `touched` (which drives the visible
|
|
476
481
|
* `data-invalid`/`aria-invalid` pair and is set on blur alone): picking an option is an
|
|
@@ -713,7 +718,9 @@ private reconcileActiveOption;private optionRefreshPending;private onOptionChang
|
|
|
713
718
|
/** Opens the listbox and resolves after `lr-after-show`. */
|
|
714
719
|
show():Promise<void>;
|
|
715
720
|
/** Closes the listbox and resolves after `lr-after-hide`. */
|
|
716
|
-
hide():Promise<void>;private onDocPointer;private positionListbox;
|
|
721
|
+
hide():Promise<void>;private onDocPointer;private positionListbox;
|
|
722
|
+
/** Reveal only the active row inside this listbox; never scroll page ancestors or move focus. */
|
|
723
|
+
private revealActiveOption;private activateListboxOverlay;private teardownListboxOverlay;private bindDocumentPointer;private unbindDocumentPointer;private reconnectOpenPopup;protected updated(changed:PropertyValues):void;private settleTransition;private waitForTransition;private resolveTransitionWaiters;
|
|
717
724
|
/** Dispatches the native value-change pair and prefixed aliases. `input`/`change` stay deliberately unprefixed -- this
|
|
718
725
|
* control is a direct `<select>` counterpart, so its value-change events keep `<select>`'s own
|
|
719
726
|
* naming instead of the `lr-` prefix `<lr-slider>` uses for its analogous rename. See the class
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{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.collectionSupport=collectionSupport}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.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.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.listboxHidden=!0,this.listboxPositioned=!1,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.optionRefreshPending=!1,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}if(isLyraOptionElement(option)&&this.adornmentClones.get(option)?.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option),this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.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)},new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),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.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1),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(){this.listboxHidden=!0;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.listboxHidden=!0,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.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get listboxOptions(){const unknown=this.unknownOptions;return unknown.length===0?this.options:[...this.options,...unknown]}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.listboxOptions.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();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"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0),positioned))}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")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("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}event==="lr-after-hide"&&(this.listboxHidden=!0,await this.updateComplete,this.transitionToken!==token)||(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
|
+
import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{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.collectionSupport=collectionSupport}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.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.options=[],this.optionsObserved=!1,this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.listboxHidden=!0,this.listboxPositioned=!1,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.optionRefreshPending=!1,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}if(isLyraOptionElement(option)&&this.adornmentClones.get(option)?.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option),this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.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)},new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),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.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1),changed.has("open")&&!this.open&&!this.openVetoed&&this.setActiveIndex(-1)}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{const assigned=s.assignedElements({flatten:!0});this.optionsObserved=!0,assigned.some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){this.listboxHidden=!0;const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.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.listboxHidden=!0,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.optionsObserved=!0,this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(this.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.optionsObserved?this.getUnknownLabel?.(value):void 0;return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return!this.optionsObserved||this.loading?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return options.filter(option=>this.isOptionAvailable(option))}get unknownValues(){return this.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get listboxOptions(){const unknown=this.unknownOptions;return unknown.length===0?this.options:[...this.options,...unknown]}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;navigable.forEach((option,index)=>{const rawIndex=this.listboxOptions.indexOf(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();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"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0,this.revealActiveOption()),positioned))}revealActiveOption(){if(!this.isConnected||!this.open||!this.listboxPositioned||!this.cleanup)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),activeId=this.triggerElement?.getAttribute("aria-activedescendant"),row=listbox?.querySelector('[part="option"][data-active]');if(!listbox||!row||!activeId||row.id!==activeId||listbox.clientHeight===0)return;let top=0,node=row;for(;node&&node!==listbox;){if(!listbox.contains(node))return;top+=node.offsetTop,node=node.offsetParent}if(node!==listbox)return;const bottom=top+row.offsetHeight;top<listbox.scrollTop||row.offsetHeight>listbox.clientHeight?listbox.scrollTop=top:bottom>listbox.scrollTop+listbox.clientHeight&&(listbox.scrollTop=bottom-listbox.clientHeight)}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")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("activeIndex")||changed.has("options")||changed.has("listboxPositioned"))&&this.revealActiveOption(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}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}event==="lr-after-hide"&&(this.listboxHidden=!0,await this.updateComplete,this.transitionToken!==token)||(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
|
|
@@ -155,4 +155,4 @@ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/gla
|
|
|
155
155
|
@lr-option-change=${this.onOptionChange}
|
|
156
156
|
hidden
|
|
157
157
|
></slot>
|
|
158
|
-
`}}__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({reflect:!0})],LyraSelect.prototype,"sync",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,attribute:"top-layer",reflect:!0})],LyraSelect.prototype,"topLayer",void 0),__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:"with-unknown-option",reflect:!0})],LyraSelect.prototype,"withUnknownOption",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),__decorate([state()],LyraSelect.prototype,"listboxHidden",void 0),__decorate([state()],LyraSelect.prototype,"listboxPositioned",void 0);export{LyraSelect};
|
|
158
|
+
`}}__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({reflect:!0})],LyraSelect.prototype,"sync",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,attribute:"top-layer",reflect:!0})],LyraSelect.prototype,"topLayer",void 0),__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:"with-unknown-option",reflect:!0})],LyraSelect.prototype,"withUnknownOption",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,"optionsObserved",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),__decorate([state()],LyraSelect.prototype,"listboxHidden",void 0),__decorate([state()],LyraSelect.prototype,"listboxPositioned",void 0);export{LyraSelect};
|