@aceshooting/lyra-ui 25.5.0 → 25.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,6 +6,8 @@ export type ButtonVariant=LyraVariant|'default'|'primary'|'text';
6
6
  /** The shared appearance vocabulary (`accent`/`filled`/`outlined`/`filled-outlined`/`plain`) plus
7
7
  * this component's two own tiers, `link` and `quiet`. */
8
8
  export type ButtonAppearance=LyraAppearance|'link'|'quiet';export type ButtonType='button'|'submit'|'reset';
9
+ /** Toggle state for the internal native button; `null` leaves toggle mode unset. */
10
+ export type ButtonPressedState=boolean|'mixed'|null;
9
11
  /** Native `formenctype` vocabulary, applied to the submission this button triggers. */
10
12
  export type ButtonFormEnctype='application/x-www-form-urlencoded'|'multipart/form-data'|'text/plain';
11
13
  /** Native `formmethod` vocabulary. `'dialog'` closes an ancestor `<dialog>` instead of submitting. */
@@ -51,7 +53,9 @@ export type ButtonFormMethod='get'|'post'|'dialog';export interface LyraButtonEv
51
53
  * Description targets follow same-ID replacement, removal, reinsertion, reconnection and document
52
54
  * adoption, including transitions between the native button and anchor.
53
55
  * Host `aria-haspopup`, `aria-expanded` and `aria-keyshortcuts` values are likewise forwarded to the internal semantic
54
- * control. `aria-pressed` (`true`, `false`, `mixed`) supports button toggles; `aria-current`
56
+ * control. The non-reflected `pressed` property (`true`, `false`, `mixed`, or `null`) supports
57
+ * button toggles without putting `aria-pressed` on the generic host. A host `aria-pressed`
58
+ * attribute remains supported for compatibility when `pressed` is `null`; `aria-current`
55
59
  * (`page`, `step`, `location`, `date`, `time`, `true`, `false`) supports current navigation.
56
60
  * These states follow attribute changes, removal and button/link replacement without changing
57
61
  * the native role. Empty or unsupported state tokens are omitted from the internal control.
@@ -88,7 +92,8 @@ export type ButtonFormMethod='get'|'post'|'dialog';export interface LyraButtonEv
88
92
  * @slot end - Trailing icon/content, rendered after the label.
89
93
  * @slot suffix - Shoelace alias for `end`, rendered through the same wrapper.
90
94
  * @attr form - ID of an external form owner. The `form` property still reads as the resolved form.
91
- * @attr aria-pressed - Toggle state forwarded reactively to the internal control: true, false or mixed.
95
+ * @attr aria-pressed - Compatibility toggle state forwarded to the internal button when `pressed`
96
+ * is `null`: true, false or mixed. Prefer the `pressed` property for new toggle buttons.
92
97
  * @attr aria-current - Current-item state forwarded reactively to the internal control: page, step, location, date, time, true or false.
93
98
  * @attr rel - Independently settable author relationship tokens (no default). `opener` is always
94
99
  * stripped, and any `target` force-adds the non-removable `noopener noreferrer` guard.
@@ -246,7 +251,12 @@ get form():HTMLFormElement|null;set form(owner:FormOwnerValue);getForm():HTMLFor
246
251
  /** Accessible name forwarded to the internal native button or anchor. Bound to the host's
247
252
  * `aria-label` content attribute so changing or removing that attribute after mount keeps the
248
253
  * actual focused control synchronized. */
249
- accessibleLabel:string|null;private triggerHasPopup;private triggerKeyShortcuts;private triggerExpanded;private triggerPressed;private triggerCurrent;private triggerControls;private triggerDescribedBy;
254
+ accessibleLabel:string|null;private triggerHasPopup;private triggerKeyShortcuts;private triggerExpanded;private triggerPressed;
255
+ /** Toggle state on the internal native button. `null` leaves it unset, or uses a host
256
+ * `aria-pressed` attribute for compatibility. This property does not reflect to the host,
257
+ * where the generic custom element does not own the button role. Links omit it.
258
+ * @default null */
259
+ pressed:ButtonPressedState;private triggerCurrent;private triggerControls;private triggerDescribedBy;
250
260
  /** Semantic tone, from the library's one `variant` vocabulary — the same five values every other
251
261
  * `variant` in the library takes. Selects which row of the semantic colour grid every fill,
252
262
  * border and foreground token below resolves against. Shoelace's `default`/`primary` spellings
@@ -1,4 +1,4 @@
1
- var _a;import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{FORM_CONTROL_LABEL_FACTORY,LyraElement}from"../../../internal/lyra-element.js";import{installFormControlInternalsCapture}from"../../../internal/form-control-labels.js";import{chevronIcon,spinnerIcon}from"../../../internal/icons.js";import{hasIconOnlyDefaultContent,IconOnlyLabelObserver}from"../../../internal/icon-only-content.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{syncAriaControlsElements}from"../../../internal/aria-reflection.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{sizes}from"../../../internal/sizes.styles.js";import{variants}from"../../../internal/variants.styles.js";import{styles}from"./button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{getFormOwner,installCustomErrorProperty,setFormOwner}from"../../../internal/direct-form-associated.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{currentValidityValidator}from"../form-validator.js";import{createButtonExternalLabelController}from"./button-external-label.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";installFormControlInternalsCapture();class LyraButton extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return[currentValidityValidator("required","disabled","loading","href","value")]}static{this.styles=[LyraElement.styles,sizes,variants,styles]}static{this.formAssociated=!0}static{this[_a]=createButtonExternalLabelController}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.requestUpdate("disabled",old),this.updateValidity()}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 effectiveDisabled(){return this._disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}constructor(){super(),this._fieldsetDisabled=!1,this._disabled=!1,this._name="",this._value="",this._required=!1,this._variant="neutral",this.localDescriptionIds="",this.customValidityMessage="",this.reflectingCustomError=!1,this.accessibleLabel=null,this.triggerHasPopup=null,this.triggerKeyShortcuts=null,this.triggerExpanded=null,this.triggerPressed=null,this.triggerCurrent=null,this.triggerControls=null,this.triggerDescribedBy=null,this.appearance="accent",this.size="m",this.pill=!1,this.circle=!1,this.outline=!1,this.withCaret=!1,this.withStart=!1,this.withEnd=!1,this.wrap=!1,this.type="button",this.formNoValidate=!1,this.loading=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.isIconButton=!1,this.iconOnlyObserver=new IconOnlyLabelObserver(this,()=>this.labelEl,()=>this.isIconButton,next=>{this.isIconButton=next,this.syncButtonStates()}),this.onClick=event=>{if(this.type!=="submit"&&this.type!=="reset")return;const ownerWindow=this.ownerDocument.defaultView;let settled=!1;const finish=()=>{settled||(settled=!0,ownerWindow?.removeEventListener("click",finishAtWindow),!(event.defaultPrevented||this.effectiveDisabled||this.loading)&&this.runClickDefaultAction())},finishAtWindow=candidate=>{candidate===event&&finish()};ownerWindow?.addEventListener("click",finishAtWindow),queueMicrotask(finish)},this.onFocusChange=event=>{relayNativeEvent(this,event)},this.onAdornmentSlotChange=()=>{this.syncAdornmentSlots()},this.onDefaultSlotChange=()=>{this.isIconButton=hasIconOnlyDefaultContent(this),this.syncButtonStates()},installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.customValidityMessage),this.updateValidity(),this.syncButtonStates()}get variant(){return this._variant}set variant(next){next==="primary"?this._variant="brand":next==="default"||next==="text"?this._variant="neutral":this._variant=next,next==="text"&&(this.appearance="plain")}get caret(){return this.withCaret}set caret(next){this.withCaret=!!next}get value(){return this._value}set value(next){this._value=next??"",this.updateValidity()}get required(){return this._required}set required(next){this._required=!!next,this.updateValidity()}get resolvedRel(){return resolveGuardedRel(this.rel,this.target)}click(){this.effectiveDisabled||this.loading||this.baseEl?.click()}focus(options){!this.effectiveDisabled&&!this.loading&&this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}[(_a=FORM_CONTROL_LABEL_FACTORY,VALIDITY_ANCHOR)](){return this.baseEl??null}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.internals.reportValidity()}setCustomValidity(message){const old=this.customValidityMessage||null,next=message??"";if(this.customValidityMessage=next,this.validityController.setCustomValidity(this.isValidationBarred?"":next),!this.reflectingCustomError){this.reflectingCustomError=!0;try{next?this.setAttribute("custom-error",next):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}}this.requestUpdate("customError",old)}resetValidity(){this.customValidityMessage="",this.validityController.setCustomValidity(""),this.updateValidity()}formStateRestoreCallback(state2,reason){this.value=typeof state2=="string"?state2:""}runClickDefaultAction(){if(this.type==="submit"){const form=this.getForm();if(!form)return;this.hasSubmitterOverrides?this.submitAsNamedSubmitter(form):form.requestSubmit()}else this.type==="reset"&&this.getForm()?.reset()}get hasSubmitterOverrides(){return!!(this.name||this.value||this.formNoValidate)||this.formAction!==void 0||this.formEnctype!==void 0||this.formMethod!==void 0||this.formTarget!==void 0}submitAsNamedSubmitter(form){const submitter=this.ownerDocument.createElement("button");submitter.type="submit",submitter.hidden=!0,submitter.tabIndex=-1,this.name&&(submitter.name=this.name,submitter.value=this.value),this.formAction!==void 0&&submitter.setAttribute("formaction",this.formAction),this.formEnctype!==void 0&&submitter.setAttribute("formenctype",this.formEnctype),this.formMethod!==void 0&&submitter.setAttribute("formmethod",this.formMethod),this.formNoValidate&&(submitter.formNoValidate=!0),this.formTarget!==void 0&&submitter.setAttribute("formtarget",this.formTarget),this.parentElement&&this.closest("form")===form?this.insertAdjacentElement("afterend",submitter):form.append(submitter);try{form.requestSubmit(submitter)}finally{submitter.remove()}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.updateValidity(),this.syncButtonStates(),this.requestUpdate()}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements(),this.updateValidity(),this.syncButtonStates(),this.hasUpdated&&this.iconOnlyObserver.arm()}disconnectedCallback(){this.releaseExternalDescription(),this.iconOnlyObserver.disarm(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||this.seedFirstRenderState(()=>{this.syncAdornmentSlots(),this.isIconButton=hasIconOnlyDefaultContent(this)})}syncAdornmentSlots(){const collection=this.children,children=collection?Array.from(collection):[];this.hasStartSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="start"||slot==="prefix"}),this.hasEndSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="end"||slot==="suffix"})}get labelGrows(){return this.withCaret||this.hasEndSlot||this.withEnd}updated(changed){super.updated(changed),syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements(),this.iconOnlyObserver.arm(),this.updateValidity(),this.syncButtonStates()}updateValidity(){if(this.validityController){if(this.isValidationBarred){this.validityController.setCustomValidity(""),this.validityController.setValidity({});return}this.required&&!this.value?this.validityController.setValidity({valueMissing:!0},this.localize("fieldRequired")):this.validityController.setValidity({}),this.validityController.setCustomValidity(this.customValidityMessage)}}get isValidationBarred(){return this.effectiveDisabled||this.loading||this.baseEl?.localName==="a"}syncButtonStates(){this.internals&&(setCustomState(this.internals,"disabled",this.effectiveDisabled||this.loading),setCustomState(this.internals,"icon-button",this.isIconButton),setCustomState(this.internals,"link",this.baseEl?.localName==="a"),setCustomState(this.internals,"loading",this.loading))}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}render(){const pressed=["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,content=html`
1
+ var _a;import{__decorate}from"tslib";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{FORM_CONTROL_LABEL_FACTORY,LyraElement}from"../../../internal/lyra-element.js";import{installFormControlInternalsCapture}from"../../../internal/form-control-labels.js";import{chevronIcon,spinnerIcon}from"../../../internal/icons.js";import{hasIconOnlyDefaultContent,IconOnlyLabelObserver}from"../../../internal/icon-only-content.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{syncAriaControlsElements}from"../../../internal/aria-reflection.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{sizes}from"../../../internal/sizes.styles.js";import{variants}from"../../../internal/variants.styles.js";import{styles}from"./button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{getFormOwner,installCustomErrorProperty,setFormOwner}from"../../../internal/direct-form-associated.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState}from"../../../internal/custom-states.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{resolveGuardedRel}from"../../../internal/link-rel.js";import{currentValidityValidator}from"../form-validator.js";import{createButtonExternalLabelController}from"./button-external-label.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";installFormControlInternalsCapture();class LyraButton extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}static get validators(){return[currentValidityValidator("required","disabled","loading","href","value")]}static{this.styles=[LyraElement.styles,sizes,variants,styles]}static{this.formAssociated=!0}static{this[_a]=createButtonExternalLabelController}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.requestUpdate("disabled",old),this.updateValidity()}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 effectiveDisabled(){return this._disabled||this._fieldsetDisabled}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}constructor(){super(),this._fieldsetDisabled=!1,this._disabled=!1,this._name="",this._value="",this._required=!1,this._variant="neutral",this.localDescriptionIds="",this.customValidityMessage="",this.reflectingCustomError=!1,this.accessibleLabel=null,this.triggerHasPopup=null,this.triggerKeyShortcuts=null,this.triggerExpanded=null,this.triggerPressed=null,this.pressed=null,this.triggerCurrent=null,this.triggerControls=null,this.triggerDescribedBy=null,this.appearance="accent",this.size="m",this.pill=!1,this.circle=!1,this.outline=!1,this.withCaret=!1,this.withStart=!1,this.withEnd=!1,this.wrap=!1,this.type="button",this.formNoValidate=!1,this.loading=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.isIconButton=!1,this.iconOnlyObserver=new IconOnlyLabelObserver(this,()=>this.labelEl,()=>this.isIconButton,next=>{this.isIconButton=next,this.syncButtonStates()}),this.onClick=event=>{if(this.type!=="submit"&&this.type!=="reset")return;const ownerWindow=this.ownerDocument.defaultView;let settled=!1;const finish=()=>{settled||(settled=!0,ownerWindow?.removeEventListener("click",finishAtWindow),!(event.defaultPrevented||this.effectiveDisabled||this.loading)&&this.runClickDefaultAction())},finishAtWindow=candidate=>{candidate===event&&finish()};ownerWindow?.addEventListener("click",finishAtWindow),queueMicrotask(finish)},this.onFocusChange=event=>{relayNativeEvent(this,event)},this.onAdornmentSlotChange=()=>{this.syncAdornmentSlots()},this.onDefaultSlotChange=()=>{this.isIconButton=hasIconOnlyDefaultContent(this),this.syncButtonStates()},installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.customValidityMessage),this.updateValidity(),this.syncButtonStates()}get variant(){return this._variant}set variant(next){next==="primary"?this._variant="brand":next==="default"||next==="text"?this._variant="neutral":this._variant=next,next==="text"&&(this.appearance="plain")}get caret(){return this.withCaret}set caret(next){this.withCaret=!!next}get value(){return this._value}set value(next){this._value=next??"",this.updateValidity()}get required(){return this._required}set required(next){this._required=!!next,this.updateValidity()}get resolvedRel(){return resolveGuardedRel(this.rel,this.target)}click(){this.effectiveDisabled||this.loading||this.baseEl?.click()}focus(options){!this.effectiveDisabled&&!this.loading&&this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}[(_a=FORM_CONTROL_LABEL_FACTORY,VALIDITY_ANCHOR)](){return this.baseEl??null}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.internals.reportValidity()}setCustomValidity(message){const old=this.customValidityMessage||null,next=message??"";if(this.customValidityMessage=next,this.validityController.setCustomValidity(this.isValidationBarred?"":next),!this.reflectingCustomError){this.reflectingCustomError=!0;try{next?this.setAttribute("custom-error",next):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}}this.requestUpdate("customError",old)}resetValidity(){this.customValidityMessage="",this.validityController.setCustomValidity(""),this.updateValidity()}formStateRestoreCallback(state2,reason){this.value=typeof state2=="string"?state2:""}runClickDefaultAction(){if(this.type==="submit"){const form=this.getForm();if(!form)return;this.hasSubmitterOverrides?this.submitAsNamedSubmitter(form):form.requestSubmit()}else this.type==="reset"&&this.getForm()?.reset()}get hasSubmitterOverrides(){return!!(this.name||this.value||this.formNoValidate)||this.formAction!==void 0||this.formEnctype!==void 0||this.formMethod!==void 0||this.formTarget!==void 0}submitAsNamedSubmitter(form){const submitter=this.ownerDocument.createElement("button");submitter.type="submit",submitter.hidden=!0,submitter.tabIndex=-1,this.name&&(submitter.name=this.name,submitter.value=this.value),this.formAction!==void 0&&submitter.setAttribute("formaction",this.formAction),this.formEnctype!==void 0&&submitter.setAttribute("formenctype",this.formEnctype),this.formMethod!==void 0&&submitter.setAttribute("formmethod",this.formMethod),this.formNoValidate&&(submitter.formNoValidate=!0),this.formTarget!==void 0&&submitter.setAttribute("formtarget",this.formTarget),this.parentElement&&this.closest("form")===form?this.insertAdjacentElement("afterend",submitter):form.append(submitter);try{form.requestSubmit(submitter)}finally{submitter.remove()}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,this.updateValidity(),this.syncButtonStates(),this.requestUpdate()}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements(),this.updateValidity(),this.syncButtonStates(),this.hasUpdated&&this.iconOnlyObserver.arm()}disconnectedCallback(){this.releaseExternalDescription(),this.iconOnlyObserver.disarm(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||this.seedFirstRenderState(()=>{this.syncAdornmentSlots(),this.isIconButton=hasIconOnlyDefaultContent(this)})}syncAdornmentSlots(){const collection=this.children,children=collection?Array.from(collection):[];this.hasStartSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="start"||slot==="prefix"}),this.hasEndSlot=children.some(element=>{const slot=element.getAttribute("slot");return slot==="end"||slot==="suffix"})}get labelGrows(){return this.withCaret||this.hasEndSlot||this.withEnd}updated(changed){super.updated(changed),syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements(),this.iconOnlyObserver.arm(),this.updateValidity(),this.syncButtonStates()}updateValidity(){if(this.validityController){if(this.isValidationBarred){this.validityController.setCustomValidity(""),this.validityController.setValidity({});return}this.required&&!this.value?this.validityController.setValidity({valueMissing:!0},this.localize("fieldRequired")):this.validityController.setValidity({}),this.validityController.setCustomValidity(this.customValidityMessage)}}get isValidationBarred(){return this.effectiveDisabled||this.loading||this.baseEl?.localName==="a"}syncButtonStates(){this.internals&&(setCustomState(this.internals,"disabled",this.effectiveDisabled||this.loading),setCustomState(this.internals,"icon-button",this.isIconButton),setCustomState(this.internals,"link",this.baseEl?.localName==="a"),setCustomState(this.internals,"loading",this.loading))}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}render(){const pressed=this.pressed==="mixed"?"mixed":typeof this.pressed=="boolean"?String(this.pressed):["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,content=html`
2
2
  <span
3
3
  part="start prefix"
4
4
  ?hidden=${!(this.hasStartSlot||this.withStart)}
@@ -59,4 +59,4 @@ var _a;import{__decorate}from"tslib";import{html,nothing}from"lit";import{proper
59
59
  >
60
60
  ${content}
61
61
  </button>
62
- `}}__decorate([property({attribute:"form"})],LyraButton.prototype,"form",null),__decorate([property({attribute:"aria-label"})],LyraButton.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"aria-haspopup"})],LyraButton.prototype,"triggerHasPopup",void 0),__decorate([property({attribute:"aria-keyshortcuts"})],LyraButton.prototype,"triggerKeyShortcuts",void 0),__decorate([property({attribute:"aria-expanded"})],LyraButton.prototype,"triggerExpanded",void 0),__decorate([property({attribute:"aria-pressed"})],LyraButton.prototype,"triggerPressed",void 0),__decorate([property({attribute:"aria-current"})],LyraButton.prototype,"triggerCurrent",void 0),__decorate([property({attribute:"aria-controls"})],LyraButton.prototype,"triggerControls",void 0),__decorate([property({attribute:"aria-describedby"})],LyraButton.prototype,"triggerDescribedBy",void 0),__decorate([property({reflect:!0})],LyraButton.prototype,"variant",null),__decorate([property({reflect:!0})],LyraButton.prototype,"appearance",void 0),__decorate([property({reflect:!0})],LyraButton.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"pill",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"circle",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"outline",void 0),__decorate([property({attribute:"with-caret",type:Boolean,reflect:!0})],LyraButton.prototype,"withCaret",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"caret",null),__decorate([property({attribute:"with-start",type:Boolean})],LyraButton.prototype,"withStart",void 0),__decorate([property({attribute:"with-end",type:Boolean})],LyraButton.prototype,"withEnd",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"wrap",void 0),__decorate([property()],LyraButton.prototype,"type",void 0),__decorate([property({reflect:!0})],LyraButton.prototype,"value",null),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"required",null),__decorate([property({attribute:"formaction"})],LyraButton.prototype,"formAction",void 0),__decorate([property({attribute:"formenctype"})],LyraButton.prototype,"formEnctype",void 0),__decorate([property({attribute:"formmethod"})],LyraButton.prototype,"formMethod",void 0),__decorate([property({attribute:"formnovalidate",type:Boolean})],LyraButton.prototype,"formNoValidate",void 0),__decorate([property({attribute:"formtarget"})],LyraButton.prototype,"formTarget",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"loading",void 0),__decorate([property({reflect:!0})],LyraButton.prototype,"href",void 0),__decorate([property()],LyraButton.prototype,"target",void 0),__decorate([property()],LyraButton.prototype,"rel",void 0),__decorate([property()],LyraButton.prototype,"download",void 0),__decorate([state()],LyraButton.prototype,"hasStartSlot",void 0),__decorate([state()],LyraButton.prototype,"hasEndSlot",void 0),__decorate([state()],LyraButton.prototype,"isIconButton",void 0),__decorate([query('[part~="base"]')],LyraButton.prototype,"baseEl",void 0),__decorate([query('[part="label"]')],LyraButton.prototype,"labelEl",void 0);export{LyraButton};
62
+ `}}__decorate([property({attribute:"form"})],LyraButton.prototype,"form",null),__decorate([property({attribute:"aria-label"})],LyraButton.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"aria-haspopup"})],LyraButton.prototype,"triggerHasPopup",void 0),__decorate([property({attribute:"aria-keyshortcuts"})],LyraButton.prototype,"triggerKeyShortcuts",void 0),__decorate([property({attribute:"aria-expanded"})],LyraButton.prototype,"triggerExpanded",void 0),__decorate([property({attribute:"aria-pressed"})],LyraButton.prototype,"triggerPressed",void 0),__decorate([property({attribute:!1})],LyraButton.prototype,"pressed",void 0),__decorate([property({attribute:"aria-current"})],LyraButton.prototype,"triggerCurrent",void 0),__decorate([property({attribute:"aria-controls"})],LyraButton.prototype,"triggerControls",void 0),__decorate([property({attribute:"aria-describedby"})],LyraButton.prototype,"triggerDescribedBy",void 0),__decorate([property({reflect:!0})],LyraButton.prototype,"variant",null),__decorate([property({reflect:!0})],LyraButton.prototype,"appearance",void 0),__decorate([property({reflect:!0})],LyraButton.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"pill",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"circle",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"outline",void 0),__decorate([property({attribute:"with-caret",type:Boolean,reflect:!0})],LyraButton.prototype,"withCaret",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"caret",null),__decorate([property({attribute:"with-start",type:Boolean})],LyraButton.prototype,"withStart",void 0),__decorate([property({attribute:"with-end",type:Boolean})],LyraButton.prototype,"withEnd",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"wrap",void 0),__decorate([property()],LyraButton.prototype,"type",void 0),__decorate([property({reflect:!0})],LyraButton.prototype,"value",null),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"required",null),__decorate([property({attribute:"formaction"})],LyraButton.prototype,"formAction",void 0),__decorate([property({attribute:"formenctype"})],LyraButton.prototype,"formEnctype",void 0),__decorate([property({attribute:"formmethod"})],LyraButton.prototype,"formMethod",void 0),__decorate([property({attribute:"formnovalidate",type:Boolean})],LyraButton.prototype,"formNoValidate",void 0),__decorate([property({attribute:"formtarget"})],LyraButton.prototype,"formTarget",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraButton.prototype,"loading",void 0),__decorate([property({reflect:!0})],LyraButton.prototype,"href",void 0),__decorate([property()],LyraButton.prototype,"target",void 0),__decorate([property()],LyraButton.prototype,"rel",void 0),__decorate([property()],LyraButton.prototype,"download",void 0),__decorate([state()],LyraButton.prototype,"hasStartSlot",void 0),__decorate([state()],LyraButton.prototype,"hasEndSlot",void 0),__decorate([state()],LyraButton.prototype,"isIconButton",void 0),__decorate([query('[part~="base"]')],LyraButton.prototype,"baseEl",void 0),__decorate([query('[part="label"]')],LyraButton.prototype,"labelEl",void 0);export{LyraButton};
@@ -56,8 +56,9 @@ export interface LyraLocaleChangeDetail{value:string;previousValue:string;direct
56
56
  *
57
57
  * Built directly on the shared trigger-button/`aria-activedescendant` listbox technique
58
58
  * `<lr-select>` uses (not composed from it). Optional `searchable` adds a text filter over the
59
- * offered rows, matching tags, native names, caller labels and localized language names. The
60
- * filter never becomes a submitted value and never selects a locale by itself.
59
+ * offered rows, matching tags, native names, caller labels, English names and localized language
60
+ * names. The filter never becomes a submitted value and never selects a locale by itself.
61
+ * Escape clears a nonempty filter first; a subsequent Escape closes and restores trigger focus.
61
62
  *
62
63
  * Selecting a row emits a cancelable `lr-change-request` before setting `value` — if a listener doesn't call
63
64
  * `event.preventDefault()`, the component applies the pick itself via `setLyraLocale()`. A host
@@ -219,10 +220,11 @@ triggerDisplay:LyraLocaleTriggerDisplay;
219
220
  * matches a consumer's own `::part(option-tag)` rule, so hiding is not omitting. The trigger,
220
221
  * the row flags and selection behaviour are identical either way. */
221
222
  optionDisplay:LyraLocaleOptionDisplay;
222
- /** Adds an optional text filter over tags, native names, caller labels and localized language
223
- * names. Filtering is case/accent insensitive, never commits a free-text value and emits no
223
+ /** Adds an optional text filter over tags, native names, caller labels, English names and
224
+ * localized language names. Filtering is case/accent insensitive, never commits a free-text value and emits no
224
225
  * selection event. Opening focuses the filter; arrows move the active match and Enter chooses
225
- * it. Escape returns to the trigger. The private query clears on close, reset, disablement,
226
+ * it. Escape first clears nonempty text without moving focus; with an empty filter it closes
227
+ * and returns to the trigger. The private query also clears on close, reset, disablement,
226
228
  * disconnect or turning this option off. Unset preserves the original closed-list behavior. */
227
229
  searchable:boolean;
228
230
  /** Native autocomplete hint for the optional filter input. */
@@ -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{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
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,locale=this.effectiveLocale){return text.toLocaleLowerCase(resolveIntlLocale(locale)).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{}let englishNames;try{englishNames=getDisplayNames("en",{type:"language"})}catch{}const invariantQuery=this.normalizeSearch(this.searchQuery,"en");return rows.filter(row=>{let localizedName="";try{localizedName=names?.of(row.tag)??""}catch{}let englishName="";try{englishName=englishNames?.of(row.tag)??""}catch{}return[row.label,localeNativeName(row.tag),localizedName].some(text=>this.normalizeSearch(text).includes(query2))||[row.tag,englishName].some(text=>this.normalizeSearch(text,"en").includes(invariantQuery))})}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(){if(this.open){if(this.searchable&&this.searchQuery.length){this.clearSearch(),this.setActiveIndex(this.visibleEntries.length?0:-1);return}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"
@@ -50,9 +50,10 @@ export interface LyraPopoverEventMap{'lr-show':CustomEvent<null>;'lr-after-show'
50
50
  * pointer travelling from the trigger to the popup never leaves both at once.
51
51
  *
52
52
  * Interaction/ARIA ownership is resolved separately from positioning. A slotted trigger wins and
53
- * receives the click listener plus `aria-haspopup`, `aria-expanded`, and `aria-controls`; without
54
- * one, a live HTML element resolved by `for` owns the same contract. A wrapper/custom trigger's
55
- * real composed focus target receives the same owned semantics and is the focus-return target. A
53
+ * receives the click listener; without one, a live HTML element resolved by `for` owns interaction.
54
+ * Only its semantic composed focus target receives `aria-haspopup`, `aria-expanded`, and
55
+ * `aria-controls`, and becomes the focus-return target. Generic wrapper hosts receive no generated
56
+ * trigger ARIA. Native controls and authored roles supporting expansion retain their own state. A
56
57
  * direct `.anchor` is positioning-only. `showAt()`'s virtual anchor wins positioning and
57
58
  * deliberately has no DOM interaction/ARIA owner while active.
58
59
  * The component supplies the real shadow popup to the shared relationship controller. Current
@@ -290,7 +291,7 @@ private popupHidden;
290
291
  * queues disconnect then connect on this element; a nested DOM operation inside the disconnect
291
292
  * teardown (releasing a slotted menu, trigger attributes) can make the engine run the queued
292
293
  * connect *before* that teardown finishes, which would then undo the reconnect. */
293
- private disconnecting;private reconnectedWhileDisconnecting;private positionedAnchor?;private positioningDirection?;private directionChanged;private observedDirectAnchor?;private observedDirectAnchorWasConnected;private stopAnchorIdentityObservation?;private triggerAria?;private accessibleTriggerAria?;
294
+ private disconnecting;private reconnectedWhileDisconnecting;private positionedAnchor?;private positioningDirection?;private directionChanged;private observedDirectAnchor?;private observedDirectAnchorWasConnected;private stopAnchorIdentityObservation?;private accessibleTriggerAria?;private accessibleTriggerObserver?;private readonly triggerUpgrades;
294
295
  /** The virtual anchor set by `showAt()`, taking priority over `trigger` for positioning while
295
296
  * set. Cleared whenever the popover closes, so a later `open = true` with no fresh `showAt()`
296
297
  * call reverts to plain trigger-based behavior. */
@@ -393,7 +394,7 @@ showAt(rect:OverlayVirtualRect,options?:{returnFocusTo?:HTMLElement;interactionB
393
394
  /** Resolves what the popup is positioned against: an explicit virtual anchor first, then the
394
395
  * direct `anchor`, then the `for` idref, then the slotted trigger. Shared with `<lr-tooltip>`,
395
396
  * which resolves the identical chain. */
396
- private resolveAnchor;protected positionPopup():void;private invalidatePositioning;private resolveCurrentPositioning;private startPositioning;private syncTriggerA11y;private get accessibleTrigger();private releaseTriggerA11y;private onTriggerSlotChange;
397
+ private resolveAnchor;protected positionPopup():void;private invalidatePositioning;private resolveCurrentPositioning;private startPositioning;private syncTriggerA11y;private get accessibleTrigger();private observeAccessibleTrigger;private releaseTriggerA11y;private onTriggerSlotChange;
397
398
  /**
398
399
  * Reads the named `trigger` slot's currently assigned element and applies it -- wired as the
399
400
  * `slotchange` handler for later mutations and called from `firstUpdated()` for initial
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{tag}from"../../../internal/prefix.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{loadAnchoredOverlayRuntime}from"../../../internal/anchored-overlay-runtime.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteDuration,finiteNumber}from"../../../internal/numbers.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{literalSetConverter,omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{styles}from"./overlay.styles.js";import{glassPopoverStyles}from"./popover-glass.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=8;let popoverConnectionSequence=0;const POPUP_ROLE=literalSetConverter(["dialog","menu","none"],"dialog"),POPOVER_TRIGGER_KEYWORDS=["click","hover","focus","manual"];function normalizeTriggerList(next){const keywords=[];for(const token of String(next??"").trim().toLowerCase().split(/\s+/)){const keyword=POPOVER_TRIGGER_KEYWORDS.find(candidate=>candidate===token);keyword&&!keywords.includes(keyword)&&keywords.push(keyword)}return keywords.length>0?keywords.join(" "):"click"}const DEFAULT_TRIGGER_DELAY=0,POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraPopover extends LyraElement{static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,popover:LYRA_DEFAULT_popover}}constructor(){super(),this._open=!1,this.placement="top",this.topLayer=!1,this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.interactionBoundary=null,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this._trigger="click",this.showDelay=0,this.hideDelay=0,this.hoverBridge=!1,this.accessibleLabel="",this._popupRole="dialog",this._disabled=!1,this.openedByInteraction=!1,this.pinned=!1,this.suppressTriggerFocusOpen=!1,this.resolvedSide="bottom",this.anchorPositioned=!1,this.popupHidden=!0,this.disconnecting=!1,this.reconnectedWhileDisconnecting=!1,this.directionChanged=!1,this.observedDirectAnchorWasConnected=!1,this.positioningGeneration=0,this.positioningReady=Promise.resolve(!1),this.generatedHostId=nextId("popover"),this.popupId=nextId("popover-popup"),this.hostIdObserverGeneration=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.connectionSequence=0,this.popoverInternals=attachInternalsSafely(this),this.onExternalTriggerKeyDown=event=>{this.onTriggerKeyDown(event)},this.onTriggerSlotChange=event=>{this.collectTriggerFromSlot(event.target)},this.onTriggerClick=()=>{if(!this.virtualAnchor&&(this.syncTriggerA11y(),!this.isManualTrigger)){if(this.cancelPendingTransition(),this.opensOn("click")&&!this.opensOn("hover")&&!this.opensOn("focus")){this.open?this.hide():this.show();return}if(this.open&&this.pinned){this.hide();return}this.open||(this.openedByInteraction=!1,this.show()),this.pinned=this.open}},this.onTriggerPointerEnter=()=>{this.opensOn("hover")&&this.requestDelayedTransition(!0)},this.onTriggerPointerLeave=event=>{this.opensOn("hover")&&this.requestInteractionClose(event.relatedTarget)},this.onPopupPointerEnter=()=>{!this.opensOn("hover")||!this.open||this.cancelPendingTransition()},this.onPopupPointerLeave=event=>{this.opensOn("hover")&&this.requestInteractionClose(event.relatedTarget)},this.onSurfaceFocusIn=event=>{!this.opensOn("focus")||this.suppressTriggerFocusOpen||(!this.open||this.triggerElement!=null&&event.composedPath().includes(this.triggerElement))&&!isKeyboardFocusEvent(event)||this.requestDelayedTransition(!0)},this.onSurfaceFocusOut=event=>{this.opensOn("focus")&&this.requestInteractionClose(event.relatedTarget)},this.onPopupClick=event=>{if(event.defaultPrevented)return;const path=event.composedPath(),hostIndex=path.indexOf(this);if(hostIndex<0)return;const closeAction=path.slice(0,hostIndex).find(target=>target.nodeType===1&&target.getAttribute("data-popover")==="close");if(!closeAction)return;event.stopPropagation();const state2=closeAction;state2.effectiveDisabled===!0||state2.disabled===!0||closeAction.hasAttribute("disabled")||closeAction.getAttribute("aria-disabled")?.trim().toLowerCase()==="true"||closeAction.hasAttribute("inert")||closeAction.closest("[inert]")||this.hide()},this.onDocumentPointer=event=>{this.overlayHandle?.isTopmost()&&(this.isInsideLightDismissBoundary(event.composedPath())||this.hide())},new GlassScrollLayer(this,'[part~="popup"]')}static{this.styles=[LyraElement.styles,styles,glassPopoverStyles]}get open(){return this._open}set open(next){const normalized=!!next&&this.canOpen;if(normalized!==this._open){if(!this.hasUpdated){this.setOpen(normalized),this.isConnected&&this.connectionSequence>0&&this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers());return}normalized?this.show():this.hide()}}get positioningStrategy(){return this._positioningStrategy??this.defaultPositioningStrategy}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??this.defaultPositioningStrategy,old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),this.onPositioningStrategyChanged(old,normalized))}onPositioningStrategyChanged(_previous,_next){}get for(){return this._for}set for(next){this._for=next??""}get trigger(){return this._trigger}set trigger(next){const normalized=normalizeTriggerList(next);if(normalized===this._trigger)return;const old=this._trigger;this._trigger=normalized,this.requestUpdate("trigger",old)}get triggerKeywords(){return new Set(this._trigger.split(" "))}get isManualTrigger(){return this.triggerKeywords.has("manual")}opensOn(keyword){return!this.isManualTrigger&&this.triggerKeywords.has(keyword)}get popupRole(){return this._popupRole}set popupRole(next){const normalized=POPUP_ROLE.normalize(next);if(normalized===this._popupRole)return;const old=this._popupRole;this._popupRole=normalized,this.requestUpdate("popupRole",old)}get disabled(){return this._disabled}set disabled(next){const normalized=!!next;if(normalized===this._disabled)return;const old=this._disabled;this._disabled=normalized,this.requestUpdate("disabled",old),normalized&&this.open&&(this.hasUpdated?this.hide():this.open=!1)}get defaultDistance(){return DEFAULT_DISTANCE}get defaultPositioningStrategy(){return"fixed"}get resolvedPositioningStrategy(){return resolveEffectivePositioningStrategy(this,this._positioningStrategy,this.defaultPositioningStrategy)}get positioningSync(){}get animationNamespace(){return"popover"}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-duration-fast"]}get popupPartNames(){return["popup","dialog","popup__popup"].join(" ")}get contentPartNames(){return["content","body"].join(" ")}get triggerPopupRole(){return this.popupRole}get popupSurfaceRole(){return this.popupRole==="none"?void 0:this.popupRole}get effectivePopupLabel(){return hostAriaLabel(this)??(this.accessibleLabel||this.localize(this.triggerPopupRole==="menu"?"menuLabel":"popover"))}get rendersArrow(){return!this.withoutArrow}get arrowPartNames(){return"arrow popup__arrow"}get rendersHoverBridge(){return this.hoverBridge&&this.opensOn("hover")&&this.open}get canOpen(){return!this.disabled}renderPopupContent(){return html`<slot></slot>`}onTriggerKeyDown(_event){}isInsideLightDismissBoundary(path){const boundary=this.virtualAnchor?this.virtualInteractionBoundary:this.interactionBoundary;return path.includes(this)||this.triggerElement!=null&&path.includes(this.triggerElement)||boundary!=null&&boundary.isConnected&&boundary.ownerDocument===this.ownerDocument&&path.includes(boundary)}onPopupPositioned(){this.openedByInteraction||this.overlayHandle?.focusAutofocus()}willUpdate(changed){super.willUpdate(changed);const direction=this.effectiveDirection;this.directionChanged=direction!==this.positioningDirection,this.positioningDirection=direction,changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose({focusTrigger:!1}),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),changed.has("open")&&this.open&&(this.popupHidden=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){if(super.updated(changed),changed.has("trigger")&&(this.cancelPendingTransition(),!this.opensOn("hover")&&!this.opensOn("focus")&&(this.pinned=!1)),changed.has("showDelay")&&this.pendingDirection==="show"&&this.requestDelayedTransition(!0,!0),changed.has("hideDelay")&&this.pendingDirection==="hide"&&this.requestDelayedTransition(!1,!0),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("for")&&this.syncInteractionTrigger(),this.directionChanged||changed.has("open")||changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("hoverBridge")||changed.has("trigger")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("popupRole")){if(this.open&&this.isConnected?this.positionPopup():changed.has("open")&&this.invalidatePositioning(),changed.has("open"))if(this.open)this.isConnected&&(this.startLightDismiss(),this.activatePopoverOverlay());else{this.pinned=!1,this.openedByInteraction=!1,this.cancelPendingTransition(),this.positionedAnchor=void 0,this.stopLightDismiss(),this.suppressTriggerFocusOpen=!0;try{this.overlayHandle?.deactivate()}finally{this.suppressTriggerFocusOpen=!1}this.overlayHandle=void 0,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.virtualInteractionBoundary=void 0,this.syncInteractionTrigger()}this.isConnected&&this.syncTriggerA11y()}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.triggerSlotElement;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.collectTriggerFromSlot(s))})}connectedCallback(){if(this.disconnecting){this.reconnectedWhileDisconnecting=!0;return}if(super.connectedCallback(),this.connectionSequence=++popoverConnectionSequence,this.addEventListener("focusin",this.onSurfaceFocusIn),this.addEventListener("focusout",this.onSurfaceFocusOut),this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers()),this.syncAnchorIdentityObservation(),this.id||(this.id=this.generatedHostId),this.observeHostId(),this.syncInteractionTrigger(),this.hasUpdated&&this.open){const wasPreviouslyActivated=this.overlayHandle?.isActive()===!0;this.startLightDismiss(),wasPreviouslyActivated?this.overlayHandle.resume():this.activatePopoverOverlay(),this.popupHidden=!1,this.positionPopup()}}disconnectedCallback(){this.disconnecting=!0;try{this.teardownOnDisconnect(),super.disconnectedCallback()}finally{this.disconnecting=!1}this.reconnectedWhileDisconnecting&&(this.reconnectedWhileDisconnecting=!1,this.isConnected&&this.connectedCallback())}teardownOnDisconnect(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.invalidatePositioning(),this.stopLightDismiss(),this.resetHostIdObserver(),this.overlayHandle?.suspend(),this.triggerElement?.removeEventListener("click",this.onTriggerClick),this.triggerElement?.removeEventListener("keydown",this.onExternalTriggerKeyDown),this.triggerElement&&this.unbindTriggerInteractions(this.triggerElement),this.releaseTriggerA11y(),this.triggerElement=void 0,this.removeEventListener("focusin",this.onSurfaceFocusIn),this.removeEventListener("focusout",this.onSurfaceFocusOut),this.cancelPendingTransition(),this.virtualInteractionBoundary=void 0,this.pinned=!1,this.openedByInteraction=!1,this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.popupHidden=!0}adoptedCallback(){super.adoptedCallback(),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.resetHostIdObserver(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose({focusTrigger:!1});return}nextAnchor!==this.positionedAnchor&&this.positionPopup()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTrigger??this.resolveForTrigger();if(next===this.triggerElement){this.syncTriggerA11y();return}if(this.triggerElement?.removeEventListener("click",this.onTriggerClick),this.triggerElement?.removeEventListener("keydown",this.onExternalTriggerKeyDown),this.triggerElement&&this.unbindTriggerInteractions(this.triggerElement),this.triggerElement=next,this.triggerElement&&this.triggerElement!==this.slottedTrigger&&(this.triggerElement.addEventListener("click",this.onTriggerClick),this.triggerElement.addEventListener("keydown",this.onExternalTriggerKeyDown)),this.triggerElement&&this.bindTriggerInteractions(this.triggerElement),this.syncTriggerA11y(),this.open){if(!this.resolveAnchor()){this.forceClose({focusTrigger:!1});return}this.updatePopoverRestoreFocusTarget(),this.positionPopup()}}activatePopoverOverlay(){!this.isConnected||this.overlayHandle?.isActive()||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger}))}updatePopoverRestoreFocusTarget(){const target=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(target);return}this.activatePopoverOverlay()}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo,previousInteractionBoundary=this.virtualInteractionBoundary,bounds=new DOMRect(normalizedRect.x,normalizedRect.y,normalizedRect.width,normalizedRect.height);if(this.virtualAnchor={getBoundingClientRect:()=>bounds,contextElement:normalizedRect.contextElement},this.returnFocusTo=options?.returnFocusTo,this.virtualInteractionBoundary=options?.interactionBoundary,this.syncInteractionTrigger(),this.open){this.updatePopoverRestoreFocusTarget(),this.positionPopup();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.virtualInteractionBoundary=previousInteractionBoundary,this.syncInteractionTrigger())}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.triggerElement})}positionPopup(){this.invalidatePositioning();const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),bridgeElement=this.renderRoot.querySelector('[part~="hover-bridge"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1;return}anchor!==this.positionedAnchor&&(this.anchorPositioned=!1);const generation=this.positioningGeneration;this.positioningReady=new Promise(resolve=>{this.resolvePositioningReady=resolve}),this.startPositioning(generation,anchor,popup,arrowElement,bridgeElement)}invalidatePositioning(){this.positioningGeneration++,this.cleanup?.(),this.cleanup=void 0,this.resolvePositioningReady?.(!1),this.resolvePositioningReady=void 0}resolveCurrentPositioning(positioned){const resolve=this.resolvePositioningReady;this.resolvePositioningReady=void 0,resolve?.(positioned)}async startPositioning(generation,anchor,popup,arrowElement,bridgeElement){try{const{place,releaseTopLayer}=await loadAnchoredOverlayRuntime();if(generation!==this.positioningGeneration||!this.open||!this.isConnected||this.resolveAnchor()!==anchor||this.renderRoot.querySelector('[part~="popup"]')!==popup)return;this.placedTopLayer&&!this.topLayer&&releaseTopLayer?.(popup),this.placedTopLayer=this.topLayer;const cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.topLayer?"fixed":this.resolvedPositioningStrategy,topLayer:this.topLayer,offset:finiteNumber(this.distance,this.defaultDistance),skidding:finiteNumber(this.skidding,0),sync:this.positioningSync,arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),hoverBridge:this.rendersHoverBridge&&bridgeElement?bridgeElement:void 0,onPlaced:({placement,arrow})=>{if(generation!==this.positioningGeneration)return;const becamePositioned=!this.anchorPositioned||this.positionedAnchor!==anchor;this.positionedAnchor=anchor,this.anchorPositioned=!0;const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-overlay-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side),this.updateComplete.then(()=>{generation!==this.positioningGeneration||!this.open||this.resolveAnchor()!==anchor||(this.resolveCurrentPositioning(!0),becamePositioned&&this.onPopupPositioned())})}});generation!==this.positioningGeneration?cleanup():this.cleanup=cleanup}catch{if(generation!==this.positioningGeneration)return;this.resolveCurrentPositioning(!1),this.forceClose({focusTrigger:!1})}}syncTriggerA11y(){const trigger=this.triggerElement??null,popup=this.renderRoot?.querySelector('[part~="popup"]')??null,contribution={attributes:{"aria-haspopup":this.triggerPopupRole==="none"?null:this.triggerPopupRole,"aria-expanded":this.open?"true":"false"},controls:popup?[popup]:[]};this.triggerAria?this.triggerAria.update(trigger,contribution):this.triggerAria=acquireAriaOwnership(trigger,contribution);const accessibleTrigger=this.accessibleTrigger,distinctAccessibleTrigger=accessibleTrigger!==trigger?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(distinctAccessibleTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(distinctAccessibleTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){return this.triggerElement?resolveAccessibleTrigger(this.triggerElement):null}releaseTriggerA11y(){this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0,this.triggerAria?.release(),this.triggerAria=void 0}collectTriggerFromSlot(slot){const next=slot.assignedElements({flatten:!0})[0];next!==this.slottedTrigger&&(this.slottedTrigger=next,this.syncInteractionTrigger())}requestInteractionClose(next){this.pinned||this.isWithinPopoverSurface(next)||this.hasFocusWithinSurface()||this.requestDelayedTransition(!1)}isWithinPopoverSurface(target){if(target===null||target.nodeType!==1)return!1;const element=target;if(composedContains(this,element))return!0;const popup=this.renderRoot?.querySelector('[part~="popup"]')??null;return popup&&composedContains(popup,element)?!0:this.triggerElement!=null&&composedContains(this.triggerElement,element)}hasFocusWithinSurface(){const active=deepActiveElementIn(this.ownerDocument);return active===null||this.triggerElement&&composedContains(this.triggerElement,active)?!1:this.isWithinPopoverSurface(active)}requestDelayedTransition(next,deferImmediate=!1){if(this.cancelPendingTransition(),next&&!this.canOpen)return;const commit=()=>{next?(this.openedByInteraction=!0,this.show()):this.hide()},delay=Math.max(0,finiteDuration(next?this.showDelay:this.hideDelay,DEFAULT_TRIGGER_DELAY)),view=this.ownerDocument.defaultView;if(!view||delay<=0&&!deferImmediate){commit();return}this.pendingDirection=next?"show":"hide",this.delayTimerView=view;const timer=view.setTimeout(()=>{this.delayTimerView!==view||this.delayTimer!==timer||(this.delayTimer=void 0,this.delayTimerView=void 0,this.pendingDirection=void 0,commit())},delay);this.delayTimer=timer}cancelPendingTransition(){this.delayTimer!==void 0&&this.delayTimerView?.clearTimeout(this.delayTimer),this.delayTimer=void 0,this.delayTimerView=void 0,this.pendingDirection=void 0}triggerNeedsOwnFocusListeners(trigger){return!composedContains(this,trigger)}bindTriggerInteractions(trigger){trigger.addEventListener("mouseenter",this.onTriggerPointerEnter),trigger.addEventListener("mouseleave",this.onTriggerPointerLeave),this.triggerNeedsOwnFocusListeners(trigger)&&(trigger.addEventListener("focusin",this.onSurfaceFocusIn),trigger.addEventListener("focusout",this.onSurfaceFocusOut))}unbindTriggerInteractions(trigger){trigger.removeEventListener("mouseenter",this.onTriggerPointerEnter),trigger.removeEventListener("mouseleave",this.onTriggerPointerLeave),trigger.removeEventListener("focusin",this.onSurfaceFocusIn),trigger.removeEventListener("focusout",this.onSurfaceFocusOut)}startLightDismiss(){const nextDocument=this.ownerDocument;this.lightDismissDocument!==nextDocument&&(this.stopLightDismiss(),nextDocument.addEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=nextDocument)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=void 0}observeHostId(){const ownerDocument=this.ownerDocument;if(this.hostIdObserver&&this.hostIdObserverDocument===ownerDocument)return;this.resetHostIdObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;const generation=this.hostIdObserverGeneration,observer=new MutationObserverCtor(()=>{this.hostIdObserver!==observer||this.hostIdObserverDocument!==ownerDocument||this.hostIdObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.id||(this.id=this.generatedHostId),this.syncTriggerA11y())});this.hostIdObserver=observer,this.hostIdObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,attributeFilter:["id"]})}resetHostIdObserver(){this.hostIdObserverGeneration+=1,this.hostIdObserver?.disconnect(),this.hostIdObserver=void 0,this.hostIdObserverDocument=void 0}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,setCustomState(this.popoverInternals,"open",next),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}show(){return this._open||!this.canOpen?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emitCancelableLifecycle("lr-show").defaultPrevented){this.syncOpenAttribute();return}if(!this.closePopoverPeers()){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.setOpen(!0),this.settleTransition("lr-after-show")})}hide(options){return this._open?this.transitionGate.request(!1,()=>{if(this.emitCancelableLifecycle("lr-hide").defaultPrevented){this.syncOpenAttribute();return}return this.forceClose(options)}):Promise.resolve()}closePopoverPeers(){if(this.virtualAnchor||this.localName!==tag("popover"))return!0;const root=this.getRootNode();for(const peer of root.querySelectorAll(tag("popover")))if(!(peer===this||!peer.open||peer.virtualAnchor)&&(peer.hide({focusTrigger:!1}),peer.open))return!1;return!0}reconcileInitialPopoverPeers(){if(!this.isConnected||!this._open||this.virtualAnchor||this.localName!==tag("popover"))return;const peers=[...this.getRootNode().querySelectorAll(tag("popover"))].filter(peer=>peer.isConnected&&peer._open&&!peer.virtualAnchor&&peer.connectionSequence>0);if(peers.reduce((latest,peer)=>!latest||peer.connectionSequence>latest.connectionSequence?peer:latest,void 0)!==this){this.closeForInitialPeerReconciliation();return}for(const peer of peers)peer!==this&&peer.closeForInitialPeerReconciliation()}closeForInitialPeerReconciliation(){this._open&&(this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.invalidatePositioning(),this.stopLightDismiss(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.positionedAnchor=void 0,this.anchorPositioned=!1,this.returnFocusTo=void 0,this.setOpen(!1),this.syncOpenAttribute())}forceClose(options){return this._open?(options?.focusTrigger===!1&&(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.setOpen(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}emitCancelableLifecycle(name){return this.emit(name,null,{cancelable:!0})}emitSettledLifecycle(name){return this.emit(name)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(event==="lr-after-show"){for(;this.open&&!this.anchorPositioned;){const readiness=this.positioningReady,positioned=await readiness;if(this.transitionToken!==token)return;if(positioned)break;if(readiness===this.positioningReady)return}if(await this.updateComplete,this.transitionToken!==token)return}if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",offset="translateY(var(--lr-size-neg-0-25rem))",animation=popup?animateRegistered(this,popup,`${this.animationNamespace}.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:this.animationDurationProperties(showing),easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&(this.removeAttribute("data-closing"),this.popupHidden=!0,await this.updateComplete,this.transitionToken!==token)||this.emitSettledLifecycle(event)}}render(){const popupRole=this.popupSurfaceRole;return html`
1
+ import{__decorate}from"tslib";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel,nextId,resolveAccessibleTrigger}from"../../../internal/a11y.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{collectComposedFocusTargets}from"../../../internal/focus-navigation.js";import{CustomElementUpgradeObserver}from"../../../internal/custom-element-upgrade-observer.js";import{acquireAriaOwnership}from"../../../internal/aria-ownership.js";import{tag}from"../../../internal/prefix.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{loadAnchoredOverlayRuntime}from"../../../internal/anchored-overlay-runtime.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{finiteDuration,finiteNumber}from"../../../internal/numbers.js";import{deepActiveElementIn}from"../../../internal/active-element.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{literalSetConverter,omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{attachInternalsSafely}from"../../../internal/element-internals.js";import{animateRegistered}from"../../../internal/registered-animation.js";import{applyOverlayArrow}from"./overlay-arrow.js";import{normalizeVirtualRect,observeOverlayAnchorIdentity,OverlayTransitionGate,resolveOverlayAnchor}from"./overlay-shared.js";import{styles}from"./overlay.styles.js";import{glassPopoverStyles}from"./popover-glass.styles.js";import{LYRA_DEFAULT_menuLabel,LYRA_DEFAULT_popover}from"../../../internal/default-strings.generated.js";const DEFAULT_DISTANCE=8,EXPANDABLE_TRIGGER_ROLES=new Set(["application","button","checkbox","combobox","gridcell","link","listbox","menuitem","row","rowheader","tab","treeitem","columnheader","menuitemcheckbox","menuitemradio","switch"]);function supportsTriggerExpansion(element){const role=element.getAttribute("role")?.trim().split(/\s+/)[0];return role?EXPANDABLE_TRIGGER_ROLES.has(role):element.matches("button, a[href], select, summary")?!0:element.localName==="input"&&["button","submit","reset","image","checkbox"].includes(element.type)}let popoverConnectionSequence=0;const POPUP_ROLE=literalSetConverter(["dialog","menu","none"],"dialog"),POPOVER_TRIGGER_KEYWORDS=["click","hover","focus","manual"];function normalizeTriggerList(next){const keywords=[];for(const token of String(next??"").trim().toLowerCase().split(/\s+/)){const keyword=POPOVER_TRIGGER_KEYWORDS.find(candidate=>candidate===token);keyword&&!keywords.includes(keyword)&&keywords.push(keyword)}return keywords.length>0?keywords.join(" "):"click"}const DEFAULT_TRIGGER_DELAY=0,POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraPopover extends LyraElement{static{this.defaultStrings={...super.defaultStrings,menuLabel:LYRA_DEFAULT_menuLabel,popover:LYRA_DEFAULT_popover}}constructor(){super(),this._open=!1,this.placement="top",this.topLayer=!1,this.distance=8,this.skidding=0,this._for="",this.anchor=null,this.interactionBoundary=null,this.withoutArrow=!1,this.arrowPlacement="anchor",this.arrowPadding=0,this._trigger="click",this.showDelay=0,this.hideDelay=0,this.hoverBridge=!1,this.accessibleLabel="",this._popupRole="dialog",this._disabled=!1,this.openedByInteraction=!1,this.pinned=!1,this.suppressTriggerFocusOpen=!1,this.resolvedSide="bottom",this.anchorPositioned=!1,this.popupHidden=!0,this.disconnecting=!1,this.reconnectedWhileDisconnecting=!1,this.directionChanged=!1,this.observedDirectAnchorWasConnected=!1,this.triggerUpgrades=new CustomElementUpgradeObserver(()=>{this.isConnected&&this.syncTriggerA11y()}),this.positioningGeneration=0,this.positioningReady=Promise.resolve(!1),this.generatedHostId=nextId("popover"),this.popupId=nextId("popover-popup"),this.hostIdObserverGeneration=0,this.transitionToken=0,this.transitionGate=new OverlayTransitionGate,this.connectionSequence=0,this.popoverInternals=attachInternalsSafely(this),this.onExternalTriggerKeyDown=event=>{this.onTriggerKeyDown(event)},this.onTriggerSlotChange=event=>{this.collectTriggerFromSlot(event.target)},this.onTriggerClick=()=>{if(!this.virtualAnchor&&(this.syncTriggerA11y(),!this.isManualTrigger)){if(this.cancelPendingTransition(),this.opensOn("click")&&!this.opensOn("hover")&&!this.opensOn("focus")){this.open?this.hide():this.show();return}if(this.open&&this.pinned){this.hide();return}this.open||(this.openedByInteraction=!1,this.show()),this.pinned=this.open}},this.onTriggerPointerEnter=()=>{this.opensOn("hover")&&this.requestDelayedTransition(!0)},this.onTriggerPointerLeave=event=>{this.opensOn("hover")&&this.requestInteractionClose(event.relatedTarget)},this.onPopupPointerEnter=()=>{!this.opensOn("hover")||!this.open||this.cancelPendingTransition()},this.onPopupPointerLeave=event=>{this.opensOn("hover")&&this.requestInteractionClose(event.relatedTarget)},this.onSurfaceFocusIn=event=>{!this.opensOn("focus")||this.suppressTriggerFocusOpen||(!this.open||this.triggerElement!=null&&event.composedPath().includes(this.triggerElement))&&!isKeyboardFocusEvent(event)||this.requestDelayedTransition(!0)},this.onSurfaceFocusOut=event=>{this.opensOn("focus")&&this.requestInteractionClose(event.relatedTarget)},this.onPopupClick=event=>{if(event.defaultPrevented)return;const path=event.composedPath(),hostIndex=path.indexOf(this);if(hostIndex<0)return;const closeAction=path.slice(0,hostIndex).find(target=>target.nodeType===1&&target.getAttribute("data-popover")==="close");if(!closeAction)return;event.stopPropagation();const state2=closeAction;state2.effectiveDisabled===!0||state2.disabled===!0||closeAction.hasAttribute("disabled")||closeAction.getAttribute("aria-disabled")?.trim().toLowerCase()==="true"||closeAction.hasAttribute("inert")||closeAction.closest("[inert]")||this.hide()},this.onDocumentPointer=event=>{this.overlayHandle?.isTopmost()&&(this.isInsideLightDismissBoundary(event.composedPath())||this.hide())},new GlassScrollLayer(this,'[part~="popup"]')}static{this.styles=[LyraElement.styles,styles,glassPopoverStyles]}get open(){return this._open}set open(next){const normalized=!!next&&this.canOpen;if(normalized!==this._open){if(!this.hasUpdated){this.setOpen(normalized),this.isConnected&&this.connectionSequence>0&&this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers());return}normalized?this.show():this.hide()}}get positioningStrategy(){return this._positioningStrategy??this.defaultPositioningStrategy}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??this.defaultPositioningStrategy,old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),this.onPositioningStrategyChanged(old,normalized))}onPositioningStrategyChanged(_previous,_next){}get for(){return this._for}set for(next){this._for=next??""}get trigger(){return this._trigger}set trigger(next){const normalized=normalizeTriggerList(next);if(normalized===this._trigger)return;const old=this._trigger;this._trigger=normalized,this.requestUpdate("trigger",old)}get triggerKeywords(){return new Set(this._trigger.split(" "))}get isManualTrigger(){return this.triggerKeywords.has("manual")}opensOn(keyword){return!this.isManualTrigger&&this.triggerKeywords.has(keyword)}get popupRole(){return this._popupRole}set popupRole(next){const normalized=POPUP_ROLE.normalize(next);if(normalized===this._popupRole)return;const old=this._popupRole;this._popupRole=normalized,this.requestUpdate("popupRole",old)}get disabled(){return this._disabled}set disabled(next){const normalized=!!next;if(normalized===this._disabled)return;const old=this._disabled;this._disabled=normalized,this.requestUpdate("disabled",old),normalized&&this.open&&(this.hasUpdated?this.hide():this.open=!1)}get defaultDistance(){return DEFAULT_DISTANCE}get defaultPositioningStrategy(){return"fixed"}get resolvedPositioningStrategy(){return resolveEffectivePositioningStrategy(this,this._positioningStrategy,this.defaultPositioningStrategy)}get positioningSync(){}get animationNamespace(){return"popover"}animationDurationProperties(showing){return[showing?"--show-duration":"--hide-duration","--lr-duration-fast"]}get popupPartNames(){return["popup","dialog","popup__popup"].join(" ")}get contentPartNames(){return["content","body"].join(" ")}get triggerPopupRole(){return this.popupRole}get popupSurfaceRole(){return this.popupRole==="none"?void 0:this.popupRole}get effectivePopupLabel(){return hostAriaLabel(this)??(this.accessibleLabel||this.localize(this.triggerPopupRole==="menu"?"menuLabel":"popover"))}get rendersArrow(){return!this.withoutArrow}get arrowPartNames(){return"arrow popup__arrow"}get rendersHoverBridge(){return this.hoverBridge&&this.opensOn("hover")&&this.open}get canOpen(){return!this.disabled}renderPopupContent(){return html`<slot></slot>`}onTriggerKeyDown(_event){}isInsideLightDismissBoundary(path){const boundary=this.virtualAnchor?this.virtualInteractionBoundary:this.interactionBoundary;return path.includes(this)||this.triggerElement!=null&&path.includes(this.triggerElement)||boundary!=null&&boundary.isConnected&&boundary.ownerDocument===this.ownerDocument&&path.includes(boundary)}onPopupPositioned(){this.openedByInteraction||this.overlayHandle?.focusAutofocus()}willUpdate(changed){super.willUpdate(changed);const direction=this.effectiveDirection;this.directionChanged=direction!==this.positioningDirection,this.positioningDirection=direction,changed.has("anchor")&&changed.get("anchor")===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.anchor?.isConnected!==!0&&this.open&&!this.resolveAnchor()&&this.forceClose({focusTrigger:!1}),changed.has("open")&&!this.open&&(this.anchorPositioned=!1),changed.has("open")&&this.open&&(this.popupHidden=!1),(changed.has("anchor")||changed.has("for"))&&(this.anchorPositioned=!1)}updated(changed){if(super.updated(changed),changed.has("trigger")&&(this.cancelPendingTransition(),!this.opensOn("hover")&&!this.opensOn("focus")&&(this.pinned=!1)),changed.has("showDelay")&&this.pendingDirection==="show"&&this.requestDelayedTransition(!0,!0),changed.has("hideDelay")&&this.pendingDirection==="hide"&&this.requestDelayedTransition(!1,!0),(changed.has("for")||changed.has("anchor")||changed.has("open"))&&this.syncAnchorIdentityObservation(),changed.has("for")&&this.syncInteractionTrigger(),this.directionChanged||changed.has("open")||changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("hoverBridge")||changed.has("trigger")||changed.has("distance")||changed.has("skidding")||changed.has("for")||changed.has("anchor")||changed.has("arrow")||changed.has("withoutArrow")||changed.has("arrowPlacement")||changed.has("arrowPadding")||changed.has("popupRole")){if(this.open&&this.isConnected?this.positionPopup():changed.has("open")&&this.invalidatePositioning(),changed.has("open"))if(this.open)this.isConnected&&(this.startLightDismiss(),this.activatePopoverOverlay());else{this.pinned=!1,this.openedByInteraction=!1,this.cancelPendingTransition(),this.positionedAnchor=void 0,this.stopLightDismiss(),this.suppressTriggerFocusOpen=!0;try{this.overlayHandle?.deactivate()}finally{this.suppressTriggerFocusOpen=!1}this.overlayHandle=void 0,this.virtualAnchor=void 0,this.returnFocusTo=void 0,this.virtualInteractionBoundary=void 0,this.syncInteractionTrigger()}this.isConnected&&this.syncTriggerA11y()}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.triggerSlotElement;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>this.collectTriggerFromSlot(s))})}connectedCallback(){if(this.disconnecting){this.reconnectedWhileDisconnecting=!0;return}if(super.connectedCallback(),this.connectionSequence=++popoverConnectionSequence,this.addEventListener("focusin",this.onSurfaceFocusIn),this.addEventListener("focusout",this.onSurfaceFocusOut),this.updateBrowserDerivedState(()=>this.reconcileInitialPopoverPeers()),this.syncAnchorIdentityObservation(),this.id||(this.id=this.generatedHostId),this.observeHostId(),this.syncInteractionTrigger(),this.hasUpdated&&this.open){const wasPreviouslyActivated=this.overlayHandle?.isActive()===!0;this.startLightDismiss(),wasPreviouslyActivated?this.overlayHandle.resume():this.activatePopoverOverlay(),this.popupHidden=!1,this.positionPopup()}}disconnectedCallback(){this.disconnecting=!0;try{this.teardownOnDisconnect(),super.disconnectedCallback()}finally{this.disconnecting=!1}this.reconnectedWhileDisconnecting&&(this.reconnectedWhileDisconnecting=!1,this.isConnected&&this.connectedCallback())}teardownOnDisconnect(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.invalidatePositioning(),this.stopLightDismiss(),this.resetHostIdObserver(),this.overlayHandle?.suspend(),this.triggerElement?.removeEventListener("click",this.onTriggerClick),this.triggerElement?.removeEventListener("keydown",this.onExternalTriggerKeyDown),this.triggerElement&&this.unbindTriggerInteractions(this.triggerElement),this.releaseTriggerA11y(),this.triggerElement=void 0,this.removeEventListener("focusin",this.onSurfaceFocusIn),this.removeEventListener("focusout",this.onSurfaceFocusOut),this.cancelPendingTransition(),this.virtualInteractionBoundary=void 0,this.pinned=!1,this.openedByInteraction=!1,this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.popupHidden=!0}adoptedCallback(){super.adoptedCallback(),this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0,this.resetHostIdObserver(),this.releaseTriggerA11y()}syncAnchorIdentityObservation(){this.stopAnchorIdentityObservation?.(),this.stopAnchorIdentityObservation=void 0;const directAnchor=this.open?this.anchor??void 0:void 0;if(this.observedDirectAnchor=directAnchor,this.observedDirectAnchorWasConnected=directAnchor?.isConnected===!0,!this.isConnected||!this.for&&!directAnchor)return;const onIdentityChange=()=>{const directAnchorRemoved=this.anchor===this.observedDirectAnchor&&this.observedDirectAnchorWasConnected&&this.observedDirectAnchor?.isConnected===!1;if(this.observedDirectAnchorWasConnected=this.observedDirectAnchor?.isConnected===!0,this.syncInteractionTrigger(),!this.open)return;const nextAnchor=this.resolveAnchor();if(directAnchorRemoved&&!nextAnchor){this.forceClose({focusTrigger:!1});return}nextAnchor!==this.positionedAnchor&&this.positionPopup()},observedRoots=new Set([this]);directAnchor&&directAnchor.getRootNode()!==this.getRootNode()&&observedRoots.add(directAnchor.isConnected?directAnchor:directAnchor.ownerDocument);const cleanups=[...observedRoots].map(root=>observeOverlayAnchorIdentity(root,onIdentityChange));this.stopAnchorIdentityObservation=()=>{for(const cleanup of cleanups)cleanup()}}resolveForTrigger(){if(!this.for)return;const target=this.getRootNode().getElementById?.(this.for)??null,HTMLElementCtor=target?.ownerDocument.defaultView?.HTMLElement;return target&&HTMLElementCtor&&target instanceof HTMLElementCtor?target:void 0}syncInteractionTrigger(){const next=this.virtualAnchor?void 0:this.slottedTrigger??this.resolveForTrigger();if(next===this.triggerElement){this.syncTriggerA11y();return}if(this.triggerElement?.removeEventListener("click",this.onTriggerClick),this.triggerElement?.removeEventListener("keydown",this.onExternalTriggerKeyDown),this.triggerElement&&this.unbindTriggerInteractions(this.triggerElement),this.triggerElement=next,this.triggerUpgrades.disconnect(),this.triggerElement&&this.triggerElement!==this.slottedTrigger&&(this.triggerElement.addEventListener("click",this.onTriggerClick),this.triggerElement.addEventListener("keydown",this.onExternalTriggerKeyDown)),this.triggerElement&&this.bindTriggerInteractions(this.triggerElement),this.syncTriggerA11y(),this.open){if(!this.resolveAnchor()){this.forceClose({focusTrigger:!1});return}this.updatePopoverRestoreFocusTarget(),this.positionPopup()}}activatePopoverOverlay(){!this.isConnected||this.overlayHandle?.isActive()||(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part~="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger}))}updatePopoverRestoreFocusTarget(){const target=this.virtualAnchor?this.returnFocusTo??null:this.accessibleTrigger;if(this.overlayHandle?.isActive()){this.overlayHandle.updateRestoreFocusTo(target);return}this.activatePopoverOverlay()}showAt(rect,options){const normalizedRect=normalizeVirtualRect(rect);if(!normalizedRect)return;const previousAnchor=this.virtualAnchor,previousReturnFocusTo=this.returnFocusTo,previousInteractionBoundary=this.virtualInteractionBoundary,bounds=new DOMRect(normalizedRect.x,normalizedRect.y,normalizedRect.width,normalizedRect.height);if(this.virtualAnchor={getBoundingClientRect:()=>bounds,contextElement:normalizedRect.contextElement},this.returnFocusTo=options?.returnFocusTo,this.virtualInteractionBoundary=options?.interactionBoundary,this.syncInteractionTrigger(),this.open){this.updatePopoverRestoreFocusTarget(),this.positionPopup();return}this.show(),!this.open&&(this.virtualAnchor=previousAnchor,this.returnFocusTo=previousReturnFocusTo,this.virtualInteractionBoundary=previousInteractionBoundary,this.syncInteractionTrigger())}resolveAnchor(){return resolveOverlayAnchor(this,{virtualAnchor:this.virtualAnchor,anchor:this.anchor,for:this.for,trigger:this.triggerElement})}positionPopup(){this.invalidatePositioning();const popup=this.renderRoot.querySelector('[part~="popup"]'),arrowElement=this.renderRoot.querySelector('[part~="arrow"]'),bridgeElement=this.renderRoot.querySelector('[part~="hover-bridge"]'),anchor=this.resolveAnchor();if(!this.open||!anchor||!popup){this.positionedAnchor=void 0,this.anchorPositioned=!1;return}anchor!==this.positionedAnchor&&(this.anchorPositioned=!1);const generation=this.positioningGeneration;this.positioningReady=new Promise(resolve=>{this.resolvePositioningReady=resolve}),this.startPositioning(generation,anchor,popup,arrowElement,bridgeElement)}invalidatePositioning(){this.positioningGeneration++,this.cleanup?.(),this.cleanup=void 0,this.resolvePositioningReady?.(!1),this.resolvePositioningReady=void 0}resolveCurrentPositioning(positioned){const resolve=this.resolvePositioningReady;this.resolvePositioningReady=void 0,resolve?.(positioned)}async startPositioning(generation,anchor,popup,arrowElement,bridgeElement){try{const{place,releaseTopLayer}=await loadAnchoredOverlayRuntime();if(generation!==this.positioningGeneration||!this.open||!this.isConnected||this.resolveAnchor()!==anchor||this.renderRoot.querySelector('[part~="popup"]')!==popup)return;this.placedTopLayer&&!this.topLayer&&releaseTopLayer?.(popup),this.placedTopLayer=this.topLayer;const cleanup=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),strategy:this.topLayer?"fixed":this.resolvedPositioningStrategy,topLayer:this.topLayer,offset:finiteNumber(this.distance,this.defaultDistance),skidding:finiteNumber(this.skidding,0),sync:this.positioningSync,arrow:this.rendersArrow&&arrowElement?arrowElement:void 0,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),hoverBridge:this.rendersHoverBridge&&bridgeElement?bridgeElement:void 0,onPlaced:({placement,arrow})=>{if(generation!==this.positioningGeneration)return;const becamePositioned=!this.anchorPositioned||this.positionedAnchor!==anchor;this.positionedAnchor=anchor,this.anchorPositioned=!0;const side=applyOverlayArrow(arrowElement,{placement,coords:arrow,enabled:this.rendersArrow,arrowPlacement:this.arrowPlacement,arrowPadding:Math.max(0,finiteNumber(this.arrowPadding,0)),rtl:this.effectiveDirection==="rtl",sizeProperty:"--arrow-size",fallbackSizeProperty:"--lr-overlay-arrow-size"});side!==this.resolvedSide&&(this.resolvedSide=side),this.updateComplete.then(()=>{generation!==this.positioningGeneration||!this.open||this.resolveAnchor()!==anchor||(this.resolveCurrentPositioning(!0),becamePositioned&&this.onPopupPositioned())})}});generation!==this.positioningGeneration?cleanup():this.cleanup=cleanup}catch{if(generation!==this.positioningGeneration)return;this.resolveCurrentPositioning(!1),this.forceClose({focusTrigger:!1})}}syncTriggerA11y(){const popup=this.renderRoot?.querySelector('[part~="popup"]')??null,contribution={attributes:{"aria-haspopup":this.triggerPopupRole==="none"?null:this.triggerPopupRole,"aria-expanded":this.open?"true":"false"},controls:popup?[popup]:[]},accessibleTrigger=this.accessibleTrigger;this.observeAccessibleTrigger(accessibleTrigger);const semanticTrigger=accessibleTrigger&&supportsTriggerExpansion(accessibleTrigger)?accessibleTrigger:null;this.accessibleTriggerAria?this.accessibleTriggerAria.update(semanticTrigger,contribution):this.accessibleTriggerAria=acquireAriaOwnership(semanticTrigger,contribution),this.overlayHandle?.isActive()&&!this.virtualAnchor&&this.overlayHandle.updateRestoreFocusTo(accessibleTrigger)}get accessibleTrigger(){const trigger=this.triggerElement;if(!trigger)return null;const resolved=resolveAccessibleTrigger(trigger);return resolved===trigger&&!trigger.hasAttribute("role")&&!trigger.matches("button, a[href], input, select, textarea, summary")?collectComposedFocusTargets(trigger,{includeRoot:!1,mode:"programmatic"}).elements[0]??trigger:resolved}observeAccessibleTrigger(target){this.accessibleTriggerObserver?.disconnect();const trigger=this.triggerElement;if(!trigger||!this.isConnected)return;const view=this.ownerDocument.defaultView;if(view?.MutationObserver){this.accessibleTriggerObserver??=new view.MutationObserver(()=>{this.isConnected&&this.syncTriggerA11y()});const roots=new Set([trigger]);trigger.shadowRoot&&roots.add(trigger.shadowRoot);let current=target;for(;current&&current!==trigger;){const root=current.getRootNode();if(root.nodeType!==11||!("host"in root))break;roots.add(root),current=root.host}for(const root of roots)this.accessibleTriggerObserver.observe(root,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["role","tabindex","disabled","href","type"]})}this.triggerUpgrades.observeElement(trigger)}releaseTriggerA11y(){this.accessibleTriggerObserver?.disconnect(),this.accessibleTriggerObserver=void 0,this.triggerUpgrades.disconnect(),this.accessibleTriggerAria?.release(),this.accessibleTriggerAria=void 0}collectTriggerFromSlot(slot){const next=slot.assignedElements({flatten:!0})[0];next!==this.slottedTrigger&&(this.slottedTrigger=next,this.syncInteractionTrigger())}requestInteractionClose(next){this.pinned||this.isWithinPopoverSurface(next)||this.hasFocusWithinSurface()||this.requestDelayedTransition(!1)}isWithinPopoverSurface(target){if(target===null||target.nodeType!==1)return!1;const element=target;if(composedContains(this,element))return!0;const popup=this.renderRoot?.querySelector('[part~="popup"]')??null;return popup&&composedContains(popup,element)?!0:this.triggerElement!=null&&composedContains(this.triggerElement,element)}hasFocusWithinSurface(){const active=deepActiveElementIn(this.ownerDocument);return active===null||this.triggerElement&&composedContains(this.triggerElement,active)?!1:this.isWithinPopoverSurface(active)}requestDelayedTransition(next,deferImmediate=!1){if(this.cancelPendingTransition(),next&&!this.canOpen)return;const commit=()=>{next?(this.openedByInteraction=!0,this.show()):this.hide()},delay=Math.max(0,finiteDuration(next?this.showDelay:this.hideDelay,DEFAULT_TRIGGER_DELAY)),view=this.ownerDocument.defaultView;if(!view||delay<=0&&!deferImmediate){commit();return}this.pendingDirection=next?"show":"hide",this.delayTimerView=view;const timer=view.setTimeout(()=>{this.delayTimerView!==view||this.delayTimer!==timer||(this.delayTimer=void 0,this.delayTimerView=void 0,this.pendingDirection=void 0,commit())},delay);this.delayTimer=timer}cancelPendingTransition(){this.delayTimer!==void 0&&this.delayTimerView?.clearTimeout(this.delayTimer),this.delayTimer=void 0,this.delayTimerView=void 0,this.pendingDirection=void 0}triggerNeedsOwnFocusListeners(trigger){return!composedContains(this,trigger)}bindTriggerInteractions(trigger){trigger.addEventListener("mouseenter",this.onTriggerPointerEnter),trigger.addEventListener("mouseleave",this.onTriggerPointerLeave),this.triggerNeedsOwnFocusListeners(trigger)&&(trigger.addEventListener("focusin",this.onSurfaceFocusIn),trigger.addEventListener("focusout",this.onSurfaceFocusOut))}unbindTriggerInteractions(trigger){trigger.removeEventListener("mouseenter",this.onTriggerPointerEnter),trigger.removeEventListener("mouseleave",this.onTriggerPointerLeave),trigger.removeEventListener("focusin",this.onSurfaceFocusIn),trigger.removeEventListener("focusout",this.onSurfaceFocusOut)}startLightDismiss(){const nextDocument=this.ownerDocument;this.lightDismissDocument!==nextDocument&&(this.stopLightDismiss(),nextDocument.addEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=nextDocument)}stopLightDismiss(){this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointer),this.lightDismissDocument=void 0}observeHostId(){const ownerDocument=this.ownerDocument;if(this.hostIdObserver&&this.hostIdObserverDocument===ownerDocument)return;this.resetHostIdObserver();const MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor||!this.isConnected)return;const generation=this.hostIdObserverGeneration,observer=new MutationObserverCtor(()=>{this.hostIdObserver!==observer||this.hostIdObserverDocument!==ownerDocument||this.hostIdObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.id||(this.id=this.generatedHostId),this.syncTriggerA11y())});this.hostIdObserver=observer,this.hostIdObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,attributeFilter:["id"]})}resetHostIdObserver(){this.hostIdObserverGeneration+=1,this.hostIdObserver?.disconnect(),this.hostIdObserver=void 0,this.hostIdObserverDocument=void 0}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,setCustomState(this.popoverInternals,"open",next),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}show(){return this._open||!this.canOpen?Promise.resolve():this.transitionGate.request(!0,()=>{if(this.emitCancelableLifecycle("lr-show").defaultPrevented){this.syncOpenAttribute();return}if(!this.closePopoverPeers()){this.syncOpenAttribute();return}return this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.setOpen(!0),this.settleTransition("lr-after-show")})}hide(options){return this._open?this.transitionGate.request(!1,()=>{if(this.emitCancelableLifecycle("lr-hide").defaultPrevented){this.syncOpenAttribute();return}return this.forceClose(options)}):Promise.resolve()}closePopoverPeers(){if(this.virtualAnchor||this.localName!==tag("popover"))return!0;const root=this.getRootNode();for(const peer of root.querySelectorAll(tag("popover")))if(!(peer===this||!peer.open||peer.virtualAnchor)&&(peer.hide({focusTrigger:!1}),peer.open))return!1;return!0}reconcileInitialPopoverPeers(){if(!this.isConnected||!this._open||this.virtualAnchor||this.localName!==tag("popover"))return;const peers=[...this.getRootNode().querySelectorAll(tag("popover"))].filter(peer=>peer.isConnected&&peer._open&&!peer.virtualAnchor&&peer.connectionSequence>0);if(peers.reduce((latest,peer)=>!latest||peer.connectionSequence>latest.connectionSequence?peer:latest,void 0)!==this){this.closeForInitialPeerReconciliation();return}for(const peer of peers)peer!==this&&peer.closeForInitialPeerReconciliation()}closeForInitialPeerReconciliation(){this._open&&(this.transitionToken++,this.cancelTransitionAnimation(),this.removeAttribute("data-closing"),this.invalidatePositioning(),this.stopLightDismiss(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.positionedAnchor=void 0,this.anchorPositioned=!1,this.returnFocusTo=void 0,this.setOpen(!1),this.syncOpenAttribute())}forceClose(options){return this._open?(options?.focusTrigger===!1&&(this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0),this.cancelTransitionAnimation(),this.isConnected&&this.setAttribute("data-closing",""),this.setOpen(!1),this.settleTransition("lr-after-hide")):Promise.resolve()}cancelTransitionAnimation(){this.transitionAnimation?.cancel(),this.transitionAnimation=void 0}emitCancelableLifecycle(name){return this.emit(name,null,{cancelable:!0})}emitSettledLifecycle(name){return this.emit(name)}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(event==="lr-after-show"){for(;this.open&&!this.anchorPositioned;){const readiness=this.positioningReady,positioned=await readiness;if(this.transitionToken!==token)return;if(positioned)break;if(readiness===this.positioningReady)return}if(await this.updateComplete,this.transitionToken!==token)return}if(this.isConnected){const popup=this.renderRoot.querySelector('[part~="popup"]'),showing=event==="lr-after-show",offset="translateY(var(--lr-size-neg-0-25rem))",animation=popup?animateRegistered(this,popup,`${this.animationNamespace}.${showing?"show":"hide"}`,this.effectiveDirection,{keyframes:showing?[{opacity:0,transform:offset},{opacity:1,transform:"translateY(0)"}]:[{opacity:1,transform:"translateY(0)"},{opacity:0,transform:offset}],durationProperties:this.animationDurationProperties(showing),easingProperties:["--lr-easing-standard"]}):void 0;if(this.transitionAnimation=animation,await animation?.finished.catch(()=>{}),this.transitionToken!==token)return;this.cancelTransitionAnimation()}event==="lr-after-hide"&&(this.removeAttribute("data-closing"),this.popupHidden=!0,await this.updateComplete,this.transitionToken!==token)||this.emitSettledLifecycle(event)}}render(){const popupRole=this.popupSurfaceRole;return html`
2
2
  <span part="trigger" @click=${this.onTriggerClick} @keydown=${this.onTriggerKeyDown}>
3
3
  <slot name="trigger" @slotchange=${this.onTriggerSlotChange}></slot>
4
4
  </span>