@aceshooting/lyra-ui 30.1.0 → 30.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +92 -0
  2. package/dist/ai/adapters/a2ui.d.ts +10 -4
  3. package/dist/ai/adapters/a2ui.js +1 -1
  4. package/dist/ai/adapters/ag-ui.d.ts +17 -4
  5. package/dist/ai/adapters/ag-ui.js +1 -1
  6. package/dist/ai/adapters/ai-sdk.js +1 -1
  7. package/dist/ai/runtime.js +1 -1
  8. package/dist/components/agent-tools/mcp-app/mcp-app-protocol.d.ts +15 -0
  9. package/dist/components/agent-tools/mcp-app/mcp-app-protocol.js +36 -0
  10. package/dist/components/agent-tools/mcp-app/mcp-app.class.d.ts +31 -4
  11. package/dist/components/agent-tools/mcp-app/mcp-app.class.js +4 -4
  12. package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
  13. package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
  14. package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
  15. package/dist/components/charts/chart/chart-prepared-data.d.ts +3 -1
  16. package/dist/components/charts/chart/chart-prepared-data.js +1 -1
  17. package/dist/components/charts/chart/chart.class.js +2 -2
  18. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  19. package/dist/components/conversation/chat-viewport/chat-viewport.class.d.ts +2 -2
  20. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  21. package/dist/components/conversation/message-parts/message-parts.class.d.ts +13 -4
  22. package/dist/components/conversation/message-parts/message-parts.class.js +12 -10
  23. package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
  24. package/dist/components/conversation/message-parts/message-parts.js +1 -1
  25. package/dist/components/forms/checkbox/checkbox.class.d.ts +1 -1
  26. package/dist/components/forms/checkbox/checkbox.class.js +2 -2
  27. package/dist/components/forms/combobox/option.class.d.ts +1 -1
  28. package/dist/components/forms/combobox/option.class.js +2 -2
  29. package/dist/components/forms/radio/radio.class.d.ts +1 -1
  30. package/dist/components/forms/radio/radio.class.js +1 -1
  31. package/dist/components/forms/select/select.class.js +1 -1
  32. package/dist/components/forms/switch/switch.class.d.ts +1 -1
  33. package/dist/components/forms/switch/switch.class.js +1 -1
  34. package/dist/components/media/file-input/file-input.styles.js +1 -1
  35. package/dist/components/media/map/map-anchor-controller.js +1 -1
  36. package/dist/components/media/map/map-control-chrome.js +1 -0
  37. package/dist/components/media/map/map-control-options.d.ts +6 -2
  38. package/dist/components/media/map/map-control-options.js +1 -1
  39. package/dist/components/media/map/map-controls-lifecycle.js +1 -1
  40. package/dist/components/media/map/map-controls-readiness.js +1 -0
  41. package/dist/components/media/map/map.class.d.ts +39 -2
  42. package/dist/components/media/map/map.class.js +13 -7
  43. package/dist/components/media/map/map.styles.js +1 -1
  44. package/dist/components/viewers/model-viewer/model-viewer-loader.js +1 -1
  45. package/dist/components/viewers/model-viewer/model-viewer.class.js +1 -1
  46. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.d.ts +11 -11
  47. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
  48. package/dist/events.d.ts +10 -1
  49. package/dist/framework-types.d.ts +1 -1
  50. package/dist/internal/accessible-text-controller.js +1 -1
  51. package/dist/internal/anchored-overlay-runtime.js +1 -1
  52. package/dist/internal/default-label-forwarding.js +1 -0
  53. package/dist/internal/hierarchy-summary-source.js +1 -0
  54. package/dist/internal/localization-types.d.ts +1 -1
  55. package/dist/internal/localization.js +1 -1
  56. package/dist/internal/package-metadata.js +1 -1
  57. package/dist/internal/positioner.d.ts +8 -0
  58. package/dist/internal/positioner.js +1 -1
  59. package/dist/internal/scoped-definitions.generated.js +1 -1
  60. package/dist/lyra.d.ts +1 -1
  61. package/llms/components/lr-file-input.md +5 -0
  62. package/llms/components/lr-map.md +87 -14
  63. package/llms/components/lr-mcp-app.md +94 -4
  64. package/llms/components/lr-message-parts.md +18 -0
  65. package/llms/components/lr-pptx-viewer.md +9 -5
  66. package/llms/components/lr-select.md +3 -2
  67. package/llms/index.md +1 -1
  68. package/llms/peers.md +1 -1
  69. package/llms/shared/ai-and-peers.md +77 -3
  70. package/llms/shared/events-and-types.md +25 -1
  71. package/llms/shared/localization-and-rtl.md +29 -0
  72. package/llms/shared.md +131 -4
  73. package/locales.json +1 -1
  74. package/package.json +12 -8
  75. package/registrations.json +1 -1
  76. package/skills/compose-lyra-interfaces/SKILL.md +5 -3
  77. package/skills/compose-lyra-interfaces/references/composition-patterns.md +8 -1
  78. package/skills/lyra-ui/SKILL.md +16 -8
  79. package/skills/lyra-ui/lyra-gen.md +86 -0
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{capOptionRows}from"../../../internal/option-selection.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-change-request"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"]),"lr-change-request":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}requestUpdate(...args){args[0]===void 0&&(this.callbackRefreshEpoch=(this.callbackRefreshEpoch??0)+1),super.requestUpdate(...args)}memoOption(key,inputs,compute){const previous=this.optionMemo.get(key);if(previous&&previous.inputs.length===inputs.length&&previous.inputs.every((input,index)=>Object.is(input,inputs[index])))return previous.value;const value=compute();return this.optionMemo.set(key,{inputs,value}),value}get optionIndex(){return this.memoOption("index",[this.options],()=>{const values=new Map,positions=new Map;return this.options.forEach((option,index)=>{positions.set(option,index),values.has(option.value)||values.set(option.value,option)}),{values,positions,members:new Set(this.options)}})}get selectedIndex(){return this.memoOption("selectedIndex",[this._selectedOptions,this.options],()=>{const values=new Map;for(const option of this._selectedOptions)values.has(option.value)||values.set(option.value,option);return{values,members:new Set(this._selectedOptions)}})}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.maxRender=200,this.options=[],this.callbackRefreshEpoch=0,this.optionMemo=new Map,this.optionsObserved=!1,this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this.listboxHidden=!0,this.listboxRendered=!1,this.listboxPositioned=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.previousValue="",this.openStateGeneration=0,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeBuffer=new TypeAheadBuffer(this),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.hasInteracted||(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.pendingSelectedWrites=new Map,this.selectedWritesQueued=!1,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isOptionSelectedWrite(e)&&isLyraOptionElement(option)&&this.optionIndex.members.has(option)){markVetoGuardWrite(this.selectionWriteGuard),this._valueDirty=!0,this._restoredStateActive=!1,this.pendingSelectedWrites.delete(option),this.pendingSelectedWrites.set(option,{selected:option.selected,value:option.value}),this.selectedWritesQueued||(this.selectedWritesQueued=!0,queueMicrotask(()=>this.flushSelectedWrites()));return}if(isLyraOptionElement(option)){const cached=this.adornmentClones.get(option);cached&&cached.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option)}if(this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.selectionWriteGuard=new VetoWriteGuard,this.selectionRequestDispatching=!1,this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229)return;const navigable=this.navigableOptions(),move=()=>resolveListMove(e,{count:navigable.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}}finally{this._resolvingPendingInitialSelection=!1}}if(this.announceOpenTransition(changed),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1,this.listboxRendered=!0),changed.has("open")&&!this.openVetoed){const navigable=this.navigableOptions();this.setActiveIndex(this.open?navigable.findIndex(option=>this.selectedIndex.members.has(option)):-1,navigable)}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{const assigned=s.assignedElements({flatten:!0});this.optionsObserved=!0,assigned.some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){this.listboxHidden=!0;const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.popupController.cancel(),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!(!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)){if(!this.isConnected){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this._resolvingPendingInitialSelection||(this._pendingInitialSelectedOptions=void 0,this.hasUpdated||(this._pendingInitialValue=next)),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values)}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){const candidates=Array.isArray(next)?next:[];this._resolvingPendingInitialSelection||(this._pendingInitialValue=void 0,this._pendingInitialSelectedOptions=this.hasUpdated?void 0:candidates.filter(option=>isLyraOptionElement(option)&&this.contains(option))),this._restoredStateActive=!1,this._valueDirty=!0;const catalog=candidates.length>1?new Set(this.options):void 0,seen=new Set,live=candidates.filter(option=>seen.has(option)?!1:(seen.add(option),isLyraOptionElement(option)&&this.contains(option)&&(catalog?catalog.has(option):this.options.includes(option)))),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){this.pendingSelectedWrites.clear(),markVetoGuardWrite(this.selectionWriteGuard);const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this.previousValue=old,this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){if(values.length===0)return[];if(values.length===1){const value=values[0],hint=preferred.length===1?preferred[0]:preferred.find(option=>option?.value===value);return[hint&&hint.value===value&&this.options.includes(hint)?hint:this.options.find(option=>option.value===value)]}const requested=new Set(values),catalog=new Set(this.options),claimed=new Set,queuesFor=options=>{const queues=new Map;for(const option of options){if(!option)continue;const value=option.value;if(!requested.has(value))continue;let queue=queues.get(value);queue||queues.set(value,queue={options:[],next:0}),queue.options.push(option)}return queues},firstUnclaimed=(queues,value)=>{const queue=queues.get(value);if(queue){for(;queue.next<queue.options.length&&claimed.has(queue.options[queue.next]);)queue.next++;return queue.options[queue.next]}},preferredQueues=preferred.length===values.length?void 0:queuesFor(preferred);let fallbackQueues;return values.map((value,index)=>{const hint=preferredQueues?firstUnclaimed(preferredQueues,value):preferred[index],match=hint&&hint.value===value&&catalog.has(hint)&&!claimed.has(hint)?hint:firstUnclaimed(fallbackQueues??=queuesFor(this.options),value);if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0)}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this._pendingInitialValue=void 0,this._pendingInitialSelectedOptions=void 0,this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;markVetoGuardWrite(this.selectionWriteGuard);const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.updateValidity(),this.hasInteracted=!0,this.reflectValidityStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.pendingSelectedWrites.clear(),markVetoGuardWrite(this.selectionWriteGuard),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.typeBuffer.clear(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}adoptedCallback(){markVetoGuardWrite(this.selectionWriteGuard),super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.typeBuffer.clear(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.optionsObserved=!0,this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0;const resolving=this._resolvingPendingInitialSelection;this._resolvingPendingInitialSelection=!0;try{this.selectedOptions=pending}finally{this._resolvingPendingInitialSelection=resolving}return}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(!(this.selectionRequestDispatching||this.effectiveDisabled)){if(this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.requestSelection(values,this.resolveOccurrenceSlots(values,this._selectedOptions),()=>{this.emitValueEvents(),this.emit("lr-activate",{value})});return}this.hide(),this.emit("lr-activate",{value})}}resolvedLabelFor(value,occurrenceIndex=0){const option=(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]:void 0)??this.selectedIndex.values.get(value)??this.optionIndex.values.get(value);return option&&(option.label||option.value)}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;if(this.loading)return this.localize("loading");const override=this.optionsObserved?this.getUnknownLabel?.(value):void 0;return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return!this.optionsObserved||this.loading||value===""?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return this.memoOption("navigable",[options],()=>options.filter(option=>this.isOptionAvailable(option)))}get unknownValues(){return this.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get optionWindow(){return this.memoOption("window",[this.callbackRefreshEpoch,this.options,this._selected,this._selectedOptions,this.activeOption,this.maxRender,this.withUnknownOption,this.loading,this.optionsObserved,this.getUnknownLabel,this.effectiveLocale,this.strings],()=>{const unknown=this.unknownOptions,all=unknown.length?[...this.options,...unknown]:this.options;return capOptionRows(all,this.maxRender,[...this.activeOption?[this.activeOption]:[],...this._selectedOptions,...unknown])})}get listboxOptions(){return this.optionWindow.rows}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;const rawPositions=new Map(this.listboxOptions.map((option,index)=>[option,index]));navigable.forEach((option,index)=>{const rawIndex=rawPositions.get(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}flushSelectedWrites(){this.selectedWritesQueued=!1;const writes=[...this.pendingSelectedWrites];if(this.pendingSelectedWrites.clear(),!this.isConnected||writes.length===0)return;if(!this.multiple){let value=this._selected[0],option=this._selectedOptions[0];for(const[candidate,write]of writes)this.optionIndex.members.has(candidate)&&(write.selected?(value=write.value,option=candidate):candidate===option&&(value=void 0,option=void 0));this.setSelection(value===void 0?[]:[value],option?[option]:[]);return}const queues=new Map;for(const option of this._selectedOptions){const value=this._selectedValuesByOption.get(option)??option.value;let queue=queues.get(value);queue||queues.set(value,queue={options:[],next:0}),queue.options.push(option)}const entries=this._selected.map(value=>{const queue=queues.get(value);return{value,option:queue?.options[queue.next++]}}),byOption=new Map(entries.flatMap(entry=>entry.option?[[entry.option,entry]]:[]));for(const[option,write]of writes){if(!this.optionIndex.members.has(option))continue;const entry=byOption.get(option);if(!write.selected)entry&&(entry.removed=!0);else if(entry&&!entry.removed)entry.value=write.value;else{const added={value:write.value,option};entries.push(added),byOption.set(option,added)}}const retained=entries.filter(entry=>!entry.removed);this.setSelection(retained.map(entry=>entry.value),retained.map(entry=>entry.option))}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0,this.revealActiveOption()),positioned))}revealActiveOption(){if(!this.isConnected||!this.open||!this.listboxPositioned||!this.cleanup)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),activeId=this.triggerElement?.getAttribute("aria-activedescendant"),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&activeId&&row.id===activeId&&revealRow(listbox,row)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.popupController.bindPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("activeIndex")||changed.has("options")||changed.has("listboxPositioned"))&&this.revealActiveOption(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return this.forceCloseOpenState(),!1}return!0},conceal:()=>{this.listboxHidden=!0,this.listboxRendered=!1}})}emitValueEvents(){const self=this,data=this.selectedData,value=self.value,previousValue=this.previousValue;dispatchNativeInputEvent(this),self.emit("lr-input",{value,previousValue,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value,previousValue,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}requestSelection(values,preferred,afterCommit,available=()=>!0){if(this.selectionRequestDispatching||this.effectiveDisabled)return!1;const multiple=this.multiple,document=this.ownerDocument,connected=this.isConnected,open=this.open,slots=this.resolveOccurrenceSlots(values,preferred),data=slots.map(option=>option?.data),value=multiple?[...values]:values[0]??"",previousValue=this.value,self=this;let committed=!1;this.selectionRequestDispatching=!0;try{requestThenCommit({requestDetail:{value,previousValue,data},guard:this.selectionWriteGuard,emitRequest:(detail,init)=>self.emit("lr-change-request",detail,init),commit:()=>{const liveOptions=new Set(this.renderRoot.querySelector("slot:not([name])")?.assignedElements({flatten:!0})??[]);this.effectiveDisabled||this.multiple!==multiple||this.ownerDocument!==document||this.isConnected!==connected||this.open!==open||!available(liveOptions)||slots.some((option,index)=>option&&(!liveOptions.has(option)||option.value!==values[index]||!Object.is(option.data,data[index])))||(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(values,preferred),committed=!0,afterCommit())}})}finally{this.selectionRequestDispatching=!1}return committed}selectOption(option){if(this.selectionRequestDispatching||this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}const value=option.value,available=liveOptions=>liveOptions.has(option)&&option.value===value&&this.isOptionAvailable(option);if(this.multiple){const currentSlots=this.resolveOccurrenceSlots(this._selected,this._selectedOptions),selectedIndex=currentSlots.indexOf(option),selected=selectedIndex>=0,occurrences=selected?currentSlots.filter((_,index)=>index!==selectedIndex):[...currentSlots,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,value];this.requestSelection(values,occurrences,()=>{this.emitValueEvents(),this.emit("lr-activate",{value})},available);return}if(!(option!==this._selectedOptions[0]||value!==this._selected[0])){this.hide(),this.emit("lr-activate",{value});return}this.requestSelection([value],[option],()=>{this.hide(),this.emitValueEvents(),this.emit("lr-activate",{value})},available)}removeValueAt(index){return this.effectiveDisabled||index<0||index>=this._selected.length?!1:this.requestSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this.resolveOccurrenceSlots(this._selected,this._selectedOptions).filter((_,candidateIndex)=>candidateIndex!==index),()=>this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||this.requestSelection([],[],()=>{this.emitValueEvents(),this.emit("lr-clear")})}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&this.removeValueAt(index)&&this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),labels=this.memoOption("typeAheadLabels",[navigable,this.effectiveLocale],()=>{const locale=resolveIntlLocale(this.effectiveLocale);return new Map(navigable.map(option=>[option,option.label.toLocaleLowerCase(locale)]))});let match=null;for(let step=1;step<=navigable.length;step++){const index=(currentIndex+step+navigable.length)%navigable.length,option=navigable[index];if((this.open||!this.multiple||!this.selectedIndex.members.has(option))&&labels.get(option)?.startsWith(this.typeBuffer.text)){match=index;break}}if(match===null)return;const candidate=navigable[match];this.open?this.setActiveIndex(match,navigable):this.selectOption(candidate)}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
1
+ import{__decorate}from"tslib";import{capOptionRows}from"../../../internal/option-selection.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{VetoWriteGuard,markVetoGuardWrite}from"../../../internal/veto-write-guard.js";import{renderFormControlHintError}from"../../../internal/form-control-template.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{FormControlController,reflectFormName}from"../../../internal/form-control-controller.js";import{GlassScrollLayer}from"../../../internal/glass-scroll-layer.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{acquireNativeControlDescription}from"../../../internal/native-control-description.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{LyraFormControlElement}from"../../../internal/form-control-element.js";import{deferredPlaceReady as place,syncTopLayerRelease,topLayerPlacement}from"../../../internal/anchored-overlay-runtime.js";import{resolveEffectivePositioningStrategy}from"../../../internal/positioning-strategy.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{PopupController,emitPopupEvent}from"../../../internal/popup-controller.js";import{revealRow}from"../../../internal/reveal-row.js";import{TypeAheadBuffer}from"../../../internal/type-ahead-buffer.js";import{resolveListMove}from"../../../internal/list-navigation.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat,resolveIntlLocale}from"../../../internal/intl-cache.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{collectInitialSlotAssignment}from"../../../internal/initial-slot-collection.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{omittedEmptyStringConverter,optionalLiteralSetConverter}from"../../../internal/converters.js";import{getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,isOptionSelectedWrite,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{tag}from"../../../internal/prefix.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_notInCatalog,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_select}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}function normalizeSelectionValues(next){return Array.isArray(next)?next.filter(value=>typeof value=="string"):typeof next=="string"?[next]:[]}const POSITIONING_STRATEGY=optionalLiteralSetConverter(["absolute","fixed"]);class LyraSelect extends LyraFormControlElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,notInCatalog:LYRA_DEFAULT_notInCatalog,removeWithContext:LYRA_DEFAULT_removeWithContext,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change","lr-change-request"])}static{this.identityEventDetailCollectionItems=Object.freeze({"lr-input":Object.freeze(["data"]),"lr-change":Object.freeze(["data"]),"lr-change-request":Object.freeze(["data"])})}static get validators(){return[currentValidityValidator("required","disabled","value","multiple")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},multiple:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{noAccessor:!0},name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:!0},defaultValue:{attribute:"default-value",noAccessor:!0}}}get open(){return this._open}set open(next){const requested=!!next,normalized=requested&&!this.effectiveDisabled;if(normalized===this._open){requested!==normalized&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(normalized)}get positioningStrategy(){return this._positioningStrategy??"absolute"}set positioningStrategy(next){const normalized=POSITIONING_STRATEGY.normalize(next)??"absolute",old=this.positioningStrategy;this._positioningStrategy=normalized,normalized!==old&&(this.requestUpdate("positioningStrategy",old),old==="fixed"!=(normalized==="fixed")&&this.requestUpdate("hoist",old==="fixed"))}get hoist(){return this.positioningStrategy==="fixed"}set hoist(next){this.positioningStrategy=next?"fixed":"absolute"}requestUpdate(...args){args[0]===void 0&&(this.callbackRefreshEpoch=(this.callbackRefreshEpoch??0)+1),super.requestUpdate(...args)}memoOption(key,inputs,compute){const previous=this.optionMemo.get(key);if(previous&&previous.inputs.length===inputs.length&&previous.inputs.every((input,index)=>Object.is(input,inputs[index])))return previous.value;const value=compute();return this.optionMemo.set(key,{inputs,value}),value}get optionIndex(){return this.memoOption("index",[this.options],()=>{const values=new Map,positions=new Map;return this.options.forEach((option,index)=>{positions.set(option,index),values.has(option.value)||values.set(option.value,option)}),{values,positions,members:new Set(this.options)}})}get selectedIndex(){return this.memoOption("selectedIndex",[this._selectedOptions,this.options],()=>{const values=new Map;for(const option of this._selectedOptions)values.has(option.value)||values.set(option.value,option);return{values,members:new Set(this._selectedOptions)}})}focus(options){this.effectiveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.effectiveDisabled||this.triggerElement?.click()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.helpText="",this.withLabel=!1,this.withHint=!1,this.errorText="",this.autofocus=!1,this.title="",this._open=!1,this.size="m",this.appearance="outlined",this.pill=!1,this.placement="bottom",this.topLayer=!1,this.filled=!1,this.withClear=!1,this.clearable=!1,this.withUnknownOption=!1,this.loading=!1,this.autoCommitSingleOption=!1,this.activeIndex=-1,this.maxRender=200,this.options=[],this.callbackRefreshEpoch=0,this.optionMemo=new Map,this.optionsObserved=!1,this.touched=!1,this.hasInteracted=!1,this.slotPresence=new SlotPresenceController(this),this._fieldsetDisabled=!1,this.listId=nextId("select-list"),this.triggerId=nextId("select-trigger"),this.valueTextId=nextId("select-value"),this.positioningReady=Promise.resolve(!1),this.restoreFocusOnClose=!0,this.popupController=new PopupController({host:this,popup:()=>this.renderRoot.querySelector('[part="listbox"]'),emit:(name,cancelable)=>emitPopupEvent(this,name,cancelable),onPointer:event=>this.onDocPointer(event)}),this.listboxHidden=!0,this.listboxRendered=!1,this.listboxPositioned=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.previousValue="",this.openStateGeneration=0,this._selected=[],this._selectedOptions=[],this._selectedValuesByOption=new Map,this.adornmentClones=new WeakMap,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultSelectedOptions=[],this._defaultCaptured=!1,this._valueDirty=!1,this._restoredStateActive=!1,this._resolvingPendingInitialSelection=!1,this._defaultValueDirty=!1,this.typeBuffer=new TypeAheadBuffer(this),this._name="",this._maxOptionsVisible=3,this.localDescriptionIds="",this.markInteracted=()=>{this.touched=!0,!this.hasInteracted&&(this.hasInteracted=!0,this.reflectValidityStates())},this.collectOptions=e=>{this.collectOptionsFromSlot(e.target)},this.unknownOptionCache=new Map,this.pendingSelectedWrites=new Map,this.selectedWritesQueued=!1,this.optionRefreshPending=!1,this.onOptionChange=e=>{e.stopPropagation();const option=e.composedPath().find(isLyraOptionElement);if(isOptionSelectedWrite(e)&&isLyraOptionElement(option)&&this.optionIndex.members.has(option)){markVetoGuardWrite(this.selectionWriteGuard),this._valueDirty=!0,this._restoredStateActive=!1,this.pendingSelectedWrites.delete(option),this.pendingSelectedWrites.set(option,{selected:option.selected,value:option.value}),this.selectedWritesQueued||(this.selectedWritesQueued=!0,queueMicrotask(()=>this.flushSelectedWrites()));return}if(isLyraOptionElement(option)){const cached=this.adornmentClones.get(option);cached&&cached.markup!==this.adornmentMarkup(option)&&this.adornmentClones.delete(option)}if(this.optionRefreshPending)return;this.optionRefreshPending=!0;const previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;queueMicrotask(()=>{this.optionRefreshPending=!1,this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.reconcileActiveOption(previousActive,previousActiveRawIndex)})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.selectionWriteGuard=new VetoWriteGuard,this.selectionRequestDispatching=!1,this.onTriggerClick=()=>{if(!this.effectiveDisabled){if(this.onlyOption)return this.selectOption(this.onlyOption);this.open?this.hide():this.show()}},this.onTriggerBlur=event=>{this.effectiveDisabled||(this.touched=!0,this.hasInteracted=!0,this.reflectValidityStates()),this.open&&(this.restoreFocusOnClose=!1),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{relayNativeEvent(this,event)},this.onKeyDown=e=>{if(e.isComposing||e.keyCode===229)return;const navigable=this.navigableOptions(),move=()=>resolveListMove(e,{count:navigable.length,current:this.activeIndex,orientation:"vertical",wrap:!1,clamp:!0,backwardFromMissing:"first"});switch(e.key){case"ArrowDown":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"ArrowUp":if(e.preventDefault(),this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){this.show();return}this.setActiveIndex(move()??-1,navigable);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];this.activeIndex>=0&&active?this.selectOption(active):this.hide()}break;case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(move()??-1,navigable));break;case"Backspace":case"Delete":this.multiple&&this._selected.length>0&&(e.preventDefault(),this.removeValueAt(this._selected.length-1));break;default:this.typeBuffer.accepts(e)&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const optionEl=e.target.closest('[part="option"]'),index=Number(optionEl?.dataset.index);if(!Number.isInteger(index))return;const option=this.listboxOptions[index];option&&this.selectOption(option)},this.validityController=new FormControlController(this,{invalid:init=>this.emit("lr-invalid",null,init),interacted:this.markInteracted,customError:()=>this.validityController.customValidityMessage}),this.internals=this.validityController.formInternals,new GlassScrollLayer(this,'[part="listbox"]',()=>this.open),this.syncFormValue()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}syncExternalDescription(){if(!this.isConnected)return;const target=this.renderRoot.querySelector('[part="trigger"]');target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireNativeControlDescription(this,target,()=>this.localDescriptionIds))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.updateValidity(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){if(super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this._isFirstUpdate&&(this._pendingInitialDefaultValue!==void 0||this._pendingInitialValue!==void 0)){this._resolvingPendingInitialSelection=!0;try{if(this._pendingInitialDefaultValue!==void 0){const pending=this._pendingInitialDefaultValue;this._pendingInitialDefaultValue=void 0,this.assignDefaultValue(pending)}if(this._pendingInitialValue!==void 0){const pending=this._pendingInitialValue;this._pendingInitialValue=void 0,this.assignValue(pending)}}finally{this._resolvingPendingInitialSelection=!1}}if(this.announceOpenTransition(changed),changed.has("open")&&!this.openVetoed&&(this.listboxPositioned=!1),this.open&&(this.listboxHidden=!1,this.listboxRendered=!0),changed.has("open")&&!this.openVetoed){const navigable=this.navigableOptions();this.setActiveIndex(this.open?navigable.findIndex(option=>this.selectedIndex.members.has(option)):-1,navigable)}}firstUpdated(changed){super.firstUpdated(changed);const slot=this.optionsSlot;queueMicrotask(()=>{collectInitialSlotAssignment(slot,s=>{const assigned=s.assignedElements({flatten:!0});this.optionsObserved=!0,assigned.some(isLyraOptionElement)&&this.collectOptionsFromSlot(s)})})}applyOpenState(next){const old=this._open;this.pendingOpenTransitionStart===void 0&&(this.pendingOpenTransitionStart=old),this.openStateGeneration++,this._open=next,this.requestUpdate("open",old)}forceCloseOpenState(){this.listboxHidden=!0;const isClosing=this._open||this.pendingOpenTransitionStart===!0;if(this.popupController.cancel(),!this._open){isClosing&&(this.suppressedOpenLifecycleGeneration=this.openStateGeneration),this.hasAttribute("open")&&this.removeAttribute("open");return}this.applyOpenState(!1),this.suppressedOpenLifecycleGeneration=this.openStateGeneration}announceOpenTransition(changed){if(this.openVetoed=!1,!(!changed.has("open")||this._isFirstUpdate||this.suppressedOpenLifecycleGeneration===this.openStateGeneration)){if(!this.isConnected){emitPopupEvent(this,"lr-hide",!1);return}this.openVetoed=this.popupController.announce(this.open,()=>{this.open=!this.open})}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",reflectFormName(this,this._name),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),!this._multiple&&this._selected.length>1?this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1)):this.syncFormValue(),this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){markVetoGuardWrite(this.selectionWriteGuard);const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._fieldsetDisabled=this.validityController?.fieldsetDisabled(this._fieldsetDisabled)??this._fieldsetDisabled,this._disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this._resolvingPendingInitialSelection||(this._pendingInitialSelectedOptions=void 0,this.hasUpdated||(this._pendingInitialValue=next)),this._restoredStateActive=!1,this._valueDirty=!0;const values=normalizeSelectionValues(next);this.setSelection(values)}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){!this.hasUpdated&&!this._resolvingPendingInitialSelection&&(this._pendingInitialDefaultValue=next),this._defaultValueDirty=!0;const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",values=normalizeSelectionValues(next);this._defaultSelected=this.multiple?[...values]:values.slice(0,1),this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected),!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]),this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){const candidates=Array.isArray(next)?next:[];this._resolvingPendingInitialSelection||(this._pendingInitialValue=void 0,this._pendingInitialSelectedOptions=this.hasUpdated?void 0:candidates.filter(option=>isLyraOptionElement(option)&&this.contains(option))),this._restoredStateActive=!1,this._valueDirty=!0;const catalog=candidates.length>1?new Set(this.options):void 0,seen=new Set,live=candidates.filter(option=>seen.has(option)?!1:(seen.add(option),isLyraOptionElement(option)&&this.contains(option)&&(catalog?catalog.has(option):this.options.includes(option)))),selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}get selectedData(){return this.resolveOccurrenceSlots(this._selected,this._selectedOptions).map(option=>option?.data)}setSelection(next,preferred=[]){this.pendingSelectedWrites.clear(),markVetoGuardWrite(this.selectionWriteGuard);const values=this.multiple?[...next]:next.slice(0,1),previousValues=this._selected,previousOptions=this._selectedOptions,old=this.multiple?[...previousValues]:previousValues[0]??"";this.previousValue=old,this._selected=values,this._selectedOptions=this.resolveOccurrences(values,preferred),this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]),sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);sameValues&&!sameOptions&&this.requestUpdate()}resolveOccurrences(values,preferred=[]){return this.resolveOccurrenceSlots(values,preferred).filter(option=>option!==void 0)}resolveOccurrenceSlots(values,preferred=[]){if(values.length===0)return[];if(values.length===1){const value=values[0],hint=preferred.length===1?preferred[0]:preferred.find(option=>option?.value===value);return[hint&&hint.value===value&&this.options.includes(hint)?hint:this.options.find(option=>option.value===value)]}const requested=new Set(values),catalog=new Set(this.options),claimed=new Set,queuesFor=options=>{const queues=new Map;for(const option of options){if(!option)continue;const value=option.value;if(!requested.has(value))continue;let queue=queues.get(value);queue||queues.set(value,queue={options:[],next:0}),queue.options.push(option)}return queues},firstUnclaimed=(queues,value)=>{const queue=queues.get(value);if(queue){for(;queue.next<queue.options.length&&claimed.has(queue.options[queue.next]);)queue.next++;return queue.options[queue.next]}},preferredQueues=preferred.length===values.length?void 0:queuesFor(preferred);let fallbackQueues;return values.map((value,index)=>{const hint=preferredQueues?firstUnclaimed(preferredQueues,value):preferred[index],match=hint&&hint.value===value&&catalog.has(hint)&&!claimed.has(hint)?hint:firstUnclaimed(fallbackQueues??=queuesFor(this.options),value);if(match)return claimed.add(match),match})}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){this.barredFromValidation?this.validityController.setValidity({}):this.required&&this._selected.length===0?this.validityController.setValidity({valueMissing:!0},this.localize("selectValueMissing")):this.validityController.setValidity({}),this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0)}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this._pendingInitialValue=void 0,this._pendingInitialSelectedOptions=void 0,this.touched=!1,this.hasInteracted=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));this._defaultSelectedOptions.length===0&&resetOptions.length>0&&(this._defaultSelectedOptions=[...resetOptions],this._defaultSelected=resetOptions.map(option=>option.value));const defaults=new Set(resetOptions);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option));this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){if(!this.multiple)this.assignValue(typeof state2=="string"?state2:void 0);else{let restored=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(entry=>typeof entry=="string")&&(restored=parsed)}catch{}this.assignValue(restored)}this._restoredStateActive=!0,this._valueDirty=!0}formDisabledCallback(disabled){if(this.validityController?.reflectingDisabled)return;markVetoGuardWrite(this.selectionWriteGuard);const wasDisabled=this.effectiveDisabled;this._fieldsetDisabled=disabled,wasDisabled!==this.effectiveDisabled&&(disabled&&this.forceCloseOpenState(),this.updateValidity(),this.requestUpdate())}checkValidity(){return this.validityController.checkValidity(()=>this.updateValidity())}reportValidity(){return this.validityController.syncConstraints(),this.updateValidity(),this.markInteracted(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.pendingSelectedWrites.clear(),markVetoGuardWrite(this.selectionWriteGuard),this.listboxHidden=!0,this.releaseExternalDescription(),this.popupController.cancel(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.typeBuffer.clear(),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.open=!1}adoptedCallback(){markVetoGuardWrite(this.selectionWriteGuard),super.adoptedCallback(),this.popupController.cancel(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription(),this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.typeBuffer.clear(),queueMicrotask(()=>this.reconnectOpenPopup())}collectOptionsFromSlot(slot){const previous=new Set(this.options),previousActive=this.activeOption,previousActiveRawIndex=previousActive?this.options.indexOf(previousActive):this.activeIndex;if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.optionsObserved=!0,this.adornmentClones=new WeakMap,this.reconcileActiveOption(previousActive,previousActiveRawIndex),this._defaultCaptured){const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected),newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...this._restoredStateActive?[]:newLive];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1),occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;newLive.length>0&&(this._valueDirty=!0),this.setSelection(occurrences.map(option=>option.value),occurrences);return}}else{this._defaultCaptured=!0;const explicitDefault=this.hasAttribute("default-value")||this._defaultValueDirty,allDefaults=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),allLive=this.options.filter(option=>option.selected),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(explicitDefault)this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);else{const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value),this._defaultSelectedOptions=[...resetOptions]}const fromDefaults=explicitDefault||defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:explicitDefault?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){(!fromDefaults||optionDirty)&&(this._valueDirty=!0),this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty&&(this._valueDirty=!0),explicitDefault&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}if(this._pendingInitialSelectedOptions!==void 0){const pending=this._pendingInitialSelectedOptions;this._pendingInitialSelectedOptions=void 0;const resolving=this._resolvingPendingInitialSelection;this._resolvingPendingInitialSelection=!0;try{this.selectedOptions=pending}finally{this._resolvingPendingInitialSelection=resolving}return}this.reflectSelected()}refreshOptionDefaults(){if(this.hasAttribute("default-value")||this._defaultValueDirty)return;const declared=this.options.filter(option=>option.defaultSelected),defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value),this._defaultSelectedOptions=[...defaults],!this._valueDirty&&!this._restoredStateActive&&this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions),this._selectedValuesByOption=new Map(this._selectedOptions.map(option=>[option,option.value]));const chosen=new Set(this._selectedOptions);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}selectUnknownValue(value){if(!(this.selectionRequestDispatching||this.effectiveDisabled)){if(this.multiple){const index=this._selected.indexOf(value),values=index>=0?this._selected.filter((_,position)=>position!==index):[...this._selected,value];this.requestSelection(values,this.resolveOccurrenceSlots(values,this._selectedOptions),()=>{this.emitValueEvents(),this.emit("lr-activate",{value})});return}this.hide(),this.emit("lr-activate",{value})}}resolvedLabelFor(value,occurrenceIndex=0){const option=(this._selectedOptions[occurrenceIndex]?.value===value?this._selectedOptions[occurrenceIndex]:void 0)??this.selectedIndex.values.get(value)??this.optionIndex.values.get(value);return option&&(option.label||option.value)}labelFor(value,occurrenceIndex=0){const resolved=this.resolvedLabelFor(value,occurrenceIndex);if(resolved!==void 0)return resolved;if(this.loading)return this.localize("loading");const override=this.optionsObserved?this.getUnknownLabel?.(value):void 0;return override!==void 0&&override.trim().length>0?override:value}isUnknownValue(value,occurrenceIndex=0){return!this.optionsObserved||this.loading||value===""?!1:this.resolvedLabelFor(value,occurrenceIndex)===void 0}get onlyOption(){if(!this.autoCommitSingleOption)return;const navigable=this.navigableOptions(this.options);return navigable.length===1?navigable[0]:void 0}isOptionAvailable(option){return!option.disabled&&!option.inert&&!option.closest("[inert]")}navigableOptions(options=this.listboxOptions){return this.memoOption("navigable",[options],()=>options.filter(option=>this.isOptionAvailable(option)))}get unknownValues(){return this.withUnknownOption?this._selected.filter((value,index)=>this.isUnknownValue(value,index)):[]}get unknownOptions(){const values=this.unknownValues;if(values.length===0)return this.unknownOptionCache.clear(),[];for(const key of[...this.unknownOptionCache.keys()])values.includes(key)||this.unknownOptionCache.delete(key);return values.map(value=>{let option=this.unknownOptionCache.get(value);return option||(option=this.ownerDocument.createElement(tag("option")),this.unknownOptionCache.set(value,option)),option.value=value,option.label=this.labelFor(value),option})}get optionWindow(){return this.memoOption("window",[this.callbackRefreshEpoch,this.options,this._selected,this._selectedOptions,this.activeOption,this.maxRender,this.withUnknownOption,this.loading,this.optionsObserved,this.getUnknownLabel,this.effectiveLocale,this.strings],()=>{const unknown=this.unknownOptions,all=unknown.length?[...this.options,...unknown]:this.options;return capOptionRows(all,this.maxRender,[...this.activeOption?[this.activeOption]:[],...this._selectedOptions,...unknown])})}get listboxOptions(){return this.optionWindow.rows}setActiveIndex(next,navigable=this.navigableOptions()){if(next<0||navigable.length===0){this.activeIndex=-1,this.activeOption=void 0;return}const index=Math.min(next,navigable.length-1);this.activeIndex=index,this.activeOption=navigable[index]}reconcileActiveOption(previousActive,previousRawIndex){if(!previousActive&&this.activeIndex<0)return;const navigable=this.navigableOptions();if(previousActive){const preservedIndex=navigable.indexOf(previousActive);if(preservedIndex>=0){this.setActiveIndex(preservedIndex,navigable);return}}if(navigable.length===0){this.setActiveIndex(-1,navigable);return}const pivot=Math.max(0,previousRawIndex);let nearestIndex=0,nearestDistance=Number.POSITIVE_INFINITY,nearestRawIndex=-1;const rawPositions=new Map(this.listboxOptions.map((option,index)=>[option,index]));navigable.forEach((option,index)=>{const rawIndex=rawPositions.get(option),distance=Math.abs(rawIndex-pivot);(distance<nearestDistance||distance===nearestDistance&&rawIndex>=pivot&&nearestRawIndex<pivot)&&(nearestIndex=index,nearestDistance=distance,nearestRawIndex=rawIndex)}),this.setActiveIndex(nearestIndex,navigable)}flushSelectedWrites(){this.selectedWritesQueued=!1;const writes=[...this.pendingSelectedWrites];if(this.pendingSelectedWrites.clear(),!this.isConnected||writes.length===0)return;if(!this.multiple){let value=this._selected[0],option=this._selectedOptions[0];for(const[candidate,write]of writes)this.optionIndex.members.has(candidate)&&(write.selected?(value=write.value,option=candidate):candidate===option&&(value=void 0,option=void 0));this.setSelection(value===void 0?[]:[value],option?[option]:[]);return}const queues=new Map;for(const option of this._selectedOptions){const value=this._selectedValuesByOption.get(option)??option.value;let queue=queues.get(value);queue||queues.set(value,queue={options:[],next:0}),queue.options.push(option)}const entries=this._selected.map(value=>{const queue=queues.get(value);return{value,option:queue?.options[queue.next++]}}),byOption=new Map(entries.flatMap(entry=>entry.option?[[entry.option,entry]]:[]));for(const[option,write]of writes){if(!this.optionIndex.members.has(option))continue;const entry=byOption.get(option);if(!write.selected)entry&&(entry.removed=!0);else if(entry&&!entry.removed)entry.value=write.value;else{const added={value:write.value,option};entries.push(added),byOption.set(option,added)}}const retained=entries.filter(entry=>!entry.removed);this.setSelection(retained.map(entry=>entry.value),retained.map(entry=>entry.option))}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();const settled=this.popupController.wait(!0);return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();const settled=this.popupController.wait(!1);return this.open=!1,settled}positionListbox(){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=this.effectiveDirection;const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');if(!anchor||!listbox)return;this.placedTopLayer=syncTopLayerRelease(listbox,this.placedTopLayer,this.topLayer),this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),...topLayerPlacement(this.topLayer,resolveEffectivePositioningStrategy(this,this._positioningStrategy,"absolute")),sync:this.sync});const operation=this.cleanup;this.positioningReady=operation.ready.then(positioned=>(positioned&&this.cleanup===operation&&this.open&&this.isConnected&&(this.listboxPositioned=!0,this.revealActiveOption()),positioned))}revealActiveOption(){if(!this.isConnected||!this.open||!this.listboxPositioned||!this.cleanup)return;const listbox=this.renderRoot.querySelector('[part="listbox"]'),activeId=this.triggerElement?.getAttribute("aria-activedescendant"),row=listbox?.querySelector('[part="option"][data-active]');listbox&&row&&activeId&&row.id===activeId&&revealRow(listbox,row)}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.triggerElement??null}),this.popupController.bindPointer(),this.positionListbox()}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.positionedDirection=void 0,this.overlayHandle?.deactivate({restoreFocus}),this.overlayHandle=void 0,this.popupController.unbindPointer(),this.restoreFocusOnClose=!0}reconnectOpenPopup(){!this.isConnected||!this.open||this.activateListboxOverlay()}updated(changed){super.updated(changed),this.syncExternalDescription();const suppressOpenLifecycle=changed.has("open")&&this.suppressedOpenLifecycleGeneration===this.openStateGeneration,shouldRefreshPosition=this.open&&this.isConnected&&(changed.has("placement")||changed.has("positioningStrategy")||changed.has("topLayer")||changed.has("sync")||this.positionedDirection!==this.effectiveDirection);changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-show")):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),!this._isFirstUpdate&&!suppressOpenLifecycle&&this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed?(this.restoreFocusOnClose=!0,shouldRefreshPosition&&this.positionListbox()):shouldRefreshPosition&&this.positionListbox(),(changed.has("activeIndex")||changed.has("options")||changed.has("listboxPositioned"))&&this.revealActiveOption(),(changed.has("touched")||changed.has("required")||changed.has("value"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("open")&&(this.pendingOpenTransitionStart=void 0,this.suppressedOpenLifecycleGeneration=void 0)}settleTransition(event){return this.popupController.settle(event,{waitForPosition:async stale=>{for(;this.open;){const readiness=this.positioningReady,positioned=await readiness;if(stale())return!1;if(positioned)break;if(readiness===this.positioningReady)return this.forceCloseOpenState(),!1}return!0},conceal:()=>{this.listboxHidden=!0,this.listboxRendered=!1}})}emitValueEvents(){const self=this,data=this.selectedData,value=self.value,previousValue=this.previousValue;dispatchNativeInputEvent(this),self.emit("lr-input",{value,previousValue,data}),dispatchNativeEvent(this,"change"),self.emit("lr-change",{value,previousValue,data})}assignValue(next){this.value=next}assignDefaultValue(next){this.defaultValue=next}requestSelection(values,preferred,afterCommit,available=()=>!0){if(this.selectionRequestDispatching||this.effectiveDisabled)return!1;const multiple=this.multiple,document=this.ownerDocument,connected=this.isConnected,open=this.open,slots=this.resolveOccurrenceSlots(values,preferred),data=slots.map(option=>option?.data),value=multiple?[...values]:values[0]??"",previousValue=this.value,self=this;let committed=!1;this.selectionRequestDispatching=!0;try{requestThenCommit({requestDetail:{value,previousValue,data},guard:this.selectionWriteGuard,emitRequest:(detail,init)=>self.emit("lr-change-request",detail,init),commit:()=>{const liveOptions=new Set(this.renderRoot.querySelector("slot:not([name])")?.assignedElements({flatten:!0})??[]);this.effectiveDisabled||this.multiple!==multiple||this.ownerDocument!==document||this.isConnected!==connected||this.open!==open||!available(liveOptions)||slots.some((option,index)=>option&&(!liveOptions.has(option)||option.value!==values[index]||!Object.is(option.data,data[index])))||(this.hasInteracted=!0,this._restoredStateActive=!1,this._valueDirty=!0,this.setSelection(values,preferred),committed=!0,afterCommit())}})}finally{this.selectionRequestDispatching=!1}return committed}selectOption(option){if(this.selectionRequestDispatching||this.effectiveDisabled||!this.isOptionAvailable(option))return;if(this.unknownOptionCache.get(option.value)===option){this.selectUnknownValue(option.value);return}const value=option.value,available=liveOptions=>liveOptions.has(option)&&option.value===value&&this.isOptionAvailable(option);if(this.multiple){const currentSlots=this.resolveOccurrenceSlots(this._selected,this._selectedOptions),selectedIndex=currentSlots.indexOf(option),selected=selectedIndex>=0,occurrences=selected?currentSlots.filter((_,index)=>index!==selectedIndex):[...currentSlots,option],values=selected?this._selected.filter((_,index)=>index!==selectedIndex):[...this._selected,value];this.requestSelection(values,occurrences,()=>{this.emitValueEvents(),this.emit("lr-activate",{value})},available);return}if(!(option!==this._selectedOptions[0]||value!==this._selected[0])){this.hide(),this.emit("lr-activate",{value});return}this.requestSelection([value],[option],()=>{this.hide(),this.emitValueEvents(),this.emit("lr-activate",{value})},available)}removeValueAt(index){return this.effectiveDisabled||index<0||index>=this._selected.length?!1:this.requestSelection(this._selected.filter((_,candidateIndex)=>candidateIndex!==index),this.resolveOccurrenceSlots(this._selected,this._selectedOptions).filter((_,candidateIndex)=>candidateIndex!==index),()=>this.emitValueEvents())}clear(){this.effectiveDisabled||this._selected.length===0||this.requestSelection([],[],()=>{this.emitValueEvents(),this.emit("lr-clear")})}removeTag(value,index,event){event.stopPropagation(),this._selected[index]===value&&this.removeValueAt(index)&&this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.typeBuffer.add(char,this.effectiveLocale);const navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1],currentIndex=navigable.indexOf(currentOption),labels=this.memoOption("typeAheadLabels",[navigable,this.effectiveLocale],()=>{const locale=resolveIntlLocale(this.effectiveLocale);return new Map(navigable.map(option=>[option,option.label.toLocaleLowerCase(locale)]))});let match=null;for(let step=1;step<=navigable.length;step++){const index=(currentIndex+step+navigable.length)%navigable.length,option=navigable[index];if((this.open||!this.multiple||!this.selectedIndex.members.has(option))&&labels.get(option)?.startsWith(this.typeBuffer.text)){match=index;break}}if(match===null)return;const candidate=navigable[match];this.open?this.setActiveIndex(match,navigable):this.selectOption(candidate)}adornmentMarkup(option){return Array.from(option.children).filter(child=>["start","end","prefix","suffix"].includes(child.getAttribute("slot")??"")).map(child=>child.outerHTML).join("")}adornmentsFor(option){const cached=this.adornmentClones.get(option);if(cached)return cached;const cloneSlot=selector=>{const nodes=Array.from(option.querySelectorAll(selector));if(nodes.length!==0)return nodes.map(node=>node.cloneNode(!0))},resolved={markup:this.adornmentMarkup(option),start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}renderRows(options,activeId){const out=[],chosen=new Set(this._selectedOptions);let currentGroup,groupRows=[],groupIndex=0;const flushGroup=()=>{if(groupRows.length!==0){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
2
2
  <div id=${labelId} class="group-label" part="group-label">${currentGroup}</div>
3
3
  ${groupRows}
4
4
  </div>`)}else out.push(...groupRows);groupRows=[]}};return options.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,unknown=this.unknownOptionCache.get(o.value)===o,selected=unknown||chosen.has(o),adornments=this.adornmentsFor(o);groupRows.push(html`<div
@@ -164,4 +164,4 @@ click():void;
164
164
  /** Moves focus to the internal switch control.*/
165
165
  focus(options?:FocusOptions):void;
166
166
  /** Removes focus from the internal switch control.*/
167
- blur():void;private externalDescriptionLease?;private syncExternalDescription;protected updated(changed:PropertyValues):void;private releaseExternalDescription;connectedCallback():void;adoptedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues):void;private setFromUser;private onClick;private onBlur;private onFocus;private onKeyDown;private isDefaultLabelNode;private labelForwardingSlots;private recomputeHasLabelSlot;private handleLabelSlotChange;private onLabelSlotChange;private onSlotChange;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-switch':LyraSwitch;}}export{};
167
+ blur():void;private externalDescriptionLease?;private syncExternalDescription;protected updated(changed:PropertyValues):void;private releaseExternalDescription;connectedCallback():void;adoptedCallback():void;disconnectedCallback():void;protected willUpdate(changed:PropertyValues):void;private setFromUser;private onClick;private onBlur;private onFocus;private onKeyDown;private recomputeHasLabelSlot;private handleLabelSlotChange;private onLabelSlotChange;private onSlotChange;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-switch':LyraSwitch;}}export{};
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_switchRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();class LyraSwitchBase extends LyraElement{}class LyraSwitch extends CheckedFormAssociated(LyraSwitchBase){constructor(){super(...arguments),this.size="m",this.hint="",this.helpText="",this.withHint=!1,this.errorText="",this.hasLabelSlot=!1,this.slotPresence=new SlotPresenceController(this),this.labelTextObserver=new AccessibleTextController(this,[""],()=>this.recomputeHasLabelSlot(),["slot"]),this.toggleGuard=new VetoWriteGuard,this.onClick=event=>{const owner=this[VALIDITY_ANCHOR]();for(const target of event.composedPath()){if(target===event.currentTarget)break;if(target&&typeof target=="object"&&target.nodeType===1&&target!==owner&&isActionableElement(target))return}this.setFromUser(!this.checked)},this.onBlur=event=>{this.liveDisabled||this.setInteracted(!0),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onKeyDown=e=>{if(!this.liveDisabled&&!e.repeat){if(e.key===" "||e.key==="Spacebar"){e.preventDefault(),this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}}},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event)}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,switchRequired:LYRA_DEFAULT_switchRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={size:{reflect:!0}}}get hasHintSlot(){return this.slotPresence.has("hint")}get hasHelpTextSlot(){return this.slotPresence.has("help-text")}get hasErrorSlot(){return this.slotPresence.has("error")}checkedWritten(previous){markVetoGuardWrite(this.toggleGuard)}requiredMessage(){return this.localize("switchRequired")}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector(".switch-owner")??null}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.liveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}updated(changed){super.updated(changed),this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.hasUpdated?this.recomputeHasLabelSlot():this.seedFirstRenderState(()=>this.recomputeHasLabelSlot())}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed)}setFromUser(next){this.liveDisabled||this.checked!==next&&requestThenCommit({requestDetail:{checked:next,value:this.value},emitRequest:(detail,init)=>this.emit("lr-switch-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{this.setInteracted(!0),this.checked=next,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:this.checked,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:this.checked,value:this.value})}})}isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}recomputeHasLabelSlot(){const renderRoot=this.renderRoot,childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(childNodes).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}handleLabelSlotChange(event){const target=event.target;if(!(target?.nodeType!==1||target.localName!=="slot")){if(target.getRootNode()===this.renderRoot){if((target.getAttribute("name")??"")!=="")return}else if(!this.labelForwardingSlots().includes(target))return;this.labelTextObserver.bind(),this.recomputeHasLabelSlot()}}render(){const hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||(this.hint??"").length>0||(this.helpText??"").length>0,hasError=this.hasErrorSlot||(this.errorText??"").length>0,describedBy=[hasError?"switch-error":"",hasHint?"switch-hint":""].filter(Boolean).join(" "),invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`
1
+ import{__decorate}from"tslib";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";import{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AccessibleTextController}from"../../../internal/accessible-text-controller.js";import{defaultLabelForwardingSlots,isDefaultLabelNode}from"../../../internal/default-label-forwarding.js";import{VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{hasRealContent}from"../../../internal/a11y.js";import{isActionableElement}from"../../../internal/focus-navigation.js";import{CheckedFormAssociated}from"../../../internal/form-associated.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_switchRequired}from"../../../internal/default-strings/forms.generated.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings/shared.generated.js";installFormControlLabelSupport();class LyraSwitchBase extends LyraElement{}class LyraSwitch extends CheckedFormAssociated(LyraSwitchBase){constructor(){super(...arguments),this.size="m",this.hint="",this.helpText="",this.withHint=!1,this.errorText="",this.hasLabelSlot=!1,this.slotPresence=new SlotPresenceController(this),this.labelTextObserver=new AccessibleTextController(this,[""],()=>this.recomputeHasLabelSlot(),["slot"]),this.toggleGuard=new VetoWriteGuard,this.onClick=event=>{const owner=this[VALIDITY_ANCHOR]();for(const target of event.composedPath()){if(target===event.currentTarget)break;if(target&&typeof target=="object"&&target.nodeType===1&&target!==owner&&isActionableElement(target))return}this.setFromUser(!this.checked)},this.onBlur=event=>{this.liveDisabled||this.setInteracted(!0),relayNativeEvent(this,event)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onKeyDown=e=>{if(!this.liveDisabled&&!e.repeat){if(e.key===" "||e.key==="Spacebar"){e.preventDefault(),this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}}},this.onLabelSlotChange=event=>this.handleLabelSlotChange(event),this.onSlotChange=event=>this.handleLabelSlotChange(event)}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,switchRequired:LYRA_DEFAULT_switchRequired}}static get validators(){return[currentValidityValidator("required","disabled","checked","value")]}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={size:{reflect:!0}}}get hasHintSlot(){return this.slotPresence.has("hint")}get hasHelpTextSlot(){return this.slotPresence.has("help-text")}get hasErrorSlot(){return this.slotPresence.has("error")}checkedWritten(previous){markVetoGuardWrite(this.toggleGuard)}requiredMessage(){return this.localize("switchRequired")}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector(".switch-owner")??null}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}click(){this.liveDisabled||this[VALIDITY_ANCHOR]()?.click()}focus(options){this.liveDisabled||this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}syncExternalDescription(){if(!this.isConnected)return;const target=this[VALIDITY_ANCHOR]();target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}updated(changed){super.updated(changed),this.syncExternalDescription()}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription(),this.addEventListener("slotchange",this.onLabelSlotChange),this.hasUpdated?this.recomputeHasLabelSlot():this.seedFirstRenderState(()=>this.recomputeHasLabelSlot())}adoptedCallback(){super.adoptedCallback(),this.labelTextObserver.adopted(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}disconnectedCallback(){this.releaseExternalDescription(),this.removeEventListener("slotchange",this.onLabelSlotChange),super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed)}setFromUser(next){this.liveDisabled||this.checked!==next&&requestThenCommit({requestDetail:{checked:next,value:this.value},emitRequest:(detail,init)=>this.emit("lr-switch-toggle-request",detail,init),guard:this.toggleGuard,commit:()=>{this.setInteracted(!0),this.checked=next,dispatchNativeEvent(this,"input"),this.emit("lr-input",{checked:this.checked,value:this.value}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{checked:this.checked,value:this.value})}})}recomputeHasLabelSlot(){const renderRoot=this.renderRoot,childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])"),nodes=slot?slot.assignedNodes({flatten:!0}):Array.from(childNodes).filter(node=>isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:!0}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}handleLabelSlotChange(event){const target=event.target;if(!(target?.nodeType!==1||target.localName!=="slot")){if(target.getRootNode()===this.renderRoot){if((target.getAttribute("name")??"")!=="")return}else if(!defaultLabelForwardingSlots(this).includes(target))return;this.labelTextObserver.bind(),this.recomputeHasLabelSlot()}}render(){const hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||(this.hint??"").length>0||(this.helpText??"").length>0,hasError=this.hasErrorSlot||(this.errorText??"").length>0,describedBy=[hasError?"switch-error":"",hasHint?"switch-hint":""].filter(Boolean).join(" "),invalid=hasError||this.hasInteracted&&!this.internals.validity.valid;return html`
2
2
  <div part="form-control">
3
3
  <span class="switch-layout" part="row" @click=${this.onClick}>
4
4
  <span
@@ -1 +1 @@
1
- import{iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{formControlFocusHalo,formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: block; min-inline-size: 0; max-inline-size: 100%; --_lr-file-input-font-size: var(--lr-form-control-font-size); --_lr-file-input-dropzone-font-size: var(--lr-font-size-md-sm); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-xl); --_lr-file-input-dropzone-padding: var(--lr-space-l); --_lr-file-input-detail-font-size: var(--lr-font-size-sm); --_lr-form-control-focus-shadow: var(--lr-form-control-focus-shadow, none); } :host([size="2xs"]), :host([size="xs"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-xs); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-md-sm); --_lr-file-input-dropzone-padding: var(--lr-space-s); --_lr-file-input-detail-font-size: var(--lr-font-size-2xs); } :host([size="s"]), :host([size="small"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-sm); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-lg); --_lr-file-input-dropzone-padding: var(--lr-space-m); --_lr-file-input-detail-font-size: var(--lr-font-size-xs); } :host([size="l"]), :host([size="large"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-lg); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-2xl); --_lr-file-input-dropzone-padding: var(--lr-space-2xl); --_lr-file-input-detail-font-size: var(--lr-font-size-md-sm); } :host([size="xl"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-xl); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-3xl); --_lr-file-input-dropzone-padding: var(--lr-space-2xl); --_lr-file-input-detail-font-size: var(--lr-font-size-m); } [part="form-control"] { min-inline-size: 0; max-inline-size: 100%; block-size: 100%; } [part~="form-control-label"] { display: block; min-inline-size: 0; margin-block-end: var(--lr-space-xs); font-size: var(--lr-file-input-font-size, var(--_lr-file-input-font-size)); font-weight: var(--lr-font-weight-semibold); overflow-wrap: anywhere; } [part~="form-control-label"][hidden], [part="hint"][hidden], [part="error"][hidden] { display: none; } ${formControlRequiredMarker} .dropzone { position: relative; display: grid; min-inline-size: 0; block-size: 100%; } [part~="file-input"] { grid-area: 1 / 1; inline-size: 100%; block-size: 100%; ${iconHitTarget} box-sizing: border-box; font: inherit; cursor: pointer; appearance: none; padding: var( --lr-file-input-dropzone-padding, var(--_lr-file-input-dropzone-padding) ); border: var(--lr-border-width-medium) dashed var(--lr-file-input-dropzone-border-color, var(--lr-color-border)); border-radius: var(--lr-file-input-radius, var(--lr-radius)); background: var(--lr-file-input-dropzone-fill, var(--lr-color-surface)); color: var(--lr-color-text-quiet); font-size: var( --lr-file-input-dropzone-font-size, var(--_lr-file-input-dropzone-font-size) ); transition: border-color var(--lr-transition-fast), background-color var(--lr-transition-fast); } .dropzone-content { grid-area: 1 / 1; z-index: var(--lr-layer-content); min-inline-size: 0; max-inline-size: 100%; box-sizing: border-box; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--lr-file-input-gap, var(--lr-space-xs)); padding: var( --lr-file-input-dropzone-padding, var(--_lr-file-input-dropzone-padding) ); color: var(--lr-color-text-quiet); text-align: center; font-size: var( --lr-file-input-dropzone-font-size, var(--_lr-file-input-dropzone-font-size) ); overflow-wrap: anywhere; pointer-events: none; } [part="dropzone-icon"] { display: inline-flex; align-items: center; justify-content: center; font-size: var( --lr-file-input-dropzone-icon-size, var(--_lr-file-input-dropzone-icon-size) ); } [part="dropzone-text"] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } ::slotted(*) { max-inline-size: 100%; min-inline-size: 0; pointer-events: auto; } :host(:is([size='s'], [size='small'])) [part~='file-input'], :host(:is([size='s'], [size='small'])) .dropzone-content { padding: var(--lr-file-input-compact-padding, var(--lr-file-input-dropzone-padding, var(--_lr-file-input-dropzone-padding))); font-size: var(--lr-file-input-compact-font-size, var(--lr-file-input-dropzone-font-size, var(--_lr-file-input-dropzone-font-size))); } :host(:is([size='s'], [size='small'])) .dropzone-content { gap: var(--lr-file-input-compact-gap, var(--lr-file-input-gap, var(--lr-space-xs))); } [part~="file-input"][data-drag-state="accept"] { border-color: var( --lr-file-input-accept-border-color, var(--lr-color-success) ); background: var( --lr-file-input-accept-bg, color-mix(in srgb, var(--lr-color-success) 8%, transparent) ); } [part~="file-input"][data-drag-state="reject"] { border-color: var( --lr-file-input-reject-border-color, var(--lr-color-danger) ); background: var( --lr-file-input-reject-bg, color-mix(in srgb, var(--lr-color-danger) 8%, transparent) ); } @media (forced-colors: active) { [part~="file-input"][data-drag-state="accept"] { border-color: Highlight; border-style: double; outline: var(--lr-border-width-thin) solid Highlight; outline-offset: calc(-1 * var(--lr-border-width-medium)); } [part~="file-input"][data-drag-state="reject"] { border-color: CanvasText; border-style: dotted; outline: var(--lr-border-width-medium) double CanvasText; outline-offset: calc(-1 * var(--lr-border-width-medium)); } } :host(:not(:disabled)) [part~="file-input"]:hover { border-color: var(--lr-file-input-dropzone-hover-border-color, var(--lr-color-brand)); } :host(:not(:disabled)) .dropzone:hover [part~="file-input"] { border-color: var(--lr-file-input-dropzone-hover-border-color, var(--lr-color-brand)); } :host(:not(:disabled)) [part~="file-input"]:active { border-color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } :host(:not(:disabled)) .dropzone:active [part~="file-input"] { border-color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part~="file-input"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part~="file-input"]:focus { ${formControlFocusHalo} } :host(:disabled) [part~="file-input"] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="rejection"] { min-inline-size: 0; max-inline-size: 100%; margin-block: var(--lr-space-2xs) 0; color: var(--lr-color-danger); font-size: var(--lr-font-size-sm); text-align: start; overflow-wrap: anywhere; } [part="rejection"] ul { margin: 0; padding-inline-start: var(--lr-space-m); } [part="file-list"] { display: grid; gap: var(--lr-space-xs); margin-block-start: var(--lr-space-xs); } [part="file"] { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: var(--lr-space-s); min-inline-size: 0; padding: var(--lr-space-xs) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); border-radius: var(--lr-radius); background: var(--lr-color-surface-raised); } [part="file-thumbnail"] { display: inline-flex; align-items: center; justify-content: center; inline-size: var(--lr-icon-button-size); block-size: var(--lr-icon-button-size); overflow: hidden; border-radius: var(--lr-radius-xs); color: var(--lr-color-text-quiet); } [part="file-image"] { inline-size: 100%; block-size: 100%; object-fit: cover; } [part="file-icon"] { display: inline-flex; font-size: var(--lr-font-size-xl); } [part="file-details"] { display: flex; flex-direction: column; min-inline-size: 0; } [part="file-name"] { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--lr-color-text); font-size: var(--lr-file-input-font-size, var(--_lr-file-input-font-size)); } [part="file-size"] { color: var(--lr-color-text-quiet); font-size: var( --lr-file-input-detail-font-size, var(--_lr-file-input-detail-font-size) ); } [part="remove-button"] { display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} padding: 0; border: none; border-radius: var(--lr-radius); background: transparent; color: var(--lr-color-text-quiet); font: inherit; cursor: pointer; transition: background-color var(--lr-transition-fast), color var(--lr-transition-fast); } [part="remove-button"]:hover:where(:not(:disabled)) { background: var(--lr-color-brand-quiet); color: var(--lr-color-text); } [part="remove-button"]:active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="remove-button"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part="remove-button"]:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="hint"] { min-inline-size: 0; margin-block-start: var(--lr-space-xs); color: var(--lr-color-text-quiet); font-size: var( --lr-file-input-detail-font-size, var(--_lr-file-input-detail-font-size) ); overflow-wrap: anywhere; } [part="error"] { min-inline-size: 0; margin-block-start: var(--lr-space-xs); color: var(--lr-color-danger); font-size: var( --lr-file-input-detail-font-size, var(--_lr-file-input-detail-font-size) ); overflow-wrap: anywhere; } `;export{styles};
1
+ import{iconHitTarget}from"../../../internal/interactive-control.styles.js";import{css}from"lit";import{formControlFocusHalo,formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: flex; flex-direction: column; min-inline-size: 0; max-inline-size: 100%; --_lr-file-input-font-size: var(--lr-form-control-font-size); --_lr-file-input-dropzone-font-size: var(--lr-font-size-md-sm); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-xl); --_lr-file-input-dropzone-padding: var(--lr-space-l); --_lr-file-input-detail-font-size: var(--lr-font-size-sm); --_lr-form-control-focus-shadow: var(--lr-form-control-focus-shadow, none); } :host([size="2xs"]), :host([size="xs"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-xs); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-md-sm); --_lr-file-input-dropzone-padding: var(--lr-space-s); --_lr-file-input-detail-font-size: var(--lr-font-size-2xs); } :host([size="s"]), :host([size="small"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-sm); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-lg); --_lr-file-input-dropzone-padding: var(--lr-space-m); --_lr-file-input-detail-font-size: var(--lr-font-size-xs); } :host([size="l"]), :host([size="large"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-lg); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-2xl); --_lr-file-input-dropzone-padding: var(--lr-space-2xl); --_lr-file-input-detail-font-size: var(--lr-font-size-md-sm); } :host([size="xl"]) { --_lr-file-input-dropzone-font-size: var(--lr-font-size-xl); --_lr-file-input-dropzone-icon-size: var(--lr-font-size-3xl); --_lr-file-input-dropzone-padding: var(--lr-space-2xl); --_lr-file-input-detail-font-size: var(--lr-font-size-m); } [part="form-control"] { display: flex; flex-direction: column; flex: 1; min-inline-size: 0; max-inline-size: 100%; } [part~="form-control-label"] { display: block; min-inline-size: 0; margin-block-end: var(--lr-space-xs); font-size: var(--lr-file-input-font-size, var(--_lr-file-input-font-size)); font-weight: var(--lr-font-weight-semibold); overflow-wrap: anywhere; } [part~="form-control-label"][hidden], [part="hint"][hidden], [part="error"][hidden] { display: none; } ${formControlRequiredMarker} .dropzone { position: relative; display: grid; flex: 1; min-inline-size: 0; } [part~="file-input"] { grid-area: 1 / 1; inline-size: 100%; ${iconHitTarget} box-sizing: border-box; font: inherit; cursor: pointer; appearance: none; padding: var( --lr-file-input-dropzone-padding, var(--_lr-file-input-dropzone-padding) ); border: var(--lr-border-width-medium) dashed var(--lr-file-input-dropzone-border-color, var(--lr-color-border)); border-radius: var(--lr-file-input-radius, var(--lr-radius)); background: var(--lr-file-input-dropzone-fill, var(--lr-color-surface)); color: var(--lr-color-text-quiet); font-size: var( --lr-file-input-dropzone-font-size, var(--_lr-file-input-dropzone-font-size) ); transition: border-color var(--lr-transition-fast), background-color var(--lr-transition-fast); } .dropzone-content { grid-area: 1 / 1; z-index: var(--lr-layer-content); min-inline-size: 0; max-inline-size: 100%; box-sizing: border-box; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: var(--lr-file-input-gap, var(--lr-space-xs)); padding: var( --lr-file-input-dropzone-padding, var(--_lr-file-input-dropzone-padding) ); color: var(--lr-color-text-quiet); text-align: center; font-size: var( --lr-file-input-dropzone-font-size, var(--_lr-file-input-dropzone-font-size) ); overflow-wrap: anywhere; pointer-events: none; } [part="dropzone-icon"] { display: inline-flex; align-items: center; justify-content: center; font-size: var( --lr-file-input-dropzone-icon-size, var(--_lr-file-input-dropzone-icon-size) ); } [part="dropzone-text"] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } ::slotted(*) { max-inline-size: 100%; min-inline-size: 0; pointer-events: auto; } :host(:is([size='s'], [size='small'])) [part~='file-input'], :host(:is([size='s'], [size='small'])) .dropzone-content { padding: var(--lr-file-input-compact-padding, var(--lr-file-input-dropzone-padding, var(--_lr-file-input-dropzone-padding))); font-size: var(--lr-file-input-compact-font-size, var(--lr-file-input-dropzone-font-size, var(--_lr-file-input-dropzone-font-size))); } :host(:is([size='s'], [size='small'])) .dropzone-content { gap: var(--lr-file-input-compact-gap, var(--lr-file-input-gap, var(--lr-space-xs))); } [part~="file-input"][data-drag-state="accept"] { border-color: var( --lr-file-input-accept-border-color, var(--lr-color-success) ); background: var( --lr-file-input-accept-bg, color-mix(in srgb, var(--lr-color-success) 8%, transparent) ); } [part~="file-input"][data-drag-state="reject"] { border-color: var( --lr-file-input-reject-border-color, var(--lr-color-danger) ); background: var( --lr-file-input-reject-bg, color-mix(in srgb, var(--lr-color-danger) 8%, transparent) ); } @media (forced-colors: active) { [part~="file-input"][data-drag-state="accept"] { border-color: Highlight; border-style: double; outline: var(--lr-border-width-thin) solid Highlight; outline-offset: calc(-1 * var(--lr-border-width-medium)); } [part~="file-input"][data-drag-state="reject"] { border-color: CanvasText; border-style: dotted; outline: var(--lr-border-width-medium) double CanvasText; outline-offset: calc(-1 * var(--lr-border-width-medium)); } } :host(:not(:disabled)) [part~="file-input"]:hover { border-color: var(--lr-file-input-dropzone-hover-border-color, var(--lr-color-brand)); } :host(:not(:disabled)) .dropzone:hover [part~="file-input"] { border-color: var(--lr-file-input-dropzone-hover-border-color, var(--lr-color-brand)); } :host(:not(:disabled)) [part~="file-input"]:active { border-color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } :host(:not(:disabled)) .dropzone:active [part~="file-input"] { border-color: var(--lr-color-brand); background: color-mix( in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part~="file-input"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part~="file-input"]:focus { ${formControlFocusHalo} } :host(:disabled) [part~="file-input"] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="rejection"] { min-inline-size: 0; max-inline-size: 100%; margin-block: var(--lr-space-2xs) 0; color: var(--lr-color-danger); font-size: var(--lr-font-size-sm); text-align: start; overflow-wrap: anywhere; } [part="rejection"] ul { margin: 0; padding-inline-start: var(--lr-space-m); } [part="file-list"] { display: grid; gap: var(--lr-space-xs); margin-block-start: var(--lr-space-xs); } [part="file"] { display: grid; grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; gap: var(--lr-space-s); min-inline-size: 0; padding: var(--lr-space-xs) var(--lr-space-s); border: var(--lr-border-width-thin) solid var(--lr-color-border-subtle); border-radius: var(--lr-radius); background: var(--lr-color-surface-raised); } [part="file-thumbnail"] { display: inline-flex; align-items: center; justify-content: center; inline-size: var(--lr-icon-button-size); block-size: var(--lr-icon-button-size); overflow: hidden; border-radius: var(--lr-radius-xs); color: var(--lr-color-text-quiet); } [part="file-image"] { inline-size: 100%; block-size: 100%; object-fit: cover; } [part="file-icon"] { display: inline-flex; font-size: var(--lr-font-size-xl); } [part="file-details"] { display: flex; flex-direction: column; min-inline-size: 0; } [part="file-name"] { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--lr-color-text); font-size: var(--lr-file-input-font-size, var(--_lr-file-input-font-size)); } [part="file-size"] { color: var(--lr-color-text-quiet); font-size: var( --lr-file-input-detail-font-size, var(--_lr-file-input-detail-font-size) ); } [part="remove-button"] { display: inline-flex; align-items: center; justify-content: center; ${iconHitTarget} padding: 0; border: none; border-radius: var(--lr-radius); background: transparent; color: var(--lr-color-text-quiet); font: inherit; cursor: pointer; transition: background-color var(--lr-transition-fast), color var(--lr-transition-fast); } [part="remove-button"]:hover:where(:not(:disabled)) { background: var(--lr-color-brand-quiet); color: var(--lr-color-text); } [part="remove-button"]:active:where(:not(:disabled)) { background: color-mix( in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active) ); } [part="remove-button"]:focus-visible { outline: var(--lr-focus-ring); outline-offset: var(--lr-focus-ring-offset); } [part="remove-button"]:disabled { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part="hint"] { min-inline-size: 0; margin-block-start: var(--lr-space-xs); color: var(--lr-color-text-quiet); font-size: var( --lr-file-input-detail-font-size, var(--_lr-file-input-detail-font-size) ); overflow-wrap: anywhere; } [part="error"] { min-inline-size: 0; margin-block-start: var(--lr-space-xs); color: var(--lr-color-danger); font-size: var( --lr-file-input-detail-font-size, var(--_lr-file-input-detail-font-size) ); overflow-wrap: anywhere; } `;export{styles};
@@ -1 +1 @@
1
- import{deferredPlaceReady as place}from"../../../internal/anchored-overlay-runtime.js";import{getInheritedPropertyDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{applyComposedFocusRepair,captureComposedFocusRepair,focusFirstAvailable}from"../../../internal/focus-navigation.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{finiteRange}from"../../../internal/numbers.js";import{reserveOverlayOrder}from"../../../internal/overlay-order.js";import{collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement,observeOverlayStack}from"../../../internal/overlay-stack.js";import{virtualAnchorFromRect}from"../../../internal/positioner-geometry.js";import{admitMapAnchorOptions}from"./map-anchor-options.js";import{MAP_ANCHOR_SEAM}from"./map-anchor-seam.js";import{mapOwnValue,renderedSizeKey}from"./map-readers.js";const escapeOwners=new Set,rankings=new WeakMap,RANK="--_lr-map-anchor-rank",LIMIT=16;let raises=0,insertions=0;class MapAnchorController{constructor(host){this.host=host,this.epoch=0,this.placed=!1,this.closingState=!1,this.observedBoundaries=[],this.raisedAt=0,this.order=0,this.fresh=!0,this.listening=!1}get closing(){return this.closingState}view(){return this.host.element.ownerDocument?.defaultView??null}stop(){this.epoch+=1,this.placed=!1,this.placedCoordinates=void 0;const cleanup=this.cleanup;this.cleanup=void 0,cleanup?.(),this.overlay?.suspend()}schedule(){if(this.stop(),this.frame!==void 0)return;const view=this.view();if(!view||typeof view.requestAnimationFrame!="function"){this.sync();return}this.frame=view.requestAnimationFrame(()=>{this.frame=void 0,this.sync()})}cancelFrame(){this.frame!==void 0&&(this.view()?.cancelAnimationFrame?.(this.frame),this.frame=void 0)}focus(){const wrapper=this.host.wrapper();if(!wrapper||!this.isOpen())return!1;const epoch=this.epoch,targets=collectFocusableElements(wrapper);return epoch!==this.epoch||!this.isOpen()||targets.length===0||(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.isOpen())?!1:focusFirstAvailable(targets)&&epoch===this.epoch&&this.isOpen()}isOpen(){const host=this.host,wrapper=host.wrapper();return host.element.isConnected&&!!host.map()&&host.styleLoaded()&&this.placed&&!host.pending()&&this.placedCoordinates===host.request()&&!!wrapper&&!wrapper.hidden&&!host.interactionBlocked()&&this.hasContent()}captureReturnTarget(wrapper){const active=deepActiveElement(this.host.element.ownerDocument);if(!(!active||composedContains(wrapper,active)))try{const descriptor=getInheritedPropertyDescriptor(active,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=active,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}close(reason){const host=this.host,wrapper=host.wrapper();if(!wrapper||!this.isOpen())return!1;const requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=captureComposedFocusRepair(wrapper,this.returnTarget??null);if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request()||!this.isOpen())return!1;this.closingState=!0;try{host.retire()}finally{this.closingState=!1}this.hide(!1,!0);const epoch=this.epoch;return host.emitClose(Object.freeze({reason})),repair&&epoch===this.epoch&&host.request()===null&&applyComposedFocusRepair(repair),!0}hide(restore=!0,retire=!1){const host=this.host,wrapper=host.wrapper(),requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=restore&&wrapper?this.repairFrom(wrapper):null;if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request())return;this.stop(),wrapper&&(wrapper.hidden=!0),rankings.get(host.element)?.delete(this)&&(wrapper?.style.removeProperty(RANK),MapAnchorController.rank(host.element)),host.placed?.(!1);const epoch=this.epoch;if(retire){const overlay=this.overlay;this.overlay=void 0,this.returnTarget=void 0,this.fresh=!0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1})}else this.overlay?.suspend();repair&&epoch===this.epoch&&!this.placed&&this.repair(repair)}capture(){const wrapper=this.host.wrapper();return wrapper?this.repairFrom(wrapper):null}repair(snapshot){if(!snapshot)return;const repair=snapshot;applyComposedFocusRepair(repair,[repair.candidate,this.host.fallback?.()])}repairFrom(wrapper){const host=this.host,document=wrapper.ownerDocument,lost=host.lost?.(),active=deepActiveElement(document),candidate=()=>this.returnTarget??host.fallback?.()??null,target=lost&&(!active||active===document.body||active===document.documentElement)?candidate():null;return captureComposedFocusRepair(wrapper,candidate)??(lost&&target?{activeElement:lost,candidate:target,document,owner:wrapper}:null)}raise(escape=!0){!rankings.get(this.host.element)?.has(this)||!this.ranked()||(this.raisedAt=++raises,MapAnchorController.rank(this.host.element),escape&&this.reRegister())}ranked(){return!!this.host.child||[...rankings.get(this.host.element)??[]].some(member=>member.host.child)}enter(wrapper){const host=this.host,members=rankings.get(host.element)??new Set;rankings.set(host.element,members);const joined=!members.has(this);if(members.add(this),host.placed?.(!0),!host.child&&!this.listening&&(this.listening=!0,wrapper.addEventListener("pointerdown",()=>{this.raise()}),wrapper.addEventListener("focusout",()=>{queueMicrotask(()=>{this.focusOut()})})),!this.fresh){joined&&MapAnchorController.rank(host.element);return}if(this.fresh=!1,this.raise(!1),!(!host.autofocus?.()||composedContains(wrapper,deepActiveElement(wrapper.ownerDocument)))){for(const target of collectAutofocusElements(wrapper))if(focusFirstAvailable(target)||focusFirstAvailable(collectFocusableElements(target)))break}}static rank(map){const members=[...rankings.get(map)??[]],ranked=members.some(member=>member.host.child),active=deepActiveElement(map.ownerDocument),keys=new Map;for(const member of members){const wrapper=member.host.wrapper();keys.set(member,wrapper&&composedContains(wrapper,active)?raises+1:member.raisedAt)}return members.sort((a,b)=>keys.get(a)-keys.get(b)),members.forEach((member,index)=>{const style=member.host.wrapper()?.style;ranked?style?.setProperty(RANK,String(index)):style?.removeProperty(RANK)}),members}focusOut(){if(!this.ranked())return;[...MapAnchorController.rank(this.host.element)].reverse().find(member=>member.host.closable()&&member.isOpen())?.reRegister()}reRegister(){const host=this.host,overlay=this.overlay,wrapper=host.wrapper();if(!overlay||overlay.isTopmost()||!wrapper)return;let entries=[];observeOverlayStack(host.element.ownerDocument,snapshot=>{entries=snapshot.entries})();const index=entries.findIndex(entry=>entry.host===host.overlayHost),anchored=other=>[...escapeOwners].some(owner=>{const panel=owner.host.wrapper();return owner!==this&&(owner.host.overlayHost===other||!!panel&&composedContains(panel,other))});index<0||entries.slice(index+1).some(entry=>composedContains(wrapper,entry.host)||!anchored(entry.host))||(this.overlay=this.activate())}activate(below=!1){const host=this.host,document=host.element.ownerDocument,focused=below?[...escapeOwners].find(owner=>{const wrapper=owner.host.wrapper();return owner!==this&&owner.ranked()&&!!wrapper&&composedContains(wrapper,deepActiveElement(document))}):void 0,order=this.order=focused?focused.order-1/(++insertions+1):reserveOverlayOrder(document)(document);return activateNonmodalOverlay({host:host.overlayHost,panel:()=>host.wrapper()??null,onEscape:()=>{host.escape?host.escape():this.close("escape")},beforeInitialFocus:()=>!1,restoreFocusTo:()=>this.returnTarget??null,orderReservation:destination=>destination===document?order:void 0})}dispose(){this.cancelFrame(),this.hide(!0,!0),this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[]}syncOverlay(wrapper){const host=this.host,element=host.element;if(!host.closable()){const overlay=this.overlay;this.overlay=void 0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1});return}if(this.overlay)this.overlay.resume();else{const epoch=this.epoch;if(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.placed||!element.isConnected)return;const overlay=this.activate(this.ranked());epoch===this.epoch&&this.placed&&element.isConnected&&host.closable()&&!this.overlay?(this.overlay=overlay,escapeOwners.add(this)):overlay.deactivate({restoreFocus:!1})}}hasContent(){return this.host.content()?.assignedNodes({flatten:!0}).some(node=>node.nodeType===1||node.nodeType===3&&!!node.textContent?.trim())??!1}observeBoundaries(boundaries){if(boundaries.length===this.observedBoundaries.length&&boundaries.every((value,index)=>value===this.observedBoundaries[index]))return;this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[...boundaries];const ResizeObserverClass=this.view()?.ResizeObserver;if(!ResizeObserverClass||boundaries.length===0)return;let sizes=boundaries.map(renderedSizeKey);this.boundaryObserver=new ResizeObserverClass(()=>{const next=boundaries.map(renderedSizeKey);next.every((value,index)=>value===sizes[index])||(sizes=next,this.host.element.isConnected&&this.schedule())});for(const boundary of boundaries)this.boundaryObserver.observe(boundary)}focusIn(event){const wrapper=this.host.wrapper(),previous=event.relatedTarget,view=this.view();if(wrapper&&view&&!(previous instanceof view.Element&&composedContains(wrapper,previous))&&this.raise(),!(!wrapper||!view||!(previous instanceof view.Element)||previous.ownerDocument!==this.host.element.ownerDocument||composedContains(wrapper,previous)))try{const descriptor=getInheritedPropertyDescriptor(previous,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=previous,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}point(){const host=this.host,position=host.request(),container=host.container();if(!container||!Array.isArray(position))return;const lng=mapOwnValue(position,"0"),lat=mapOwnValue(position,"1");if(typeof lng!="number"||!Number.isFinite(lng)||typeof lat!="number"||!Number.isFinite(lat)||Math.abs(lat)>90)return;const point=host.element.project([lng,lat]);if(!point)return;const[x,y]=point;return x>=0&&y>=0&&x<=container.clientWidth&&y<=container.clientHeight?point:void 0}sync(){const host=this.host,element=host.element;if(host.updateActive()){const[generation,connection]=host.generations(),map2=host.map();host.afterUpdate(()=>{const[style,current2]=host.generations();element.isConnected&&current2===connection&&style===generation&&host.map()===map2&&this.sync()},`${host.key}-${connection}-${generation}`);return}const wrapper=host.wrapper(),container=host.container(),fence=host.fence();if(!wrapper||!container||!fence||!element.isConnected||!host.map()||!host.styleLoaded()||host.interactionBlocked()||!this.hasContent()){this.hide();return}this.stop();const epoch=this.epoch,map=host.map(),coordinates=host.request(),boundary=host.boundary(),safeArea=host.safeArea(),direction=host.direction(),current=()=>element.isConnected&&host.map()===map&&host.styleLoaded()&&epoch===this.epoch&&host.request()===coordinates&&host.boundary()===boundary&&host.safeArea()===safeArea&&host.direction()===direction&&!host.interactionBlocked();try{const admitted=admitMapAnchorOptions({boundary,safeArea},element.ownerDocument,{current});if(!admitted.ok||!current()){epoch===this.epoch&&this.hide();return}this.observeBoundaries(admitted.boundaries);const point=this.point();if(!current())return;const width=finiteRange(container.clientWidth,0,0),height=finiteRange(container.clientHeight,0,0),edges=admitted.safeArea,start=Math.min(width,edges.inlineStart),end=Math.min(width,edges.inlineEnd),top=Math.min(height,edges.blockStart),bottom=Math.min(height,edges.blockEnd);if(!point||start+end>=width||top+bottom>=height){this.hide();return}fence.style.insetInlineStart=`${start}px`,fence.style.insetInlineEnd=`${end}px`,fence.style.insetBlockStart=`${top}px`,fence.style.insetBlockEnd=`${bottom}px`,host.child&&(fence.style.direction=direction);const clip=fence.getBoundingClientRect();let left=clip.left,right=clip.right,upper=clip.top,lower=clip.bottom;for(const clipping of admitted.boundaries){const bounds=clipping.getBoundingClientRect();if(!current())return;left=Math.max(left,bounds.left),right=Math.min(right,bounds.right),upper=Math.max(upper,bounds.top),lower=Math.min(lower,bounds.bottom)}if(!(right-left>16&&lower-upper>16)){this.hide();return}wrapper.hidden=!1;const rect=container.getBoundingClientRect();if(!current())return;const placement=place(virtualAnchorFromRect({x:rect.left+point[0],y:rect.top+point[1],contextElement:container}),wrapper,{placement:"top",strategy:"absolute",offset:12,boundary:[fence,...admitted.boundaries],padding:8,shiftCrossAxis:!0,onPlaced:()=>{if(!current()||!this.hasContent())return;const first=!this.placed;first&&this.captureReturnTarget(wrapper),current()&&(this.placed=!0,this.placedCoordinates=coordinates,this.syncOverlay(wrapper),first&&current()&&this.enter(wrapper))}});if(!current()){placement();return}this.cleanup=placement,placement.ready.then(ready=>{!ready&&current()&&this.hide()})}catch{current()&&this.hide()}}}const CHILD_EVENTS=["focusin","focusout","pointerdown"];class MapAnchorChildren{constructor(host,anchors){this.host=host,this.entries=new Map,this.serial=0;for(const anchor of anchors)this.attach(anchor)}run(anchor,operation,value){const entry=this.entries.get(anchor);switch(operation){case"attach":this.sync(this.attach(anchor));return;case"detach":if(entry){for(const type of CHILD_EVENTS)anchor.removeEventListener(type,entry.listener);this.entries.delete(anchor),entry.controller.dispose(),this.sync(entry)}return;case"capture":return entry?.controller.capture();case"retire":entry&&(entry.open=!1,entry.focused=void 0,entry.controller.hide(!1,!0));return;case"repair":if(value){const repair=value;applyComposedFocusRepair(repair,[repair.candidate,this.host.canvas()])}return;case"focus":return entry?.controller.focus()??!1;default:entry&&this.sync(entry);return}}sync(only){this.each(only,controller=>{controller.sync()})}schedule(){this.each(void 0,controller=>{controller.schedule()})}stop(){for(const{controller}of this.entries.values())controller.stop()}hide(){for(const{controller,open}of this.entries.values())open&&controller.hide()}dispose(){for(const{controller}of this.entries.values())controller.dispose()}each(only,place2){const changed=this.admit();for(const[anchor,entry]of this.entries)only&&entry!==only&&!changed.has(entry)||(anchor.open?(entry.open=!0,place2(entry.controller)):entry.open&&(entry.open=!1,entry.controller.hide(!0,!0)))}admit(){const open=[...this.entries.keys()].filter(anchor=>anchor.open).sort((a,b)=>a.compareDocumentPosition(b)&2?1:-1);open.length>LIMIT&&devWarnOnce("lyra-map-anchor-limit",`<${this.host.element.localName}>: only the first ${LIMIT} open <${open[LIMIT].localName}> children are placed; later ones stay hidden until one closes.`);const changed=new Set;for(const[anchor,entry]of this.entries){const admitted=open.indexOf(anchor)<LIMIT&&anchor.open;admitted!==entry.admitted&&(entry.admitted=admitted,changed.add(entry))}return changed}attach(anchor){const existing=this.entries.get(anchor);if(existing)return existing;const host=this.host,shadow=selector=>anchor.shadowRoot?.querySelector(selector)??void 0,controller=new MapAnchorController({...host,key:`map-anchor-child-${++this.serial}`,overlayHost:anchor,child:!0,wrapper:()=>shadow('[part~="base"]'),fence:()=>shadow(".fence"),content:()=>anchor.shadowRoot?.querySelector("slot:not([name])"),styleLoaded:()=>host.engineReady(),request:()=>anchor.open&&entry.admitted&&!anchor.hidden?anchor.lngLat:null,boundary:()=>anchor.boundary===void 0?host.element.anchorBoundary:anchor.boundary,safeArea:()=>anchor.safeArea===void 0?host.element.anchorSafeArea:anchor.safeArea,closable:()=>anchor.closable,pending:()=>anchor.isUpdatePending,retire:()=>{},emitClose:()=>{},escape:()=>{anchor[MAP_ANCHOR_SEAM]("escape")},fallback:()=>host.canvas(),lost:()=>entry.focused,placed:placed=>{anchor[MAP_ANCHOR_SEAM](placed?"placed":"unplaced")},autofocus:()=>anchor[MAP_ANCHOR_SEAM]("autofocus")}),entry={controller,admitted:!1,open:!1,listener:event=>{if(event.type==="pointerdown"){controller.raise();return}const focus=event,next=focus.relatedTarget;event.type==="focusout"&&queueMicrotask(()=>{controller.focusOut()}),event.type==="focusin"?(entry.focused=focus.composedPath()[0],controller.focusIn(focus)):next?composedContains(anchor,next)||(entry.focused=void 0):queueMicrotask(()=>{anchor.isConnected&&entry.focused?.isConnected&&!composedContains(anchor,deepActiveElement(anchor.ownerDocument))&&(entry.focused=void 0)})}};for(const type of CHILD_EVENTS)anchor.addEventListener(type,entry.listener);return this.entries.set(anchor,entry),entry}}export{MapAnchorChildren,MapAnchorController};
1
+ import{deferredPlaceSession as place}from"../../../internal/anchored-overlay-runtime.js";import{getInheritedPropertyDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{applyComposedFocusRepair,captureComposedFocusRepair,focusFirstAvailable}from"../../../internal/focus-navigation.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{finiteRange}from"../../../internal/numbers.js";import{reserveOverlayOrder}from"../../../internal/overlay-order.js";import{collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement,observeOverlayStack}from"../../../internal/overlay-stack.js";import{virtualAnchorFromRect}from"../../../internal/positioner-geometry.js";import{admitMapAnchorOptions}from"./map-anchor-options.js";import{MAP_ANCHOR_SEAM}from"./map-anchor-seam.js";import{mapOwnValue,renderedSizeKey}from"./map-readers.js";const escapeOwners=new Set,rankings=new WeakMap,RANK="--_lr-map-anchor-rank",LIMIT=16;let raises=0,insertions=0;class MapAnchorController{constructor(host){this.host=host,this.epoch=0,this.placed=!1,this.closingState=!1,this.observedBoundaries=[],this.raisedAt=0,this.order=0,this.fresh=!0,this.listening=!1}get closing(){return this.closingState}view(){return this.host.element.ownerDocument?.defaultView??null}invalidate(){this.epoch+=1,this.placed=!1,this.placedCoordinates=void 0,this.placement?.handle?.invalidate(),this.overlay?.suspend()}stop(){this.invalidate();const placement=this.placement;this.placement=void 0,placement?.handle?.()}schedule(){if(this.invalidate(),this.frame!==void 0)return;const view=this.view();if(!view||typeof view.requestAnimationFrame!="function"){this.sync();return}this.frame=view.requestAnimationFrame(()=>{this.frame=void 0,this.sync()})}cancelFrame(){this.frame!==void 0&&(this.view()?.cancelAnimationFrame?.(this.frame),this.frame=void 0)}focus(){const wrapper=this.host.wrapper();if(!wrapper||!this.isOpen())return!1;const epoch=this.epoch,targets=collectFocusableElements(wrapper);return epoch!==this.epoch||!this.isOpen()||targets.length===0||(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.isOpen())?!1:focusFirstAvailable(targets)&&epoch===this.epoch&&this.isOpen()}isOpen(){const host=this.host,wrapper=host.wrapper();return host.element.isConnected&&!!host.map()&&host.styleLoaded()&&this.placed&&!host.pending()&&this.placedCoordinates===host.request()&&!!wrapper&&!wrapper.hidden&&!host.interactionBlocked()&&this.hasContent()}captureReturnTarget(wrapper){const active=deepActiveElement(this.host.element.ownerDocument);if(!(!active||composedContains(wrapper,active)))try{const descriptor=getInheritedPropertyDescriptor(active,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=active,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}close(reason){const host=this.host,wrapper=host.wrapper();if(!wrapper||!this.isOpen())return!1;const requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=captureComposedFocusRepair(wrapper,this.returnTarget??null);if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request()||!this.isOpen())return!1;this.closingState=!0;try{host.retire()}finally{this.closingState=!1}this.hide(!1,!0);const epoch=this.epoch;return host.emitClose(Object.freeze({reason})),repair&&epoch===this.epoch&&host.request()===null&&applyComposedFocusRepair(repair),!0}hide(restore=!0,retire=!1){const host=this.host,wrapper=host.wrapper(),requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=restore&&wrapper?this.repairFrom(wrapper):null;if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request())return;this.stop(),wrapper&&(wrapper.hidden=!0),rankings.get(host.element)?.delete(this)&&(wrapper?.style.removeProperty(RANK),MapAnchorController.rank(host.element)),host.placed?.(!1);const epoch=this.epoch;if(retire){const overlay=this.overlay;this.overlay=void 0,this.returnTarget=void 0,this.fresh=!0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1})}else this.overlay?.suspend();repair&&epoch===this.epoch&&!this.placed&&this.repair(repair)}capture(){const wrapper=this.host.wrapper();return wrapper?this.repairFrom(wrapper):null}repair(snapshot){if(!snapshot)return;const repair=snapshot;applyComposedFocusRepair(repair,[repair.candidate,this.host.fallback?.()])}repairFrom(wrapper){const host=this.host,document=wrapper.ownerDocument,lost=host.lost?.(),active=deepActiveElement(document),candidate=()=>this.returnTarget??host.fallback?.()??null,target=lost&&(!active||active===document.body||active===document.documentElement)?candidate():null;return captureComposedFocusRepair(wrapper,candidate)??(lost&&target?{activeElement:lost,candidate:target,document,owner:wrapper}:null)}raise(escape=!0){!rankings.get(this.host.element)?.has(this)||!this.ranked()||(this.raisedAt=++raises,MapAnchorController.rank(this.host.element),escape&&this.reRegister())}ranked(){return!!this.host.child||[...rankings.get(this.host.element)??[]].some(member=>member.host.child)}enter(wrapper){const host=this.host,members=rankings.get(host.element)??new Set;rankings.set(host.element,members);const joined=!members.has(this);if(members.add(this),host.placed?.(!0),!host.child&&!this.listening&&(this.listening=!0,wrapper.addEventListener("pointerdown",()=>{this.raise()}),wrapper.addEventListener("focusout",()=>{queueMicrotask(()=>{this.focusOut()})})),!this.fresh){joined&&MapAnchorController.rank(host.element);return}if(this.fresh=!1,this.raise(!1),!(!host.autofocus?.()||composedContains(wrapper,deepActiveElement(wrapper.ownerDocument)))){for(const target of collectAutofocusElements(wrapper))if(focusFirstAvailable(target)||focusFirstAvailable(collectFocusableElements(target)))break}}static rank(map){const members=[...rankings.get(map)??[]],ranked=members.some(member=>member.host.child),active=deepActiveElement(map.ownerDocument),keys=new Map;for(const member of members){const wrapper=member.host.wrapper();keys.set(member,wrapper&&composedContains(wrapper,active)?raises+1:member.raisedAt)}return members.sort((a,b)=>keys.get(a)-keys.get(b)),members.forEach((member,index)=>{const style=member.host.wrapper()?.style;ranked?style?.setProperty(RANK,String(index)):style?.removeProperty(RANK)}),members}focusOut(){if(!this.ranked())return;[...MapAnchorController.rank(this.host.element)].reverse().find(member=>member.host.closable()&&member.isOpen())?.reRegister()}reRegister(){const host=this.host,overlay=this.overlay,wrapper=host.wrapper();if(!overlay||overlay.isTopmost()||!wrapper)return;let entries=[];observeOverlayStack(host.element.ownerDocument,snapshot=>{entries=snapshot.entries})();const index=entries.findIndex(entry=>entry.host===host.overlayHost),anchored=other=>[...escapeOwners].some(owner=>{const panel=owner.host.wrapper();return owner!==this&&(owner.host.overlayHost===other||!!panel&&composedContains(panel,other))});index<0||entries.slice(index+1).some(entry=>composedContains(wrapper,entry.host)||!anchored(entry.host))||(this.overlay=this.activate())}activate(below=!1){const host=this.host,document=host.element.ownerDocument,focused=below?[...escapeOwners].find(owner=>{const wrapper=owner.host.wrapper();return owner!==this&&owner.ranked()&&!!wrapper&&composedContains(wrapper,deepActiveElement(document))}):void 0,order=this.order=focused?focused.order-1/(++insertions+1):reserveOverlayOrder(document)(document);return activateNonmodalOverlay({host:host.overlayHost,panel:()=>host.wrapper()??null,onEscape:()=>{host.escape?host.escape():this.close("escape")},beforeInitialFocus:()=>!1,restoreFocusTo:()=>this.returnTarget??null,orderReservation:destination=>destination===document?order:void 0})}dispose(){this.cancelFrame(),this.hide(!0,!0),this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[]}suspendAdmission(){this.cancelFrame(),this.hide(),!(this.placement||this.placed)&&(this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[])}syncOverlay(wrapper){const host=this.host,element=host.element;if(!host.closable()){const overlay=this.overlay;this.overlay=void 0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1});return}if(this.overlay)this.overlay.resume();else{const epoch=this.epoch;if(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.placed||!element.isConnected)return;const overlay=this.activate(this.ranked());epoch===this.epoch&&this.placed&&element.isConnected&&host.closable()&&!this.overlay?(this.overlay=overlay,escapeOwners.add(this)):overlay.deactivate({restoreFocus:!1})}}hasContent(){return this.host.content()?.assignedNodes({flatten:!0}).some(node=>node.nodeType===1||node.nodeType===3&&!!node.textContent?.trim())??!1}observeBoundaries(boundaries){if(boundaries.length===this.observedBoundaries.length&&boundaries.every((value,index)=>value===this.observedBoundaries[index]))return;this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[...boundaries];const ResizeObserverClass=this.view()?.ResizeObserver;if(!ResizeObserverClass||boundaries.length===0)return;let sizes=boundaries.map(renderedSizeKey);this.boundaryObserver=new ResizeObserverClass(()=>{const next=boundaries.map(renderedSizeKey);next.every((value,index)=>value===sizes[index])||(sizes=next,this.host.element.isConnected&&this.schedule())});for(const boundary of boundaries)this.boundaryObserver.observe(boundary)}focusIn(event){const wrapper=this.host.wrapper(),previous=event.relatedTarget,view=this.view();if(wrapper&&view&&!(previous instanceof view.Element&&composedContains(wrapper,previous))&&this.raise(),!(!wrapper||!view||!(previous instanceof view.Element)||previous.ownerDocument!==this.host.element.ownerDocument||composedContains(wrapper,previous)))try{const descriptor=getInheritedPropertyDescriptor(previous,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=previous,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}point(){const host=this.host,position=host.request();if(!Array.isArray(position))return;const lng=mapOwnValue(position,"0"),lat=mapOwnValue(position,"1");if(!(typeof lng!="number"||!Number.isFinite(lng)||typeof lat!="number"||!Number.isFinite(lat)||Math.abs(lat)>90))return host.element.project([lng,lat])}sync(){const host=this.host,element=host.element;if(this.invalidate(),host.updateActive()){const[generation,connection2]=host.generations(),map2=host.map();host.afterUpdate(()=>{const[style2,current2]=host.generations();element.isConnected&&current2===connection2&&style2===generation&&host.map()===map2&&this.sync()},`${host.key}-${connection2}-${generation}`);return}const wrapper=host.wrapper(),container=host.container(),fence=host.fence();if(!wrapper||!container||!fence||!element.isConnected||!host.map()||!host.styleLoaded()||host.interactionBlocked()||!this.hasContent()){this.hide();return}const epoch=this.epoch,map=host.map(),coordinates=host.request(),document=element.ownerDocument,[style,connection]=host.generations(),boundary=host.boundary(),safeArea=host.safeArea(),direction=host.direction(),current=()=>element.isConnected&&element.ownerDocument===document&&host.map()===map&&host.styleLoaded()&&host.generations()[0]===style&&host.generations()[1]===connection&&host.wrapper()===wrapper&&host.container()===container&&host.fence()===fence&&epoch===this.epoch&&host.request()===coordinates&&host.boundary()===boundary&&host.safeArea()===safeArea&&host.direction()===direction&&!host.interactionBlocked();try{const admitted=admitMapAnchorOptions({boundary,safeArea},element.ownerDocument,{current});if(!admitted.ok||!current()){epoch===this.epoch&&this.hide();return}this.observeBoundaries(admitted.boundaries);const point=this.point();if(!current())return;const width=finiteRange(container.clientWidth,0,0),height=finiteRange(container.clientHeight,0,0);if(!current())return;const edges=admitted.safeArea,start=Math.min(width,edges.inlineStart),end=Math.min(width,edges.inlineEnd),top=Math.min(height,edges.blockStart),bottom=Math.min(height,edges.blockEnd);if(!point||!(point[0]>=0&&point[1]>=0&&point[0]<=width&&point[1]<=height)||start+end>=width||top+bottom>=height){this.hide();return}fence.style.insetInlineStart=`${start}px`,fence.style.insetInlineEnd=`${end}px`,fence.style.insetBlockStart=`${top}px`,fence.style.insetBlockEnd=`${bottom}px`,host.child&&(fence.style.direction=direction);const clip=fence.getBoundingClientRect();let left=clip.left,right=clip.right,upper=clip.top,lower=clip.bottom;for(const clipping of admitted.boundaries){const bounds=clipping.getBoundingClientRect();if(!current())return;left=Math.max(left,bounds.left),right=Math.min(right,bounds.right),upper=Math.max(upper,bounds.top),lower=Math.min(lower,bounds.bottom)}if(!(right-left>16&&lower-upper>16)){this.hide();return}wrapper.hidden=!1;const rect=container.getBoundingClientRect();if(!current())return;const pointRect=virtualAnchorFromRect({x:rect.left+point[0],y:rect.top+point[1]}).getBoundingClientRect(),publish=()=>{if(!current()||!this.hasContent())return;const first=!this.placed;first&&this.captureReturnTarget(wrapper),current()&&(this.placed=!0,this.placedCoordinates=coordinates,this.syncOverlay(wrapper),first&&current()&&this.enter(wrapper))},previous=this.placement;if(previous?.handle?.isActive()&&previous.document===document&&previous.map===map&&previous.wrapper===wrapper&&previous.container===container&&previous.fence===fence&&previous.direction===direction&&previous.style===style&&previous.connection===connection&&previous.boundaries.length===admitted.boundaries.length&&previous.boundaries.every((value,index)=>value===admitted.boundaries[index])&&previous.safeArea.blockStart===edges.blockStart&&previous.safeArea.blockEnd===edges.blockEnd&&previous.safeArea.inlineStart===edges.inlineStart&&previous.safeArea.inlineEnd===edges.inlineEnd){previous.rect=pointRect,previous.current=current,previous.publish=publish,previous.handle?.update();return}if(this.placement=void 0,previous?.handle?.(),!current())return;const placement={document,map,wrapper,container,fence,direction,style,connection,boundaries:admitted.boundaries,safeArea:edges,rect:pointRect,current,publish};this.placement=placement;const handle=place({contextElement:container,getBoundingClientRect:()=>placement.rect},wrapper,{placement:"top",strategy:"absolute",offset:12,boundary:[fence,...admitted.boundaries],padding:8,shiftCrossAxis:!0,onPlaced:()=>{this.placement===placement&&placement.publish()}});if(!current()||this.placement!==placement){this.placement===placement&&(this.placement=void 0),handle();return}placement.handle=handle,handle.ready.then(ready=>{!ready&&this.placement===placement&&placement.current()&&this.hide()})}catch{current()&&this.hide()}}}const CHILD_EVENTS=["focusin","focusout","pointerdown"];class MapAnchorChildren{constructor(host,anchors){this.host=host,this.entries=new Map,this.admittedControllers=new Set,this.serial=0;for(const anchor of anchors)this.attach(anchor)}run(anchor,operation,value){const entry=this.entries.get(anchor);switch(operation){case"attach":this.sync(this.attach(anchor));return;case"detach":if(entry){for(const type of CHILD_EVENTS)anchor.removeEventListener(type,entry.listener);this.entries.delete(anchor),entry.controller.dispose(),this.sync(entry)}return;case"capture":return entry?.controller.capture();case"retire":entry&&(entry.open=!1,entry.focused=void 0,entry.controller.hide(!1,!0));return;case"repair":if(value){const repair=value;applyComposedFocusRepair(repair,[repair.candidate,this.host.canvas()])}return;case"focus":return entry?.controller.focus()??!1;default:entry&&this.sync(entry);return}}sync(only){this.each(only,controller=>{controller.sync()})}schedule(){this.each(void 0,controller=>{controller.schedule()})}invalidate(){for(const controller of this.admittedControllers)controller.invalidate()}stop(){for(const{controller}of this.entries.values())controller.stop()}hide(){for(const{controller,open}of this.entries.values())open&&controller.hide()}dispose(){for(const{controller}of this.entries.values())controller.dispose()}each(only,place2){const changed=this.admit();for(const[anchor,entry]of this.entries)only&&entry!==only&&!changed.has(entry)||(anchor.open?(entry.open=!0,entry.admitted?place2(entry.controller):changed.has(entry)&&entry.controller.suspendAdmission()):entry.open&&(entry.open=!1,entry.controller.hide(!0,!0)))}admit(){const first=[];let open=0,overflow;for(const anchor of this.entries.keys()){if(!anchor.open||(++open>LIMIT&&(overflow??=anchor),first.length===LIMIT&&anchor.compareDocumentPosition(first[LIMIT-1])&2))continue;let low=0,high=first.length;for(;low<high;){const middle=low+high>>>1;anchor.compareDocumentPosition(first[middle])&2?low=middle+1:high=middle}first.splice(low,0,anchor),first.length>LIMIT&&first.pop()}overflow&&devWarnOnce("lyra-map-anchor-limit",`<${this.host.element.localName}>: only the first ${LIMIT} open <${overflow.localName}> children are placed; later ones stay hidden until one closes.`);const selected=new Set(first),changed=new Set;this.admittedControllers.clear();for(const[anchor,entry]of this.entries){const admitted=selected.has(anchor);admitted!==entry.admitted&&(entry.admitted=admitted,changed.add(entry)),admitted&&this.admittedControllers.add(entry.controller)}return changed}attach(anchor){const existing=this.entries.get(anchor);if(existing)return existing;const host=this.host,shadow=selector=>anchor.shadowRoot?.querySelector(selector)??void 0,controller=new MapAnchorController({...host,key:`map-anchor-child-${++this.serial}`,overlayHost:anchor,child:!0,wrapper:()=>shadow('[part~="base"]'),fence:()=>shadow(".fence"),content:()=>anchor.shadowRoot?.querySelector("slot:not([name])"),styleLoaded:()=>host.engineReady(),request:()=>anchor.open&&entry.admitted&&!anchor.hidden?anchor.lngLat:null,boundary:()=>anchor.boundary===void 0?host.element.anchorBoundary:anchor.boundary,safeArea:()=>anchor.safeArea===void 0?host.element.anchorSafeArea:anchor.safeArea,closable:()=>anchor.closable,pending:()=>anchor.isUpdatePending,retire:()=>{},emitClose:()=>{},escape:()=>{anchor[MAP_ANCHOR_SEAM]("escape")},fallback:()=>host.canvas(),lost:()=>entry.focused,placed:placed=>{anchor[MAP_ANCHOR_SEAM](placed?"placed":"unplaced")},autofocus:()=>anchor[MAP_ANCHOR_SEAM]("autofocus")}),entry={controller,admitted:!1,open:!1,listener:event=>{if(event.type==="pointerdown"){controller.raise();return}const focus=event,next=focus.relatedTarget;event.type==="focusout"&&queueMicrotask(()=>{controller.focusOut()}),event.type==="focusin"?(entry.focused=focus.composedPath()[0],controller.focusIn(focus)):next?composedContains(anchor,next)||(entry.focused=void 0):queueMicrotask(()=>{anchor.isConnected&&entry.focused?.isConnected&&!composedContains(anchor,deepActiveElement(anchor.ownerDocument))&&(entry.focused=void 0)})}};for(const type of CHILD_EVENTS)anchor.addEventListener(type,entry.listener);return this.entries.set(anchor,entry),entry}}export{MapAnchorChildren,MapAnchorController};
@@ -0,0 +1 @@
1
+ import{deepActiveElementIn}from"../../../internal/active-element.js";function syncMapControlRows(container,isCurrent){for(const controls of container.querySelectorAll(".maplibregl-control-container")){const current=()=>isCurrent()&&container.contains(controls);for(const edge of["top","bottom"]){if(!current())return;let row=controls.querySelector(`:scope > .map-control-row-${edge}`);row||(row=container.ownerDocument.createElement("div"),row.className=`map-control-row map-control-row-${edge}`,row.part.add(edge==="top"?"controls-top":"controls-bottom"),controls.append(row));for(const side of["right","left"]){if(!current())return;const corner=controls.querySelector(`.maplibregl-ctrl-${edge}-${side}`);if(!corner)continue;const before=side==="left"?row.querySelector(`.maplibregl-ctrl-${edge}-right`):null;if(corner.parentNode===row&&corner.nextSibling===before)continue;const document=corner.ownerDocument,active=deepActiveElementIn(document),focus=active instanceof HTMLElement&&corner.contains(active)?active:void 0;let transferred=!1;const trackFocus=()=>{transferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{typeof row.moveBefore=="function"?row.moveBefore(corner,before):row.insertBefore(corner,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(!current())return;const remaining=deepActiveElementIn(document),lost=!remaining||remaining===document.body||remaining===document.documentElement;focus?.isConnected&&corner.contains(focus)&&focus.ownerDocument===document&&!transferred&&lost&&focus.focus({preventScroll:!0})}}}}export{syncMapControlRows};
@@ -6,11 +6,15 @@ export type LyraMapScaleUnit='metric'|'imperial';
6
6
  /** Options of the declarative navigation control (zoom buttons and compass).*/
7
7
  export interface LyraMapNavigationControlOptions{
8
8
  /** Corner to add the control to. Defaults to `'top-right'`.*/
9
- readonly position?:LyraMapControlPosition;}
9
+ readonly position?:LyraMapControlPosition;
10
+ /** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, attribution.*/
11
+ readonly order?:number;}
10
12
  /** Options of the declarative scale control.*/
11
13
  export interface LyraMapScaleControlOptions{
12
14
  /** Corner to add the control to. Defaults to `'bottom-left'`.*/
13
15
  readonly position?:LyraMapControlPosition;
16
+ /** Ascending visual and keyboard order within the corner. Defaults to 0; ties use navigation, scale, geolocate, attribution.*/
17
+ readonly order?:number;
14
18
  /** Unit system. Defaults to `'metric'`.*/
15
19
  readonly unit?:LyraMapScaleUnit;}
16
20
  /** Options of the declarative geolocation control.*/
@@ -26,7 +30,7 @@ export interface LyraMapAttributionControlOptions extends LyraMapNavigationContr
26
30
  /** Omission retains the peer's automatic compact layout.*/
27
31
  readonly compact?:boolean;
28
32
  /** Text or guarded links; at most 32 items and 16 KiB of labels and URLs. Caller HTML is never interpreted.*/
29
- readonly customAttribution?:string|LyraMapAttributionLink|readonly(string|LyraMapAttributionLink)[];}export interface NormalizedMapControlOptions{readonly kind:MapOwnedControlKind;readonly position:LyraMapControlPosition;readonly unit:LyraMapScaleUnit|undefined;readonly options:Readonly<Record<string,unknown>>;readonly key:string;
33
+ readonly customAttribution?:string|LyraMapAttributionLink|readonly(string|LyraMapAttributionLink)[];}export interface NormalizedMapControlOptions{readonly kind:MapOwnedControlKind;readonly position:LyraMapControlPosition;readonly order:number;readonly unit:LyraMapScaleUnit|undefined;readonly options:Readonly<Record<string,unknown>>;readonly key:string;
30
34
  /** Escaped labels only, for text export without URLs or link markup.*/
31
35
  readonly attributionText?:readonly string[];}export interface MapControlOptionsResult{readonly controls:ReadonlyMap<MapOwnedControlKind,NormalizedMapControlOptions>;readonly diagnostics:readonly{readonly kind:MapOwnedControlKind;readonly code:'invalid-options';}[];}
32
36
  /**
@@ -1 +1 @@
1
- import{resolveGuardedRel}from"../../../internal/link-rel.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const positions=new Set(["top-left","top-right","bottom-left","bottom-right"]);function runtimeRecord(input){try{return input!==null&&typeof input=="object"&&!Array.isArray(input)}catch{return!1}}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Unsafe control option");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function optionalLegacy(input,key){try{return own(input,key)}catch{return}}function plain(input){if(!isPlainDataRecord(input))throw new TypeError("Expected plain control options");return input}function bool(input,key,fallback){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="boolean")throw new TypeError("Invalid boolean control option");return value}function number(input,key,fallback,maximum){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<0||value>maximum)throw new RangeError("Invalid numeric control option");return value}function position(input,fallback){const value=own(input,"position");if(value===void 0)return fallback;if(!positions.has(value))throw new TypeError("Invalid control position");return value}const escapeText=value=>value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;");function attributionText(input){let total=0;const labels=[],text=value=>{if(typeof value!="string"||value.length>4096||(total+=value.length)>16384)throw new RangeError("Attribution text limit");return escapeText(value)},item=value=>{if(typeof value=="string"){const label2=text(value);return labels.push(label2),label2}const record=plain(value),label=text(own(record,"label")),raw=own(record,"url");if(typeof raw!="string"||raw.length>2048||/[\u0000-\u0020\u007f-\u009f]/.test(raw))throw new TypeError("Invalid attribution URL");const url=new URL(raw);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.href.length>2048||(total+=url.href.length)>16384)throw new TypeError("Invalid attribution URL");const snapshot=Object.freeze({label,url:url.href});return labels.push(snapshot.label),`<a href="${escapeText(snapshot.url)}" target="_blank" rel="${resolveGuardedRel(void 0,"_blank")}">${snapshot.label}</a>`};let html;if(!Array.isArray(input))html=item(input);else{const length=own(input,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>32)throw new RangeError("Attribution count limit");const result=[];for(let index=0;index<length;index++)result.push(item(own(input,String(index))));html=Object.freeze(result)}return Object.freeze({html,text:Object.freeze(labels)})}function normalizeMapControlOptions(input){const controls=new Map,diagnostics=[],done=()=>Object.freeze({controls,diagnostics:Object.freeze(diagnostics.map(item=>Object.freeze(item)))});if(!runtimeRecord(input))return done();for(const kind of["navigation","scale","geolocate","attribution"])try{const value=kind==="navigation"||kind==="scale"?optionalLegacy(input,kind):own(input,kind);if(value===void 0||value===!1)continue;if(kind==="navigation"||kind==="scale"){if(value!==!0&&!runtimeRecord(value))continue;const entry2=value===!0?{}:value,fallback=kind==="navigation"?"top-right":"bottom-left",requested=optionalLegacy(entry2,"position"),corner2=positions.has(requested)?requested:fallback,unit=kind==="scale"?optionalLegacy(entry2,"unit")==="imperial"?"imperial":"metric":void 0;controls.set(kind,Object.freeze({kind,position:corner2,unit,options:Object.freeze(kind==="scale"?{unit}:{}),key:`${corner2}:${unit??""}`}));continue}const entry=value===!0?{}:plain(value),corner=position(entry,kind==="geolocate"?"top-right":"bottom-right");let options,attributionLabels;if(kind==="geolocate"){const rawPosition=own(entry,"positionOptions"),rawFit=own(entry,"fitBoundsOptions"),positionOptions=rawPosition===void 0?{}:plain(rawPosition),fit=rawFit===void 0?{}:plain(rawFit),showUserLocation=bool(entry,"showUserLocation",!0),showAccuracyCircle=bool(entry,"showAccuracyCircle",!0),zoomToUserAccuracy=own(entry,"zoomToUserAccuracy");if(zoomToUserAccuracy!==void 0&&typeof zoomToUserAccuracy!="boolean")throw new TypeError("Invalid zoom option");options=Object.freeze({trackUserLocation:bool(entry,"trackUserLocation",!1),showUserLocation,showAccuracyCircle:showUserLocation&&showAccuracyCircle,positionOptions:Object.freeze({enableHighAccuracy:bool(positionOptions,"enableHighAccuracy",!1),timeout:number(positionOptions,"timeout",6e3,864e5),maximumAge:number(positionOptions,"maximumAge",0,864e5)}),fitBoundsOptions:Object.freeze({maxZoom:number(fit,"maxZoom",15,24)}),...zoomToUserAccuracy===void 0?{}:{zoomToUserAccuracy}})}else{const compact=own(entry,"compact"),custom=own(entry,"customAttribution");if(compact!==void 0&&typeof compact!="boolean")throw new TypeError("Invalid attribution mode");const credits=custom===void 0?void 0:attributionText(custom);attributionLabels=credits?.text,options=Object.freeze({...compact===void 0?{}:{compact},...credits===void 0?{}:{customAttribution:credits.html}})}controls.set(kind,Object.freeze({kind,position:corner,unit:void 0,options,...attributionLabels?{attributionText:attributionLabels}:{},key:`${corner}:${JSON.stringify(options)}`}))}catch{diagnostics.push({kind,code:"invalid-options"})}return done()}function mapGeolocationErrorCode(code){return code===1?"permission-denied":code===2?"position-unavailable":code===3?"timeout":"unknown"}export{mapGeolocationErrorCode,normalizeMapControlOptions};
1
+ import{resolveGuardedRel}from"../../../internal/link-rel.js";import{getOwnDataDescriptor,isPlainDataRecord,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";const positions=new Set(["top-left","top-right","bottom-left","bottom-right"]);function runtimeRecord(input){try{return input!==null&&typeof input=="object"&&!Array.isArray(input)}catch{return!1}}function own(input,key){const descriptor=getOwnDataDescriptor(input,key);if(descriptor===UNSAFE_OWN_DATA_DESCRIPTOR)throw new TypeError("Unsafe control option");return descriptor===MISSING_OWN_DATA_DESCRIPTOR?void 0:descriptor.value}function optionalLegacy(input,key){try{return own(input,key)}catch{return}}function plain(input){if(!isPlainDataRecord(input))throw new TypeError("Expected plain control options");return input}function bool(input,key,fallback){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="boolean")throw new TypeError("Invalid boolean control option");return value}function number(input,key,fallback,maximum){const value=own(input,key);if(value===void 0)return fallback;if(typeof value!="number"||!Number.isFinite(value)||value<0||value>maximum)throw new RangeError("Invalid numeric control option");return value}function controlOrder(input){const value=own(input,"order");if(value===void 0)return 0;if(typeof value!="number"||!Number.isFinite(value))throw new TypeError("Invalid control order");return value}function position(input,fallback){const value=own(input,"position");if(value===void 0)return fallback;if(!positions.has(value))throw new TypeError("Invalid control position");return value}const escapeText=value=>value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;");function attributionText(input){let total=0;const labels=[],text=value=>{if(typeof value!="string"||value.length>4096||(total+=value.length)>16384)throw new RangeError("Attribution text limit");return escapeText(value)},item=value=>{if(typeof value=="string"){const label2=text(value);return labels.push(label2),label2}const record=plain(value),label=text(own(record,"label")),raw=own(record,"url");if(typeof raw!="string"||raw.length>2048||/[\u0000-\u0020\u007f-\u009f]/.test(raw))throw new TypeError("Invalid attribution URL");const url=new URL(raw);if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.href.length>2048||(total+=url.href.length)>16384)throw new TypeError("Invalid attribution URL");const snapshot=Object.freeze({label,url:url.href});return labels.push(snapshot.label),`<a href="${escapeText(snapshot.url)}" target="_blank" rel="${resolveGuardedRel(void 0,"_blank")}">${snapshot.label}</a>`};let html;if(!Array.isArray(input))html=item(input);else{const length=own(input,"length");if(typeof length!="number"||!Number.isSafeInteger(length)||length<0||length>32)throw new RangeError("Attribution count limit");const result=[];for(let index=0;index<length;index++)result.push(item(own(input,String(index))));html=Object.freeze(result)}return Object.freeze({html,text:Object.freeze(labels)})}function normalizeMapControlOptions(input){const controls=new Map,diagnostics=[],done=()=>Object.freeze({controls,diagnostics:Object.freeze(diagnostics.map(item=>Object.freeze(item)))});if(!runtimeRecord(input))return done();for(const kind of["navigation","scale","geolocate","attribution"])try{const value=kind==="navigation"||kind==="scale"?optionalLegacy(input,kind):own(input,kind);if(value===void 0||value===!1)continue;if(kind==="navigation"||kind==="scale"){if(value!==!0&&!runtimeRecord(value))continue;const entry2=value===!0?{}:value,order2=controlOrder(entry2),fallback=kind==="navigation"?"top-right":"bottom-left",requested=optionalLegacy(entry2,"position"),corner2=positions.has(requested)?requested:fallback,unit=kind==="scale"?optionalLegacy(entry2,"unit")==="imperial"?"imperial":"metric":void 0;controls.set(kind,Object.freeze({kind,position:corner2,order:order2,unit,options:Object.freeze(kind==="scale"?{unit}:{}),key:`${corner2}:${order2}:${unit??""}`}));continue}const entry=value===!0?{}:plain(value),order=controlOrder(entry),corner=position(entry,kind==="geolocate"?"top-right":"bottom-right");let options,attributionLabels;if(kind==="geolocate"){const rawPosition=own(entry,"positionOptions"),rawFit=own(entry,"fitBoundsOptions"),positionOptions=rawPosition===void 0?{}:plain(rawPosition),fit=rawFit===void 0?{}:plain(rawFit),showUserLocation=bool(entry,"showUserLocation",!0),showAccuracyCircle=bool(entry,"showAccuracyCircle",!0),zoomToUserAccuracy=own(entry,"zoomToUserAccuracy");if(zoomToUserAccuracy!==void 0&&typeof zoomToUserAccuracy!="boolean")throw new TypeError("Invalid zoom option");options=Object.freeze({trackUserLocation:bool(entry,"trackUserLocation",!1),showUserLocation,showAccuracyCircle:showUserLocation&&showAccuracyCircle,positionOptions:Object.freeze({enableHighAccuracy:bool(positionOptions,"enableHighAccuracy",!1),timeout:number(positionOptions,"timeout",6e3,864e5),maximumAge:number(positionOptions,"maximumAge",0,864e5)}),fitBoundsOptions:Object.freeze({maxZoom:number(fit,"maxZoom",15,24)}),...zoomToUserAccuracy===void 0?{}:{zoomToUserAccuracy}})}else{const compact=own(entry,"compact"),custom=own(entry,"customAttribution");if(compact!==void 0&&typeof compact!="boolean")throw new TypeError("Invalid attribution mode");const credits=custom===void 0?void 0:attributionText(custom);attributionLabels=credits?.text,options=Object.freeze({...compact===void 0?{}:{compact},...credits===void 0?{}:{customAttribution:credits.html}})}controls.set(kind,Object.freeze({kind,position:corner,order,unit:void 0,options,...attributionLabels?{attributionText:attributionLabels}:{},key:`${corner}:${order}:${JSON.stringify(options)}`}))}catch{diagnostics.push({kind,code:"invalid-options"})}return done()}function mapGeolocationErrorCode(code){return code===1?"permission-denied":code===2?"position-unavailable":code===3?"timeout":"unknown"}export{mapGeolocationErrorCode,normalizeMapControlOptions};
@@ -1 +1 @@
1
- import{deepActiveElementIn}from"../../../internal/active-element.js";import{mapGeolocationErrorCode}from"./map-control-options.js";function geolocatedPosition(event){try{if(event===null||typeof event!="object")return{};const coords=event.coords;if(coords===null||typeof coords!="object")return{};const{longitude,latitude,accuracy}=coords;return typeof longitude!="number"||typeof latitude!="number"||typeof accuracy!="number"||!Number.isFinite(longitude)||!Number.isFinite(latitude)||!Number.isFinite(accuracy)||Math.abs(longitude)>180||Math.abs(latitude)>90||accuracy<0?{}:{lngLat:Object.freeze([longitude,latitude]),accuracy}}catch{return{}}}class MapControlsLifecycle{constructor(load){this.load=load,this.generation=0,this.entries=new Map}async sync(map,desired,context){const generation=++this.generation,retired=[];for(const[kind,entry]of this.entries){const next=desired.get(kind);entry.map===map&&entry.installed&&next&&(next.key===entry.options.key||entry.root&&map.controlContainer&&JSON.stringify(next.options)===JSON.stringify(entry.options.options))?(entry.context=context,entry.options=next):(this.entries.delete(kind),retired.push(entry))}for(const entry of retired)this.retire(entry);if(generation!==this.generation||!this.validContext(context)||generation!==this.generation)return;const pending=[];for(const[kind,options]of desired){if(generation!==this.generation)break;if(this.entries.has(kind))continue;const entry={map,options,context,installed:!1,attempted:!1,adding:!1,subscribing:!1,removed:!1,retired:!1,subscriptions:[]};this.entries.set(kind,entry),pending.push(entry)}const loaded=await Promise.all(pending.map(async entry=>{try{return await this.load(entry.options.kind)}catch{return}}));if(generation!==this.generation||!this.validContext(context))return;const constructors=new Map(pending.map((entry,index)=>[entry,loaded[index]])),priority=["navigation","scale","geolocate","attribution"];for(const corner of["top-left","top-right","bottom-left","bottom-right"]){const order=corner.startsWith("bottom")?[...priority].reverse():priority;for(const kind of order){if(generation!==this.generation||!this.validContext(context))return;const entry=this.entries.get(kind);entry?.options.position===corner&&constructors.has(entry)&&this.install(entry,constructors.get(entry))}}for(const corner of["top-left","top-right","bottom-left","bottom-right"]){if(generation!==this.generation||!this.validContext(context))return;const entries=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.installed&&entry.options.position===corner);for(let index=entries.length-1;index>=0;index--){const entry=entries[index];if(generation!==this.generation||!this.current(entry))return;try{const parent=map.controlContainer?.(corner);if(generation!==this.generation||!this.current(entry))return;if(!parent||!entry.root)continue;const before=entries.slice(index+1).find(next=>next.root?.parentNode===parent)?.root??null,root=entry.root;if(root.parentNode===parent&&(before?root.nextSibling===before:root.nextSibling===null))continue;const active=root.getRootNode().activeElement,focus=active instanceof HTMLElement&&root.contains(active)?active:void 0;if(generation!==this.generation||!this.current(entry))return;const document=root.ownerDocument;let focusTransferred=!1;const trackFocus=()=>{focusTransferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{parent.insertBefore(root,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(generation!==this.generation||!this.current(entry))return;const remaining=deepActiveElementIn(document),lostFocus=remaining===null||remaining===document.body||remaining===document.documentElement;if(focus?.isConnected&&root.contains(focus)&&focus.ownerDocument===document&&!focusTransferred&&lostFocus&&focus.focus({preventScroll:!0}),generation!==this.generation||!this.current(entry))return}catch{if(generation===this.generation&&this.current(entry))try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}}}dispose(){this.generation+=1;const retired=[...this.entries.values()];this.entries.clear();for(const entry of retired)this.retire(entry)}validContext(context){try{return context.isCurrent()}catch{return!1}}current(entry){const owned=()=>!entry.retired&&this.entries.get(entry.options.kind)===entry;return owned()&&this.validContext(entry.context)&&owned()}install(entry,Constructor){try{if(!this.current(entry)){this.release(entry);return}if(typeof Constructor!="function")throw new Error("Map control is unavailable.");const control=new Constructor(entry.options.options);if(control===null||typeof control!="object"&&typeof control!="function")throw new Error("Map control is unavailable.");if(entry.control=control,!this.current(entry)){this.release(entry);return}if(entry.options.kind==="geolocate"){if(typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Map control events are unavailable.");if(this.subscribe(entry,"error",event=>{if(!this.current(entry))return;let code;try{event!==null&&typeof event=="object"&&(code=event.code)}catch{}this.current(entry)&&entry.context.onEvent({kind:"geolocate-error",code:mapGeolocationErrorCode(code)})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"outofmaxbounds",()=>{this.current(entry)&&entry.context.onEvent({kind:"geolocate-out-of-bounds",code:"out-of-bounds"})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"geolocate",event=>{if(!this.current(entry))return;const position=geolocatedPosition(event);this.current(entry)&&entry.context.onEvent(Object.freeze({kind:"geolocate-success",...position}))}),!this.current(entry)){this.release(entry);return}}const onAdd=entry.control.onAdd;if(!this.current(entry)){this.release(entry);return}const descriptor=Object.getOwnPropertyDescriptor(entry.control,"onAdd");if(!this.current(entry)){this.release(entry);return}try{if(onAdd&&(entry.control.onAdd=function(...args){const root=onAdd.apply(this,args);return entry.root=root,root}),!this.current(entry)){this.release(entry);return}entry.attempted=!0,entry.adding=!0,entry.map.addControl(entry.control,entry.options.position)}finally{try{onAdd&&(descriptor?Object.defineProperty(entry.control,"onAdd",descriptor):delete entry.control.onAdd)}finally{entry.adding=!1,entry.retired&&this.retire(entry)}}if(!this.current(entry)){this.release(entry);return}entry.installed=!0}catch{const report=this.current(entry),generation=this.generation;if(this.release(entry),report&&generation===this.generation&&this.validContext(entry.context)&&generation===this.generation)try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}subscribe(entry,type,callback){entry.subscriptions.push({type,callback}),entry.subscribing=!0;try{entry.control.on(type,callback)}finally{entry.subscribing=!1,entry.retired&&this.retire(entry)}}release(entry){this.entries.get(entry.options.kind)===entry&&this.entries.delete(entry.options.kind),this.retire(entry)}retire(entry){if(entry.retired=!0,entry.subscribing)return;const subscriptions=entry.subscriptions.splice(0);for(const{type,callback}of subscriptions)try{entry.control?.off?.(type,callback)}catch{}if(!(!entry.attempted||entry.adding||entry.removed||!entry.control)){entry.removed=!0;try{entry.map.removeControl(entry.control)}catch{}}}}export{MapControlsLifecycle};
1
+ import{deepActiveElementIn}from"../../../internal/active-element.js";import{mapGeolocationErrorCode}from"./map-control-options.js";function geolocatedPosition(event){try{if(event===null||typeof event!="object")return{};const coords=event.coords;if(coords===null||typeof coords!="object")return{};const{longitude,latitude,accuracy}=coords;return typeof longitude!="number"||typeof latitude!="number"||typeof accuracy!="number"||!Number.isFinite(longitude)||!Number.isFinite(latitude)||!Number.isFinite(accuracy)||Math.abs(longitude)>180||Math.abs(latitude)>90||accuracy<0?{}:{lngLat:Object.freeze([longitude,latitude]),accuracy}}catch{return{}}}class MapControlsLifecycle{constructor(load){this.load=load,this.generation=0,this.entries=new Map}async sync(map,desired,context){const generation=++this.generation,retired=[];for(const[kind,entry]of this.entries){const next=desired.get(kind);entry.map===map&&entry.installed&&next&&(next.key===entry.options.key||entry.root&&map.controlContainer&&JSON.stringify(next.options)===JSON.stringify(entry.options.options))?(entry.context=context,entry.options=next):(this.entries.delete(kind),retired.push(entry))}for(const entry of retired)this.retire(entry);if(generation!==this.generation||!this.validContext(context)||generation!==this.generation)return;const pending=[];for(const[kind,options]of desired){if(generation!==this.generation)break;if(this.entries.has(kind))continue;const entry={map,options,context,installed:!1,attempted:!1,adding:!1,subscribing:!1,removed:!1,retired:!1,subscriptions:[]};this.entries.set(kind,entry),pending.push(entry)}const loaded=await Promise.all(pending.map(async entry=>{try{return await this.load(entry.options.kind)}catch{return}}));if(generation!==this.generation||!this.validContext(context))return;const constructors=new Map(pending.map((entry,index)=>[entry,loaded[index]])),priority=["navigation","scale","geolocate","attribution"];for(const corner of["top-left","top-right","bottom-left","bottom-right"]){const ordered=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order),order=corner.startsWith("bottom")?ordered.reverse():ordered;for(const entry of order){if(generation!==this.generation||!this.validContext(context))return;constructors.has(entry)&&this.install(entry,constructors.get(entry))}}for(const corner of["top-left","top-right","bottom-left","bottom-right"]){if(generation!==this.generation||!this.validContext(context))return;const entries=priority.map(kind=>this.entries.get(kind)).filter(entry=>entry!==void 0&&entry.installed&&entry.options.position===corner).sort((a,b)=>a.options.order-b.options.order);for(let index=entries.length-1;index>=0;index--){const entry=entries[index];if(generation!==this.generation||!this.current(entry))return;try{const parent=map.controlContainer?.(corner);if(generation!==this.generation||!this.current(entry))return;if(!parent||!entry.root)continue;const before=entries.slice(index+1).find(next=>next.root?.parentNode===parent)?.root??null,root=entry.root;if(root.parentNode===parent&&(before?root.nextSibling===before:root.nextSibling===null))continue;const active=root.getRootNode().activeElement,focus=active instanceof HTMLElement&&root.contains(active)?active:void 0;if(generation!==this.generation||!this.current(entry))return;const document=root.ownerDocument;let focusTransferred=!1;const trackFocus=()=>{focusTransferred=!0};focus&&document.addEventListener("focus",trackFocus,!0);try{parent.insertBefore(root,before)}finally{focus&&document.removeEventListener("focus",trackFocus,!0)}if(generation!==this.generation||!this.current(entry))return;const remaining=deepActiveElementIn(document),lostFocus=remaining===null||remaining===document.body||remaining===document.documentElement;if(focus?.isConnected&&root.contains(focus)&&focus.ownerDocument===document&&!focusTransferred&&lostFocus&&focus.focus({preventScroll:!0}),generation!==this.generation||!this.current(entry))return}catch{if(generation===this.generation&&this.current(entry))try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}}}dispose(){this.generation+=1;const retired=[...this.entries.values()];this.entries.clear();for(const entry of retired)this.retire(entry)}validContext(context){try{return context.isCurrent()}catch{return!1}}current(entry){const owned=()=>!entry.retired&&this.entries.get(entry.options.kind)===entry;return owned()&&this.validContext(entry.context)&&owned()}install(entry,Constructor){try{if(!this.current(entry)){this.release(entry);return}if(typeof Constructor!="function")throw new Error("Map control is unavailable.");const control=new Constructor(entry.options.options);if(control===null||typeof control!="object"&&typeof control!="function")throw new Error("Map control is unavailable.");if(entry.control=control,!this.current(entry)){this.release(entry);return}if(entry.options.kind==="geolocate"){if(typeof entry.control.on!="function"||typeof entry.control.off!="function")throw new Error("Map control events are unavailable.");if(this.subscribe(entry,"error",event=>{if(!this.current(entry))return;let code;try{event!==null&&typeof event=="object"&&(code=event.code)}catch{}this.current(entry)&&entry.context.onEvent({kind:"geolocate-error",code:mapGeolocationErrorCode(code)})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"outofmaxbounds",()=>{this.current(entry)&&entry.context.onEvent({kind:"geolocate-out-of-bounds",code:"out-of-bounds"})}),!this.current(entry)){this.release(entry);return}if(this.subscribe(entry,"geolocate",event=>{if(!this.current(entry))return;const position=geolocatedPosition(event);this.current(entry)&&entry.context.onEvent(Object.freeze({kind:"geolocate-success",...position}))}),!this.current(entry)){this.release(entry);return}}const onAdd=entry.control.onAdd;if(!this.current(entry)){this.release(entry);return}const descriptor=Object.getOwnPropertyDescriptor(entry.control,"onAdd");if(!this.current(entry)){this.release(entry);return}try{if(onAdd&&(entry.control.onAdd=function(...args){const root=onAdd.apply(this,args);return entry.root=root,root}),!this.current(entry)){this.release(entry);return}entry.attempted=!0,entry.adding=!0,entry.map.addControl(entry.control,entry.options.position)}finally{try{onAdd&&(descriptor?Object.defineProperty(entry.control,"onAdd",descriptor):delete entry.control.onAdd)}finally{entry.adding=!1,entry.retired&&this.retire(entry)}}if(!this.current(entry)){this.release(entry);return}entry.installed=!0}catch{const report=this.current(entry),generation=this.generation;if(this.release(entry),report&&generation===this.generation&&this.validContext(entry.context)&&generation===this.generation)try{entry.context.onFailure({kind:entry.options.kind,code:"control-failed"})}catch{}}}subscribe(entry,type,callback){entry.subscriptions.push({type,callback}),entry.subscribing=!0;try{entry.control.on(type,callback)}finally{entry.subscribing=!1,entry.retired&&this.retire(entry)}}release(entry){this.entries.get(entry.options.kind)===entry&&this.entries.delete(entry.options.kind),this.retire(entry)}retire(entry){if(entry.retired=!0,entry.subscribing)return;const subscriptions=entry.subscriptions.splice(0);for(const{type,callback}of subscriptions)try{entry.control?.off?.(type,callback)}catch{}if(!(!entry.attempted||entry.adding||entry.removed||!entry.control)){entry.removed=!0;try{entry.map.removeControl(entry.control)}catch{}}}}export{MapControlsLifecycle};
@@ -0,0 +1 @@
1
+ function aborted(){return new DOMException("Map controls readiness was cancelled.","AbortError")}class MapControlsReadiness{reset(){this.cancel();let resolve,reject;const promise=new Promise((yes,no)=>{resolve=yes,reject=no});promise.catch(()=>{}),this.generation={promise,resolve,reject,run:0}}whenReady(){const generation=this.generation;return generation?.error?Promise.reject(generation.error):generation?.promise??Promise.reject(aborted())}begin(){const generation=this.generation;generation?.stop?.();const cancelled=new Promise(resolve=>{generation?generation.stop=resolve:resolve()}),run=generation?++generation.run:0,isCurrent=()=>generation!==void 0&&this.generation===generation&&generation.run===run;return{isCurrent,cancelled,resolve:()=>{isCurrent()&&!generation.error&&generation.resolve()},fail:()=>{isCurrent()&&this.fail()}}}fail(){const generation=this.generation;if(!generation||generation.error)return;const error=new Error("Map controls readiness failed.");error.name="MapReadinessError",generation.error=error,generation.reject(error)}cancel(){const previous=this.generation;this.generation=void 0,previous?.stop?.(),previous?.reject(aborted())}}export{MapControlsReadiness};