@aceshooting/lyra-ui 10.0.1 → 11.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/custom-elements.json +1 -1
  3. package/design-tokens.json +13 -0
  4. package/dist/cli/migrate-wa.mjs +164 -1
  5. package/dist/cli/migration-contract.json +1 -1
  6. package/dist/components/charts/chart/box-plot.class.d.ts +27 -0
  7. package/dist/components/charts/chart/box-plot.class.js +14 -4
  8. package/dist/components/charts/chart/box-plot.styles.js +28 -0
  9. package/dist/components/charts/chart/chart.class.d.ts +27 -0
  10. package/dist/components/charts/chart/chart.class.js +15 -5
  11. package/dist/components/charts/chart/chart.styles.js +28 -0
  12. package/dist/components/data/heatmap/heatmap.class.d.ts +35 -2
  13. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  14. package/dist/components/forms/combobox/combobox.class.d.ts +71 -3
  15. package/dist/components/forms/combobox/combobox.class.js +4 -2
  16. package/dist/components/forms/combobox/combobox.styles.js +9 -0
  17. package/dist/components/forms/date-picker/date-picker.class.d.ts +46 -0
  18. package/dist/components/forms/date-picker/date-picker.class.js +15 -3
  19. package/dist/components/forms/date-picker/date-picker.styles.js +46 -0
  20. package/dist/components/media/flag/flag.class.d.ts +3 -1
  21. package/dist/components/media/flag/flag.class.js +1 -1
  22. package/dist/components/media/map/map.class.d.ts +39 -2
  23. package/dist/components/media/map/map.class.js +1 -1
  24. package/dist/components/overlays/dialog/dialog.class.d.ts +20 -0
  25. package/dist/components/overlays/overlay/popover.class.d.ts +19 -3
  26. package/dist/components/overlays/overlay/popover.class.js +1 -1
  27. package/dist/custom-elements-jsx.d.ts +27 -14
  28. package/dist/internal/package-metadata.d.ts +1 -1
  29. package/dist/internal/package-metadata.js +1 -1
  30. package/dist/internal/tokens.styles.js +1 -0
  31. package/dist/lyra.d.ts +1 -1
  32. package/dist/svelte.d.ts +27 -14
  33. package/dist/vue.d.ts +27 -14
  34. package/llms/components/lr-bar-chart.md +4 -3
  35. package/llms/components/lr-box-plot.md +14 -3
  36. package/llms/components/lr-bubble-chart.md +4 -3
  37. package/llms/components/lr-chart.md +13 -3
  38. package/llms/components/lr-combobox.md +42 -6
  39. package/llms/components/lr-date-input.md +22 -2
  40. package/llms/components/lr-date-picker.md +23 -3
  41. package/llms/components/lr-dialog.md +2 -1
  42. package/llms/components/lr-doughnut-chart.md +4 -3
  43. package/llms/components/lr-flag.md +10 -3
  44. package/llms/components/lr-heatmap.md +20 -2
  45. package/llms/components/lr-histogram.md +4 -3
  46. package/llms/components/lr-line-chart.md +4 -3
  47. package/llms/components/lr-map.md +21 -4
  48. package/llms/components/lr-option.md +41 -5
  49. package/llms/components/lr-pie-chart.md +4 -3
  50. package/llms/components/lr-polar-area-chart.md +4 -3
  51. package/llms/components/lr-popover.md +20 -1
  52. package/llms/components/lr-radar-chart.md +4 -3
  53. package/llms/components/lr-scatter-chart.md +4 -3
  54. package/llms/tokens.md +15 -1
  55. package/llms-full.txt +197 -26
  56. package/package.json +1 -1
  57. package/vscode-css-data.json +56 -0
  58. package/vscode-html-data.json +115 -18
  59. package/web-types.json +162 -21
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import"./option.class.js";import{autocorrectConverter,omittedEmptyStringConverter,spellcheckConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{tag}from"../../../internal/prefix.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]),comboboxSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const MAX_SOURCE_ROWS=2e3,MAX_SOURCE_TEXT_UNITS=25e4,MAX_SOURCE_FIELD_UNITS=4096,MAX_RENDER_ROWS=1e3;function normalizeSourceResult(input){let candidateRows,candidateTotal;try{Array.isArray(input)?candidateRows=input:typeof input=="object"&&input!==null&&(candidateRows=input.rows,candidateTotal=input.total)}catch{throw new TypeError("Invalid combobox source result")}if(!Array.isArray(candidateRows))throw new TypeError("Invalid combobox source result");const providerTotal=typeof candidateTotal=="number"&&Number.isFinite(candidateTotal)&&candidateTotal>=0?Math.trunc(candidateTotal):candidateRows.length,rows=[];let textUnits=0;const limit=Math.min(candidateRows.length,MAX_SOURCE_ROWS);for(let index=0;index<limit;index++)try{const value=candidateRows[index]?.value,label=candidateRows[index]?.label;if(typeof value!="string"||typeof label!="string"||value.length>MAX_SOURCE_FIELD_UNITS||label.length>MAX_SOURCE_FIELD_UNITS)continue;const source=candidateRows[index],optionalText=key=>{const candidate=source[key];return typeof candidate=="string"&&candidate.length<=MAX_SOURCE_FIELD_UNITS?candidate:void 0},sub=optionalText("sub"),accessibleLabel=optionalText("accessibleLabel"),dotColor=optionalText("dotColor"),group=optionalText("group"),badgeCandidate=source.badge,badge=typeof badgeCandidate=="string"&&badgeCandidate.length<=MAX_SOURCE_FIELD_UNITS||typeof badgeCandidate=="number"&&Number.isFinite(badgeCandidate)?badgeCandidate:void 0,units=value.length+label.length+(sub?.length??0)+(accessibleLabel?.length??0)+(dotColor?.length??0)+(group?.length??0)+(typeof badge=="string"?badge.length:0);if(textUnits+units>MAX_SOURCE_TEXT_UNITS)break;textUnits+=units,rows.push({value,label,...sub===void 0?{}:{sub},...source.icon===void 0?{}:{icon:source.icon},...badge===void 0?{}:{badge},...accessibleLabel===void 0?{}:{accessibleLabel},...source.data===void 0?{}:{data:source.data},...dotColor===void 0?{}:{dotColor},...group===void 0?{}:{group},...typeof source.disabled=="boolean"?{disabled:source.disabled}:{}})}catch{}const total=Math.max(providerTotal,candidateRows.length);return{rows,total,truncated:total>rows.length}}class LyraCombobox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-change","input","change"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}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},maxRender:{type:Number,attribute:"max-render",noAccessor:!0},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=!0,this.query=next??"",this.activeIndex=-1,this.source&&this.runSource(this.query),this.requestUpdate()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.errorText="",this.allowCreate=!1,this.allowCustomValue=!1,this.appearance="outlined",this.placement="bottom",this.size="m",this.pill=!1,this.clearable=!1,this.withClear=!1,this.withLabel=!1,this.withHint=!1,this.validators=[],this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.filter=null,this.source=null,this.query="",this.explicitInputValue=!1,this.activeIndex=-1,this.options=[],this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.loading=!1,this.sourceFailed=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.sourceToken=0,this._sourceWarmed=!1,this._selectedLabelCache=new Map,this._selectedRowCache=new Map,this._rowsByValue=new Map,this._open=!1,this._fieldsetDisabled=!1,this.listId=nextId("combobox-list"),this.inputId=nextId("combobox-input"),this.restoreFocusOnClose=!0,this.restoringOverlayFocus=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.closeCleanupPending=!1,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._valueDirty=!1,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultCaptured=!1,this._restoredStateActive=!1,this._name="",this._maxOptionsVisible=3,this._maxRender=200,this._sourceDelay=200,this.collectOptions=e=>{const slot=e.target,previous=new Set(this.options);if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.normalizeActiveIndex(),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){const values=eligible.map(option=>option.value),next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];newLive.length>0?this.value=next:this.setValue(next,!1);return}}else{this._defaultCaptured=!0;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value),allLive=this.options.filter(option=>option.selected).map(option=>option.value),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtyValues=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected).map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];fromDefaults&&!optionDirty?this.setValue(next,!1):this.value=next;return}optionDirty&&(this._valueDirty=!0)}this.reflectSelected()},this.onOptionChange=e=>{e.stopPropagation(),queueMicrotask(()=>{this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.normalizeActiveIndex()})},this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onInput=e=>{this.liveDisabled||(this.explicitInputValue=!1,this.query=e.target.value,this.activeIndex=-1,this.show(),this.source&&this.runSource(this.query),this.emit("lr-filter",{value:this.query}))},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.restoreFocusOnClose=!1,this.hide(),relayNativeEvent(this,event)},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.restoringOverlayFocus||this.show(),relayNativeEvent(this,event)},this.onKeyDown=e=>{if(this.liveDisabled)return;const navigable=this.renderedRows.rows.filter(r=>!r.disabled);switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open){this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":if(e.preventDefault(),!this.open){this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault(),this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault(),this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault(),this.commitCustomValue(this.query.trim());break}submitOnEnter(this,e);break}case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.activeIndex=0);break;case"End":this.open&&(e.preventDefault(),this.activeIndex=navigable.length-1);break;case"Backspace":this.multiple&&!this.query&&this._selected.length&&this.removeValue(this._selected[this._selected.length-1]);break}},this.onComboMouseDown=e=>{this.liveDisabled||e.composedPath()[0]!==this.inputEl&&(e.target.closest("button")||(e.preventDefault(),this.inputEl?.focus(),this.show()))},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const value=e.target.closest('[part="option"]')?.dataset.value;if(value===void 0)return;const row=this._rowsByValue.get(value);row&&this.pickRow(row)},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init))}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value)}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){this.liveDisabled||(this.inputEl?.focus(),this.show())}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.explicitInputValue=!0,this.query=input.value,this.activeIndex=-1,this.source&&this.runSource(this.query))}[VALIDITY_ANCHOR](){return this.validationTarget}connectedCallback(){super.connectedCallback(),this.syncSourceErrorAnnouncementSink(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.hasUpdated&&queueMicrotask(()=>{this.open?this.reconnectOpenPopup():this.source&&this._selected.length&&this.asyncRows.length===0&&this.runSource("")})}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.releaseSourceErrorAnnouncementSink(),this.syncSourceErrorAnnouncementSink()}syncSourceErrorAnnouncementSink(){this.isConnected&&this.sourceErrorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseSourceErrorAnnouncementSink(),this.sourceErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseSourceErrorAnnouncementSink(){this.sourceErrorAnnouncementSink?.release(),this.sourceErrorAnnouncementSink=void 0}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.announceOpenTransition(changed),changed.has("open")&&this.openVetoed?this.closeCleanupPending=!1:changed.has("open")&&!this.open&&this.finalizeCloseState(),changed.has("source")&&(this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceToken++,this.loading=!1,this.sourceFailed=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this._sourceWarmed=!1,this.source&&this.open&&this.runSource(this.query)),!this._sourceWarmed&&this.source&&this._selected.length&&this.asyncRows.length===0&&(this._sourceWarmed=!0,this.runSource(""))}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),this.syncFormValue(),this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,!0)}setValue(next,dirty){const old=this._selected;dirty&&(this._restoredStateActive=!1,this._valueDirty=!0),this._selected=Array.isArray(next)?[...next]:next?[next]:[];const selected=new Set(this._selected);for(const value of selected){const row=this.effectiveRows.find(candidate=>candidate.value===value)??this.asyncRows.find(candidate=>candidate.value===value);row&&this._selectedRowCache.set(value,row)}for(const value of this._selectedRowCache.keys())selected.has(value)||this._selectedRowCache.delete(value);for(const value of this._selectedLabelCache.keys())selected.has(value)||this._selectedLabelCache.delete(value);this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200),this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=Math.min(finiteCount(next,200),MAX_RENDER_ROWS),this.requestUpdate("maxRender",old)}get sourceTotal(){return this._sourceTotal}get sourceTruncated(){return this._sourceTruncated}get selectedRows(){return this._selected.map(value=>this._selectedRowCache.get(value)??this.effectiveRows.find(row=>row.value===value)??this.asyncRows.find(row=>row.value===value)).filter(row=>row!=null).map(row=>({...row}))}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}result=typeof validator=="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.syncCustomStates();return}const flags={};let message="";this.required&&this._selected.length===0&&(flags.valueMissing=!0,message=this.localize("comboboxRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else this.internals.setFormValue(this._selected[0]??"",state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);this._defaultSelected.length===0&&resetValues.length>0&&(this._defaultSelected=[...resetValues]);const defaults=new Set(resetValues);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value));this.setValue(this.multiple?[...resetValues]:resetValues[0]??"",!1),this.query="",this.explicitInputValue=!1}formStateRestoreCallback(state2,reason){let selected=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(selected=parsed)}catch{}this.value=this.multiple?selected:selected[0]??"",this._restoredStateActive=!0}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates()}disconnectedCallback(){this.transitionToken++,this.releaseSourceErrorAnnouncementSink(),this.disconnectValidatorAttributeObserver(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),this.open=!1}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1),!this._valueDirty&&!this._restoredStateActive&&this.setValue(this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",!1)}reflectSelected(){const sel=new Set(this._selected);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](sel.has(option.value))}labelFor(value){return this._selectedLabelCache.get(value)??this.options.find(o=>o.value===value)?.label??this.asyncRows.find(r=>r.value===value)?.label??value}get effectiveRows(){return this.source?this.asyncRows:this.filtered.map(o=>({value:o.value,label:o.label,sub:o.sub||void 0,dotColor:o.dotColor||void 0,group:o.group||void 0,disabled:o.disabled}))}get createRow(){if(!this.allowCreate)return;const inputValue=this.query.trim();if(!inputValue)return;const locale=this.effectiveLocale,folded=inputValue.toLocaleLowerCase(locale);if(!(this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}))).some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded))return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}get renderedRows(){const all=this.effectiveRows,create=this.createRow,sourceOverflow=this.source?Math.max(0,this._sourceTotal-all.length):0;if(all.length<=this.maxRender)return{rows:create?[...all,create]:all,overflow:sourceOverflow};const originalIndex=new Map(all.map((r,i)=>[r,i])),capped=all.slice(0,this.maxRender),cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=!1;for(const v of this._selected)if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);selectedRow&&(capped.push(selectedRow),appendedOutOfCap=!0)}return appendedOutOfCap&&capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b)),create&&capped.push(create),{rows:capped,overflow:all.length-capped.length+(create?1:0)+sourceOverflow}}normalizeActiveIndex(){if(this.activeIndex<0)return;const navigableCount=this.renderedRows.rows.filter(row=>!row.disabled).length,next=navigableCount>0?Math.min(this.activeIndex,navigableCount-1):-1;next!==this.activeIndex&&(this.activeIndex=next)}get filtered(){const locale=this.effectiveLocale,q=this.query.trim().toLocaleLowerCase(locale),selectedLabel=this.multiple?"":this.labelFor(this._selected[0]??"")??"",effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){return this.multiple||this.open||this.explicitInputValue?this.query:this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open,this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show"))}show(){if(this.open||this.liveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.closeCleanupPending=!0,this.open=!1,settled}finalizeCloseState(){if(this.closeCleanupPending&&(this.closeCleanupPending=!1,this.activeIndex=-1,!this.multiple)){const queryChanged=this.query!=="";this.query="",this.explicitInputValue=!1,queryChanged&&this.source&&(this.asyncRows=[],this.sourceFailed=!1,this._sourceTotal=0,this._sourceTruncated=!1)}}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.inputEl??null,modal:!1,trapFocus:!1}),this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="combobox"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`}))}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.restoringOverlayFocus=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.restoringOverlayFocus=!1}this.overlayHandle=void 0,this.unbindDocumentPointer(),this.restoreFocusOnClose=!0}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener,!0)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener,!0),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){!this.isConnected||!this.open||(this.activateListboxOverlay(),this.source&&this.asyncRows.length===0&&this.runSource(this.query))}updated(changed){super.updated(changed),changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-show"),this.source&&this.asyncRows.length===0&&this.runSource(this.query)):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed&&(this.restoreFocusOnClose=!0),changed.has("name")&&this.syncFormValue(),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("validators")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("activeIndex")&&this.renderRoot.querySelector('[part="option"][data-active]')?.scrollIntoView({block:"nearest"})}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}emitValueEvents(){this.emit("input",{value:this.value}),this.emit("change",{value:this.value}),this.emit("lr-change",{value:this.value})}createOption(inputValue){if(this.liveDisabled||this.emit("lr-create",{inputValue},{cancelable:!0}).defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue),option.textContent=inputValue,this.append(option),this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.liveDisabled||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this._selectedLabelCache.set(inputValue,inputValue),this.value=inputValue,this.query="",this.explicitInputValue=!1,this.hide(),selectionChanged&&this.emitValueEvents()}pickRow(row){if(this.liveDisabled||row.disabled)return;if(row.createInput!==void 0){this.createOption(row.createInput);return}const selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);set.has(row.value)?(set.delete(row.value),this._selectedRowCache.delete(row.value)):(set.add(row.value),this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.set(row.value,row)),this.value=[...set],this.query="",this.explicitInputValue=!1}else this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.clear(),this._selectedRowCache.set(row.value,row),this.value=row.value,this.query="",this.explicitInputValue=!1,this.hide();this.source&&this.runSource(this.query),selectionChanged&&this.emitValueEvents()}removeValue(value){if(this.liveDisabled)return;const next=this._selected.filter(v=>v!==value);next.length!==this._selected.length&&(this.value=next,this.emitValueEvents())}clear(){if(this.liveDisabled)return;const hadSelection=this._selected.length>0,queryChanged=this.query!=="";!hadSelection&&!queryChanged||(hadSelection&&(this.value=[]),this.query="",this.explicitInputValue=!1,this.source&&this.runSource(this.query),hadSelection&&(this.emitValueEvents(),this.emit("lr-clear")),queryChanged&&this.emit("lr-filter",{value:this.query}))}runSource(query2){const source=this.source;if(!source)return;this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0;const token=++this.sourceToken,ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const timer={owner:ownerWindow,handle:0,token};timer.handle=ownerWindow.setTimeout(()=>{if(this.sourceTimer!==timer||token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;this.sourceTimer=void 0;const controller=new ownerWindow.AbortController;this.sourceAbort=controller,this.loading=!0,this.sourceFailed=!1,Promise.resolve().then(()=>source(query2,{signal:controller.signal,limit:MAX_SOURCE_ROWS})).then(result=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const normalized=normalizeSourceResult(result);this._sourceTotal=normalized.total,this._sourceTruncated=normalized.truncated,this.asyncRows=normalized.rows,this.sourceFailed=!1,this.normalizeActiveIndex();const selected=new Set(this._selected);for(const row of normalized.rows)selected.has(row.value)&&this._selectedRowCache.set(row.value,row)}).catch(err=>{token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||typeof err=="object"&&err!==null&&"name"in err&&err.name==="AbortError"||(this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this.sourceFailed=!0,this.sourceErrorAnnouncementSink?.announce(this.localize("comboboxLoadError")),console.warn("<lr-combobox> source() rejected:",err))}).finally(()=>{token===this.sourceToken&&(this.loading=!1)})},this._sourceDelay),this.sourceTimer=timer}clearSourceTimer(){const timer=this.sourceTimer;this.sourceTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}renderRows(rows,activeId){const out=[];let currentGroup,currentGroupRows=[],groupIndex=0;const selectedSet=new Set(this._selected),flushGroup=()=>{if(currentGroupRows.length){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{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{place}from"../../../internal/positioner.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{finiteCount,finiteDuration}from"../../../internal/numbers.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./combobox.styles.js";import"./option.class.js";import{autocorrectConverter,omittedEmptyStringConverter,spellcheckConverter}from"../../../internal/converters.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{tag}from"../../../internal/prefix.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{isHtmlElement}from"../../../internal/dom-guards.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_comboboxCreate,LYRA_DEFAULT_comboboxLabel,LYRA_DEFAULT_comboboxLoadError,LYRA_DEFAULT_comboboxOverflow,LYRA_DEFAULT_comboboxRequired,LYRA_DEFAULT_comboboxSelectedOverflow,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";function isLyraOptionElement(value){return isHtmlElement(value)&&value.localName===tag("option")}const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]),comboboxSpellcheckConverter={...spellcheckConverter,fromAttribute:(value,type)=>value===null?void 0:spellcheckConverter.fromAttribute?.(value,type)};function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const MAX_SOURCE_ROWS=2e3,MAX_SOURCE_TEXT_UNITS=25e4,MAX_SOURCE_FIELD_UNITS=4096,MAX_RENDER_ROWS=1e3;function normalizeSourceResult(input){let candidateRows,candidateTotal;try{Array.isArray(input)?candidateRows=input:typeof input=="object"&&input!==null&&(candidateRows=input.rows,candidateTotal=input.total)}catch{throw new TypeError("Invalid combobox source result")}if(!Array.isArray(candidateRows))throw new TypeError("Invalid combobox source result");const providerTotal=typeof candidateTotal=="number"&&Number.isFinite(candidateTotal)&&candidateTotal>=0?Math.trunc(candidateTotal):candidateRows.length,rows=[];let textUnits=0;const limit=Math.min(candidateRows.length,MAX_SOURCE_ROWS);for(let index=0;index<limit;index++)try{const value=candidateRows[index]?.value,label=candidateRows[index]?.label;if(typeof value!="string"||typeof label!="string"||value.length>MAX_SOURCE_FIELD_UNITS||label.length>MAX_SOURCE_FIELD_UNITS)continue;const source=candidateRows[index],optionalText=key=>{const candidate=source[key];return typeof candidate=="string"&&candidate.length<=MAX_SOURCE_FIELD_UNITS?candidate:void 0},sub=optionalText("sub"),accessibleLabel=optionalText("accessibleLabel"),dotColor=optionalText("dotColor"),group=optionalText("group"),badgeCandidate=source.badge,badge=typeof badgeCandidate=="string"&&badgeCandidate.length<=MAX_SOURCE_FIELD_UNITS||typeof badgeCandidate=="number"&&Number.isFinite(badgeCandidate)?badgeCandidate:void 0,units=value.length+label.length+(sub?.length??0)+(accessibleLabel?.length??0)+(dotColor?.length??0)+(group?.length??0)+(typeof badge=="string"?badge.length:0);if(textUnits+units>MAX_SOURCE_TEXT_UNITS)break;textUnits+=units,rows.push({value,label,...sub===void 0?{}:{sub},...source.icon===void 0?{}:{icon:source.icon},...source.start===void 0?{}:{start:source.start},...source.end===void 0?{}:{end:source.end},...badge===void 0?{}:{badge},...accessibleLabel===void 0?{}:{accessibleLabel},...source.data===void 0?{}:{data:source.data},...dotColor===void 0?{}:{dotColor},...group===void 0?{}:{group},...typeof source.disabled=="boolean"?{disabled:source.disabled}:{}})}catch{}const total=Math.max(providerTotal,candidateRows.length);return{rows,total,truncated:total>rows.length}}class LyraCombobox extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,comboboxCreate:LYRA_DEFAULT_comboboxCreate,comboboxLabel:LYRA_DEFAULT_comboboxLabel,comboboxLoadError:LYRA_DEFAULT_comboboxLoadError,comboboxOverflow:LYRA_DEFAULT_comboboxOverflow,comboboxRequired:LYRA_DEFAULT_comboboxRequired,comboboxSelectedOverflow:LYRA_DEFAULT_comboboxSelectedOverflow,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-change","input","change"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}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},maxRender:{type:Number,attribute:"max-render",noAccessor:!0},sourceDelay:{type:Number,attribute:"source-delay",noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=!!next,this.requestUpdate()}get inputmode(){return this.inputMode}set inputmode(next){this.inputMode=next??""}get enterkeyhint(){return this.enterKeyHint}set enterkeyhint(next){this.enterKeyHint=next??""}get inputValue(){return this.query}set inputValue(next){this.explicitInputValue=!0,this.query=next??"",this.activeIndex=-1,this.source&&this.runSource(this.query),this.requestUpdate()}constructor(){super(),this.placeholder="",this.label="",this.hint="",this.errorText="",this.allowCreate=!1,this.allowCustomValue=!1,this.appearance="outlined",this.placement="bottom",this.size="m",this.pill=!1,this.clearable=!1,this.withClear=!1,this.withLabel=!1,this.withHint=!1,this.validators=[],this.autocomplete="off",this.inputMode="",this.enterKeyHint="",this.spellcheck=!1,this.autocapitalize="",this.autocorrectValue=!0,this.filter=null,this.source=null,this.query="",this.explicitInputValue=!1,this.activeIndex=-1,this.options=[],this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.loading=!1,this.sourceFailed=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.sourceToken=0,this._sourceWarmed=!1,this._selectedLabelCache=new Map,this._selectedRowCache=new Map,this._rowsByValue=new Map,this._open=!1,this._fieldsetDisabled=!1,this.listId=nextId("combobox-list"),this.inputId=nextId("combobox-input"),this.restoreFocusOnClose=!0,this.restoringOverlayFocus=!1,this._isFirstUpdate=!0,this.openVetoed=!1,this.closeCleanupPending=!1,this.transitionToken=0,this.transitionWaiters=new Map,this._selected=[],this._valueDirty=!1,this._multiple=!1,this._disabled=!1,this._required=!1,this._defaultSelected=[],this._defaultCaptured=!1,this._restoredStateActive=!1,this._name="",this._maxOptionsVisible=3,this._maxRender=200,this._sourceDelay=200,this.collectOptions=e=>{const slot=e.target,previous=new Set(this.options);if(this.options=slot.assignedElements({flatten:!0}).filter(isLyraOptionElement),this.adornmentClones=new WeakMap,this.normalizeActiveIndex(),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){const values=eligible.map(option=>option.value),next=this.multiple?[...new Set([...this._selected,...values])]:values[values.length-1];newLive.length>0?this.value=next:this.setValue(next,!1);return}}else{this._defaultCaptured=!0;const allDefaults=this.options.filter(option=>option.defaultSelected).map(option=>option.value),allLive=this.options.filter(option=>option.selected).map(option=>option.value),defaults=this.multiple?allDefaults:allDefaults.slice(0,1),live=this.multiple?allLive:allLive.slice(0,1),initialLive=this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value),optionDirty=this.options.some(option=>isOptionSelectedDirty(option)),dirtyValues=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected).map(option=>option.value);this._defaultSelected=[...defaults.length>0?defaults:initialLive.length>0?initialLive:live];const fromDefaults=defaults.length>0,initial=optionDirty?this.multiple?allLive:dirtyValues.slice(-1)[0]?dirtyValues.slice(-1):live:fromDefaults?defaults:live;if(initial.length&&!this._restoredStateActive&&!this._valueDirty){const next=this.multiple?initial:initial[0];fromDefaults&&!optionDirty?this.setValue(next,!1):this.value=next;return}optionDirty&&(this._valueDirty=!0)}this.reflectSelected()},this.onOptionChange=e=>{e.stopPropagation(),queueMicrotask(()=>{this.refreshOptionDefaults(),this.reflectSelected(),this.options=[...this.options],this.normalizeActiveIndex()})},this.adornmentClones=new WeakMap,this.onDocPointer=e=>{if(!e.composedPath().includes(this)){if(this.overlayHandle?.isActive()){this.overlayHandle.dismissBackdrop();return}this.restoreFocusOnClose=!1,this.hide()}},this.onInput=e=>{this.liveDisabled||(this.explicitInputValue=!1,this.query=e.target.value,this.activeIndex=-1,this.show(),this.source&&this.runSource(this.query),this.emit("lr-filter",{value:this.query}))},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.restoreFocusOnClose=!1,this.hide(),relayNativeEvent(this,event)},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}this.restoringOverlayFocus||this.show(),relayNativeEvent(this,event)},this.onKeyDown=e=>{if(this.liveDisabled)return;const navigable=this.renderedRows.rows.filter(r=>!r.disabled);switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open){this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":if(e.preventDefault(),!this.open){this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":{const activeRow=navigable[this.activeIndex];if(this.open&&this.activeIndex>=0&&activeRow){e.preventDefault(),this.pickRow(activeRow);break}const create=this.createRow;if(this.open&&create){e.preventDefault(),this.createOption(create.createInput);break}if(this.open&&this.allowCustomValue&&!this.multiple&&this.query.trim()){e.preventDefault(),this.commitCustomValue(this.query.trim());break}submitOnEnter(this,e);break}case"Escape":this.open&&(!this.overlayHandle?.isActive()||this.overlayHandle.isTopmost())&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.activeIndex=0);break;case"End":this.open&&(e.preventDefault(),this.activeIndex=navigable.length-1);break;case"Backspace":this.multiple&&!this.query&&this._selected.length&&this.removeValue(this._selected[this._selected.length-1]);break}},this.onComboMouseDown=e=>{this.liveDisabled||e.composedPath()[0]!==this.inputEl&&(e.target.closest("button")||(e.preventDefault(),this.inputEl?.focus(),this.show()))},this.onListboxMouseDown=e=>{e.preventDefault()},this.onListboxClick=e=>{const value=e.target.closest('[part="option"]')?.dataset.value;if(value===void 0)return;const row=this._rowsByValue.get(value);row&&this.pickRow(row)},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init))}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get validationTarget(){return this.validationTargetOverride??this.inputEl??void 0}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity()}get input(){return this.inputEl??null}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){this.inputEl&&(this.inputEl.selectionStart=value)}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){this.inputEl&&(this.inputEl.selectionEnd=value)}get selectionDirection(){return this.inputEl?.selectionDirection}set selectionDirection(value){this.inputEl&&(this.inputEl.selectionDirection=value)}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}click(){this.liveDisabled||(this.inputEl?.focus(),this.show())}select(){this.inputEl?.select()}setSelectionRange(start,end,direction){this.inputEl?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputEl;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.explicitInputValue=!0,this.query=input.value,this.activeIndex=-1,this.source&&this.runSource(this.query))}[VALIDITY_ANCHOR](){return this.validationTarget}connectedCallback(){super.connectedCallback(),this.syncSourceErrorAnnouncementSink(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.hasUpdated&&queueMicrotask(()=>{this.open?this.reconnectOpenPopup():this.source&&this._selected.length&&this.asyncRows.length===0&&this.runSource("")})}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.releaseSourceErrorAnnouncementSink(),this.syncSourceErrorAnnouncementSink()}syncSourceErrorAnnouncementSink(){this.isConnected&&this.sourceErrorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseSourceErrorAnnouncementSink(),this.sourceErrorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseSourceErrorAnnouncementSink(){this.sourceErrorAnnouncementSink?.release(),this.sourceErrorAnnouncementSink=void 0}willUpdate(changed){super.willUpdate(changed),this._isFirstUpdate=!this.hasUpdated,this.announceOpenTransition(changed),changed.has("open")&&this.openVetoed?this.closeCleanupPending=!1:changed.has("open")&&!this.open&&this.finalizeCloseState(),changed.has("source")&&(this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0,this.sourceToken++,this.loading=!1,this.sourceFailed=!1,this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this._sourceWarmed=!1,this.source&&this.open&&this.runSource(this.query)),!this._sourceWarmed&&this.source&&this._selected.length&&this.asyncRows.length===0&&(this._sourceWarmed=!0,this.runSource(""))}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormValue(),this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=!!next,this.toggleAttribute("multiple",this._multiple),this.syncFormValue(),this.requestUpdate("multiple",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this.setValue(next,!0)}setValue(next,dirty){const old=this._selected;dirty&&(this._restoredStateActive=!1,this._valueDirty=!0),this._selected=Array.isArray(next)?[...next]:next?[next]:[];const selected=new Set(this._selected);for(const value of selected){const row=this.effectiveRows.find(candidate=>candidate.value===value)??this.asyncRows.find(candidate=>candidate.value===value);row&&this._selectedRowCache.set(value,row)}for(const value of this._selectedRowCache.keys())selected.has(value)||this._selectedRowCache.delete(value);for(const value of this._selectedLabelCache.keys())selected.has(value)||this._selectedLabelCache.delete(value);this.syncFormValue(),this.reflectSelected(),this.updateValidity(),this.requestUpdate("value",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3),this.requestUpdate("maxOptionsVisible",old)}get maxRender(){return this._maxRender}get sourceDelay(){return this._sourceDelay}set sourceDelay(next){const old=this._sourceDelay;this._sourceDelay=finiteDuration(next,200),this.requestUpdate("sourceDelay",old)}set maxRender(next){const old=this._maxRender;this._maxRender=Math.min(finiteCount(next,200),MAX_RENDER_ROWS),this.requestUpdate("maxRender",old)}get sourceTotal(){return this._sourceTotal}get sourceTruncated(){return this._sourceTruncated}get selectedRows(){return this._selected.map(value=>this._selectedRowCache.get(value)??this.effectiveRows.find(row=>row.value===value)??this.asyncRows.find(row=>row.value===value)).filter(row=>row!=null).map(row=>({...row}))}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}result=typeof validator=="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.syncCustomStates();return}const flags={};let message="";this.required&&this._selected.length===0&&(flags.valueMissing=!0,message=this.localize("comboboxRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.syncCustomStates()}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._selected.length===0),setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormValue(){const state2=JSON.stringify(this._selected);if(this.multiple){if(!this.name){this.internals.setFormValue(null,state2);return}const fd=new FormData;for(const v of this._selected)fd.append(this.name,v);this.internals.setFormValue(fd,state2)}else this.internals.setFormValue(this._selected[0]??"",state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=!1,this._restoredStateActive=!1,this._valueDirty=!1;const resetValues=this._defaultSelected.length>0?this._defaultSelected:this.options.filter(option=>wasOptionInitiallySelected(option)).map(option=>option.value);this._defaultSelected.length===0&&resetValues.length>0&&(this._defaultSelected=[...resetValues]);const defaults=new Set(resetValues);for(const option of this.options)option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option.value));this.setValue(this.multiple?[...resetValues]:resetValues[0]??"",!1),this.query="",this.explicitInputValue=!1}formStateRestoreCallback(state2,reason){let selected=[];if(typeof state2=="string")try{const parsed=JSON.parse(state2);Array.isArray(parsed)&&parsed.every(value=>typeof value=="string")&&(selected=parsed)}catch{}this.value=this.multiple?selected:selected[0]??"",this._restoredStateActive=!0}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.syncCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.syncCustomStates()}disconnectedCallback(){this.transitionToken++,this.releaseSourceErrorAnnouncementSink(),this.disconnectValidatorAttributeObserver(),super.disconnectedCallback(),this.cleanup?.(),this.cleanup=void 0,this.clearSourceTimer(),this.sourceToken+=1,this.sourceAbort?.abort(),this.sourceAbort=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindDocumentPointer(),this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide"),this.open=!1}refreshOptionDefaults(){const declared=this.options.filter(option=>option.defaultSelected).map(option=>option.value);this._defaultSelected=this.multiple?declared:declared.slice(0,1),!this._valueDirty&&!this._restoredStateActive&&this.setValue(this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"",!1)}reflectSelected(){const sel=new Set(this._selected);for(const option of this.options)option[SET_OPTION_SELECTED_FROM_OWNER](sel.has(option.value))}labelFor(value){return this._selectedLabelCache.get(value)??this.options.find(o=>o.value===value)?.label??this.asyncRows.find(r=>r.value===value)?.label??value}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={start:cloneSlot(':scope > [slot="start"], :scope > [slot="prefix"]'),end:cloneSlot(':scope > [slot="end"], :scope > [slot="suffix"]')};return this.adornmentClones.set(option,resolved),resolved}get effectiveRows(){return this.source?this.asyncRows:this.filtered.map(o=>{const adornments=this.adornmentsFor(o);return{value:o.value,label:o.label,sub:o.sub||void 0,dotColor:o.dotColor||void 0,group:o.group||void 0,disabled:o.disabled,...adornments.start===void 0?{}:{start:adornments.start},...adornments.end===void 0?{}:{end:adornments.end}}})}get createRow(){if(!this.allowCreate)return;const inputValue=this.query.trim();if(!inputValue)return;const locale=this.effectiveLocale,folded=inputValue.toLocaleLowerCase(locale);if(!(this.source?this.asyncRows:this.options.map(option=>({value:option.value,label:option.label}))).some(row=>row.value.toLocaleLowerCase(locale)===folded||row.label.toLocaleLowerCase(locale)===folded))return{value:inputValue,label:this.localize("comboboxCreate",void 0,{value:inputValue}),createInput:inputValue}}get renderedRows(){const all=this.effectiveRows,create=this.createRow,sourceOverflow=this.source?Math.max(0,this._sourceTotal-all.length):0;if(all.length<=this.maxRender)return{rows:create?[...all,create]:all,overflow:sourceOverflow};const originalIndex=new Map(all.map((r,i)=>[r,i])),capped=all.slice(0,this.maxRender),cappedValues=new Set(capped.map(r=>r.value));let appendedOutOfCap=!1;for(const v of this._selected)if(!cappedValues.has(v)){const selectedRow=all.find(r=>r.value===v);selectedRow&&(capped.push(selectedRow),appendedOutOfCap=!0)}return appendedOutOfCap&&capped.sort((a,b)=>originalIndex.get(a)-originalIndex.get(b)),create&&capped.push(create),{rows:capped,overflow:all.length-capped.length+(create?1:0)+sourceOverflow}}normalizeActiveIndex(){if(this.activeIndex<0)return;const navigableCount=this.renderedRows.rows.filter(row=>!row.disabled).length,next=navigableCount>0?Math.min(this.activeIndex,navigableCount-1):-1;next!==this.activeIndex&&(this.activeIndex=next)}get filtered(){const locale=this.effectiveLocale,q=this.query.trim().toLocaleLowerCase(locale),selectedLabel=this.multiple?"":this.labelFor(this._selected[0]??"")??"",effective=q&&q===selectedLabel.toLocaleLowerCase(locale)?"":q;if(!effective)return this.options;const fn=this.filter??((o,query2)=>o.label.toLocaleLowerCase(locale).includes(query2)||o.searchText.toLocaleLowerCase(locale).includes(query2));return this.options.filter(o=>fn(o,effective))}get displayValue(){return this.multiple||this.open||this.explicitInputValue?this.query:this._selected[0]?this.labelFor(this._selected[0]):""}announceOpenTransition(changed){if(this.openVetoed=!1,!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}this.emit(name,null,{cancelable:!0}).defaultPrevented&&(this.openVetoed=!0,this.open=!this.open,this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show"))}show(){if(this.open||this.liveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.closeCleanupPending=!0,this.open=!1,settled}finalizeCloseState(){if(this.closeCleanupPending&&(this.closeCleanupPending=!1,this.activeIndex=-1,!this.multiple)){const queryChanged=this.query!=="";this.query="",this.explicitInputValue=!1,queryChanged&&this.source&&(this.asyncRows=[],this.sourceFailed=!1,this._sourceTotal=0,this._sourceTruncated=!1)}}activateListboxOverlay(){this.cleanup?.(),this.cleanup=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.restoreFocusOnClose=!0,this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="listbox"]'),onEscape:()=>{this.hide()},onBackdrop:()=>{this.restoreFocusOnClose=!1,this.hide()},restoreFocusTo:this.inputEl??null,modal:!1,trapFocus:!1}),this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="combobox"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox,{placement:`${this.placement}-start`}))}teardownListboxOverlay(restoreFocus=this.restoreFocusOnClose){this.cleanup?.(),this.cleanup=void 0,this.restoringOverlayFocus=restoreFocus;try{this.overlayHandle?.deactivate({restoreFocus})}finally{this.restoringOverlayFocus=!1}this.overlayHandle=void 0,this.unbindDocumentPointer(),this.restoreFocusOnClose=!0}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener,!0)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener,!0),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){!this.isConnected||!this.open||(this.activateListboxOverlay(),this.source&&this.asyncRows.length===0&&this.runSource(this.query))}syncVisibleOptionsCap(){const listbox=this.renderRoot?.querySelector('[part="listbox"]');if(!listbox)return;const clear=()=>{listbox.style.removeProperty("max-block-size")},requested=typeof this.visibleOptions=="number"?finiteCount(this.visibleOptions,0):0;if(requested<=0)return clear();const rows=listbox.querySelectorAll('[part="option"]');if(rows.length<=requested)return clear();const boundary=rows[requested];if(!boundary)return clear();const cap=boundary.getBoundingClientRect().top-listbox.getBoundingClientRect().top;if(!Number.isFinite(cap)||cap<=0)return clear();listbox.style.setProperty("max-block-size",`min(${Math.ceil(cap)}px, var(--lr-positioner-available-block-size, var(--lr-size-18rem)))`)}updated(changed){super.updated(changed),this.syncVisibleOptionsCap(),changed.has("open")&&!this.openVetoed?this.open&&this.isConnected?(this.activateListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-show"),this.source&&this.asyncRows.length===0&&this.runSource(this.query)):this.open?this.teardownListboxOverlay(!1):(this.teardownListboxOverlay(),this._isFirstUpdate||this.settleTransition("lr-after-hide")):changed.has("open")&&this.openVetoed&&(this.restoreFocusOnClose=!0),changed.has("name")&&this.syncFormValue(),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("validators")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid),changed.has("activeIndex")&&this.renderRoot.querySelector('[part="option"][data-active]')?.scrollIntoView({block:"nearest"})}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="listbox"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}emitValueEvents(){this.emit("input",{value:this.value}),this.emit("change",{value:this.value}),this.emit("lr-change",{value:this.value})}createOption(inputValue){if(this.liveDisabled||this.emit("lr-create",{inputValue},{cancelable:!0}).defaultPrevented)return;const option=this.ownerDocument.createElement(tag("option"));option.setAttribute("value",inputValue),option.textContent=inputValue,this.append(option),this.pickRow({value:inputValue,label:inputValue})}commitCustomValue(inputValue){if(this.liveDisabled||this.multiple||!inputValue)return;const selectionChanged=this._selected[0]!==inputValue;this._selectedLabelCache.set(inputValue,inputValue),this.value=inputValue,this.query="",this.explicitInputValue=!1,this.hide(),selectionChanged&&this.emitValueEvents()}pickRow(row){if(this.liveDisabled||row.disabled)return;if(row.createInput!==void 0){this.createOption(row.createInput);return}const selectionChanged=this.multiple||this._selected[0]!==row.value;if(this.multiple){const set=new Set(this._selected);set.has(row.value)?(set.delete(row.value),this._selectedRowCache.delete(row.value)):(set.add(row.value),this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.set(row.value,row)),this.value=[...set],this.query="",this.explicitInputValue=!1}else this._selectedLabelCache.set(row.value,row.label),this._selectedRowCache.clear(),this._selectedRowCache.set(row.value,row),this.value=row.value,this.query="",this.explicitInputValue=!1,this.hide();this.source&&this.runSource(this.query),selectionChanged&&this.emitValueEvents()}removeValue(value){if(this.liveDisabled)return;const next=this._selected.filter(v=>v!==value);next.length!==this._selected.length&&(this.value=next,this.emitValueEvents())}clear(){if(this.liveDisabled)return;const hadSelection=this._selected.length>0,queryChanged=this.query!=="";!hadSelection&&!queryChanged||(hadSelection&&(this.value=[]),this.query="",this.explicitInputValue=!1,this.source&&this.runSource(this.query),hadSelection&&(this.emitValueEvents(),this.emit("lr-clear")),queryChanged&&this.emit("lr-filter",{value:this.query}))}runSource(query2){const source=this.source;if(!source)return;this.clearSourceTimer(),this.sourceAbort?.abort(),this.sourceAbort=void 0;const token=++this.sourceToken,ownerWindow=this.ownerDocument.defaultView;if(!this.isConnected||!ownerWindow)return;const timer={owner:ownerWindow,handle:0,token};timer.handle=ownerWindow.setTimeout(()=>{if(this.sourceTimer!==timer||token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;this.sourceTimer=void 0;const controller=new ownerWindow.AbortController;this.sourceAbort=controller,this.loading=!0,this.sourceFailed=!1,Promise.resolve().then(()=>source(query2,{signal:controller.signal,limit:MAX_SOURCE_ROWS})).then(result=>{if(token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow)return;const normalized=normalizeSourceResult(result);this._sourceTotal=normalized.total,this._sourceTruncated=normalized.truncated,this.asyncRows=normalized.rows,this.sourceFailed=!1,this.normalizeActiveIndex();const selected=new Set(this._selected);for(const row of normalized.rows)selected.has(row.value)&&this._selectedRowCache.set(row.value,row)}).catch(err=>{token!==this.sourceToken||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||typeof err=="object"&&err!==null&&"name"in err&&err.name==="AbortError"||(this.asyncRows=[],this._sourceTotal=0,this._sourceTruncated=!1,this.activeIndex=-1,this.sourceFailed=!0,this.sourceErrorAnnouncementSink?.announce(this.localize("comboboxLoadError")),console.warn("<lr-combobox> source() rejected:",err))}).finally(()=>{token===this.sourceToken&&(this.loading=!1)})},this._sourceDelay),this.sourceTimer=timer}clearSourceTimer(){const timer=this.sourceTimer;this.sourceTimer=void 0,timer&&timer.owner.clearTimeout(timer.handle)}renderRows(rows,activeId){const out=[];let currentGroup,currentGroupRows=[],groupIndex=0;const selectedSet=new Set(this._selected),flushGroup=()=>{if(currentGroupRows.length){if(currentGroup){const labelId=`${this.listId}-group-${groupIndex++}`;out.push(html`<div role="group" aria-labelledby=${labelId}>
2
2
  <div id=${labelId} part="group-label" class="group-label">${currentGroup}</div>
3
3
  ${currentGroupRows}
4
4
  </div>`)}else out.push(...currentGroupRows);currentGroupRows=[]}};return rows.forEach((o,i)=>{o.group!==currentGroup&&(flushGroup(),currentGroup=o.group);const id=`${this.listId}-opt-${i}`,selected=selectedSet.has(o.value);currentGroupRows.push(html`<div
@@ -12,6 +12,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
12
12
  aria-label=${o.accessibleLabel||nothing}
13
13
  ?data-active=${id===activeId}
14
14
  >
15
+ ${o.start?renderInertPresentation(o.start,{part:"option-start"}):""}
15
16
  ${o.icon?renderInertPresentation(o.icon,{part:"option-icon"}):""}
16
17
  ${o.dotColor?html`<span
17
18
  part="option-dot"
@@ -22,6 +23,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
22
23
  ${o.sub?html`<span part="option-sub">${o.sub}</span>`:""}
23
24
  </span>
24
25
  ${o.badge!=null?html`<span part="option-badge">${o.badge}</span>`:""}
26
+ ${o.end?renderInertPresentation(o.end,{part:"option-end"}):""}
25
27
  </div>`)}),flushGroup(),out}renderTag(value,index){const option=this.options.find(candidate=>candidate.value===value);if(this.getTag&&option)return this.getTag(option,index);const label=this.labelFor(value);return html`<span part="tag">
26
28
  <span part="tag-label"><span part="tag__content">${label}</span></span>
27
29
  <button
@@ -132,4 +134,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
132
134
  @lr-option-change=${this.onOptionChange}
133
135
  hidden
134
136
  ></slot>
135
- `}}__decorate([property()],LyraCombobox.prototype,"placeholder",void 0),__decorate([property()],LyraCombobox.prototype,"label",void 0),__decorate([property()],LyraCombobox.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraCombobox.prototype,"errorText",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"open",null),__decorate([property({type:Boolean,attribute:"allow-create"})],LyraCombobox.prototype,"allowCreate",void 0),__decorate([property({type:Boolean,attribute:"allow-custom-value"})],LyraCombobox.prototype,"allowCustomValue",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"appearance",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"placement",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"pill",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"clearable",void 0),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraCombobox.prototype,"withClear",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraCombobox.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraCombobox.prototype,"withHint",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"getTag",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"validators",void 0),__decorate([property()],LyraCombobox.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraCombobox.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraCombobox.prototype,"enterKeyHint",void 0),__decorate([property({converter:comboboxSpellcheckConverter,useDefault:!0})],LyraCombobox.prototype,"spellcheck",void 0),__decorate([property()],LyraCombobox.prototype,"autocapitalize",void 0),__decorate([property({attribute:"empty-text"})],LyraCombobox.prototype,"emptyText",void 0),__decorate([property({attribute:"loading-text"})],LyraCombobox.prototype,"loadingText",void 0),__decorate([property({attribute:"overflow-text"})],LyraCombobox.prototype,"overflowText",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"filter",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"source",void 0),__decorate([property({converter:autocorrectConverter})],LyraCombobox.prototype,"autocorrect",null),__decorate([state()],LyraCombobox.prototype,"query",void 0),__decorate([state()],LyraCombobox.prototype,"activeIndex",void 0),__decorate([state()],LyraCombobox.prototype,"options",void 0),__decorate([state()],LyraCombobox.prototype,"touched",void 0),__decorate([state()],LyraCombobox.prototype,"validityRevision",void 0),__decorate([state()],LyraCombobox.prototype,"loading",void 0),__decorate([state()],LyraCombobox.prototype,"sourceFailed",void 0),__decorate([state()],LyraCombobox.prototype,"asyncRows",void 0),__decorate([query('[part="combobox-input"]')],LyraCombobox.prototype,"inputEl",void 0);export{LyraCombobox};
137
+ `}}__decorate([property()],LyraCombobox.prototype,"placeholder",void 0),__decorate([property()],LyraCombobox.prototype,"label",void 0),__decorate([property()],LyraCombobox.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraCombobox.prototype,"errorText",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"open",null),__decorate([property({type:Boolean,attribute:"allow-create"})],LyraCombobox.prototype,"allowCreate",void 0),__decorate([property({type:Boolean,attribute:"allow-custom-value"})],LyraCombobox.prototype,"allowCustomValue",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"appearance",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"placement",void 0),__decorate([property({reflect:!0})],LyraCombobox.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"pill",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraCombobox.prototype,"clearable",void 0),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraCombobox.prototype,"withClear",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraCombobox.prototype,"withLabel",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraCombobox.prototype,"withHint",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"getTag",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"validators",void 0),__decorate([property()],LyraCombobox.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraCombobox.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraCombobox.prototype,"enterKeyHint",void 0),__decorate([property({converter:comboboxSpellcheckConverter,useDefault:!0})],LyraCombobox.prototype,"spellcheck",void 0),__decorate([property()],LyraCombobox.prototype,"autocapitalize",void 0),__decorate([property({attribute:"empty-text"})],LyraCombobox.prototype,"emptyText",void 0),__decorate([property({attribute:"loading-text"})],LyraCombobox.prototype,"loadingText",void 0),__decorate([property({attribute:"overflow-text"})],LyraCombobox.prototype,"overflowText",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"filter",void 0),__decorate([property({attribute:!1})],LyraCombobox.prototype,"source",void 0),__decorate([property({converter:autocorrectConverter})],LyraCombobox.prototype,"autocorrect",null),__decorate([state()],LyraCombobox.prototype,"query",void 0),__decorate([state()],LyraCombobox.prototype,"activeIndex",void 0),__decorate([state()],LyraCombobox.prototype,"options",void 0),__decorate([state()],LyraCombobox.prototype,"touched",void 0),__decorate([state()],LyraCombobox.prototype,"validityRevision",void 0),__decorate([state()],LyraCombobox.prototype,"loading",void 0),__decorate([state()],LyraCombobox.prototype,"sourceFailed",void 0),__decorate([state()],LyraCombobox.prototype,"asyncRows",void 0),__decorate([query('[part="combobox-input"]')],LyraCombobox.prototype,"inputEl",void 0),__decorate([property({type:Number,attribute:"visible-options"})],LyraCombobox.prototype,"visibleOptions",void 0);export{LyraCombobox};
@@ -342,6 +342,15 @@ import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/for
342
342
  flex: 0 0 auto;
343
343
  color: var(--lr-color-text-quiet);
344
344
  }
345
+ [part="option-start"],
346
+ [part="option-end"] {
347
+ display: inline-flex;
348
+ align-items: center;
349
+ justify-content: center;
350
+ flex: 0 0 auto;
351
+ max-inline-size: 40%;
352
+ overflow: hidden;
353
+ }
345
354
  [part="option-label"] {
346
355
  display: flex;
347
356
  flex-direction: column;
@@ -22,6 +22,21 @@ export interface LyraDatePickerEventMap {
22
22
  date: Date;
23
23
  }>;
24
24
  }
25
+ /**
26
+ * One quick-range option for `presets`.
27
+ *
28
+ * Deliberately the same shape as `<lr-time-range>`'s `TimeRangePreset` (`label`/`start`/`end`,
29
+ * rendered as an `aria-pressed` button row) so the library has one preset vocabulary rather than
30
+ * two. The only difference is the unit: ISO `YYYY-MM-DD` dates instead of numbers, because this
31
+ * control's domain is dates.
32
+ */
33
+ export interface LyraDateRangePreset {
34
+ readonly label: string;
35
+ /** Inclusive range start, ISO `YYYY-MM-DD`. */
36
+ readonly start: string;
37
+ /** Inclusive range end, ISO `YYYY-MM-DD`. */
38
+ readonly end: string;
39
+ }
25
40
  /**
26
41
  * `<lr-date-picker>` — an inline month-grid calendar for picking a single date
27
42
  * or a date range. Mirrors the core `<wa-date-picker>` API under `lr-`.
@@ -79,6 +94,15 @@ export interface LyraDatePickerEventMap {
79
94
  * @csspart day-label - The visible day label.
80
95
  * @csspart day-weekend - A Saturday or Sunday.
81
96
  * @csspart day-placeholder - A non-day grid placeholder.
97
+ * @csspart presets - The quick-range button row, rendered only in range mode with `presets` set.
98
+ * @csspart preset-button - One quick-range button; carries `data-active` while its range is the
99
+ * current value.
100
+ * @cssprop [--lr-date-picker-preset-hover-bg=var(--lr-color-brand-quiet)] - Hover background of a
101
+ * quick-range button.
102
+ * @cssprop --lr-date-picker-preset-active-bg - Pressed background of a quick-range button;
103
+ * defaults to a mix of the hover background with the shared active mix partner.
104
+ * @cssprop [--lr-date-picker-preset-selected-bg=var(--lr-color-brand)] - Background and border of
105
+ * the quick-range button whose range is currently selected.
82
106
  * @csspart weeknumbers - The week-number column.
83
107
  * @csspart weeknumber - One week number.
84
108
  * @csspart footer - The footer region.
@@ -152,6 +176,20 @@ export declare class LyraDatePicker extends LyraElement<LyraDatePickerEventMap>
152
176
  isDateDisabled?: (date: Date) => boolean;
153
177
  /** Optional JavaScript renderer for individual calendar-day content. */
154
178
  dayContent?: LyraDatePickerDayContent;
179
+ /**
180
+ * Quick-range options rendered as a `[part="presets"]` button row above the calendar, for the
181
+ * dashboard time-filter shape (Today / Last 7 days / Last 30 days / This month / All time).
182
+ *
183
+ * Range mode only — a preset names two dates, so it has no meaning for a single-date picker and
184
+ * is ignored there rather than rendering a row that cannot do anything. Unset renders nothing at
185
+ * all, so an existing picker is unchanged.
186
+ *
187
+ * Applying one commits the range exactly as a two-click selection would (clamped to `min`/`max`,
188
+ * then `input` followed by `change`), so a consumer's existing change handling needs no special
189
+ * case. The active preset carries `aria-pressed="true"` and `data-active`, mirroring
190
+ * `<lr-time-range>`'s already-shipped preset row.
191
+ */
192
+ presets: readonly LyraDateRangePreset[];
155
193
  minRange: number;
156
194
  maxRange: number;
157
195
  pageBy: LyraDatePickerPageBy;
@@ -266,6 +304,14 @@ export declare class LyraDatePicker extends LyraElement<LyraDatePickerEventMap>
266
304
  private pickViewItem;
267
305
  private navView;
268
306
  private renderView;
307
+ /** The quick-range row. Range mode only -- see `presets`. */
308
+ private renderPresets;
309
+ /**
310
+ * Commits a preset through the same `commit()` path a two-click range selection uses, so the
311
+ * event pair, the ISO serialization and the min/max clamping are identical -- a consumer's
312
+ * change handler cannot tell the two apart, which is the point.
313
+ */
314
+ private applyPreset;
269
315
  render(): TemplateResult;
270
316
  }
271
317
  declare global {
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{chevronIcon}from"../../../internal/icons.js";import{nextId}from"../../../internal/a11y.js";import{isRtl}from"../../../internal/rtl.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{isDateObject}from"../../../internal/dom-guards.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{styles}from"./date-picker.styles.js";import{monthMatrix,weekdayLabels,monthTitle,formatISO,parseISO,isSameDay,addMonths,addMonthsClampingDay,clampDate,dateTimeFormat,localDate,utcDate,normalizeCalendarMode,normalizeCalendarMonths,normalizeWeekdayFormat,resolveFirstDayOfWeek}from"./calendar-core.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_nextMonth,LYRA_DEFAULT_previousMonth}from"../../../internal/default-strings.generated.js";const MAX_VIEW_PERIOD_DAYS=366*10,modeConverter={fromAttribute:normalizeCalendarMode,toAttribute:normalizeCalendarMode},monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths},weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizePageBy(value){return value==="single"?"single":"months"}function normalizeView(value){return value==="months"||value==="years"||value==="decades"?value:"days"}const pageByConverter={fromAttribute:normalizePageBy,toAttribute:normalizePageBy},viewConverter={fromAttribute:normalizeView,toAttribute:normalizeView};class LyraDatePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,nextMonth:LYRA_DEFAULT_nextMonth,previousMonth:LYRA_DEFAULT_previousMonth}}static{this.styles=[LyraElement.styles,styles]}constructor(){super(),this.value="",this.mode="single",this.min="",this.max="",this.disabled=!1,this.readonly=!1,this.months=1,this.size="m",this.locale="",this.firstDayOfWeek="auto",this.weekdayFormat="short",this.disablePast=!1,this.disableFuture=!1,this.withOutsideDays=!1,this.withWeekNumbers=!1,this.disabledDates="",this.disabledDaysOfWeek="",this.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.focusedDate="",this.view="days",this.previousLabel="Previous month",this.nextLabel="Next month",this.viewDate=localDate(new Date().getFullYear(),new Date().getMonth(),1),this.rangePreview=null,this.focusedViewStart="",this.focusPending=!1,this.viewFocusPending=!1,this.restoringViewFocus=!1,this.internals=attachInternalsSafely(this),this.disabledDatesCache=new Set,this.disabledWeekdaysCache=new Set,this.viewPeriodAvailabilityCache=new Map,this.titleIds=[nextId("date-picker-title"),nextId("date-picker-title")],this.suppressViewSync=!1,this.onViewGridKey=event=>{const view=this.effectiveView;if(view==="days")return;const periods=this.viewPeriods(view),source=event.composedPath().find(node=>node instanceof HTMLElement&&node.hasAttribute("data-view-start")),currentSource=parseISO(source?.getAttribute("data-view-start")??"")??this.resolveViewFocus(periods);if(!currentSource)return;const current=this.viewPeriodStart(currentSource,view),span=this.viewPeriodMonths(view),rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=null;switch(event.key){case backwardKey:next=this.firstEnabledViewPeriod(addMonths(current,-span),-1);break;case forwardKey:next=this.firstEnabledViewPeriod(addMonths(current,span),1);break;case"ArrowUp":next=this.firstEnabledViewPeriod(addMonths(current,-4*span),-1);break;case"ArrowDown":next=this.firstEnabledViewPeriod(addMonths(current,4*span),1);break;case"Home":next=periods.find(period=>!this.viewPeriodDisabled(period.start,period.end))?.start??null;break;case"End":next=[...periods].reverse().find(period=>!this.viewPeriodDisabled(period.start,period.end))?.start??null;break;case"Enter":case" ":event.preventDefault(),this.pickViewItem(current);return;default:return}event.preventDefault(),next&&(this.viewDate=localDate(next.getFullYear(),next.getMonth(),1),this.focusViewPeriod(next,view))},this.onGridKey=e=>{const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday(),current=this.focusedDateValue??this.selection.from??this.firstEnabledDate(min,max,today)??localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),step=(base,days)=>localDate(base.getFullYear(),base.getMonth(),base.getDate()+days),firstEnabledFrom=(base,dayStep)=>{let d=base;for(let i=0;i<366;i++){if(!this.isDisabled(d,min,max,today))return d;d=step(d,dayStep)}return null},rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=null;switch(e.key){case backwardKey:next=firstEnabledFrom(step(current,-1),-1);break;case forwardKey:next=firstEnabledFrom(step(current,1),1);break;case"ArrowUp":next=firstEnabledFrom(step(current,-7),-1);break;case"ArrowDown":next=firstEnabledFrom(step(current,7),1);break;case"PageUp":next=firstEnabledFrom(addMonthsClampingDay(current,-1),1);break;case"PageDown":next=firstEnabledFrom(addMonthsClampingDay(current,1),1);break;case"Home":next=firstEnabledFrom(localDate(current.getFullYear(),current.getMonth(),1),1);break;case"End":next=firstEnabledFrom(localDate(current.getFullYear(),current.getMonth()+1,0),-1);break;case"Enter":case" ":e.preventDefault(),this.selectDate(current);return;default:return}e.preventDefault(),next&&(this.setFocusedDate(next),this.viewDate=this.viewDateForFocus(next),this.focusPending=!0)},observeScrollOverflow(this,()=>this.renderRoot.querySelectorAll(".calendar-scroll")[0]),observeScrollOverflow(this,()=>this.renderRoot.querySelectorAll(".calendar-scroll")[1])}get effectiveMode(){return normalizeCalendarMode(this.mode)}get visibleMonths(){return normalizeCalendarMonths(this.months)}get effectiveWeekdayFormat(){return normalizeWeekdayFormat(this.weekdayFormat)}get effectiveView(){return normalizeView(this.view)}get selection(){const parts=this.value.split("/");return{from:parseISO(parts[0]??""),to:parseISO(parts[1]??"")}}get valueAsDate(){return this.effectiveMode==="single"?this.selection.from:null}set valueAsDate(next){if(!isDateObject(next)||!Number.isFinite(next.getTime())){this.value="";return}this.value=formatISO(next)}get valueAsRange(){return this.effectiveMode==="range"?this.selection:{from:null,to:null}}set valueAsRange(next){let from=isDateObject(next?.from)&&Number.isFinite(next.from.getTime())?next.from:null,to=isDateObject(next?.to)&&Number.isFinite(next.to.getTime())?next.to:null;from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get focusedDateValue(){return parseISO(this.focusedDate)}setFocusedDate(date){this.focusedDate=date?formatISO(date):""}resolvedToday(){const today=parseISO(this.today)??new Date;return localDate(today.getFullYear(),today.getMonth(),today.getDate())}syncCustomStates(){setCustomState(this.internals,"disabled",this.disabled),setCustomState(this.internals,"range",this.effectiveMode==="range"),setCustomState(this.internals,"readonly",this.readonly)}willUpdate(changed){super.willUpdate(changed),this.viewPeriodAvailabilityCache.clear();const activeElement=this.renderRoot?.activeElement??null,activeViewStart=activeElement?.matches('[part~="view-item"]')?parseISO(activeElement.getAttribute("data-view-start")??""):null;if(changed.has("value")){const external=!this.suppressViewSync;if(this.suppressViewSync=!1,external&&this.value){const from=this.selection.from;from&&(this.viewDate=localDate(from.getFullYear(),from.getMonth(),1))}}if(changed.has("focusedDate")){const focused=this.focusedDateValue;focused&&!this.isVisibleDate(focused)&&(this.viewDate=this.viewDateForFocus(focused))}const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday();if(this.normalizeFocusedDate(min,max,today),this.clampViewDateToEnabledPeriod(),this.syncCustomStates(),activeViewStart&&this.effectiveView!=="days"){const next=this.resolveViewFocus(this.viewPeriods());next&&!isSameDay(activeViewStart,next)&&(this.setFocusedViewStart(next),this.viewFocusPending=!0)}}get fdow(){return resolveFirstDayOfWeek(this.firstDayOfWeek,this.effectiveLocale)}get disabledDateKeys(){if(this.disabledDatesCacheSource===this.disabledDates)return this.disabledDatesCache;this.disabledDatesCacheSource=this.disabledDates;const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return this.disabledDatesCache=new Set(values.map(value=>isDateObject(value)?value:parseISO(String(value))).filter(value=>isDateObject(value)&&Number.isFinite(value.getTime())).map(value=>formatISO(value))),this.disabledDatesCache}get disabledWeekdays(){if(this.disabledWeekdaysCacheSource===this.disabledDaysOfWeek)return this.disabledWeekdaysCache;this.disabledWeekdaysCacheSource=this.disabledDaysOfWeek;const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6},parsed=String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0);return this.disabledWeekdaysCache=new Set(parsed),this.disabledWeekdaysCache}rangeLength(from,to){const fromUtc=utcDate(from.getFullYear(),from.getMonth(),from.getDate()).getTime(),toUtc=utcDate(to.getFullYear(),to.getMonth(),to.getDate()).getTime();return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}isDisabled(d,min,max,today){if(this.disabled||this.readonly||min&&d<min||max&&d>max||this.disablePast&&d<today||this.disableFuture&&d>today||this.disabledDateKeys.has(formatISO(d))||this.disabledWeekdays.has(d.getDay()))return!0;try{if(this.isDateDisabled?.(new Date(d.getTime())))return!0}catch{}if(this.effectiveMode==="range"){const{from,to}=this.selection;if(from&&!to&&!isSameDay(from,d)){const length=this.rangeLength(from,d),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);if(minimum>0&&length<minimum||maximum>0&&length>maximum)return!0}}return!1}nearestEnabledDate(anchor,min,max,today){if(!this.isDisabled(anchor,min,max,today))return new Date(anchor.getTime());for(let distance=1;distance<=732;distance++){const before=localDate(anchor.getFullYear(),anchor.getMonth(),anchor.getDate()-distance);if(!this.isDisabled(before,min,max,today))return before;const after=localDate(anchor.getFullYear(),anchor.getMonth(),anchor.getDate()+distance);if(!this.isDisabled(after,min,max,today))return after}return null}isVisibleDate(date){const start=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),end=addMonths(start,this.visibleMonths);return date>=start&&date<end}normalizeFocusedDate(min,max,today){const anchor=this.focusedDateValue??this.selection.from;if(!anchor)return;const disabled=this.isDisabled(anchor,min,max,today);if(!disabled&&this.isVisibleDate(anchor))return;const next=disabled?this.nearestEnabledDate(anchor,min,max,today):this.firstEnabledDate(min,max,today);if(!next){this.setFocusedDate(null),this.focusPending=!1;return}this.setFocusedDate(next),this.viewDate=this.viewDateForFocus(next),disabled&&(this.focusPending=!0)}firstEnabledDate(min,max,today){let d=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1);const lastVisibleMonth=addMonths(d,this.visibleMonths-1),boundEnd=localDate(lastVisibleMonth.getFullYear(),lastVisibleMonth.getMonth()+1,0);for(let i=0;i<732&&d<=boundEnd;i++){if(!this.isDisabled(d,min,max,today))return d;d=localDate(d.getFullYear(),d.getMonth(),d.getDate()+1)}return null}commit(from,to,fire){const next=this.effectiveMode==="range"?from&&to?`${formatISO(from)}/${formatISO(to)}`:from?formatISO(from):"":from?formatISO(from):"";next!==this.value&&(this.suppressViewSync=!0),this.value=next,dispatchNativeInputEvent(this),fire&&dispatchNativeEvent(this,"change")}selectDate(date){const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday();if(!this.isDisabled(date,min,max,today))if(this.setFocusedDate(date),this.effectiveMode==="range"){const{from,to}=this.selection;if(!from||from&&to)this.commit(date,null,!1);else{let a=from,b=date;b<a&&([a,b]=[b,a]),this.commit(a,b,!0)}}else this.commit(date,null,!0)}clear(){this.commit(null,null,!0)}goToToday(){this.goToDate(this.resolvedToday())}goToDate(date){const d=typeof date=="string"?parseISO(date):date;if(!d||!Number.isFinite(d.getTime()))return;const midnight=localDate(d.getFullYear(),d.getMonth(),d.getDate()),clamped=clampDate(midnight,parseISO(this.min),parseISO(this.max));this.viewDate=localDate(clamped.getFullYear(),clamped.getMonth(),1),this.setFocusedDate(clamped),this.focusPending=!0}nav(delta){const page=this.pageBy==="single"?1:this.visibleMonths;this.viewDate=addMonths(this.viewDate,delta*page)}focus(options){this.renderRoot?.querySelector('[part~="day"][tabindex="0"], [part~="view-item"][tabindex="0"]:not(:disabled)')?.focus(options)}viewPeriodMonths(view=this.effectiveView){return view==="years"?12:view==="decades"?120:1}viewPeriodStart(date,view=this.effectiveView){return view==="years"?localDate(date.getFullYear(),0,1):view==="decades"?localDate(Math.floor(date.getFullYear()/10)*10,0,1):localDate(date.getFullYear(),date.getMonth(),1)}viewPageStart(view=this.effectiveView){const year=this.viewDate.getFullYear();return view==="months"?localDate(year,0,1):view==="years"?localDate(Math.floor(year/12)*12,0,1):localDate(Math.floor(year/120)*120,0,1)}viewPeriods(view=this.effectiveView){const pageStart=this.viewPageStart(view),span=this.viewPeriodMonths(view);return Array.from({length:12},(_,index)=>{const start=addMonths(pageStart,index*span);return{start,end:localDate(start.getFullYear(),start.getMonth()+span,0)}})}clampViewDateToEnabledPeriod(view=this.effectiveView){if(view==="days")return null;const periods=this.viewPeriods(view);if(this.disabled||this.readonly||periods.some(period=>!this.viewPeriodDisabled(period.start,period.end)))return null;const first=periods[0],last=periods[periods.length-1],span=this.viewPeriodMonths(view),min=parseISO(this.min),max=parseISO(this.max),forward=min&&last.end<min,backward=max&&first.start>max,next=forward?this.firstEnabledViewPeriod(addMonths(last.start,span),1):backward?this.firstEnabledViewPeriod(addMonths(first.start,-span),-1):this.firstEnabledViewPeriod(addMonths(last.start,span),1)??this.firstEnabledViewPeriod(addMonths(first.start,-span),-1);return next?(this.viewDate=localDate(next.getFullYear(),next.getMonth(),1),next):null}resolveViewFocus(periods){const inView=candidate=>{if(!candidate)return null;const start=this.viewPeriodStart(candidate),period=periods.find(item=>isSameDay(item.start,start));return period&&!this.viewPeriodDisabled(period.start,period.end)?period.start:null},fallback=periods.find(period=>!this.viewPeriodDisabled(period.start,period.end));return inView(parseISO(this.focusedViewStart))??inView(this.selection.from)??inView(this.viewDate)??fallback?.start??null}setFocusedViewStart(date,view=this.effectiveView,requestUpdate=!1){const next=formatISO(this.viewPeriodStart(date,view));this.focusedViewStart!==next&&(this.focusedViewStart=next,requestUpdate&&this.requestUpdate())}onViewItemFocus(start){this.restoringViewFocus||this.setFocusedViewStart(start,this.effectiveView,!0)}firstEnabledViewPeriod(start,direction){const span=this.viewPeriodMonths();let candidate=this.viewPeriodStart(start);for(let index=0;index<366;index++){const end=localDate(candidate.getFullYear(),candidate.getMonth()+span,0);if(!this.viewPeriodDisabled(candidate,end))return candidate;candidate=addMonths(candidate,direction*span)}return null}focusViewPeriod(date,view=this.effectiveView){this.setFocusedViewStart(date,view),this.viewFocusPending=!0}setView(next,date=this.viewDate){next!==this.view&&(this.view=next,this.emit("lr-view-change",{view:next,date:new Date(date.getTime())}))}advanceView(){const next={days:"months",months:"years",years:"decades",decades:"decades"},current=this.effectiveView,nextView=next[current];if(nextView===current)return;const focused=current==="days"?this.focusedDateValue??this.selection.from??this.viewDate:this.resolveViewFocus(this.viewPeriods(current))??this.viewDate;this.focusViewPeriod(focused,nextView),this.setView(nextView)}onDayFocus(date){this.setFocusedDate(date),this.emit("lr-focus-day",{date:new Date(date.getTime())})}viewDateForFocus(next){const firstMonth=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),nextMonth=localDate(next.getFullYear(),next.getMonth(),1),lastMonth=addMonths(firstMonth,this.visibleMonths-1);return nextMonth<firstMonth?nextMonth:nextMonth>lastMonth?addMonths(nextMonth,-(this.visibleMonths-1)):firstMonth}updated(changed){super.updated(changed);const focusedDate=this.focusedDateValue;if(this.focusPending&&focusedDate){this.focusPending=!1;const iso=formatISO(focusedDate);this.renderRoot.querySelector(`[data-date="${iso}"][tabindex="0"]`)?.focus()}if(this.viewFocusPending){this.viewFocusPending=!1;const item=this.renderRoot.querySelector('[part~="view-item"][tabindex="0"]:not(:disabled)');if(item){this.restoringViewFocus=!0;try{item.focus()}finally{this.restoringViewFocus=!1}}}}renderDay(date,shownMonth,selection,min,max,today,rowHasVisibleDay,fallbackFocusDate,dayLabelFmt){const outside=date.getMonth()!==shownMonth;if(outside&&!this.withOutsideDays)return html`<span
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{chevronIcon}from"../../../internal/icons.js";import{nextId}from"../../../internal/a11y.js";import{isRtl}from"../../../internal/rtl.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{isDateObject}from"../../../internal/dom-guards.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{styles}from"./date-picker.styles.js";import{monthMatrix,weekdayLabels,monthTitle,formatISO,parseISO,isSameDay,addMonths,addMonthsClampingDay,clampDate,dateTimeFormat,localDate,utcDate,normalizeCalendarMode,normalizeCalendarMonths,normalizeWeekdayFormat,resolveFirstDayOfWeek}from"./calendar-core.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_nextMonth,LYRA_DEFAULT_previousMonth}from"../../../internal/default-strings.generated.js";const MAX_VIEW_PERIOD_DAYS=366*10,modeConverter={fromAttribute:normalizeCalendarMode,toAttribute:normalizeCalendarMode},monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths},weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizePageBy(value){return value==="single"?"single":"months"}function normalizeView(value){return value==="months"||value==="years"||value==="decades"?value:"days"}const pageByConverter={fromAttribute:normalizePageBy,toAttribute:normalizePageBy},viewConverter={fromAttribute:normalizeView,toAttribute:normalizeView};class LyraDatePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,nextMonth:LYRA_DEFAULT_nextMonth,previousMonth:LYRA_DEFAULT_previousMonth}}static{this.styles=[LyraElement.styles,styles]}constructor(){super(),this.value="",this.mode="single",this.min="",this.max="",this.disabled=!1,this.readonly=!1,this.months=1,this.size="m",this.locale="",this.firstDayOfWeek="auto",this.weekdayFormat="short",this.disablePast=!1,this.disableFuture=!1,this.withOutsideDays=!1,this.withWeekNumbers=!1,this.disabledDates="",this.disabledDaysOfWeek="",this.presets=Object.freeze([]),this.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.focusedDate="",this.view="days",this.previousLabel="Previous month",this.nextLabel="Next month",this.viewDate=localDate(new Date().getFullYear(),new Date().getMonth(),1),this.rangePreview=null,this.focusedViewStart="",this.focusPending=!1,this.viewFocusPending=!1,this.restoringViewFocus=!1,this.internals=attachInternalsSafely(this),this.disabledDatesCache=new Set,this.disabledWeekdaysCache=new Set,this.viewPeriodAvailabilityCache=new Map,this.titleIds=[nextId("date-picker-title"),nextId("date-picker-title")],this.suppressViewSync=!1,this.onViewGridKey=event=>{const view=this.effectiveView;if(view==="days")return;const periods=this.viewPeriods(view),source=event.composedPath().find(node=>node instanceof HTMLElement&&node.hasAttribute("data-view-start")),currentSource=parseISO(source?.getAttribute("data-view-start")??"")??this.resolveViewFocus(periods);if(!currentSource)return;const current=this.viewPeriodStart(currentSource,view),span=this.viewPeriodMonths(view),rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=null;switch(event.key){case backwardKey:next=this.firstEnabledViewPeriod(addMonths(current,-span),-1);break;case forwardKey:next=this.firstEnabledViewPeriod(addMonths(current,span),1);break;case"ArrowUp":next=this.firstEnabledViewPeriod(addMonths(current,-4*span),-1);break;case"ArrowDown":next=this.firstEnabledViewPeriod(addMonths(current,4*span),1);break;case"Home":next=periods.find(period=>!this.viewPeriodDisabled(period.start,period.end))?.start??null;break;case"End":next=[...periods].reverse().find(period=>!this.viewPeriodDisabled(period.start,period.end))?.start??null;break;case"Enter":case" ":event.preventDefault(),this.pickViewItem(current);return;default:return}event.preventDefault(),next&&(this.viewDate=localDate(next.getFullYear(),next.getMonth(),1),this.focusViewPeriod(next,view))},this.onGridKey=e=>{const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday(),current=this.focusedDateValue??this.selection.from??this.firstEnabledDate(min,max,today)??localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),step=(base,days)=>localDate(base.getFullYear(),base.getMonth(),base.getDate()+days),firstEnabledFrom=(base,dayStep)=>{let d=base;for(let i=0;i<366;i++){if(!this.isDisabled(d,min,max,today))return d;d=step(d,dayStep)}return null},rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=null;switch(e.key){case backwardKey:next=firstEnabledFrom(step(current,-1),-1);break;case forwardKey:next=firstEnabledFrom(step(current,1),1);break;case"ArrowUp":next=firstEnabledFrom(step(current,-7),-1);break;case"ArrowDown":next=firstEnabledFrom(step(current,7),1);break;case"PageUp":next=firstEnabledFrom(addMonthsClampingDay(current,-1),1);break;case"PageDown":next=firstEnabledFrom(addMonthsClampingDay(current,1),1);break;case"Home":next=firstEnabledFrom(localDate(current.getFullYear(),current.getMonth(),1),1);break;case"End":next=firstEnabledFrom(localDate(current.getFullYear(),current.getMonth()+1,0),-1);break;case"Enter":case" ":e.preventDefault(),this.selectDate(current);return;default:return}e.preventDefault(),next&&(this.setFocusedDate(next),this.viewDate=this.viewDateForFocus(next),this.focusPending=!0)},observeScrollOverflow(this,()=>this.renderRoot.querySelectorAll(".calendar-scroll")[0]),observeScrollOverflow(this,()=>this.renderRoot.querySelectorAll(".calendar-scroll")[1])}get effectiveMode(){return normalizeCalendarMode(this.mode)}get visibleMonths(){return normalizeCalendarMonths(this.months)}get effectiveWeekdayFormat(){return normalizeWeekdayFormat(this.weekdayFormat)}get effectiveView(){return normalizeView(this.view)}get selection(){const parts=this.value.split("/");return{from:parseISO(parts[0]??""),to:parseISO(parts[1]??"")}}get valueAsDate(){return this.effectiveMode==="single"?this.selection.from:null}set valueAsDate(next){if(!isDateObject(next)||!Number.isFinite(next.getTime())){this.value="";return}this.value=formatISO(next)}get valueAsRange(){return this.effectiveMode==="range"?this.selection:{from:null,to:null}}set valueAsRange(next){let from=isDateObject(next?.from)&&Number.isFinite(next.from.getTime())?next.from:null,to=isDateObject(next?.to)&&Number.isFinite(next.to.getTime())?next.to:null;from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get focusedDateValue(){return parseISO(this.focusedDate)}setFocusedDate(date){this.focusedDate=date?formatISO(date):""}resolvedToday(){const today=parseISO(this.today)??new Date;return localDate(today.getFullYear(),today.getMonth(),today.getDate())}syncCustomStates(){setCustomState(this.internals,"disabled",this.disabled),setCustomState(this.internals,"range",this.effectiveMode==="range"),setCustomState(this.internals,"readonly",this.readonly)}willUpdate(changed){super.willUpdate(changed),this.viewPeriodAvailabilityCache.clear();const activeElement=this.renderRoot?.activeElement??null,activeViewStart=activeElement?.matches('[part~="view-item"]')?parseISO(activeElement.getAttribute("data-view-start")??""):null;if(changed.has("value")){const external=!this.suppressViewSync;if(this.suppressViewSync=!1,external&&this.value){const from=this.selection.from;from&&(this.viewDate=localDate(from.getFullYear(),from.getMonth(),1))}}if(changed.has("focusedDate")){const focused=this.focusedDateValue;focused&&!this.isVisibleDate(focused)&&(this.viewDate=this.viewDateForFocus(focused))}const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday();if(this.normalizeFocusedDate(min,max,today),this.clampViewDateToEnabledPeriod(),this.syncCustomStates(),activeViewStart&&this.effectiveView!=="days"){const next=this.resolveViewFocus(this.viewPeriods());next&&!isSameDay(activeViewStart,next)&&(this.setFocusedViewStart(next),this.viewFocusPending=!0)}}get fdow(){return resolveFirstDayOfWeek(this.firstDayOfWeek,this.effectiveLocale)}get disabledDateKeys(){if(this.disabledDatesCacheSource===this.disabledDates)return this.disabledDatesCache;this.disabledDatesCacheSource=this.disabledDates;const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return this.disabledDatesCache=new Set(values.map(value=>isDateObject(value)?value:parseISO(String(value))).filter(value=>isDateObject(value)&&Number.isFinite(value.getTime())).map(value=>formatISO(value))),this.disabledDatesCache}get disabledWeekdays(){if(this.disabledWeekdaysCacheSource===this.disabledDaysOfWeek)return this.disabledWeekdaysCache;this.disabledWeekdaysCacheSource=this.disabledDaysOfWeek;const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6},parsed=String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0);return this.disabledWeekdaysCache=new Set(parsed),this.disabledWeekdaysCache}rangeLength(from,to){const fromUtc=utcDate(from.getFullYear(),from.getMonth(),from.getDate()).getTime(),toUtc=utcDate(to.getFullYear(),to.getMonth(),to.getDate()).getTime();return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}isDisabled(d,min,max,today){if(this.disabled||this.readonly||min&&d<min||max&&d>max||this.disablePast&&d<today||this.disableFuture&&d>today||this.disabledDateKeys.has(formatISO(d))||this.disabledWeekdays.has(d.getDay()))return!0;try{if(this.isDateDisabled?.(new Date(d.getTime())))return!0}catch{}if(this.effectiveMode==="range"){const{from,to}=this.selection;if(from&&!to&&!isSameDay(from,d)){const length=this.rangeLength(from,d),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);if(minimum>0&&length<minimum||maximum>0&&length>maximum)return!0}}return!1}nearestEnabledDate(anchor,min,max,today){if(!this.isDisabled(anchor,min,max,today))return new Date(anchor.getTime());for(let distance=1;distance<=732;distance++){const before=localDate(anchor.getFullYear(),anchor.getMonth(),anchor.getDate()-distance);if(!this.isDisabled(before,min,max,today))return before;const after=localDate(anchor.getFullYear(),anchor.getMonth(),anchor.getDate()+distance);if(!this.isDisabled(after,min,max,today))return after}return null}isVisibleDate(date){const start=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),end=addMonths(start,this.visibleMonths);return date>=start&&date<end}normalizeFocusedDate(min,max,today){const anchor=this.focusedDateValue??this.selection.from;if(!anchor)return;const disabled=this.isDisabled(anchor,min,max,today);if(!disabled&&this.isVisibleDate(anchor))return;const next=disabled?this.nearestEnabledDate(anchor,min,max,today):this.firstEnabledDate(min,max,today);if(!next){this.setFocusedDate(null),this.focusPending=!1;return}this.setFocusedDate(next),this.viewDate=this.viewDateForFocus(next),disabled&&(this.focusPending=!0)}firstEnabledDate(min,max,today){let d=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1);const lastVisibleMonth=addMonths(d,this.visibleMonths-1),boundEnd=localDate(lastVisibleMonth.getFullYear(),lastVisibleMonth.getMonth()+1,0);for(let i=0;i<732&&d<=boundEnd;i++){if(!this.isDisabled(d,min,max,today))return d;d=localDate(d.getFullYear(),d.getMonth(),d.getDate()+1)}return null}commit(from,to,fire){const next=this.effectiveMode==="range"?from&&to?`${formatISO(from)}/${formatISO(to)}`:from?formatISO(from):"":from?formatISO(from):"";next!==this.value&&(this.suppressViewSync=!0),this.value=next,dispatchNativeInputEvent(this),fire&&dispatchNativeEvent(this,"change")}selectDate(date){const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday();if(!this.isDisabled(date,min,max,today))if(this.setFocusedDate(date),this.effectiveMode==="range"){const{from,to}=this.selection;if(!from||from&&to)this.commit(date,null,!1);else{let a=from,b=date;b<a&&([a,b]=[b,a]),this.commit(a,b,!0)}}else this.commit(date,null,!0)}clear(){this.commit(null,null,!0)}goToToday(){this.goToDate(this.resolvedToday())}goToDate(date){const d=typeof date=="string"?parseISO(date):date;if(!d||!Number.isFinite(d.getTime()))return;const midnight=localDate(d.getFullYear(),d.getMonth(),d.getDate()),clamped=clampDate(midnight,parseISO(this.min),parseISO(this.max));this.viewDate=localDate(clamped.getFullYear(),clamped.getMonth(),1),this.setFocusedDate(clamped),this.focusPending=!0}nav(delta){const page=this.pageBy==="single"?1:this.visibleMonths;this.viewDate=addMonths(this.viewDate,delta*page)}focus(options){this.renderRoot?.querySelector('[part~="day"][tabindex="0"], [part~="view-item"][tabindex="0"]:not(:disabled)')?.focus(options)}viewPeriodMonths(view=this.effectiveView){return view==="years"?12:view==="decades"?120:1}viewPeriodStart(date,view=this.effectiveView){return view==="years"?localDate(date.getFullYear(),0,1):view==="decades"?localDate(Math.floor(date.getFullYear()/10)*10,0,1):localDate(date.getFullYear(),date.getMonth(),1)}viewPageStart(view=this.effectiveView){const year=this.viewDate.getFullYear();return view==="months"?localDate(year,0,1):view==="years"?localDate(Math.floor(year/12)*12,0,1):localDate(Math.floor(year/120)*120,0,1)}viewPeriods(view=this.effectiveView){const pageStart=this.viewPageStart(view),span=this.viewPeriodMonths(view);return Array.from({length:12},(_,index)=>{const start=addMonths(pageStart,index*span);return{start,end:localDate(start.getFullYear(),start.getMonth()+span,0)}})}clampViewDateToEnabledPeriod(view=this.effectiveView){if(view==="days")return null;const periods=this.viewPeriods(view);if(this.disabled||this.readonly||periods.some(period=>!this.viewPeriodDisabled(period.start,period.end)))return null;const first=periods[0],last=periods[periods.length-1],span=this.viewPeriodMonths(view),min=parseISO(this.min),max=parseISO(this.max),forward=min&&last.end<min,backward=max&&first.start>max,next=forward?this.firstEnabledViewPeriod(addMonths(last.start,span),1):backward?this.firstEnabledViewPeriod(addMonths(first.start,-span),-1):this.firstEnabledViewPeriod(addMonths(last.start,span),1)??this.firstEnabledViewPeriod(addMonths(first.start,-span),-1);return next?(this.viewDate=localDate(next.getFullYear(),next.getMonth(),1),next):null}resolveViewFocus(periods){const inView=candidate=>{if(!candidate)return null;const start=this.viewPeriodStart(candidate),period=periods.find(item=>isSameDay(item.start,start));return period&&!this.viewPeriodDisabled(period.start,period.end)?period.start:null},fallback=periods.find(period=>!this.viewPeriodDisabled(period.start,period.end));return inView(parseISO(this.focusedViewStart))??inView(this.selection.from)??inView(this.viewDate)??fallback?.start??null}setFocusedViewStart(date,view=this.effectiveView,requestUpdate=!1){const next=formatISO(this.viewPeriodStart(date,view));this.focusedViewStart!==next&&(this.focusedViewStart=next,requestUpdate&&this.requestUpdate())}onViewItemFocus(start){this.restoringViewFocus||this.setFocusedViewStart(start,this.effectiveView,!0)}firstEnabledViewPeriod(start,direction){const span=this.viewPeriodMonths();let candidate=this.viewPeriodStart(start);for(let index=0;index<366;index++){const end=localDate(candidate.getFullYear(),candidate.getMonth()+span,0);if(!this.viewPeriodDisabled(candidate,end))return candidate;candidate=addMonths(candidate,direction*span)}return null}focusViewPeriod(date,view=this.effectiveView){this.setFocusedViewStart(date,view),this.viewFocusPending=!0}setView(next,date=this.viewDate){next!==this.view&&(this.view=next,this.emit("lr-view-change",{view:next,date:new Date(date.getTime())}))}advanceView(){const next={days:"months",months:"years",years:"decades",decades:"decades"},current=this.effectiveView,nextView=next[current];if(nextView===current)return;const focused=current==="days"?this.focusedDateValue??this.selection.from??this.viewDate:this.resolveViewFocus(this.viewPeriods(current))??this.viewDate;this.focusViewPeriod(focused,nextView),this.setView(nextView)}onDayFocus(date){this.setFocusedDate(date),this.emit("lr-focus-day",{date:new Date(date.getTime())})}viewDateForFocus(next){const firstMonth=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),nextMonth=localDate(next.getFullYear(),next.getMonth(),1),lastMonth=addMonths(firstMonth,this.visibleMonths-1);return nextMonth<firstMonth?nextMonth:nextMonth>lastMonth?addMonths(nextMonth,-(this.visibleMonths-1)):firstMonth}updated(changed){super.updated(changed);const focusedDate=this.focusedDateValue;if(this.focusPending&&focusedDate){this.focusPending=!1;const iso=formatISO(focusedDate);this.renderRoot.querySelector(`[data-date="${iso}"][tabindex="0"]`)?.focus()}if(this.viewFocusPending){this.viewFocusPending=!1;const item=this.renderRoot.querySelector('[part~="view-item"][tabindex="0"]:not(:disabled)');if(item){this.restoringViewFocus=!0;try{item.focus()}finally{this.restoringViewFocus=!1}}}}renderDay(date,shownMonth,selection,min,max,today,rowHasVisibleDay,fallbackFocusDate,dayLabelFmt){const outside=date.getMonth()!==shownMonth;if(outside&&!this.withOutsideDays)return html`<span
2
2
  part="day-placeholder"
3
3
  role="gridcell"
4
4
  aria-hidden=${rowHasVisibleDay?"true":nothing}
@@ -140,9 +140,21 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
140
140
  ${row.map(item=>this.renderViewItem(item.start,item.end,item.label,today,selected,focused!=null&&isSameDay(item.start,focused)))}
141
141
  </div>`)}
142
142
  </div>
143
- `}render(){const selection=this.selection,min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday(),fdow=this.fdow,labels=weekdayLabels(fdow,this.effectiveWeekdayFormat,this.effectiveLocale),dayLabelFmt=dateTimeFormat(this.effectiveLocale,{weekday:"long",year:"numeric",month:"long",day:"numeric"}),fallbackFocusDate=this.focusedDateValue||selection.from?null:this.firstEnabledDate(min,max,today),monthEls=[];if(this.effectiveView==="days")for(let i=0;i<this.visibleMonths;i++)monthEls.push(this.renderMonth(i,selection,min,max,today,fdow,labels,fallbackFocusDate,dayLabelFmt));return html`<div part="base date-picker">
143
+ `}renderPresets(){return this.effectiveMode!=="range"||this.presets.length===0?nothing:html`<div part="presets">
144
+ ${this.presets.map(preset=>{const active=this.value===`${preset.start}/${preset.end}`;return html`<button
145
+ part="preset-button"
146
+ type="button"
147
+ ?disabled=${this.disabled||this.readonly}
148
+ aria-pressed=${active?"true":"false"}
149
+ ?data-active=${active}
150
+ @click=${()=>this.applyPreset(preset)}
151
+ >
152
+ ${preset.label}
153
+ </button>`})}
154
+ </div>`}applyPreset(preset){if(this.disabled||this.readonly)return;const from=parseISO(preset.start),to=parseISO(preset.end);if(!from||!to)return;const[start,end]=from.getTime()<=to.getTime()?[from,to]:[to,from];this.setFocusedDate(start),this.commit(start,end,!0)}render(){const selection=this.selection,min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday(),fdow=this.fdow,labels=weekdayLabels(fdow,this.effectiveWeekdayFormat,this.effectiveLocale),dayLabelFmt=dateTimeFormat(this.effectiveLocale,{weekday:"long",year:"numeric",month:"long",day:"numeric"}),fallbackFocusDate=this.focusedDateValue||selection.from?null:this.firstEnabledDate(min,max,today),monthEls=[];if(this.effectiveView==="days")for(let i=0;i<this.visibleMonths;i++)monthEls.push(this.renderMonth(i,selection,min,max,today,fdow,labels,fallbackFocusDate,dayLabelFmt));return html`<div part="base date-picker">
144
155
  <div class="content">
156
+ ${this.renderPresets()}
145
157
  ${this.effectiveView==="days"?html`<div part="months">${monthEls}</div>`:this.renderView(today)}
146
158
  <div part="footer"><slot name="footer"></slot></div>
147
159
  </div>
148
- </div>`}}__decorate([property({reflect:!0})],LyraDatePicker.prototype,"value",void 0),__decorate([property({converter:modeConverter,reflect:!0})],LyraDatePicker.prototype,"mode",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"min",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"max",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDatePicker.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDatePicker.prototype,"readonly",void 0),__decorate([property({converter:monthsConverter,reflect:!0})],LyraDatePicker.prototype,"months",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"locale",void 0),__decorate([property({attribute:"first-day-of-week",reflect:!0})],LyraDatePicker.prototype,"firstDayOfWeek",void 0),__decorate([property({attribute:"weekday-format",converter:weekdayFormatConverter,reflect:!0})],LyraDatePicker.prototype,"weekdayFormat",void 0),__decorate([property({type:Boolean,attribute:"disable-past",reflect:!0})],LyraDatePicker.prototype,"disablePast",void 0),__decorate([property({type:Boolean,attribute:"disable-future",reflect:!0})],LyraDatePicker.prototype,"disableFuture",void 0),__decorate([property({type:Boolean,attribute:"with-outside-days",reflect:!0})],LyraDatePicker.prototype,"withOutsideDays",void 0),__decorate([property({type:Boolean,attribute:"with-week-numbers",reflect:!0})],LyraDatePicker.prototype,"withWeekNumbers",void 0),__decorate([property({attribute:"disabled-dates"})],LyraDatePicker.prototype,"disabledDates",void 0),__decorate([property({attribute:"disabled-days-of-week"})],LyraDatePicker.prototype,"disabledDaysOfWeek",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"isDateDisabled",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"dayContent",void 0),__decorate([property({type:Number,attribute:"min-range",reflect:!0})],LyraDatePicker.prototype,"minRange",void 0),__decorate([property({type:Number,attribute:"max-range",reflect:!0})],LyraDatePicker.prototype,"maxRange",void 0),__decorate([property({attribute:"page-by",reflect:!0,converter:pageByConverter})],LyraDatePicker.prototype,"pageBy",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"today",void 0),__decorate([property({attribute:"focused-date",reflect:!0})],LyraDatePicker.prototype,"focusedDate",void 0),__decorate([property({reflect:!0,converter:viewConverter})],LyraDatePicker.prototype,"view",void 0),__decorate([property({attribute:"previous-label"})],LyraDatePicker.prototype,"previousLabel",void 0),__decorate([property({attribute:"next-label"})],LyraDatePicker.prototype,"nextLabel",void 0),__decorate([state()],LyraDatePicker.prototype,"viewDate",void 0),__decorate([state()],LyraDatePicker.prototype,"rangePreview",void 0);export{LyraDatePicker};
160
+ </div>`}}__decorate([property({reflect:!0})],LyraDatePicker.prototype,"value",void 0),__decorate([property({converter:modeConverter,reflect:!0})],LyraDatePicker.prototype,"mode",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"min",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"max",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDatePicker.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDatePicker.prototype,"readonly",void 0),__decorate([property({converter:monthsConverter,reflect:!0})],LyraDatePicker.prototype,"months",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"locale",void 0),__decorate([property({attribute:"first-day-of-week",reflect:!0})],LyraDatePicker.prototype,"firstDayOfWeek",void 0),__decorate([property({attribute:"weekday-format",converter:weekdayFormatConverter,reflect:!0})],LyraDatePicker.prototype,"weekdayFormat",void 0),__decorate([property({type:Boolean,attribute:"disable-past",reflect:!0})],LyraDatePicker.prototype,"disablePast",void 0),__decorate([property({type:Boolean,attribute:"disable-future",reflect:!0})],LyraDatePicker.prototype,"disableFuture",void 0),__decorate([property({type:Boolean,attribute:"with-outside-days",reflect:!0})],LyraDatePicker.prototype,"withOutsideDays",void 0),__decorate([property({type:Boolean,attribute:"with-week-numbers",reflect:!0})],LyraDatePicker.prototype,"withWeekNumbers",void 0),__decorate([property({attribute:"disabled-dates"})],LyraDatePicker.prototype,"disabledDates",void 0),__decorate([property({attribute:"disabled-days-of-week"})],LyraDatePicker.prototype,"disabledDaysOfWeek",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"isDateDisabled",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"dayContent",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"presets",void 0),__decorate([property({type:Number,attribute:"min-range",reflect:!0})],LyraDatePicker.prototype,"minRange",void 0),__decorate([property({type:Number,attribute:"max-range",reflect:!0})],LyraDatePicker.prototype,"maxRange",void 0),__decorate([property({attribute:"page-by",reflect:!0,converter:pageByConverter})],LyraDatePicker.prototype,"pageBy",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"today",void 0),__decorate([property({attribute:"focused-date",reflect:!0})],LyraDatePicker.prototype,"focusedDate",void 0),__decorate([property({reflect:!0,converter:viewConverter})],LyraDatePicker.prototype,"view",void 0),__decorate([property({attribute:"previous-label"})],LyraDatePicker.prototype,"previousLabel",void 0),__decorate([property({attribute:"next-label"})],LyraDatePicker.prototype,"nextLabel",void 0),__decorate([state()],LyraDatePicker.prototype,"viewDate",void 0),__decorate([state()],LyraDatePicker.prototype,"rangePreview",void 0);export{LyraDatePicker};
@@ -324,6 +324,47 @@ import{css}from"lit";const styles=css`
324
324
  var(--lr-opacity-disabled)
325
325
  );
326
326
  }
327
+ [part~="presets"] {
328
+ display: flex;
329
+ flex-wrap: wrap;
330
+ gap: var(--lr-space-2xs);
331
+ margin-block-end: var(--lr-space-xs);
332
+ }
333
+ [part~="preset-button"] {
334
+ font: inherit;
335
+ font-size: var(--lr-font-size-xs);
336
+ min-block-size: var(--lr-icon-button-size);
337
+ padding: var(--lr-size-0-15rem) var(--lr-size-0-5rem);
338
+ border: var(--lr-border-width-thin) solid var(--lr-color-border);
339
+ border-radius: var(--lr-radius);
340
+ background: var(--lr-color-surface);
341
+ color: var(--lr-color-text);
342
+ cursor: pointer;
343
+ white-space: normal;
344
+ overflow-wrap: break-word;
345
+ }
346
+ [part~="preset-button"]:hover:not(:disabled) {
347
+ background: var(--lr-date-picker-preset-hover-bg, var(--lr-color-brand-quiet));
348
+ }
349
+ [part~="preset-button"]:active:not(:disabled) {
350
+ background: var(
351
+ --lr-date-picker-preset-active-bg,
352
+ color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active))
353
+ );
354
+ }
355
+ [part~="preset-button"][data-active] {
356
+ background: var(--lr-date-picker-preset-selected-bg, var(--lr-color-brand));
357
+ border-color: var(--lr-date-picker-preset-selected-bg, var(--lr-color-brand));
358
+ color: var(--lr-color-brand-contrast, var(--lr-color-surface));
359
+ }
360
+ [part~="preset-button"]:focus-visible {
361
+ outline: var(--lr-focus-ring);
362
+ outline-offset: var(--lr-focus-ring-offset);
363
+ }
364
+ [part~="preset-button"]:disabled {
365
+ cursor: not-allowed;
366
+ opacity: var(--lr-opacity-disabled);
367
+ }
327
368
  @media (forced-colors: active) {
328
369
  .calendar-scroll[data-scroll-overflow] {
329
370
  -webkit-mask-image: none;
@@ -363,5 +404,10 @@ import{css}from"lit";const styles=css`
363
404
  color: GrayText;
364
405
  forced-color-adjust: none;
365
406
  }
407
+ [part~="preset-button"][data-active] {
408
+ forced-color-adjust: none;
409
+ background: Highlight;
410
+ color: HighlightText;
411
+ }
366
412
  }
367
413
  `;export{styles};
@@ -25,7 +25,9 @@ export declare function setFlagUrlResolver(value: LyraFlagUrlResolver | Promise<
25
25
  * a representative country). While that peer package's `flagUrl()` resolves,
26
26
  * the host carries `aria-busy="true"`; a decorative skeleton and ordinary, non-live localized
27
27
  * loading text render in its place. A missing or failed peer resolver fails closed with a localized visible error and a
28
- * shared light-DOM assertive announcement;
28
+ * shared light-DOM assertive announcement, plus a one-time `console.warn` naming the code and the
29
+ * `flag-peer.js` import that registers a resolver -- the visible error alone cannot tell a
30
+ * developer that the fix is a missing import rather than missing flag data;
29
31
  * an installed resolver returning no URL for an unknown code remains a valid
30
32
  * empty result.
31
33
  *
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadFlagUrl(importFlags){try{const resolver=resolverFromModule(await importFlags());if(resolver)return resolver;throw new TypeError("The flag peer does not expose a callable flagUrl capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadFlagUrl(importFlags){try{const resolver=resolverFromModule(await importFlags());if(resolver)return resolver;throw new TypeError("The flag peer does not expose a callable flagUrl capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;let warnedMissingFlagResolver=!1;function warnMissingFlagResolver(code){warnedMissingFlagResolver||(warnedMissingFlagResolver=!0,console.warn(`<lr-flag> could not resolve the code "${code}" because no flag resolver is registered. Import the optional peer entry once at startup -- import '@aceshooting/lyra-ui/components/media/flag/flag-peer.js' -- and install '@aceshooting/lyra-flags', or pass an already-resolved URL through 'src' instead.`))}function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),warnedMissingFlagResolver=!1,flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){warnMissingFlagResolver(code),this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
2
2
  >${this.fallback?html`<img part="fallback-image" src=${this.fallback} alt=${this.label??""} />`:nothing}</slot
3
3
  >`;if(state2.status==="error")return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`;const url=state2.status==="loading"||state2.status==="loaded"?state2.url:void 0;if(!url&&state2.status!=="loading")return html``;const code=this.code,alt=hostAriaLabel(this)??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`
4
4
  ${state2.status==="loading"?html`