@aceshooting/lyra-ui 30.2.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 (51) hide show
  1. package/CHANGELOG.md +71 -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/conversation/chat-viewport/chat-viewport.class.d.ts +2 -2
  13. package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
  14. package/dist/components/conversation/message-parts/message-parts.class.d.ts +13 -4
  15. package/dist/components/conversation/message-parts/message-parts.class.js +12 -10
  16. package/dist/components/conversation/message-parts/message-parts.d.ts +1 -1
  17. package/dist/components/conversation/message-parts/message-parts.js +1 -1
  18. package/dist/components/forms/select/select.class.js +1 -1
  19. package/dist/components/media/file-input/file-input.styles.js +1 -1
  20. package/dist/components/media/map/map-control-chrome.js +1 -0
  21. package/dist/components/media/map/map-control-options.d.ts +6 -2
  22. package/dist/components/media/map/map-control-options.js +1 -1
  23. package/dist/components/media/map/map-controls-lifecycle.js +1 -1
  24. package/dist/components/media/map/map-controls-readiness.js +1 -0
  25. package/dist/components/media/map/map.class.d.ts +39 -2
  26. package/dist/components/media/map/map.class.js +13 -7
  27. package/dist/components/media/map/map.styles.js +1 -1
  28. package/dist/events.d.ts +10 -1
  29. package/dist/framework-types.d.ts +1 -1
  30. package/dist/internal/localization-types.d.ts +1 -1
  31. package/dist/internal/localization.js +1 -1
  32. package/dist/internal/package-metadata.js +1 -1
  33. package/dist/internal/scoped-definitions.generated.js +1 -1
  34. package/dist/lyra.d.ts +1 -1
  35. package/llms/components/lr-file-input.md +5 -0
  36. package/llms/components/lr-map.md +80 -8
  37. package/llms/components/lr-mcp-app.md +94 -4
  38. package/llms/components/lr-message-parts.md +18 -0
  39. package/llms/components/lr-select.md +3 -2
  40. package/llms/peers.md +1 -1
  41. package/llms/shared/ai-and-peers.md +77 -3
  42. package/llms/shared/events-and-types.md +25 -1
  43. package/llms/shared/localization-and-rtl.md +29 -0
  44. package/llms/shared.md +131 -4
  45. package/locales.json +1 -1
  46. package/package.json +8 -4
  47. package/registrations.json +1 -1
  48. package/skills/compose-lyra-interfaces/SKILL.md +5 -3
  49. package/skills/compose-lyra-interfaces/references/composition-patterns.md +8 -1
  50. package/skills/lyra-ui/SKILL.md +16 -8
  51. 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
@@ -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};
@@ -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};
@@ -595,6 +595,14 @@ readonly noData?:true;}>;}
595
595
  * @csspart initialization-activate - Localized button covering an `initialization="interaction"`
596
596
  * placeholder until the first input builds the map.
597
597
  * @csspart initialization-control - Decorative outline of a requested native control before construction.
598
+ * @csspart initialization-navigation - Decorative navigation control placeholder.
599
+ * @csspart initialization-scale - Decorative scale control placeholder.
600
+ * @csspart initialization-geolocate - Decorative geolocation control placeholder.
601
+ * @csspart initialization-attribution - Decorative attribution control placeholder.
602
+ * @csspart initialization-skeleton - Decorative map skeleton before construction.
603
+ * @csspart initialization-activate-label - Visible activation prompt; hiding it preserves the button's localized accessible name.
604
+ * @csspart initialization-controls - Decorative requested controls, also exposing controls.
605
+ * @csspart initialization-corner - Decorative control corner, also exposing its controls-top-left, controls-top-right, controls-bottom-left or controls-bottom-right token.
598
606
  * @event lr-map-style-load - `detail: { generation }` (`LyraMapReadinessDetail`). Fired once per
599
607
  * connection/style after generated and registered overlays, images, style overrides and their
600
608
  * asynchronous preparation are restored.
@@ -680,6 +688,19 @@ readonly noData?:true;}>;}
680
688
  * @csspart configuration-error - Localized control or URL configuration feedback.
681
689
  * @csspart geolocate - Native user-activated geolocation button.
682
690
  * @csspart geolocate-control - Native geolocation control wrapper, for group-level layout offsets.
691
+ * @csspart geolocate-icon - Decorative native geolocation icon span.
692
+ * @csspart geolocate-waiting - Additional geolocate button token while the peer awaits a position.
693
+ * @csspart geolocate-active - Additional geolocate button token while actively tracking.
694
+ * @csspart geolocate-background - Additional geolocate button token while tracking in the background.
695
+ * @csspart geolocate-error - Additional geolocate button token for active or background location errors.
696
+ * @csspart controls - Native or deferred control layout container; each row shares its available inline space.
697
+ * @csspart controls-top - Native or deferred top control row; use display: contents for a custom flattened layout.
698
+ * @csspart controls-bottom - Native or deferred bottom control row.
699
+ * @csspart controls-attribution-expanded - Additional token on controls, both rows and all four corners while any native attribution in that container is expanded.
700
+ * @csspart controls-top-left - Native or deferred top-left corner, following the control position vocabulary.
701
+ * @csspart controls-top-right - Native or deferred top-right control corner.
702
+ * @csspart controls-bottom-left - Native or deferred bottom-left control corner.
703
+ * @csspart controls-bottom-right - Native or deferred bottom-right control corner.
683
704
  * @csspart container - The MapLibre container. Its generated canvas is the actual focusable map
684
705
  * region and receives the host-first accessible name and effective locale.
685
706
  * @slot anchor - Content placed at `anchorLngLat`: above the point, flipped below near the top edge
@@ -736,11 +757,17 @@ readonly noData?:true;}>;}
736
757
  * @csspart attribution - MapLibre-generated map attribution.
737
758
  * @csspart attribution-toggle - MapLibre's compact-attribution disclosure control with a decorative information glyph.
738
759
  * @csspart attribution-content - Native attribution credits, independently positionable from the compact disclosure control.
760
+ * @csspart attribution-link - Each native attribution link, with a minimum 24px target in both axes.
761
+ * @csspart attribution-expanded - Additional token on attribution, attribution-toggle and attribution-content while credits are expanded.
739
762
  * @csspart navigation - Standard peer NavigationControl group, added through `controls` or the map getter.
740
763
  * @csspart zoom-in - Peer zoom-in button with a localized accessible name and tokenized target.
764
+ * @csspart zoom-in-icon - Decorative native zoom-in icon span.
741
765
  * @csspart zoom-out - Peer zoom-out button.
766
+ * @csspart zoom-out-icon - Decorative native zoom-out icon span.
742
767
  * @csspart compass - Peer compass/reset-north button; its glyph retains the peer's bearing rotation.
768
+ * @csspart compass-icon - Decorative native compass span; native bearing transforms remain on this node.
743
769
  * @csspart scale - Standard peer ScaleControl bar. Units and updates remain owned by MapLibre.
770
+ * @cssprop [--lr-map-scale-bar-display=block] - Display of the decorative scale ruler; set to none for a text-only scale.
744
771
  * @csspart error - Visible localized message shown instead of `container` when `mapStyle` is
745
772
  * missing, the optional peer is unavailable, WebGL2 cannot be created, or map initialization
746
773
  * fails; the transition is announced through the shared light-DOM assertive region.
@@ -1149,7 +1176,7 @@ label?:string;
1149
1176
  /** Optional engine. Set before connecting; changes take effect after disconnect/reconnect.
1150
1177
  * `modular` loads `@aceshooting/lyra-map`; `maplibre` explicitly selects the full `maplibre-gl`
1151
1178
  * peer. No engine is substituted when the selected peer is unavailable. */
1152
- engine:LyraMapEngine;private loading;private failure?;private readonly announcements;private loadLibrary;private visible;private constructionScheduler?;private constructionMode;private constructionDelay?;private containerEl?;private anchorEl?;private anchorBoundaryEl?;private _map?;private _styleLoaded;private _appliedChoroplethSourceId?;private _appliedFillLayerId?;private _appliedDataLayerIds;private _appliedDataLayerShapes;private _appliedGeoJson;private _nextDataLayerId;private nextPointIconId;private appliedPointPaint;private appliedPointMuting;private appliedPointIcons;private _maplibreModule?;private _webglReady;private _markerInstances;private _markerLabels;private _markerPopupIds;private readonly markerActivationDetails;private _configuredPopups;private _nextPopupId;private peerChromeObserver?;private observedPeerContainer?;private mapResizeObserver?;private observedMapContainer?;private _markerColors;private _markerSources;private _connectGeneration;private _styleGeneration;private readonly readiness;private ownedFeatures?;private externalFeatures?;private externalFeatureWorkStarted;private externalIdStyle;private externalIdCounter;private readonly externalSourceIds;private readonly appliedGeoLabels;private readonly peerEvents;private optionalFeatureWorkStarted;
1179
+ engine:LyraMapEngine;private loading;private failure?;private readonly announcements;private loadLibrary;private visible;private constructionScheduler?;private constructionMode;private constructionDelay?;private containerEl?;private anchorEl?;private anchorBoundaryEl?;private _map?;private _styleLoaded;private _appliedChoroplethSourceId?;private _appliedFillLayerId?;private _appliedDataLayerIds;private _appliedDataLayerShapes;private _appliedGeoJson;private _nextDataLayerId;private nextPointIconId;private appliedPointPaint;private appliedPointMuting;private appliedPointIcons;private _maplibreModule?;private _webglReady;private _markerInstances;private _markerLabels;private _markerPopupIds;private readonly markerActivationDetails;private _configuredPopups;private _nextPopupId;private peerChromeObserver?;private observedPeerContainer?;private mapResizeObserver?;private observedMapContainer?;private _markerColors;private _markerSources;private _connectGeneration;private _styleGeneration;private readonly readiness;private readonly controlsReadiness;private ownedFeatures?;private externalFeatures?;private externalFeatureWorkStarted;private externalIdStyle;private externalIdCounter;private readonly externalSourceIds;private readonly appliedGeoLabels;private readonly peerEvents;private optionalFeatureWorkStarted;
1153
1180
  /** Explicit basemap layer opt-in; all other basemap features remain noninteractive. Each entry
1154
1181
  * names one layer by `layerId`, or selects every current style layer whose `source`,
1155
1182
  * `sourceLayer` and `layerType` match the fields it gives (for example
@@ -1185,6 +1212,16 @@ get map():LyraMapInstance|undefined;
1185
1212
  */
1186
1213
  whenStyleReady():Promise<void>;
1187
1214
  /**
1215
+ * Resolves after the current connection's configured native controls, including default
1216
+ * attribution unless disabled, are installed and their chrome is synchronized. Callable before
1217
+ * deferred construction, including initialization="interaction". An explicitly empty control
1218
+ * configuration resolves after construction. Rejects with AbortError on disconnect or controls
1219
+ * replacement, and MapReadinessError on initialization, invalid configuration or control loading
1220
+ * failure. Style-only changes preserve this barrier. A completed promise describes its captured
1221
+ * configuration; call again after assigning controls.
1222
+ */
1223
+ whenControlsReady():Promise<void>;
1224
+ /**
1188
1225
  * Resolves when the current style, camera, sources and component preparation are idle. Each
1189
1226
  * call checks current work; the first idle is not reused after a later update. Rejects with
1190
1227
  * AbortError on disconnect/style replacement and MapReadinessError on a current peer or
@@ -1349,7 +1386,7 @@ undoDrawing():boolean;
1349
1386
  completeDrawing():boolean;
1350
1387
  /** Cancels an armed or started drawing and clears its temporary resources and mode. An armed
1351
1388
  * mode whose drawing runtime is still loading is cancelled synchronously as well. */
1352
- cancelDrawing():boolean;private cancelMapDrawing;private resetDrawingMode;private syncDrawing;private drawingRuntime;private drawingHost;private showDrawingError;private drawingErrorMessage;private drawMapCenter;private cancelMapPick;private pickMapCenter;private handleMapInteraction;private cancelFeaturePreparation;private generatedFeatureRequirements;private externalSourceEffects?;private externalLayerInput;private dataLayerOrderGroups;private nativeLayerOrder;private applyDataLayerOrder;private reconcileGeneratedLayers;private resolveStyleOverride;private appliedChoroplethPaintKey?;private applyChoropleth;private choroplethColorExpression;private choroplethNoDataColor;private choroplethOutlineExpression;private resolveChoroplethSourceId;private removeChoropleth;private readonly appliedLayerPaintKeys;private readonly appliedRowRanges;private applyDataLayers;private applyDataLayerRange;private applyDataLayerRendering;private paintDataLayer;private applyGeoLabel;private applyGeometryLayers;private paintGeometryLayers;private lineColor;private mutedPointOpacity;private paintPoints;private pointIconColor;private removePointIcons;private applyPointIcons;private paintPointIcons;private clusterColorExpression;private applyClusterLayers;private paintClusterLayers;private applyHeatmapLayer;private paintHeatmapLayer;private heatmapColorExpression;private styleHasTextFonts;private styleProvidesGlyphs;private resolveDataLayerSourceId;private removeDataLayer;private applyMarkers;private readonly configuredMarkerElements;private configureMarkerInteraction;private emitMarkerActivation;private get effectiveMapLabel();private popupId;private configurePopupSemantics;private stopObservingMapAllocation;private observeMapAllocation;private stopObservingPeerChrome;private peerControlsResizeObserver?;private peerControlsResizeFrame?;private schedulePeerControlInsets;private measurePeerControlInsets;private syncPeerChromeParts;private observePeerChrome;private syncPopupSemantics;private syncMapSemantics;private formatDistance;private formatArea;private drawingSummary;private drawingLabelText;private formatCount;private legendLimitText;private onLegendSlotChange;
1389
+ cancelDrawing():boolean;private cancelMapDrawing;private resetDrawingMode;private syncDrawing;private drawingRuntime;private drawingHost;private showDrawingError;private drawingErrorMessage;private drawMapCenter;private cancelMapPick;private pickMapCenter;private handleMapInteraction;private cancelFeaturePreparation;private generatedFeatureRequirements;private externalSourceEffects?;private externalLayerInput;private dataLayerOrderGroups;private nativeLayerOrder;private applyDataLayerOrder;private reconcileGeneratedLayers;private resolveStyleOverride;private appliedChoroplethPaintKey?;private applyChoropleth;private choroplethColorExpression;private choroplethNoDataColor;private choroplethOutlineExpression;private resolveChoroplethSourceId;private removeChoropleth;private readonly appliedLayerPaintKeys;private readonly appliedRowRanges;private applyDataLayers;private applyDataLayerRange;private applyDataLayerRendering;private paintDataLayer;private applyGeoLabel;private applyGeometryLayers;private paintGeometryLayers;private lineColor;private mutedPointOpacity;private paintPoints;private pointIconColor;private removePointIcons;private applyPointIcons;private paintPointIcons;private clusterColorExpression;private applyClusterLayers;private paintClusterLayers;private applyHeatmapLayer;private paintHeatmapLayer;private heatmapColorExpression;private styleHasTextFonts;private styleProvidesGlyphs;private resolveDataLayerSourceId;private removeDataLayer;private applyMarkers;private readonly configuredMarkerElements;private configureMarkerInteraction;private emitMarkerActivation;private get effectiveMapLabel();private popupId;private configurePopupSemantics;private stopObservingMapAllocation;private observeMapAllocation;private stopObservingPeerChrome;private peerControlsResizeObserver?;private peerControlsResizeFrame?;private schedulePeerControlInsets;private measurePeerControlInsets;private syncPeerChromeParts;private syncPeerAttributionExpansion;private observePeerChrome;private syncPopupSemantics;private syncMapSemantics;private formatDistance;private formatArea;private drawingSummary;private drawingLabelText;private formatCount;private legendLimitText;private onLegendSlotChange;
1353
1390
  /**
1354
1391
  * The continuous gradient bar plus its two endpoint captions, or nothing when `legendGradient`
1355
1392
  * holds fewer than two usable stops. Part names mirror `lr-heatmap`'s