@aceshooting/lyra-ui 8.2.0 → 8.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  3. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  4. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  5. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  6. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  7. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  8. package/dist/components/forms/combobox/combobox.class.js +1 -1
  9. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  10. package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
  11. package/dist/components/forms/input/input.class.js +1 -1
  12. package/dist/components/forms/input/time-input.class.js +1 -1
  13. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  14. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  15. package/dist/components/forms/phone-input/phone-input.class.js +1 -1
  16. package/dist/components/forms/select/select.class.js +1 -1
  17. package/dist/components/forms/switch/switch.class.js +1 -1
  18. package/dist/components/forms/textarea/textarea.class.js +1 -1
  19. package/dist/components/forms/token-input/token-input.class.js +1 -1
  20. package/dist/components/media/file-input/file-input.class.js +1 -1
  21. package/dist/components/utility/known-date/known-date.class.js +1 -1
  22. package/dist/internal/form-associated.js +1 -1
  23. package/dist/internal/localization-runtime.d.ts +13 -0
  24. package/dist/internal/localization-runtime.js +1 -1
  25. package/dist/internal/lyra-element.d.ts +15 -0
  26. package/dist/internal/lyra-element.js +1 -1
  27. package/dist/internal/package-metadata.d.ts +1 -1
  28. package/dist/internal/package-metadata.js +1 -1
  29. package/dist/testing/happy-dom-shims.d.ts +1 -1
  30. package/dist/testing/happy-dom-shims.js +1 -1
  31. package/package.json +2 -2
  32. package/web-types.json +1 -1
@@ -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--)if(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,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon,calendarIcon,chevronIcon}from"../../../internal/icons.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{dateTimeFormat,parseISO,formatISO,normalizeCalendarMonths,normalizeWeekdayFormat}from"./calendar-core.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./date-input.styles.js";import{LyraDatePicker}from"./date-picker.class.js";import"./date-picker.class.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_chooseDate,LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_dateInputFutureDisabled,LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_dateInputPastDisabled,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_openCalendar,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";function localeDateOrder(locale){try{const parts=getDateTimeFormat(locale||void 0,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2));const order=parts.filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}const monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths};const weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizeDateInputAppearance(value){return value==="filled"||value==="filled-outlined"?value:"outlined"}const appearanceConverter={fromAttribute:normalizeDateInputAppearance,toAttribute:normalizeDateInputAppearance};const placements=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function normalizeDateInputPlacement(value){return typeof value==="string"&&placements.has(value)?value:"bottom-start"}const placementConverter={fromAttribute:normalizeDateInputPlacement,toAttribute:normalizeDateInputPlacement};function normalizeDateInputPageBy(value){return value==="single"?"single":"months"}const pageByConverter={fromAttribute:normalizeDateInputPageBy,toAttribute:normalizeDateInputPageBy};const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value==="string"&&VALIDITY_FLAG_KEYS.has(value)}class LyraDateInputBase extends LyraElement{}class LyraDateInput extends FormAssociated(LyraDateInputBase){static{this.defaultStrings={...super.defaultStrings,chooseDate:LYRA_DEFAULT_chooseDate,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,dateInputFutureDisabled:LYRA_DEFAULT_dateInputFutureDisabled,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,dateInputPastDisabled:LYRA_DEFAULT_dateInputPastDisabled,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,openCalendar:LYRA_DEFAULT_openCalendar,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={mode:{reflect:true,noAccessor:true},min:{reflect:true,noAccessor:true},max:{reflect:true,noAccessor:true},readonly:{type:Boolean,reflect:true,noAccessor:true},disablePast:{type:Boolean,attribute:"disable-past",reflect:true,noAccessor:true},disableFuture:{type:Boolean,attribute:"disable-future",reflect:true,noAccessor:true}}}constructor(){super();this.appearance="outlined";this.open=false;this.withClear=false;this.withHint=false;this.withLabel=false;this.size="m";this.pill=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.accessibleLabel=null;this.locale="";this.months=1;this.firstDayOfWeek="auto";this.weekdayFormat="short";this.withOutsideDays=false;this.withWeekNumbers=false;this.disabledDates="";this.disabledDaysOfWeek="";this.minRange=0;this.maxRange=0;this.pageBy="months";this.today="";this.distance=0;this.placement="bottom-start";this.assumeInteractionOn=["input"];this.validators=[];this.clearLabel="";this.openLabel="";this.dialogLabel="Choose date";this.enterCommittedText=null;this.inputRelayedSinceCommit=false;this.restorePopupFocusOnClose=false;this.transitionToken=0;this.transitionWaiters=new Map;this.interactionListeners=new Map;this.inputId=nextId("date-input");this.popupId=nextId("date-popup");this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.hasStartSlot=false;this.hasEndSlot=false;this.validityRevision=0;this._mode="single";this._min="";this._max="";this._readonly=false;this._disablePast=false;this._disableFuture=false;this.typedBadInput=false;this.now=()=>new Date;this.onVisibilityChange=()=>{if(this.ownerDocument.visibilityState!=="visible")return;this.updateValidity();this.validityRevision++};this.onDocPointer=e=>{if(!e.composedPath().includes(this))void this.hide(false)};this.onInputChange=e=>{e.stopPropagation();const raw=e.target.value;if(this.enterCommittedText!==null&&(raw===this.enterCommittedText||raw===this.displayText)){return}this.enterCommittedText=null;const committed=this.applyTypedText(raw);if(committed){if(!this.inputRelayedSinceCommit){dispatchNativeInputEvent(this,{inputType:"insertReplacementText"})}this.inputRelayedSinceCommit=false;relayNativeEvent(this,e)}else{this.inputRelayedSinceCommit=false}};this.onInput=event=>{this.inputRelayedSinceCommit=true;relayNativeEvent(this,event)};this.onInputKey=e=>{if(e.altKey&&e.key==="ArrowDown"){e.preventDefault();this.show();return}if(this.effectiveDisabled||this.readonly)return;if(!isImplicitSubmission(e))return;const input=this.inputElement;if(input&&input.value!==this.displayText){const raw=input.value;if(this.applyTypedText(raw)){if(!this.inputRelayedSinceCommit){dispatchNativeInputEvent(this,{inputType:"insertReplacementText"})}this.inputRelayedSinceCommit=false;dispatchNativeEvent(this,"change")}else{this.inputRelayedSinceCommit=false}this.enterCommittedText=raw}submitOnEnter(this,e)};this.onInputBlur=event=>{this.touched=true;relayNativeEvent(this,event)};this.onInputFocus=event=>{relayNativeEvent(this,event)};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:true}).length>0};this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:true}).length>0};this.onPickerInput=e=>{const picker=e.target;this.value=picker.value;this.inputRelayedSinceCommit=false;relayNativeEvent(this,e)};this.onPickerChange=e=>{const picker=e.target;this.value=picker.value;relayNativeEvent(this,e);this.hide(true)};this.addEventListener("invalid",()=>{this.touched=true})}get mode(){return this._mode}set mode(next){const old=this._mode;this._mode=next==="range"?"range":"single";this.internals.setFormValue(this.isIncompleteRangeValue(this.value)?"":this.value);this.updateValidity();this.syncCustomStates();this.requestUpdate("mode",old)}get min(){return this._min}set min(next){const old=this._min;this._min=next??"";this.updateValidity();this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"";this.updateValidity();this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=Boolean(next);this.toggleAttribute("readonly",this._readonly);if(this._readonly)void this.hide();this.updateValidity();this.requestUpdate("readonly",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next;if(next)void this.hide();this.syncCustomStates()}get disablePast(){return this._disablePast}set disablePast(next){const old=this._disablePast;this._disablePast=Boolean(next);this.updateValidity();this.requestUpdate("disablePast",old)}get disableFuture(){return this._disableFuture}set disableFuture(next){const old=this._disableFuture;this._disableFuture=Boolean(next);this.updateValidity();this.requestUpdate("disableFuture",old)}get input(){return this.inputElement}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){if(this.inputElement)this.inputElement.selectionStart=value??0}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){if(this.inputElement)this.inputElement.selectionEnd=value??0}get selectionDirection(){return this.inputElement?.selectionDirection??null}set selectionDirection(value){if(this.inputElement)this.inputElement.selectionDirection=value??"none"}get value(){return super.value}set value(next){this.setTypedBadInput(false);const normalized=this.normalizeCommittedValue(next??"");super.value=normalized;this.internals.setFormValue(this.isIncompleteRangeValue(normalized)?"":normalized);this.syncCustomStates()}get valueAsDate(){return this.mode==="single"?this.parseStrictISO(this.value):null}set valueAsDate(next){this.value=next instanceof Date&&Number.isFinite(next.getTime())?formatISO(next):""}get valueAsRange(){if(this.mode!=="range")return{from:null,to:null};const[from="",to=""]=this.value.split("/");return{from:this.parseStrictISO(from),to:this.parseStrictISO(to)}}set valueAsRange(next){let from=next?.from instanceof Date&&Number.isFinite(next.from.getTime())?next.from:null;let to=next?.to instanceof Date&&Number.isFinite(next.to.getTime())?next.to:null;if(from&&to&&to<from)[from,to]=[to,from];this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get validationTarget(){return this.validationTargetOverride??this.inputElement}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0;this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity("");this.updateValidity()}setTypedBadInput(next){const old=this.typedBadInput;this.typedBadInput=next;if(old!==next)this.requestUpdate("typedBadInput",old)}parseStrictISO(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return null;return parseISO(value)}normalizeCommittedValue(value){if(value==="")return"";const parts=value.split("/");if(parts.length!==1&&parts.length!==2)return"";const dates=parts.map(part=>this.parseStrictISO(part));if(dates.some(date=>date===null))return"";if(parts.length===2&&dates[0]>dates[1])return`${parts[1]}/${parts[0]}`;return value}isIncompleteRangeValue(value){return this.mode==="range"&&value!==""&&!value.includes("/")}valueDates(value){const parts=value.split("/");const expectedParts=this.mode==="range"&&parts.length===2?2:1;if(parts.length!==expectedParts)return null;const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?null:dates}configuredDisabledDateKeys(){const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return new Set(values.map(value=>value instanceof Date?value:parseISO(String(value))).filter(value=>value instanceof Date&&Number.isFinite(value.getTime())).map(value=>formatISO(value)))}configuredDisabledWeekdays(){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};return new Set(String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0))}rangeLength(from,to){const fromUtc=Date.UTC(from.getFullYear(),from.getMonth(),from.getDate());const toUtc=Date.UTC(to.getFullYear(),to.getMonth(),to.getDate());return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}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===true)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[]){if(isValidityFlagKey(key))flags[key]=true}if(!Object.values(flags).some(Boolean))flags.customError=true;let message=typeof checked?.message==="string"?checked.message:"";if(!message&&typeof validator.message==="string")message=validator.message;if(!message&&typeof validator.message==="function"){message=validator.message(this)}return{flags,message:message||this.localize("dateInputInvalid")}}result=typeof validator==="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:true},message:this.localize("dateInputInvalid")}}if(result===void 0||result===true)continue;if(typeof result==="string")return{flags:{customError:true},message:result};if(result===false)return{flags:{customError:true},message:this.localize("dateInputInvalid")};if(result&&typeof result==="object"&&Object.values(result).some(Boolean)){return{flags:result,message:this.localize("dateInputInvalid")}}}return{}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let underflowMessage="";let overflowMessage="";const incompleteRange=this.isIncompleteRangeValue(this.value);if(this.required&&(this.value===""||incompleteRange))flags.valueMissing=true;if(this.typedBadInput)flags.badInput=true;if(this.value!==""){const dates=this.valueDates(this.value);if(!dates){flags.badInput=true}else{const min=this.parseStrictISO(this.min);const max=this.parseStrictISO(this.max);const configuredToday=this.parseStrictISO(this.today);const now=configuredToday??this.now();const today=new Date(now.getFullYear(),now.getMonth(),now.getDate());if(min!==null&&dates.some(date=>date<min)){flags.rangeUnderflow=true;underflowMessage=this.localize("dateInputMinMessage",void 0,{min:this.min})}if(this.disablePast&&dates.some(date=>date<today)){flags.rangeUnderflow=true;underflowMessage||=this.localize("dateInputPastDisabled")}if(max!==null&&dates.some(date=>date>max)){flags.rangeOverflow=true;overflowMessage=this.localize("dateInputMaxMessage",void 0,{max:this.max})}if(this.disableFuture&&dates.some(date=>date>today)){flags.rangeOverflow=true;overflowMessage||=this.localize("dateInputFutureDisabled")}const disabledDates=this.configuredDisabledDateKeys();const disabledWeekdays=this.configuredDisabledWeekdays();let configuredDisabled=dates.some(date=>disabledDates.has(formatISO(date))||disabledWeekdays.has(date.getDay()));if(!configuredDisabled&&this.isDateDisabled){try{configuredDisabled=dates.some(date=>Boolean(this.isDateDisabled?.(new Date(date.getTime()))))}catch{configuredDisabled=false}}if(configuredDisabled)flags.customError=true;if(this.mode==="range"&&dates.length===2){const length=this.rangeLength(dates[0],dates[1]);const minimum=finiteCount(this.minRange,0);const maximum=finiteCount(this.maxRange,0);if(minimum>0&&length<minimum){flags.rangeUnderflow=true;underflowMessage||=this.localize("dateInputInvalid")}if(maximum>0&&length>maximum){flags.rangeOverflow=true;overflowMessage||=this.localize("dateInputInvalid")}}}}const configured=this.validatorResult();if(configured.flags)Object.assign(flags,configured.flags);let message="";if(configured.message)message=configured.message;else if(flags.badInput||flags.customError)message=this.localize("dateInputInvalid");else if(flags.rangeUnderflow)message=underflowMessage;else if(flags.rangeOverflow)message=overflowMessage;else if(flags.valueMissing)message=this.localize("fieldRequired");this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){this.updateValidity();return super.checkValidity()}reportValidity(){this.updateValidity();return super.reportValidity()}bindVisibilityListener(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.visibilityListenerDocument===ownerDocument&&this.visibilityListener)return;this.unbindVisibilityListener();const listener=()=>{if(this.visibilityListener!==listener||this.visibilityListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onVisibilityChange()};this.visibilityListenerDocument=ownerDocument;this.visibilityListener=listener;ownerDocument.addEventListener("visibilitychange",listener)}unbindVisibilityListener(){if(this.visibilityListenerDocument&&this.visibilityListener){this.visibilityListenerDocument.removeEventListener("visibilitychange",this.visibilityListener)}this.visibilityListenerDocument=void 0;this.visibilityListener=void 0}get displayText(){const parts=this.value.split("/");const from=parseISO(parts[0]);const to=parseISO(parts[1]??"");if(!from)return"";const formatter=dateTimeFormat(this.effectiveLocale,{});const fmt=d=>formatter.format(d);return this.mode==="range"&&to?`${fmt(from)} \u2013 ${fmt(to)}`:fmt(from)}willUpdate(changed){if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error");this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasStartSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="start");this.hasEndSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="end")}if(changed.has("open")){if(this.open&&this.isConnected){this.bindDocumentPointer()}else{this.unbindDocumentPointer()}}}show(){if(this.open||this.effectiveDisabled||this.readonly)return Promise.resolve();const request=this.emit("lr-show",void 0,{cancelable:true});if(request.defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;void this.settleTransition("lr-after-show");return settled}hide(restoreFocus=false){if(!this.open)return Promise.resolve();const request=this.emit("lr-hide",void 0,{cancelable:true});if(request.defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.restorePopupFocusOnClose||=restoreFocus;this.open=false;void this.settleTransition("lr-after-hide");return settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.bindDocumentPointer();this.cleanupFn?.();const anchor=this.renderRoot.querySelector('[part="input-wrapper"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)});this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{void this.hide(true)},modal:false,trapFocus:false})}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const popup=this.renderRoot.querySelector('[part="popup"]');const animations=popup?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(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)return;this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}connectedCallback(){super.connectedCallback();this.bindVisibilityListener();this.syncInteractionListeners();this.syncValidatorAttributeObserver();this.syncCustomStates();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.reconnectOpenPopup())}clear(){if(!this.value||this.effectiveDisabled||this.readonly)return;this.touched=true;this.value="";this.emit("lr-clear");this.inputRelayedSinceCommit=false;dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"});dispatchNativeEvent(this,"change")}syncInteractionListeners(){const requested=new Set((Array.isArray(this.assumeInteractionOn)?this.assumeInteractionOn:[]).filter(name=>typeof name==="string"&&name.length>0));for(const[name,listener]of this.interactionListeners){if(requested.has(name))continue;this.removeEventListener(name,listener);this.interactionListeners.delete(name)}for(const name of requested){if(this.interactionListeners.has(name))continue;const listener=()=>{this.touched=true;this.syncCustomStates()};this.addEventListener(name,listener);this.interactionListeners.set(name,listener)}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView;const 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))continue;for(const name of observed){if(typeof name==="string"&&name.length>0)attributes.add(name)}}if(attributes.size===0)return;const binding={};const observer=new MutationObserverCtor(()=>{if(this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.updateValidity();this.validityRevision++});binding.observer=observer;binding.owner=owner;try{observer.observe(this,{attributes:true,attributeFilter:[...attributes]});this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0;binding?.observer.disconnect()}syncCustomStates(){setCustomState(this.internals,"blank",this.value==="");setCustomState(this.internals,"disabled",this.effectiveDisabled);setCustomState(this.internals,"open",this.open);setCustomState(this.internals,"range",this.mode==="range")}disconnectedCallback(){this.transitionToken++;this.cleanupFn?.();this.cleanupFn=void 0;this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=void 0;this.unbindVisibilityListener();this.unbindDocumentPointer();this.disconnectValidatorAttributeObserver();this.restorePopupFocusOnClose=false;this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");for(const[name,listener]of this.interactionListeners)this.removeEventListener(name,listener);this.interactionListeners.clear();this.enterCommittedText=null;this.inputRelayedSinceCommit=false;this.open=false;super.disconnectedCallback()}adoptedCallback(){this.cleanupFn?.();this.cleanupFn=void 0;this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=void 0;this.unbindVisibilityListener();this.unbindDocumentPointer();this.disconnectValidatorAttributeObserver()}updated(changed){super.updated(changed);if(changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("isDateDisabled")||changed.has("minRange")||changed.has("maxRange")||changed.has("today")||changed.has("validators")){this.updateValidity()}if(changed.has("open")||this.open&&(changed.has("placement")||changed.has("distance"))){this.cleanupFn?.();this.cleanupFn=void 0;if(this.open&&this.isConnected){const anchor=this.renderRoot.querySelector('[part="input-wrapper"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(anchor&&popup){this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)})}}}if(changed.has("open")){if(this.open&&this.isConnected){const popup=this.renderRoot.querySelector('[part="popup"]');if(popup){this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{void this.hide(true)},modal:false,trapFocus:false})}}else if(!this.open){this.overlayHandle?.deactivate({restoreFocus:this.restorePopupFocusOnClose});this.overlayHandle=void 0;this.restorePopupFocusOnClose=false}}if(changed.has("assumeInteractionOn"))this.syncInteractionListeners();if(changed.has("validators"))this.syncValidatorAttributeObserver();this.syncCustomStates();if(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("mode")||changed.has("min")||changed.has("max")||changed.has("readonly")||changed.has("disablePast")||changed.has("disableFuture")||changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("minRange")||changed.has("maxRange")||changed.has("validators")||changed.has("typedBadInput")||changed.has("validityRevision")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}applyTypedText(raw){this.enterCommittedText=null;const trimmed=raw.trim();if(!trimmed){this.value="";return true}const parsed=this.mode==="range"?this.parseRangeText(trimmed):this.parseSingleText(trimmed);if(parsed){this.value=parsed;return true}if(this.inputElement)this.inputElement.value=this.displayText;this.setTypedBadInput(true);this.updateValidity();return false}parseOneDate(raw){const looksLikeISO=/^\d{4}-\d{2}-\d{2}$/.test(raw);if(looksLikeISO)return parseISO(raw);const ambiguous=/^(\d{1,4})[/.-](\d{1,4})[/.-](\d{1,4})$/.exec(raw);if(ambiguous){const[,g1,g2,g3]=ambiguous;if(g1.length===4){return parseISO(`${g1}-${g2.padStart(2,"0")}-${g3.padStart(2,"0")}`)}const order=localeDateOrder(this.effectiveLocale);const values=[Number(g1),Number(g2),Number(g3)];const fields={};order.forEach((type,i)=>{fields[type]=values[i]});if(fields.day!=null&&fields.month!=null&&fields.year!=null){const year=fields.year<100?2e3+fields.year:fields.year;return parseISO(`${String(year).padStart(4,"0")}-${String(fields.month).padStart(2,"0")}-${String(fields.day).padStart(2,"0")}`)}}const timestamp=Date.parse(raw);return Number.isNaN(timestamp)?null:new Date(timestamp)}parseSingleText(raw){const parsed=this.parseOneDate(raw);return parsed?formatISO(parsed):null}parseRangeText(raw){if(/^\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}$/.test(raw)){const[a,b]=raw.split("/");const from2=parseISO(a);const to2=parseISO(b);if(!from2||!to2)return null;return from2<=to2?raw:`${b}/${a}`}const separator=" \u2013 ";const idx=raw.indexOf(separator);if(idx===-1)return null;const from=this.parseOneDate(raw.slice(0,idx).trim());const to=this.parseOneDate(raw.slice(idx+separator.length).trim());if(!from||!to)return null;return from<=to?`${formatISO(from)}/${formatISO(to)}`:`${formatISO(to)}/${formatISO(from)}`}click(){if(!this.effectiveDisabled)this.inputElement?.click()}focus(options){this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.applyTypedText(input.value)}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formResetCallback(){super.formResetCallback();this.touched=false}formDisabledCallback(disabled){const parent=Object.getPrototypeOf(LyraDateInput.prototype);parent.formDisabledCallback.call(this,disabled);if(disabled)void this.hide();this.syncCustomStates()}render(){const hasValue=this.value.length>0;const hasHint=this.withHint||this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const hasLabel=this.withLabel||this.hasLabelSlot||this.label.length>0;const invalid=this.touched&&!this.internals.validity.valid;const describedBy=[hasError?"date-input-error":"",hasHint?"date-input-hint":""].filter(Boolean).join(" ");const dynamicDaySlots=[...new Set(Array.from(this.children).map(child=>child.getAttribute("slot")??"").filter(name=>/^day-\d{4}-\d{2}-\d{2}$/.test(name)))];return html`
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--)if(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,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon,calendarIcon,chevronIcon}from"../../../internal/icons.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{dateTimeFormat,parseISO,formatISO,normalizeCalendarMonths,normalizeWeekdayFormat}from"./calendar-core.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./date-input.styles.js";import{LyraDatePicker}from"./date-picker.class.js";import"./date-picker.class.js";import{getDateTimeFormat}from"../../../internal/intl-cache.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_chooseDate,LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_dateInputFutureDisabled,LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_dateInputPastDisabled,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_openCalendar,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";function localeDateOrder(locale){try{const parts=getDateTimeFormat(locale||void 0,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2));const order=parts.filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}const monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths};const weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizeDateInputAppearance(value){return value==="filled"||value==="filled-outlined"?value:"outlined"}const appearanceConverter={fromAttribute:normalizeDateInputAppearance,toAttribute:normalizeDateInputAppearance};const placements=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function normalizeDateInputPlacement(value){return typeof value==="string"&&placements.has(value)?value:"bottom-start"}const placementConverter={fromAttribute:normalizeDateInputPlacement,toAttribute:normalizeDateInputPlacement};function normalizeDateInputPageBy(value){return value==="single"?"single":"months"}const pageByConverter={fromAttribute:normalizeDateInputPageBy,toAttribute:normalizeDateInputPageBy};const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value==="string"&&VALIDITY_FLAG_KEYS.has(value)}class LyraDateInputBase extends LyraElement{}class LyraDateInput extends FormAssociated(LyraDateInputBase){static{this.defaultStrings={...super.defaultStrings,chooseDate:LYRA_DEFAULT_chooseDate,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,dateInputFutureDisabled:LYRA_DEFAULT_dateInputFutureDisabled,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,dateInputPastDisabled:LYRA_DEFAULT_dateInputPastDisabled,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,openCalendar:LYRA_DEFAULT_openCalendar,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={mode:{reflect:true,noAccessor:true},min:{reflect:true,noAccessor:true},max:{reflect:true,noAccessor:true},readonly:{type:Boolean,reflect:true,noAccessor:true},disablePast:{type:Boolean,attribute:"disable-past",reflect:true,noAccessor:true},disableFuture:{type:Boolean,attribute:"disable-future",reflect:true,noAccessor:true}}}constructor(){super();this.appearance="outlined";this.open=false;this.withClear=false;this.withHint=false;this.withLabel=false;this.size="m";this.pill=false;this.label="";this.hint="";this.errorText="";this.placeholder="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.autocomplete="";this.inputMode="";this.enterKeyHint="";this.accessibleLabel=null;this.locale="";this.months=1;this.firstDayOfWeek="auto";this.weekdayFormat="short";this.withOutsideDays=false;this.withWeekNumbers=false;this.disabledDates="";this.disabledDaysOfWeek="";this.minRange=0;this.maxRange=0;this.pageBy="months";this.today="";this.distance=0;this.placement="bottom-start";this.assumeInteractionOn=["input"];this.validators=[];this.clearLabel="";this.openLabel="";this.dialogLabel="Choose date";this.enterCommittedText=null;this.inputRelayedSinceCommit=false;this.restorePopupFocusOnClose=false;this.transitionToken=0;this.transitionWaiters=new Map;this.interactionListeners=new Map;this.inputId=nextId("date-input");this.popupId=nextId("date-popup");this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.hasStartSlot=false;this.hasEndSlot=false;this.validityRevision=0;this._mode="single";this._min="";this._max="";this._readonly=false;this._disablePast=false;this._disableFuture=false;this.typedBadInput=false;this.now=()=>new Date;this.onVisibilityChange=()=>{if(this.ownerDocument.visibilityState!=="visible")return;this.updateValidity();this.validityRevision++};this.onDocPointer=e=>{if(!e.composedPath().includes(this))void this.hide(false)};this.onInputChange=e=>{e.stopPropagation();const raw=e.target.value;if(this.enterCommittedText!==null&&(raw===this.enterCommittedText||raw===this.displayText)){return}this.enterCommittedText=null;const committed=this.applyTypedText(raw);if(committed){if(!this.inputRelayedSinceCommit){dispatchNativeInputEvent(this,{inputType:"insertReplacementText"})}this.inputRelayedSinceCommit=false;relayNativeEvent(this,e)}else{this.inputRelayedSinceCommit=false}};this.onInput=event=>{this.inputRelayedSinceCommit=true;relayNativeEvent(this,event)};this.onInputKey=e=>{if(e.altKey&&e.key==="ArrowDown"){e.preventDefault();this.show();return}if(this.effectiveDisabled||this.readonly)return;if(!isImplicitSubmission(e))return;const input=this.inputElement;if(input&&input.value!==this.displayText){const raw=input.value;if(this.applyTypedText(raw)){if(!this.inputRelayedSinceCommit){dispatchNativeInputEvent(this,{inputType:"insertReplacementText"})}this.inputRelayedSinceCommit=false;dispatchNativeEvent(this,"change")}else{this.inputRelayedSinceCommit=false}this.enterCommittedText=raw}submitOnEnter(this,e)};this.onInputBlur=event=>{if(!this.effectiveDisabled)this.touched=true;relayNativeEvent(this,event)};this.onInputFocus=event=>{relayNativeEvent(this,event)};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:true}).length>0};this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:true}).length>0};this.onPickerInput=e=>{const picker=e.target;this.value=picker.value;this.inputRelayedSinceCommit=false;relayNativeEvent(this,e)};this.onPickerChange=e=>{const picker=e.target;this.value=picker.value;relayNativeEvent(this,e);this.hide(true)};this.addEventListener("invalid",()=>{this.touched=true})}get mode(){return this._mode}set mode(next){const old=this._mode;this._mode=next==="range"?"range":"single";this.internals.setFormValue(this.isIncompleteRangeValue(this.value)?"":this.value);this.updateValidity();this.syncCustomStates();this.requestUpdate("mode",old)}get min(){return this._min}set min(next){const old=this._min;this._min=next??"";this.updateValidity();this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"";this.updateValidity();this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=Boolean(next);this.toggleAttribute("readonly",this._readonly);if(this._readonly)void this.hide();this.updateValidity();this.requestUpdate("readonly",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next;if(next)void this.hide();this.syncCustomStates()}get disablePast(){return this._disablePast}set disablePast(next){const old=this._disablePast;this._disablePast=Boolean(next);this.updateValidity();this.requestUpdate("disablePast",old)}get disableFuture(){return this._disableFuture}set disableFuture(next){const old=this._disableFuture;this._disableFuture=Boolean(next);this.updateValidity();this.requestUpdate("disableFuture",old)}get input(){return this.inputElement}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){if(this.inputElement)this.inputElement.selectionStart=value??0}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){if(this.inputElement)this.inputElement.selectionEnd=value??0}get selectionDirection(){return this.inputElement?.selectionDirection??null}set selectionDirection(value){if(this.inputElement)this.inputElement.selectionDirection=value??"none"}get value(){return super.value}set value(next){this.setTypedBadInput(false);const normalized=this.normalizeCommittedValue(next??"");super.value=normalized;this.internals.setFormValue(this.isIncompleteRangeValue(normalized)?"":normalized);this.syncCustomStates()}get valueAsDate(){return this.mode==="single"?this.parseStrictISO(this.value):null}set valueAsDate(next){this.value=next instanceof Date&&Number.isFinite(next.getTime())?formatISO(next):""}get valueAsRange(){if(this.mode!=="range")return{from:null,to:null};const[from="",to=""]=this.value.split("/");return{from:this.parseStrictISO(from),to:this.parseStrictISO(to)}}set valueAsRange(next){let from=next?.from instanceof Date&&Number.isFinite(next.from.getTime())?next.from:null;let to=next?.to instanceof Date&&Number.isFinite(next.to.getTime())?next.to:null;if(from&&to&&to<from)[from,to]=[to,from];this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get validationTarget(){return this.validationTargetOverride??this.inputElement}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0;this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity("");this.updateValidity()}setTypedBadInput(next){const old=this.typedBadInput;this.typedBadInput=next;if(old!==next)this.requestUpdate("typedBadInput",old)}parseStrictISO(value){if(!/^\d{4}-\d{2}-\d{2}$/.test(value))return null;return parseISO(value)}normalizeCommittedValue(value){if(value==="")return"";const parts=value.split("/");if(parts.length!==1&&parts.length!==2)return"";const dates=parts.map(part=>this.parseStrictISO(part));if(dates.some(date=>date===null))return"";if(parts.length===2&&dates[0]>dates[1])return`${parts[1]}/${parts[0]}`;return value}isIncompleteRangeValue(value){return this.mode==="range"&&value!==""&&!value.includes("/")}valueDates(value){const parts=value.split("/");const expectedParts=this.mode==="range"&&parts.length===2?2:1;if(parts.length!==expectedParts)return null;const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?null:dates}configuredDisabledDateKeys(){const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return new Set(values.map(value=>value instanceof Date?value:parseISO(String(value))).filter(value=>value instanceof Date&&Number.isFinite(value.getTime())).map(value=>formatISO(value)))}configuredDisabledWeekdays(){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};return new Set(String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0))}rangeLength(from,to){const fromUtc=Date.UTC(from.getFullYear(),from.getMonth(),from.getDate());const toUtc=Date.UTC(to.getFullYear(),to.getMonth(),to.getDate());return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}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===true)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[]){if(isValidityFlagKey(key))flags[key]=true}if(!Object.values(flags).some(Boolean))flags.customError=true;let message=typeof checked?.message==="string"?checked.message:"";if(!message&&typeof validator.message==="string")message=validator.message;if(!message&&typeof validator.message==="function"){message=validator.message(this)}return{flags,message:message||this.localize("dateInputInvalid")}}result=typeof validator==="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:true},message:this.localize("dateInputInvalid")}}if(result===void 0||result===true)continue;if(typeof result==="string")return{flags:{customError:true},message:result};if(result===false)return{flags:{customError:true},message:this.localize("dateInputInvalid")};if(result&&typeof result==="object"&&Object.values(result).some(Boolean)){return{flags:result,message:this.localize("dateInputInvalid")}}}return{}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let underflowMessage="";let overflowMessage="";const incompleteRange=this.isIncompleteRangeValue(this.value);if(this.required&&(this.value===""||incompleteRange))flags.valueMissing=true;if(this.typedBadInput)flags.badInput=true;if(this.value!==""){const dates=this.valueDates(this.value);if(!dates){flags.badInput=true}else{const min=this.parseStrictISO(this.min);const max=this.parseStrictISO(this.max);const configuredToday=this.parseStrictISO(this.today);const now=configuredToday??this.now();const today=new Date(now.getFullYear(),now.getMonth(),now.getDate());if(min!==null&&dates.some(date=>date<min)){flags.rangeUnderflow=true;underflowMessage=this.localize("dateInputMinMessage",void 0,{min:this.min})}if(this.disablePast&&dates.some(date=>date<today)){flags.rangeUnderflow=true;underflowMessage||=this.localize("dateInputPastDisabled")}if(max!==null&&dates.some(date=>date>max)){flags.rangeOverflow=true;overflowMessage=this.localize("dateInputMaxMessage",void 0,{max:this.max})}if(this.disableFuture&&dates.some(date=>date>today)){flags.rangeOverflow=true;overflowMessage||=this.localize("dateInputFutureDisabled")}const disabledDates=this.configuredDisabledDateKeys();const disabledWeekdays=this.configuredDisabledWeekdays();let configuredDisabled=dates.some(date=>disabledDates.has(formatISO(date))||disabledWeekdays.has(date.getDay()));if(!configuredDisabled&&this.isDateDisabled){try{configuredDisabled=dates.some(date=>Boolean(this.isDateDisabled?.(new Date(date.getTime()))))}catch{configuredDisabled=false}}if(configuredDisabled)flags.customError=true;if(this.mode==="range"&&dates.length===2){const length=this.rangeLength(dates[0],dates[1]);const minimum=finiteCount(this.minRange,0);const maximum=finiteCount(this.maxRange,0);if(minimum>0&&length<minimum){flags.rangeUnderflow=true;underflowMessage||=this.localize("dateInputInvalid")}if(maximum>0&&length>maximum){flags.rangeOverflow=true;overflowMessage||=this.localize("dateInputInvalid")}}}}const configured=this.validatorResult();if(configured.flags)Object.assign(flags,configured.flags);let message="";if(configured.message)message=configured.message;else if(flags.badInput||flags.customError)message=this.localize("dateInputInvalid");else if(flags.rangeUnderflow)message=underflowMessage;else if(flags.rangeOverflow)message=overflowMessage;else if(flags.valueMissing)message=this.localize("fieldRequired");this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){this.updateValidity();return super.checkValidity()}reportValidity(){this.updateValidity();return super.reportValidity()}bindVisibilityListener(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.visibilityListenerDocument===ownerDocument&&this.visibilityListener)return;this.unbindVisibilityListener();const listener=()=>{if(this.visibilityListener!==listener||this.visibilityListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onVisibilityChange()};this.visibilityListenerDocument=ownerDocument;this.visibilityListener=listener;ownerDocument.addEventListener("visibilitychange",listener)}unbindVisibilityListener(){if(this.visibilityListenerDocument&&this.visibilityListener){this.visibilityListenerDocument.removeEventListener("visibilitychange",this.visibilityListener)}this.visibilityListenerDocument=void 0;this.visibilityListener=void 0}get displayText(){const parts=this.value.split("/");const from=parseISO(parts[0]);const to=parseISO(parts[1]??"");if(!from)return"";const formatter=dateTimeFormat(this.effectiveLocale,{});const fmt=d=>formatter.format(d);return this.mode==="range"&&to?`${fmt(from)} \u2013 ${fmt(to)}`:fmt(from)}willUpdate(changed){if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error");this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasStartSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="start");this.hasEndSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="end")}if(changed.has("open")){if(this.open&&this.isConnected){this.bindDocumentPointer()}else{this.unbindDocumentPointer()}}}show(){if(this.open||this.effectiveDisabled||this.readonly)return Promise.resolve();const request=this.emit("lr-show",void 0,{cancelable:true});if(request.defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;void this.settleTransition("lr-after-show");return settled}hide(restoreFocus=false){if(!this.open)return Promise.resolve();const request=this.emit("lr-hide",void 0,{cancelable:true});if(request.defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.restorePopupFocusOnClose||=restoreFocus;this.open=false;void this.settleTransition("lr-after-hide");return settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.bindDocumentPointer();this.cleanupFn?.();const anchor=this.renderRoot.querySelector('[part="input-wrapper"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)});this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{void this.hide(true)},modal:false,trapFocus:false})}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const popup=this.renderRoot.querySelector('[part="popup"]');const animations=popup?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(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)return;this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}connectedCallback(){super.connectedCallback();this.bindVisibilityListener();this.syncInteractionListeners();this.syncValidatorAttributeObserver();this.syncCustomStates();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.reconnectOpenPopup())}clear(){if(!this.value||this.effectiveDisabled||this.readonly)return;this.touched=true;this.value="";this.emit("lr-clear");this.inputRelayedSinceCommit=false;dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"});dispatchNativeEvent(this,"change")}syncInteractionListeners(){const requested=new Set((Array.isArray(this.assumeInteractionOn)?this.assumeInteractionOn:[]).filter(name=>typeof name==="string"&&name.length>0));for(const[name,listener]of this.interactionListeners){if(requested.has(name))continue;this.removeEventListener(name,listener);this.interactionListeners.delete(name)}for(const name of requested){if(this.interactionListeners.has(name))continue;const listener=()=>{this.touched=true;this.syncCustomStates()};this.addEventListener(name,listener);this.interactionListeners.set(name,listener)}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView;const 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))continue;for(const name of observed){if(typeof name==="string"&&name.length>0)attributes.add(name)}}if(attributes.size===0)return;const binding={};const observer=new MutationObserverCtor(()=>{if(this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner)return;this.updateValidity();this.validityRevision++});binding.observer=observer;binding.owner=owner;try{observer.observe(this,{attributes:true,attributeFilter:[...attributes]});this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0;binding?.observer.disconnect()}syncCustomStates(){setCustomState(this.internals,"blank",this.value==="");setCustomState(this.internals,"disabled",this.effectiveDisabled);setCustomState(this.internals,"open",this.open);setCustomState(this.internals,"range",this.mode==="range")}disconnectedCallback(){this.transitionToken++;this.cleanupFn?.();this.cleanupFn=void 0;this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=void 0;this.unbindVisibilityListener();this.unbindDocumentPointer();this.disconnectValidatorAttributeObserver();this.restorePopupFocusOnClose=false;this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");for(const[name,listener]of this.interactionListeners)this.removeEventListener(name,listener);this.interactionListeners.clear();this.enterCommittedText=null;this.inputRelayedSinceCommit=false;this.open=false;super.disconnectedCallback()}adoptedCallback(){this.cleanupFn?.();this.cleanupFn=void 0;this.overlayHandle?.deactivate({restoreFocus:false});this.overlayHandle=void 0;this.unbindVisibilityListener();this.unbindDocumentPointer();this.disconnectValidatorAttributeObserver()}updated(changed){super.updated(changed);if(changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("isDateDisabled")||changed.has("minRange")||changed.has("maxRange")||changed.has("today")||changed.has("validators")){this.updateValidity()}if(changed.has("open")||this.open&&(changed.has("placement")||changed.has("distance"))){this.cleanupFn?.();this.cleanupFn=void 0;if(this.open&&this.isConnected){const anchor=this.renderRoot.querySelector('[part="input-wrapper"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(anchor&&popup){this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)})}}}if(changed.has("open")){if(this.open&&this.isConnected){const popup=this.renderRoot.querySelector('[part="popup"]');if(popup){this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{void this.hide(true)},modal:false,trapFocus:false})}}else if(!this.open){this.overlayHandle?.deactivate({restoreFocus:this.restorePopupFocusOnClose});this.overlayHandle=void 0;this.restorePopupFocusOnClose=false}}if(changed.has("assumeInteractionOn"))this.syncInteractionListeners();if(changed.has("validators"))this.syncValidatorAttributeObserver();this.syncCustomStates();if(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("mode")||changed.has("min")||changed.has("max")||changed.has("readonly")||changed.has("disablePast")||changed.has("disableFuture")||changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("minRange")||changed.has("maxRange")||changed.has("validators")||changed.has("typedBadInput")||changed.has("validityRevision")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}applyTypedText(raw){this.enterCommittedText=null;const trimmed=raw.trim();if(!trimmed){this.value="";return true}const parsed=this.mode==="range"?this.parseRangeText(trimmed):this.parseSingleText(trimmed);if(parsed){this.value=parsed;return true}if(this.inputElement)this.inputElement.value=this.displayText;this.setTypedBadInput(true);this.updateValidity();return false}parseOneDate(raw){const looksLikeISO=/^\d{4}-\d{2}-\d{2}$/.test(raw);if(looksLikeISO)return parseISO(raw);const ambiguous=/^(\d{1,4})[/.-](\d{1,4})[/.-](\d{1,4})$/.exec(raw);if(ambiguous){const[,g1,g2,g3]=ambiguous;if(g1.length===4){return parseISO(`${g1}-${g2.padStart(2,"0")}-${g3.padStart(2,"0")}`)}const order=localeDateOrder(this.effectiveLocale);const values=[Number(g1),Number(g2),Number(g3)];const fields={};order.forEach((type,i)=>{fields[type]=values[i]});if(fields.day!=null&&fields.month!=null&&fields.year!=null){const year=fields.year<100?2e3+fields.year:fields.year;return parseISO(`${String(year).padStart(4,"0")}-${String(fields.month).padStart(2,"0")}-${String(fields.day).padStart(2,"0")}`)}}const timestamp=Date.parse(raw);return Number.isNaN(timestamp)?null:new Date(timestamp)}parseSingleText(raw){const parsed=this.parseOneDate(raw);return parsed?formatISO(parsed):null}parseRangeText(raw){if(/^\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}$/.test(raw)){const[a,b]=raw.split("/");const from2=parseISO(a);const to2=parseISO(b);if(!from2||!to2)return null;return from2<=to2?raw:`${b}/${a}`}const separator=" \u2013 ";const idx=raw.indexOf(separator);if(idx===-1)return null;const from=this.parseOneDate(raw.slice(0,idx).trim());const to=this.parseOneDate(raw.slice(idx+separator.length).trim());if(!from||!to)return null;return from<=to?`${formatISO(from)}/${formatISO(to)}`:`${formatISO(to)}/${formatISO(from)}`}click(){if(!this.effectiveDisabled)this.inputElement?.click()}focus(options){this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.applyTypedText(input.value)}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formResetCallback(){super.formResetCallback();this.touched=false}formDisabledCallback(disabled){const parent=Object.getPrototypeOf(LyraDateInput.prototype);parent.formDisabledCallback.call(this,disabled);if(disabled)void this.hide();this.syncCustomStates()}render(){const hasValue=this.value.length>0;const hasHint=this.withHint||this.hasHintSlot||this.hint.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const hasLabel=this.withLabel||this.hasLabelSlot||this.label.length>0;const invalid=this.touched&&!this.internals.validity.valid;const describedBy=[hasError?"date-input-error":"",hasHint?"date-input-hint":""].filter(Boolean).join(" ");const dynamicDaySlots=[...new Set(Array.from(this.children).map(child=>child.getAttribute("slot")??"").filter(name=>/^day-\d{4}-\d{2}-\d{2}$/.test(name)))];return html`
2
2
  <div part="date-input">
3
3
  <div part="base">
4
4
  <div part="form-control">
@@ -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--)if(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,query}from"lit/decorators.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{nextId}from"../../../internal/a11y.js";import{styles}from"./emoji-picker.styles.js";import{loadEmojiDataCached}from"./emoji-data-loader.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_emojiPickerEmpty,LYRA_DEFAULT_emojiPickerGridLabel,LYRA_DEFAULT_emojiPickerGroupActivities,LYRA_DEFAULT_emojiPickerGroupAnimalsNature,LYRA_DEFAULT_emojiPickerGroupComponent,LYRA_DEFAULT_emojiPickerGroupFlags,LYRA_DEFAULT_emojiPickerGroupFoodDrink,LYRA_DEFAULT_emojiPickerGroupObjects,LYRA_DEFAULT_emojiPickerGroupPeopleBody,LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,LYRA_DEFAULT_emojiPickerGroupSymbols,LYRA_DEFAULT_emojiPickerGroupTravelPlaces,LYRA_DEFAULT_emojiPickerSearchLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const VIRTUALIZE_AT=200;const ITEM_SIZE_FALLBACK=40;const GAP_FALLBACK=2;const VIRTUAL_ROW_HEIGHT_FALLBACK=56;const MAX_VIRTUAL_COLUMNS=20;function probePixels(probe,fallback,allowZero=false){const computed=probe.ownerDocument.defaultView?.getComputedStyle(probe);if(!computed)return fallback;const px=Number.parseFloat(computed.inlineSize);if(!Number.isFinite(px)||px<0)return fallback;return px>0||allowZero?px:fallback}class EmojiPickerBase extends LyraElement{}class LyraEmojiPicker extends FormAssociated(EmojiPickerBase){constructor(){super(...arguments);this._groups=[];this.groupsWereSet=false;this.accessibleLabel="";this.size="m";this.label="";this.hint="";this.errorText="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.touched=false;this.labelId=nextId("emoji-picker-label");this.hintId=nextId("emoji-picker-hint");this.errorId=nextId("emoji-picker-error");this.loadGroups=loadEmojiDataCached;this.queryText="";this.activeIndex=0;this.virtualScrollTop=0;this.observedGridVirtualized=false;this.ownerRealmGeneration=0;this.gridId=nextId("emoji-picker-grid");this.haystacks=new WeakMap;this.onGeometryResize=()=>{const previous=this.geometryCache;this.geometryCache=void 0;if(!previous)return;const next=this.geometry();if(next.itemSize===previous.itemSize&&next.gap===previous.gap&&next.rowHeight===previous.rowHeight){return}this.requestUpdate()};this.onSearchInput=event=>{this.queryText=event.target.value;this.activeIndex=0};this.onSearchFocus=()=>{this.emit("focus")};this.onSearchBlur=()=>{this.touched=true;this.emit("blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedElements({flatten:true}).length>0};this.onNavigationKeyDown=event=>{if(this.effectiveDisabled)return;const items=this.flatItems;if(items.length===0)return;const inSearch=event.currentTarget===this.searchEl;const forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";const backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let target;if(event.key===forwardKey)target=this.activeIndex+1;else if(event.key===backwardKey)target=this.activeIndex-1;else if(event.key==="ArrowDown")target=this.activeIndex+this.columnsPerRow();else if(event.key==="ArrowUp")target=this.activeIndex-this.columnsPerRow();else if(event.key==="Home"&&!inSearch)target=0;else if(event.key==="End"&&!inSearch)target=items.length-1;else if(event.key==="Enter"||event.key===" "&&!inSearch){event.preventDefault();const item=items[this.activeIndex];if(item)this.pick(item);return}else{return}event.preventDefault();this.setActiveIndex(target,!inSearch)};this.onGridFocusIn=event=>{const button=event.target;if(button?.nodeType!==1||button.localName!=="button"){return}const option=button;const indexed=Number(option.dataset["index"]);const index=Number.isInteger(indexed)?indexed:this.optionButtons().indexOf(option);if(index>=0&&index!==this.activeIndex)this.setActiveIndex(index,false)};this.onGridScroll=event=>{if(!this.isVirtualized)return;const grid=event.currentTarget;this.virtualScrollTop=grid.scrollTop;const ownerDocument=this.ownerDocument;const ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;if(this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow===ownerWindow&&this.virtualScrollRafDocument===ownerDocument){return}this.cancelVirtualScrollFrame();const generation=this.ownerRealmGeneration;let handle=0;handle=ownerWindow.requestAnimationFrame(()=>{if(this.virtualScrollRaf!==handle||this.virtualScrollRafWindow!==ownerWindow||this.virtualScrollRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.virtualScrollRaf=void 0;this.virtualScrollRafWindow=void 0;this.virtualScrollRafDocument=void 0;this.requestUpdate()});this.virtualScrollRaf=handle;this.virtualScrollRafWindow=ownerWindow;this.virtualScrollRafDocument=ownerDocument}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,emojiPickerEmpty:LYRA_DEFAULT_emojiPickerEmpty,emojiPickerGridLabel:LYRA_DEFAULT_emojiPickerGridLabel,emojiPickerGroupActivities:LYRA_DEFAULT_emojiPickerGroupActivities,emojiPickerGroupAnimalsNature:LYRA_DEFAULT_emojiPickerGroupAnimalsNature,emojiPickerGroupComponent:LYRA_DEFAULT_emojiPickerGroupComponent,emojiPickerGroupFlags:LYRA_DEFAULT_emojiPickerGroupFlags,emojiPickerGroupFoodDrink:LYRA_DEFAULT_emojiPickerGroupFoodDrink,emojiPickerGroupObjects:LYRA_DEFAULT_emojiPickerGroupObjects,emojiPickerGroupPeopleBody:LYRA_DEFAULT_emojiPickerGroupPeopleBody,emojiPickerGroupSmileysEmotion:LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,emojiPickerGroupSymbols:LYRA_DEFAULT_emojiPickerGroupSymbols,emojiPickerGroupTravelPlaces:LYRA_DEFAULT_emojiPickerGroupTravelPlaces,emojiPickerSearchLabel:LYRA_DEFAULT_emojiPickerSearchLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,styles]}get groups(){return this._groups}set groups(value){const old=this._groups;this.groupsWereSet=true;this._groups=Array.isArray(value)?value:[];this.requestUpdate("groups",old)}connectedCallback(){super.connectedCallback();this.observeGeometryProbe();this.syncGridObserver();if(this.groupsWereSet)return;const ownerDocument=this.ownerDocument;const generation=this.ownerRealmGeneration;void this.loadGroups().then(loaded=>{if(this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||!loaded||this.groupsWereSet){return}this.groups=loaded})}haystackFor(item){const locale=this.effectiveLocale;let cached=this.haystacks.get(item);if(cached===void 0||cached.locale!==locale){cached={locale,value:[item.name,...item.shortcodes??[]].join(" ").toLocaleLowerCase(locale)};this.haystacks.set(item,cached)}return cached.value}get filteredGroups(){const q=this.queryText.trim().toLocaleLowerCase(this.effectiveLocale);if(!q)return this.groups;return this.groups.map(group=>({...group,emojis:group.emojis.filter(item=>this.haystackFor(item).includes(q))})).filter(group=>group.emojis.length>0)}get flatItems(){return this.filteredGroups.flatMap(group=>group.emojis)}get isVirtualized(){return this.flatItems.length>=VIRTUALIZE_AT}geometry(){if(this.geometryCache)return this.geometryCache;const probe=this.geometryProbe;if(!probe){return{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK}}this.geometryCache={itemSize:probePixels(probe.item,ITEM_SIZE_FALLBACK),gap:probePixels(probe.gap,GAP_FALLBACK,true),rowHeight:probePixels(probe.row,VIRTUAL_ROW_HEIGHT_FALLBACK)};return this.geometryCache}syncGeometryProbe(){if(this.geometryProbe||!this.isVirtualized)return;const makeProbe=name=>{const probe=this.ownerDocument.createElement("div");probe.dataset["probe"]=name;return probe};const root=makeProbe("root");root.setAttribute("aria-hidden","true");const item=makeProbe("item");const gap=makeProbe("gap");const row=makeProbe("row");root.append(item,gap,row);this.renderRoot.append(root);this.geometryProbe={root,item,gap,row};this.observeGeometryProbe()}observeGeometryProbe(){const probe=this.geometryProbe;const ownerDocument=this.ownerDocument;if(!probe||!this.isConnected)return;if(this.geometryObserver&&this.geometryObserverDocument===ownerDocument&&this.geometryObserverRoot===probe.root){return}this.resetGeometryObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration;const observer=new ResizeObserverCtor(()=>{if(this.geometryObserver!==observer||this.geometryObserverDocument!==ownerDocument||this.geometryObserverRoot!==probe.root||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onGeometryResize()});this.geometryObserver=observer;this.geometryObserverDocument=ownerDocument;this.geometryObserverRoot=probe.root;observer.observe(probe.item);observer.observe(probe.gap);observer.observe(probe.row)}resetGeometryObserver(){this.geometryObserver?.disconnect();this.geometryObserver=void 0;this.geometryObserverDocument=void 0;this.geometryObserverRoot=void 0}groupLabel(group){return group.labelKey?this.localize(group.labelKey):group.label}virtualRows(){const columns=this.columnsPerRow();let index=0;const rows=[];for(const group of this.filteredGroups){for(let offset=0;offset<group.emojis.length;offset+=columns){rows.push({label:offset===0?this.groupLabel(group):void 0,items:group.emojis.slice(offset,offset+columns).map(item=>({item,index:index++}))})}}return rows}optionButtons(){return[...this.renderRoot.querySelectorAll('[part="emoji"]')]}columnsPerRow(){if(this.isVirtualized){const grid=this.renderRoot.querySelector('[part="grid"]');const width=grid?.clientWidth??0;const{itemSize,gap}=this.geometry();return Math.min(MAX_VIRTUAL_COLUMNS,Math.max(1,Math.floor((Math.max(width,itemSize)+gap)/(itemSize+gap))))}const buttons=this.optionButtons();if(buttons.length===0)return 1;const firstTop=buttons[0].offsetTop;let columns=0;for(const button of buttons){if(button.offsetTop!==firstTop)break;columns+=1}return Math.max(1,columns)}setActiveIndex(next,focusTarget){const buttons=this.optionButtons();if(buttons.length===0&&!this.isVirtualized)return;this.activeIndex=Math.max(0,Math.min(next,this.flatItems.length-1));const target=this.isVirtualized?this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`):buttons[this.activeIndex];const previous=this.renderRoot.querySelector('[part="emoji"][data-active]');if(previous&&previous!==target){previous.tabIndex=-1;previous.setAttribute("aria-selected","false");previous.removeAttribute("data-active")}if(target){target.tabIndex=0;target.setAttribute("aria-selected","true");target.setAttribute("data-active","");this.searchEl?.setAttribute("aria-activedescendant",target.id);target.scrollIntoView({block:"nearest"})}else if(this.isVirtualized){this.searchEl?.setAttribute("aria-activedescendant",`${this.gridId}-item-${this.activeIndex}`);const rowIndex=this.virtualRows().findIndex(row=>row.items.some(({index})=>index===this.activeIndex));const grid=this.renderRoot.querySelector('[part="grid"]');if(rowIndex>=0&&grid){grid.scrollTop=rowIndex*this.geometry().rowHeight;this.virtualScrollTop=grid.scrollTop;this.requestUpdate()}}if(focusTarget)target?.focus()}pick(item){if(this.effectiveDisabled)return;this.value=item.emoji;this.emit("input");this.emit("change");this.emit("lr-change",{emoji:item.emoji})}cancelVirtualScrollFrame(){if(this.virtualScrollRaf!==void 0){this.virtualScrollRafWindow?.cancelAnimationFrame(this.virtualScrollRaf)}this.virtualScrollRaf=void 0;this.virtualScrollRafWindow=void 0;this.virtualScrollRafDocument=void 0}syncGridObserver(){const grid=this.renderRoot.querySelector('[part="grid"]');const virtualized=this.isVirtualized;const ownerDocument=this.ownerDocument;if(grid===this.observedGrid&&virtualized===this.observedGridVirtualized&&(!virtualized||this.gridResizeObserverDocument===ownerDocument)){return}this.resetGridObserver();if(!this.isConnected)return;this.observedGrid=grid??void 0;this.observedGridVirtualized=virtualized;if(!grid||!virtualized)return;grid.addEventListener("scroll",this.onGridScroll,{passive:true});const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration;const observer=new ResizeObserverCtor(()=>{if(this.gridResizeObserver!==observer||this.gridResizeObserverDocument!==ownerDocument||this.observedGrid!==grid||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.requestUpdate()});this.gridResizeObserver=observer;this.gridResizeObserverDocument=ownerDocument;observer.observe(grid)}resetGridObserver(){this.observedGrid?.removeEventListener("scroll",this.onGridScroll);this.gridResizeObserver?.disconnect();this.gridResizeObserver=void 0;this.gridResizeObserverDocument=void 0;this.observedGrid=void 0;this.observedGridVirtualized=false;this.cancelVirtualScrollFrame()}willUpdate(changed){super.willUpdate(changed);this.syncGeometryProbe();if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}updated(changed){this.syncGridObserver();if(!changed.has("queryText")&&!changed.has("groups"))return;const buttons=this.optionButtons();if(buttons.length===0){this.searchEl?.removeAttribute("aria-activedescendant");return}if(!this.isVirtualized&&this.activeIndex>=buttons.length)this.activeIndex=0;this.setActiveIndex(this.activeIndex,false)}disconnectedCallback(){super.disconnectedCallback();this.resetOwnerRealmResources()}adoptedCallback(){this.resetOwnerRealmResources()}resetOwnerRealmResources(){this.ownerRealmGeneration+=1;this.resetGridObserver();this.resetGeometryObserver()}renderEmojiButton(item,itemIndex,total){return html`<button
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--)if(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,query}from"lit/decorators.js";import{live}from"lit/directives/live.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated}from"../../../internal/form-associated.js";import{nextId}from"../../../internal/a11y.js";import{styles}from"./emoji-picker.styles.js";import{loadEmojiDataCached}from"./emoji-data-loader.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_emojiPickerEmpty,LYRA_DEFAULT_emojiPickerGridLabel,LYRA_DEFAULT_emojiPickerGroupActivities,LYRA_DEFAULT_emojiPickerGroupAnimalsNature,LYRA_DEFAULT_emojiPickerGroupComponent,LYRA_DEFAULT_emojiPickerGroupFlags,LYRA_DEFAULT_emojiPickerGroupFoodDrink,LYRA_DEFAULT_emojiPickerGroupObjects,LYRA_DEFAULT_emojiPickerGroupPeopleBody,LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,LYRA_DEFAULT_emojiPickerGroupSymbols,LYRA_DEFAULT_emojiPickerGroupTravelPlaces,LYRA_DEFAULT_emojiPickerSearchLabel,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_item,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const VIRTUALIZE_AT=200;const ITEM_SIZE_FALLBACK=40;const GAP_FALLBACK=2;const VIRTUAL_ROW_HEIGHT_FALLBACK=56;const MAX_VIRTUAL_COLUMNS=20;function probePixels(probe,fallback,allowZero=false){const computed=probe.ownerDocument.defaultView?.getComputedStyle(probe);if(!computed)return fallback;const px=Number.parseFloat(computed.inlineSize);if(!Number.isFinite(px)||px<0)return fallback;return px>0||allowZero?px:fallback}class EmojiPickerBase extends LyraElement{}class LyraEmojiPicker extends FormAssociated(EmojiPickerBase){constructor(){super(...arguments);this._groups=[];this.groupsWereSet=false;this.accessibleLabel="";this.size="m";this.label="";this.hint="";this.errorText="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.touched=false;this.labelId=nextId("emoji-picker-label");this.hintId=nextId("emoji-picker-hint");this.errorId=nextId("emoji-picker-error");this.loadGroups=loadEmojiDataCached;this.queryText="";this.activeIndex=0;this.virtualScrollTop=0;this.observedGridVirtualized=false;this.ownerRealmGeneration=0;this.gridId=nextId("emoji-picker-grid");this.haystacks=new WeakMap;this.onGeometryResize=()=>{const previous=this.geometryCache;this.geometryCache=void 0;if(!previous)return;const next=this.geometry();if(next.itemSize===previous.itemSize&&next.gap===previous.gap&&next.rowHeight===previous.rowHeight){return}this.requestUpdate()};this.onSearchInput=event=>{this.queryText=event.target.value;this.activeIndex=0};this.onSearchFocus=()=>{this.emit("focus")};this.onSearchBlur=()=>{if(!this.effectiveDisabled)this.touched=true;this.emit("blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedElements({flatten:true}).length>0};this.onNavigationKeyDown=event=>{if(this.effectiveDisabled)return;const items=this.flatItems;if(items.length===0)return;const inSearch=event.currentTarget===this.searchEl;const forwardKey=this.effectiveDirection==="rtl"?"ArrowLeft":"ArrowRight";const backwardKey=this.effectiveDirection==="rtl"?"ArrowRight":"ArrowLeft";let target;if(event.key===forwardKey)target=this.activeIndex+1;else if(event.key===backwardKey)target=this.activeIndex-1;else if(event.key==="ArrowDown")target=this.activeIndex+this.columnsPerRow();else if(event.key==="ArrowUp")target=this.activeIndex-this.columnsPerRow();else if(event.key==="Home"&&!inSearch)target=0;else if(event.key==="End"&&!inSearch)target=items.length-1;else if(event.key==="Enter"||event.key===" "&&!inSearch){event.preventDefault();const item=items[this.activeIndex];if(item)this.pick(item);return}else{return}event.preventDefault();this.setActiveIndex(target,!inSearch)};this.onGridFocusIn=event=>{const button=event.target;if(button?.nodeType!==1||button.localName!=="button"){return}const option=button;const indexed=Number(option.dataset["index"]);const index=Number.isInteger(indexed)?indexed:this.optionButtons().indexOf(option);if(index>=0&&index!==this.activeIndex)this.setActiveIndex(index,false)};this.onGridScroll=event=>{if(!this.isVirtualized)return;const grid=event.currentTarget;this.virtualScrollTop=grid.scrollTop;const ownerDocument=this.ownerDocument;const ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;if(this.virtualScrollRaf!==void 0&&this.virtualScrollRafWindow===ownerWindow&&this.virtualScrollRafDocument===ownerDocument){return}this.cancelVirtualScrollFrame();const generation=this.ownerRealmGeneration;let handle=0;handle=ownerWindow.requestAnimationFrame(()=>{if(this.virtualScrollRaf!==handle||this.virtualScrollRafWindow!==ownerWindow||this.virtualScrollRafDocument!==ownerDocument||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.virtualScrollRaf=void 0;this.virtualScrollRafWindow=void 0;this.virtualScrollRafDocument=void 0;this.requestUpdate()});this.virtualScrollRaf=handle;this.virtualScrollRafWindow=ownerWindow;this.virtualScrollRafDocument=ownerDocument}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,emojiPickerEmpty:LYRA_DEFAULT_emojiPickerEmpty,emojiPickerGridLabel:LYRA_DEFAULT_emojiPickerGridLabel,emojiPickerGroupActivities:LYRA_DEFAULT_emojiPickerGroupActivities,emojiPickerGroupAnimalsNature:LYRA_DEFAULT_emojiPickerGroupAnimalsNature,emojiPickerGroupComponent:LYRA_DEFAULT_emojiPickerGroupComponent,emojiPickerGroupFlags:LYRA_DEFAULT_emojiPickerGroupFlags,emojiPickerGroupFoodDrink:LYRA_DEFAULT_emojiPickerGroupFoodDrink,emojiPickerGroupObjects:LYRA_DEFAULT_emojiPickerGroupObjects,emojiPickerGroupPeopleBody:LYRA_DEFAULT_emojiPickerGroupPeopleBody,emojiPickerGroupSmileysEmotion:LYRA_DEFAULT_emojiPickerGroupSmileysEmotion,emojiPickerGroupSymbols:LYRA_DEFAULT_emojiPickerGroupSymbols,emojiPickerGroupTravelPlaces:LYRA_DEFAULT_emojiPickerGroupTravelPlaces,emojiPickerSearchLabel:LYRA_DEFAULT_emojiPickerSearchLabel,fieldRequired:LYRA_DEFAULT_fieldRequired,item:LYRA_DEFAULT_item,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.styles=[LyraElement.styles,styles]}get groups(){return this._groups}set groups(value){const old=this._groups;this.groupsWereSet=true;this._groups=Array.isArray(value)?value:[];this.requestUpdate("groups",old)}connectedCallback(){super.connectedCallback();this.observeGeometryProbe();this.syncGridObserver();if(this.groupsWereSet)return;const ownerDocument=this.ownerDocument;const generation=this.ownerRealmGeneration;void this.loadGroups().then(loaded=>{if(this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||!loaded||this.groupsWereSet){return}this.groups=loaded})}haystackFor(item){const locale=this.effectiveLocale;let cached=this.haystacks.get(item);if(cached===void 0||cached.locale!==locale){cached={locale,value:[item.name,...item.shortcodes??[]].join(" ").toLocaleLowerCase(locale)};this.haystacks.set(item,cached)}return cached.value}get filteredGroups(){const q=this.queryText.trim().toLocaleLowerCase(this.effectiveLocale);if(!q)return this.groups;return this.groups.map(group=>({...group,emojis:group.emojis.filter(item=>this.haystackFor(item).includes(q))})).filter(group=>group.emojis.length>0)}get flatItems(){return this.filteredGroups.flatMap(group=>group.emojis)}get isVirtualized(){return this.flatItems.length>=VIRTUALIZE_AT}geometry(){if(this.geometryCache)return this.geometryCache;const probe=this.geometryProbe;if(!probe){return{itemSize:ITEM_SIZE_FALLBACK,gap:GAP_FALLBACK,rowHeight:VIRTUAL_ROW_HEIGHT_FALLBACK}}this.geometryCache={itemSize:probePixels(probe.item,ITEM_SIZE_FALLBACK),gap:probePixels(probe.gap,GAP_FALLBACK,true),rowHeight:probePixels(probe.row,VIRTUAL_ROW_HEIGHT_FALLBACK)};return this.geometryCache}syncGeometryProbe(){if(this.geometryProbe||!this.isVirtualized)return;const makeProbe=name=>{const probe=this.ownerDocument.createElement("div");probe.dataset["probe"]=name;return probe};const root=makeProbe("root");root.setAttribute("aria-hidden","true");const item=makeProbe("item");const gap=makeProbe("gap");const row=makeProbe("row");root.append(item,gap,row);this.renderRoot.append(root);this.geometryProbe={root,item,gap,row};this.observeGeometryProbe()}observeGeometryProbe(){const probe=this.geometryProbe;const ownerDocument=this.ownerDocument;if(!probe||!this.isConnected)return;if(this.geometryObserver&&this.geometryObserverDocument===ownerDocument&&this.geometryObserverRoot===probe.root){return}this.resetGeometryObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration;const observer=new ResizeObserverCtor(()=>{if(this.geometryObserver!==observer||this.geometryObserverDocument!==ownerDocument||this.geometryObserverRoot!==probe.root||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onGeometryResize()});this.geometryObserver=observer;this.geometryObserverDocument=ownerDocument;this.geometryObserverRoot=probe.root;observer.observe(probe.item);observer.observe(probe.gap);observer.observe(probe.row)}resetGeometryObserver(){this.geometryObserver?.disconnect();this.geometryObserver=void 0;this.geometryObserverDocument=void 0;this.geometryObserverRoot=void 0}groupLabel(group){return group.labelKey?this.localize(group.labelKey):group.label}virtualRows(){const columns=this.columnsPerRow();let index=0;const rows=[];for(const group of this.filteredGroups){for(let offset=0;offset<group.emojis.length;offset+=columns){rows.push({label:offset===0?this.groupLabel(group):void 0,items:group.emojis.slice(offset,offset+columns).map(item=>({item,index:index++}))})}}return rows}optionButtons(){return[...this.renderRoot.querySelectorAll('[part="emoji"]')]}columnsPerRow(){if(this.isVirtualized){const grid=this.renderRoot.querySelector('[part="grid"]');const width=grid?.clientWidth??0;const{itemSize,gap}=this.geometry();return Math.min(MAX_VIRTUAL_COLUMNS,Math.max(1,Math.floor((Math.max(width,itemSize)+gap)/(itemSize+gap))))}const buttons=this.optionButtons();if(buttons.length===0)return 1;const firstTop=buttons[0].offsetTop;let columns=0;for(const button of buttons){if(button.offsetTop!==firstTop)break;columns+=1}return Math.max(1,columns)}setActiveIndex(next,focusTarget){const buttons=this.optionButtons();if(buttons.length===0&&!this.isVirtualized)return;this.activeIndex=Math.max(0,Math.min(next,this.flatItems.length-1));const target=this.isVirtualized?this.renderRoot.querySelector(`[part="emoji"][data-index="${this.activeIndex}"]`):buttons[this.activeIndex];const previous=this.renderRoot.querySelector('[part="emoji"][data-active]');if(previous&&previous!==target){previous.tabIndex=-1;previous.setAttribute("aria-selected","false");previous.removeAttribute("data-active")}if(target){target.tabIndex=0;target.setAttribute("aria-selected","true");target.setAttribute("data-active","");this.searchEl?.setAttribute("aria-activedescendant",target.id);target.scrollIntoView({block:"nearest"})}else if(this.isVirtualized){this.searchEl?.setAttribute("aria-activedescendant",`${this.gridId}-item-${this.activeIndex}`);const rowIndex=this.virtualRows().findIndex(row=>row.items.some(({index})=>index===this.activeIndex));const grid=this.renderRoot.querySelector('[part="grid"]');if(rowIndex>=0&&grid){grid.scrollTop=rowIndex*this.geometry().rowHeight;this.virtualScrollTop=grid.scrollTop;this.requestUpdate()}}if(focusTarget)target?.focus()}pick(item){if(this.effectiveDisabled)return;this.value=item.emoji;this.emit("input");this.emit("change");this.emit("lr-change",{emoji:item.emoji})}cancelVirtualScrollFrame(){if(this.virtualScrollRaf!==void 0){this.virtualScrollRafWindow?.cancelAnimationFrame(this.virtualScrollRaf)}this.virtualScrollRaf=void 0;this.virtualScrollRafWindow=void 0;this.virtualScrollRafDocument=void 0}syncGridObserver(){const grid=this.renderRoot.querySelector('[part="grid"]');const virtualized=this.isVirtualized;const ownerDocument=this.ownerDocument;if(grid===this.observedGrid&&virtualized===this.observedGridVirtualized&&(!virtualized||this.gridResizeObserverDocument===ownerDocument)){return}this.resetGridObserver();if(!this.isConnected)return;this.observedGrid=grid??void 0;this.observedGridVirtualized=virtualized;if(!grid||!virtualized)return;grid.addEventListener("scroll",this.onGridScroll,{passive:true});const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.ownerRealmGeneration;const observer=new ResizeObserverCtor(()=>{if(this.gridResizeObserver!==observer||this.gridResizeObserverDocument!==ownerDocument||this.observedGrid!==grid||this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.requestUpdate()});this.gridResizeObserver=observer;this.gridResizeObserverDocument=ownerDocument;observer.observe(grid)}resetGridObserver(){this.observedGrid?.removeEventListener("scroll",this.onGridScroll);this.gridResizeObserver?.disconnect();this.gridResizeObserver=void 0;this.gridResizeObserverDocument=void 0;this.observedGrid=void 0;this.observedGridVirtualized=false;this.cancelVirtualScrollFrame()}willUpdate(changed){super.willUpdate(changed);this.syncGeometryProbe();if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error")}}updated(changed){this.syncGridObserver();if(!changed.has("queryText")&&!changed.has("groups"))return;const buttons=this.optionButtons();if(buttons.length===0){this.searchEl?.removeAttribute("aria-activedescendant");return}if(!this.isVirtualized&&this.activeIndex>=buttons.length)this.activeIndex=0;this.setActiveIndex(this.activeIndex,false)}disconnectedCallback(){super.disconnectedCallback();this.resetOwnerRealmResources()}adoptedCallback(){this.resetOwnerRealmResources()}resetOwnerRealmResources(){this.ownerRealmGeneration+=1;this.resetGridObserver();this.resetGeometryObserver()}renderEmojiButton(item,itemIndex,total){return html`<button
2
2
  type="button"
3
3
  part="emoji"
4
4
  id=${`${this.gridId}-item-${itemIndex}`}
@@ -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--)if(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{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthViolations}from"../../../internal/length-constraints.js";import{closeIcon,eyeIcon,eyeOffIcon}from"../../../internal/icons.js";import{styles}from"./input.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{finiteCount}from"../../../internal/numbers.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_hidePassword,LYRA_DEFAULT_inputLabel,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showPassword,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const LENGTH_CONSTRAINED_TYPES=["text","password","email","search","tel","url"];class LyraInputBase extends LyraElement{}class LyraInput extends FormAssociated(LyraInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,hidePassword:LYRA_DEFAULT_hidePassword,inputLabel:LYRA_DEFAULT_inputLabel,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showPassword:LYRA_DEFAULT_showPassword,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}get value(){return super.value}set value(next){super.value=next??""}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(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 defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}constructor(){super();this.type="text";this.size="m";this.appearance="outlined";this.filled=false;this.pill=false;this.placeholder="";this.clearable=false;this.withClear=false;this.readonly=false;this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel=null;this.autocomplete="";this.title="";this.autofocus=false;this.spellcheck=true;this.autocapitalize="";this.autocorrectValue=true;this.inputMode="";this.enterKeyHint="";this.passwordToggle=false;this.passwordVisible=false;this.withoutSpinButtons=false;this.noSpinButtons=false;this.touched=false;this.slotPresence=new SlotPresenceController(this);this.onInput=event=>{if(!this.inputEl)return;this.value=this.inputEl.value;relayNativeEvent(this,event);this.emit("lr-input",{value:this.value})};this.onChange=event=>{if(!this.inputEl)return;this.value=this.inputEl.value;relayNativeEvent(this,event);this.emit("lr-change",{value:this.value})};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onBlur=event=>{this.touched=true;relayNativeEvent(this,event);this.emit("lr-blur")};this.onKeyDown=event=>{if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,event)};this.onTogglePasswordVisible=()=>{this.passwordVisible=!this.passwordVisible};this.onClear=()=>{if(this.effectiveDisabled||this.readonly||this.value==="")return;this.value="";if(this.inputEl)this.inputEl.value="";dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"});this.emit("lr-input",{value:this.value});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value});this.emit("lr-clear");this.inputEl?.focus()};this.addEventListener("invalid",()=>{this.touched=true})}formResetCallback(){super.formResetCallback();this.touched=false}get input(){return this.inputEl??null}click(){if(!this.effectiveDisabled)this.inputEl?.click()}focus(options){if(!this.effectiveDisabled)this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}select(){this.inputEl?.select()}get valueAsDate(){const native=this.inputEl;if(!native)return null;if(native.value!==this.value)native.value=this.value;return native.valueAsDate}set valueAsDate(next){const native=this.inputEl;if(!native)return;native.valueAsDate=next;this.value=native.value}get valueAsNumber(){const native=this.inputEl;if(!native)return Number.NaN;if(native.value!==this.value)native.value=this.value;return native.valueAsNumber}set valueAsNumber(next){const native=this.inputEl;if(!native)return;native.valueAsNumber=next;this.value=native.value}showPicker(){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;if(!("showPicker"in HTMLInputElement.prototype))return;try{native.showPicker()}catch{}}stepUp(steps=1){this.applyStep("up",steps)}stepDown(steps=1){this.applyStep("down",steps)}applyStep(direction,steps){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;const count=finiteCount(steps,1);if(count===0)return;try{if(direction==="up")native.stepUp(count);else native.stepDown(count)}catch{return}if(this.value!==native.value)this.value=native.value}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){if(this.inputEl)this.inputEl.selectionStart=value??0}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){if(this.inputEl)this.inputEl.selectionEnd=value??0}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.value=input.value}updateValidity(){const native=this.inputEl;if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(!native){if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:true},this.localize("fieldRequired"))}else{this[SET_ANCHORED_VALIDITY]({})}return}if(native.value!==this.value)native.value=this.value;const sanitizedAway=this.value!==""&&native.value==="";const v=native.validity;const own=LENGTH_CONSTRAINED_TYPES.includes(this.type)?lengthViolations(this.value,this.minlength,this.maxlength):{tooShort:false,tooLong:false};const tooShort=v.tooShort||own.tooShort;const tooLong=v.tooLong||own.tooLong;if(v.valid&&!tooShort&&!tooLong){if(sanitizedAway){this[SET_ANCHORED_VALIDITY]({badInput:true},this.localize("valueInvalid"));return}this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({valueMissing:v.valueMissing,typeMismatch:v.typeMismatch,rangeUnderflow:v.rangeUnderflow,rangeOverflow:v.rangeOverflow,stepMismatch:v.stepMismatch,tooShort,tooLong,patternMismatch:v.patternMismatch,badInput:v.badInput},native.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed);if(changed.has("value")){if(this.value==="")this.internals.states.add("blank");else this.internals.states.delete("blank")}if(changed.has("type")||changed.has("min")||changed.has("max")||changed.has("step")||changed.has("minlength")||changed.has("maxlength")||changed.has("pattern")||changed.has("readonly")){this.updateValidity()}}renderControls(){return nothing}get inputWrapperParts(){return"base form-control-input input-wrapper"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||this.hint.length>0||this.helpText.length>0||this.withHint;const hasError=this.slotPresence.has("error")||this.errorText.length>0;const hasLabel=this.slotPresence.has("label")||this.label.length>0||this.withLabel;const describedBy=[hasError?"input-error":"",hasHint?"input-hint":""].filter(Boolean).join(" ");const isPassword=this.type==="password";const showPasswordToggle=isPassword&&this.passwordToggle;const nativeType=isPassword&&this.passwordVisible?"text":this.type;const canClear=(this.clearable||this.withClear)&&(this.type==="text"||this.type==="search")&&this.value!=="";return html`
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--)if(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{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{lengthViolations}from"../../../internal/length-constraints.js";import{closeIcon,eyeIcon,eyeOffIcon}from"../../../internal/icons.js";import{styles}from"./input.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{autocorrectConverter,normalizeAutocorrect,spellcheckConverter}from"../../../internal/converters.js";import{finiteCount}from"../../../internal/numbers.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_hidePassword,LYRA_DEFAULT_inputLabel,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showPassword,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const LENGTH_CONSTRAINED_TYPES=["text","password","email","search","tel","url"];class LyraInputBase extends LyraElement{}class LyraInput extends FormAssociated(LyraInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,hidePassword:LYRA_DEFAULT_hidePassword,inputLabel:LYRA_DEFAULT_inputLabel,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showPassword:LYRA_DEFAULT_showPassword,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}get value(){return super.value}set value(next){super.value=next??""}get autocorrect(){return this.autocorrectValue}set autocorrect(next){this.autocorrectValue=normalizeAutocorrect(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 defaultValueAlias(){return this.defaultValue}set defaultValueAlias(next){this.defaultValue=next??""}constructor(){super();this.type="text";this.size="m";this.appearance="outlined";this.filled=false;this.pill=false;this.placeholder="";this.clearable=false;this.withClear=false;this.readonly=false;this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel=null;this.autocomplete="";this.title="";this.autofocus=false;this.spellcheck=true;this.autocapitalize="";this.autocorrectValue=true;this.inputMode="";this.enterKeyHint="";this.passwordToggle=false;this.passwordVisible=false;this.withoutSpinButtons=false;this.noSpinButtons=false;this.touched=false;this.slotPresence=new SlotPresenceController(this);this.onInput=event=>{if(!this.inputEl)return;this.value=this.inputEl.value;relayNativeEvent(this,event);this.emit("lr-input",{value:this.value})};this.onChange=event=>{if(!this.inputEl)return;this.value=this.inputEl.value;relayNativeEvent(this,event);this.emit("lr-change",{value:this.value})};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onBlur=event=>{if(!this.effectiveDisabled)this.touched=true;relayNativeEvent(this,event);this.emit("lr-blur")};this.onKeyDown=event=>{if(this.effectiveDisabled||this.readonly)return;submitOnEnter(this,event)};this.onTogglePasswordVisible=()=>{this.passwordVisible=!this.passwordVisible};this.onClear=()=>{if(this.effectiveDisabled||this.readonly||this.value==="")return;this.value="";if(this.inputEl)this.inputEl.value="";dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"});this.emit("lr-input",{value:this.value});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value});this.emit("lr-clear");this.inputEl?.focus()};this.addEventListener("invalid",()=>{this.touched=true})}formResetCallback(){super.formResetCallback();this.touched=false}get input(){return this.inputEl??null}click(){if(!this.effectiveDisabled)this.inputEl?.click()}focus(options){if(!this.effectiveDisabled)this.inputEl?.focus(options)}blur(){this.inputEl?.blur()}select(){this.inputEl?.select()}get valueAsDate(){const native=this.inputEl;if(!native)return null;if(native.value!==this.value)native.value=this.value;return native.valueAsDate}set valueAsDate(next){const native=this.inputEl;if(!native)return;native.valueAsDate=next;this.value=native.value}get valueAsNumber(){const native=this.inputEl;if(!native)return Number.NaN;if(native.value!==this.value)native.value=this.value;return native.valueAsNumber}set valueAsNumber(next){const native=this.inputEl;if(!native)return;native.valueAsNumber=next;this.value=native.value}showPicker(){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;if(!("showPicker"in HTMLInputElement.prototype))return;try{native.showPicker()}catch{}}stepUp(steps=1){this.applyStep("up",steps)}stepDown(steps=1){this.applyStep("down",steps)}applyStep(direction,steps){const native=this.inputEl;if(!native||this.effectiveDisabled||this.readonly)return;const count=finiteCount(steps,1);if(count===0)return;try{if(direction==="up")native.stepUp(count);else native.stepDown(count)}catch{return}if(this.value!==native.value)this.value=native.value}get selectionStart(){return this.inputEl?.selectionStart??null}set selectionStart(value){if(this.inputEl)this.inputEl.selectionStart=value??0}get selectionEnd(){return this.inputEl?.selectionEnd??null}set selectionEnd(value){if(this.inputEl)this.inputEl.selectionEnd=value??0}setSelectionRange(selectionStart,selectionEnd,selectionDirection="none"){this.inputEl?.setSelectionRange(selectionStart,selectionEnd,selectionDirection)}setRangeText(replacement,start,end,selectMode="preserve"){const input=this.inputEl;if(!input)return;if(start===void 0||end===void 0){input.setRangeText(replacement)}else{input.setRangeText(replacement,start,end,selectMode)}this.value=input.value}updateValidity(){const native=this.inputEl;if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}if(!native){if(this.required&&this.value===""){this[SET_ANCHORED_VALIDITY]({valueMissing:true},this.localize("fieldRequired"))}else{this[SET_ANCHORED_VALIDITY]({})}return}if(native.value!==this.value)native.value=this.value;const sanitizedAway=this.value!==""&&native.value==="";const v=native.validity;const own=LENGTH_CONSTRAINED_TYPES.includes(this.type)?lengthViolations(this.value,this.minlength,this.maxlength):{tooShort:false,tooLong:false};const tooShort=v.tooShort||own.tooShort;const tooLong=v.tooLong||own.tooLong;if(v.valid&&!tooShort&&!tooLong){if(sanitizedAway){this[SET_ANCHORED_VALIDITY]({badInput:true},this.localize("valueInvalid"));return}this[SET_ANCHORED_VALIDITY]({});return}this[SET_ANCHORED_VALIDITY]({valueMissing:v.valueMissing,typeMismatch:v.typeMismatch,rangeUnderflow:v.rangeUnderflow,rangeOverflow:v.rangeOverflow,stepMismatch:v.stepMismatch,tooShort,tooLong,patternMismatch:v.patternMismatch,badInput:v.badInput},native.validationMessage||this.localize("valueInvalid"))}updated(changed){super.updated(changed);if(changed.has("value")){if(this.value==="")this.internals.states.add("blank");else this.internals.states.delete("blank")}if(changed.has("type")||changed.has("min")||changed.has("max")||changed.has("step")||changed.has("minlength")||changed.has("maxlength")||changed.has("pattern")||changed.has("readonly")){this.updateValidity()}}renderControls(){return nothing}get inputWrapperParts(){return"base form-control-input input-wrapper"}render(){const hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||this.hint.length>0||this.helpText.length>0||this.withHint;const hasError=this.slotPresence.has("error")||this.errorText.length>0;const hasLabel=this.slotPresence.has("label")||this.label.length>0||this.withLabel;const describedBy=[hasError?"input-error":"",hasHint?"input-hint":""].filter(Boolean).join(" ");const isPassword=this.type==="password";const showPasswordToggle=isPassword&&this.passwordToggle;const nativeType=isPassword&&this.passwordVisible?"text":this.type;const canClear=(this.clearable||this.withClear)&&(this.type==="text"||this.type==="search")&&this.value!=="";return html`
2
2
  <div part="form-control">
3
3
  <label part="form-control-label" for="input" ?hidden=${!hasLabel}>
4
4
  <span part="label">${this.label}<slot name="label"></slot></span>
@@ -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--)if(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{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteInteger,finiteNumber}from"../../../internal/numbers.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateOverlay,composedContains}from"../../../internal/overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,to24Hour}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}};const hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}};const PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);const placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}};const blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null});const pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!=="object")return false;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode==="function"&&typeof candidate.contains==="function"}function containsElement(container,value){if(!container||!isElementNode(value))return false;try{return container.contains(value)}catch{return false}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:true,noAccessor:true},readonly:{type:Boolean,reflect:true,noAccessor:true},step:{converter:stepConverter,reflect:true,noAccessor:true}}}constructor(){super();this.appearance="outlined";this.autocomplete="";this.distance=0;this.hint="";this.hourFormat="auto";this.label="";this.min="";this.max="";this.pill=false;this.placement="bottom-start";this.size="m";this.withClear=false;this.withHint=false;this.withLabel=false;this.withNow=false;this.errorText="";this.activeSegment="hour";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasStartSlot=false;this.hasEndSlot=false;this.hasFooterSlot=false;this._open=false;this._readonly=false;this._step=60;this.draft=blankDraft();this.partial=false;this.secondsVisible=false;this.digitBuffer="";this.restoreFocusOnClose=true;this.transitionToken=0;this.visibilityPromise=Promise.resolve();this.segmentOrderKey="";this.inputId=nextId("time-input");this.labelId=nextId("time-input-label");this.hintId=nextId("time-input-hint");this.errorId=nextId("time-input-error");this.popupId=nextId("time-input-popup");this.now=()=>new Date;this.onSegmentKeyDown=event=>{const target=event.currentTarget;const name=target.dataset["segment"];if(this.effectiveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault();void this.show();return}if(/^\d$/.test(event.key)&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault();this.acceptDigit(name,event.key);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault();this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer();this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault();this.resetDigitBuffer();this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name);const next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault();this.resetDigitBuffer();this.setDraftSegment(name,null);return}if(event.key==="Enter"){if(this.open)void this.hide();else if(!this.readonly)submitOnEnter(this,event)}};this.onSegmentPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");if(!pasted)return;event.preventDefault();this.resetDigitBuffer();this.commitUserValue(pasted,"insertFromPaste",true)};this.onSegmentFocus=event=>{event.stopPropagation();const target=event.target;this.activeSegment=target.dataset["segment"]??this.activeSegment;const related=event.relatedTarget;if(containsElement(this.renderRoot.querySelector('[part="input"]'),related))return;relayNativeEvent(this,event);this.emit("lr-focus")};this.onSegmentBlur=event=>{event.stopPropagation();const related=event.relatedTarget;if(containsElement(this.renderRoot.querySelector('[part="input"]'),related))return;this.touched=true;this.resetDigitBuffer();relayNativeEvent(this,event);this.emit("lr-blur")};this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];if(isElementNode(target)&&composedContains(this,target))return;void this.requestVisibility(false,true,false)};this.onExpand=()=>{if(this.open)void this.hide();else void this.show()};this.onClear=()=>{if(this.effectiveDisabled||this.readonly||!this.draftHasAny&&this.value==="")return;this.touched=true;this.commitUserValue("","deleteContentBackward",true);this.emit("lr-clear");this.focus()};this.onNow=()=>{if(this.effectiveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;if(this.includeSeconds)value+=`:${pad(now.getSeconds())}`;this.commitUserValue(value)};this.onPopupPointerDown=event=>{event.preventDefault()};this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget;const normalized=normalizeTimeValue(input.value);if(!normalized||this.readonly||this.effectiveDisabled)return;this.value=normalized;dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"});this.emit("lr-input",{value:this.value})};this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget;const normalized=normalizeTimeValue(input.value);if(!normalized||this.readonly||this.effectiveDisabled)return;this.value=normalized;dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})};this.addEventListener("invalid",()=>{this.touched=true})}get open(){return this._open}set open(next){void this.requestVisibility(Boolean(next),this.isConnected&&this.hasUpdated,true)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=Boolean(next);this.toggleAttribute("readonly",this._readonly);this.updateValidity();this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any"){this._step=next}else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}if(this.numericStep<60)this.secondsVisible=true;this.updateValidity();this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next;if(next)this.forceClose(false);this.syncComponentStates()}get value(){return super.value}set value(next){let normalized=normalizeTimeValue(next);if(normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"){normalized+=":00"}this.partial=false;this.resetDigitBuffer();this.syncDraft(normalized);super.value=normalized;this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond);return result}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get pattern(){return localeTimePattern(this.effectiveLocale,this.hourFormat,this.includeSeconds)}get segmentOrder(){return this.pattern.filter(part=>part.type!=="literal").map(part=>part.type)}get usesTwelveHour(){return this.segmentOrder.includes("dayPeriod")}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft();this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"};this.secondsVisible=this.numericStep<60||parsed.precision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value==="");setCustomState(this.internals,"disabled",this.effectiveDisabled);setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){try{return getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:false}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}segmentNumericValue(name){if(name==="hour"){if(this.draft.hour===null)return null;return this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour}if(name==="minute")return this.draft.minute;if(name==="second")return this.draft.second;return this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer){return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length)}if(name==="dayPeriod"){const labels=dayPeriodLabels(this.effectiveLocale);return this.draft.dayPeriod?labels[this.draft.dayPeriod]:"--"}const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){if(name==="hour")return this.usesTwelveHour?{min:1,max:12}:{min:0,max:23};if(name==="dayPeriod")return{min:0,max:1};return{min:0,max:59}}setDraftSegment(name,value,user=true){if(this.effectiveDisabled||user&&this.readonly)return;if(name==="hour"){if(value===null){this.draft.hour=null}else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else{this.draft[name]=value===null?null:Number(value)}if(!user){this.requestUpdate();return}this.publishDraftEdit()}publishDraftEdit(){const before=super.value;const next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete;super.value=next;this.syncComponentStates();dispatchNativeInputEvent(this,{inputType:"insertReplacementText"});this.emit("lr-input",{value:this.value});if(next!==""&&next!==before){dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})}this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=false){const before=this.value;this.value=value;dispatchNativeInputEvent(this,{inputType});this.emit("lr-input",{value:this.value});if(forceChange||this.value!==before){dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})}}resetDigitBuffer(){this.digitBuffer="";this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder;const current=Math.max(0,order.indexOf(from));const next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour";this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;if(this.digitSegment!==name){this.digitSegment=name;this.digitBuffer=""}const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2);let candidate=Number(candidateText);if(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min){candidateText=digit;candidate=Number(digit)}this.digitBuffer=candidateText;if(candidate>=bounds.min&&candidate<=bounds.max)this.setDraftSegment(name,candidate);else this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;if(candidateText.length===2||cannotAcceptAnother){this.resetDigitBuffer();this.moveSegment(name,1)}}stepSegment(name,delta){const bounds=this.segmentBounds(name);const current=this.segmentNumericValue(name);const next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;if(name==="dayPeriod")this.setDraftSegment(name,next===0?"am":"pm");else this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){const order=this.segmentOrder;if(!order.includes(this.activeSegment))this.activeSegment=order[0]??"hour";this.segmentElement(this.activeSegment)?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;if(active&&typeof active.blur==="function"){active.blur()}}click(){if(!this.effectiveDisabled)this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next;this.syncComponentStates();this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){if(this._open===next)return this.visibilityPromise;if(next&&this.effectiveDisabled){this.syncOpenAttribute();return Promise.resolve()}if(announce){const event=this.emit(next?"lr-show":"lr-hide",void 0,{cancelable:true});if(event.defaultPrevented){this.syncOpenAttribute();return Promise.resolve()}}this.restoreFocusOnClose=restoreFocus;this.setOpen(next);this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve();return this.visibilityPromise}show(){return this.requestVisibility(true,true,true)}hide(){return this.requestVisibility(false,true,true)}forceClose(restoreFocus){if(!this._open)return;this.restoreFocusOnClose=restoreFocus;this.setOpen(false)}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const popup=this.renderRoot.querySelector('[part="popup"]');const animations=popup?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(this.transitionToken!==token)return}this.emit(event)}positionPopup(){this.cleanupPositioner?.();this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"})}activatePopup(){if(!this.isConnected)return;this.positionPopup();this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>void this.hide(),restoreFocusTo:this.segmentElement(this.activeSegment),modal:false,trapFocus:false});this.lightDismissDocument=this.ownerDocument;this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,true);this.updateComplete.then(()=>{this.renderRoot.querySelector('[part~="column-item-selected"]')?.scrollIntoView({block:"center"})})}teardownPopup(){this.cleanupPositioner?.();this.cleanupPositioner=void 0;this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose});this.overlayHandle=void 0;this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,true);this.lightDismissDocument=void 0;this.restoreFocusOnClose=true}onColumnSelect(name,value){if(this.readonly||this.effectiveDisabled)return;this.resetDigitBuffer();this.setDraftSegment(name,value);this.activeSegment=name;this.updateComplete.then(()=>this.segmentElement(name)?.focus())}updateSlotState(event){const slot=event.currentTarget;const present=slot.assignedNodes({flatten:true}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);if(slot.name==="label")this.hasLabelSlot=present;else if(slot.name==="hint")this.hasHintSlot=present;else if(slot.name==="error")this.hasErrorSlot=present;else if(slot.name==="start")this.hasStartSlot=present;else if(slot.name==="end")this.hasEndSlot=present;else if(slot.name==="footer")this.hasFooterSlot=present}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";if(this.required&&this.value==="")flags.valueMissing=true;if(this.partial)flags.badInput=true;const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed)flags.badInput=true;if(parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min);const parsedMax=parseTimeValue(this.max);if(parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds){flags.rangeUnderflow=true;message=this.localize("timeInputRangeMessage",void 0,{min:this.min,max:this.max})}else if(parsedMin&&parsed.milliseconds<parsedMin.milliseconds){flags.rangeUnderflow=true;message=this.localize("timeInputMinMessage",void 0,{min:this.min})}else{flags.rangeOverflow=true;message=this.localize("timeInputMaxMessage",void 0,{max:this.max})}}if(parsed&&hasTimeStepMismatch(this.value,this.step,this.min)){flags.stepMismatch=true;message||=this.localize("timeInputStepMessage")}if(flags.badInput)message=this.localize("timeInputInvalid");else if(flags.valueMissing)message=this.localize("fieldRequired");this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){this.updateValidity();return super.checkValidity()}reportValidity(){this.touched=true;this.updateValidity();return super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegment)}formResetCallback(){super.formResetCallback();this.touched=false;this.partial=false;this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){const slots=Array.from(this.children).map(element=>element.getAttribute("slot"));this.hasLabelSlot=slots.includes("label");this.hasHintSlot=slots.includes("hint");this.hasErrorSlot=slots.includes("error");this.hasStartSlot=slots.includes("start");this.hasEndSlot=slots.includes("end");this.hasFooterSlot=slots.includes("footer")}if(this.open&&this.effectiveDisabled)this.forceClose(false);const order=this.segmentOrder;const orderKey=order.join("|");if(orderKey!==this.segmentOrderKey||!order.includes(this.activeSegment)){this.activeSegment=order[0]??"hour"}this.segmentOrderKey=orderKey}updated(changed){super.updated(changed);if(changed.has("open")){if(this.open)this.activatePopup();else this.teardownPopup()}else if(this.open&&(changed.has("placement")||changed.has("distance"))){this.positionPopup()}if(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step")){this.updateValidity()}this.syncComponentStates();this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid)}disconnectedCallback(){this.transitionToken++;this.teardownPopup();this._open=false;this.syncOpenAttribute();this.partial=false;this.resetDigitBuffer();super.disconnectedCallback()}renderSegment(name){const value=this.segmentNumericValue(name);const bounds=this.segmentBounds(name);const empty=value===null;return html`
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--)if(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{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteInteger,finiteNumber}from"../../../internal/numbers.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateOverlay,composedContains}from"../../../internal/overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,to24Hour}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}};const hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}};const PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);const placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}};const blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null});const pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!=="object")return false;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode==="function"&&typeof candidate.contains==="function"}function containsElement(container,value){if(!container||!isElementNode(value))return false;try{return container.contains(value)}catch{return false}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:true,noAccessor:true},readonly:{type:Boolean,reflect:true,noAccessor:true},step:{converter:stepConverter,reflect:true,noAccessor:true}}}constructor(){super();this.appearance="outlined";this.autocomplete="";this.distance=0;this.hint="";this.hourFormat="auto";this.label="";this.min="";this.max="";this.pill=false;this.placement="bottom-start";this.size="m";this.withClear=false;this.withHint=false;this.withLabel=false;this.withNow=false;this.errorText="";this.activeSegment="hour";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasStartSlot=false;this.hasEndSlot=false;this.hasFooterSlot=false;this._open=false;this._readonly=false;this._step=60;this.draft=blankDraft();this.partial=false;this.secondsVisible=false;this.digitBuffer="";this.restoreFocusOnClose=true;this.transitionToken=0;this.visibilityPromise=Promise.resolve();this.segmentOrderKey="";this.inputId=nextId("time-input");this.labelId=nextId("time-input-label");this.hintId=nextId("time-input-hint");this.errorId=nextId("time-input-error");this.popupId=nextId("time-input-popup");this.now=()=>new Date;this.onSegmentKeyDown=event=>{const target=event.currentTarget;const name=target.dataset["segment"];if(this.effectiveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault();void this.show();return}if(/^\d$/.test(event.key)&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault();this.acceptDigit(name,event.key);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault();this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer();this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault();this.resetDigitBuffer();this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name);const next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault();this.resetDigitBuffer();this.setDraftSegment(name,null);return}if(event.key==="Enter"){if(this.open)void this.hide();else if(!this.readonly)submitOnEnter(this,event)}};this.onSegmentPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");if(!pasted)return;event.preventDefault();this.resetDigitBuffer();this.commitUserValue(pasted,"insertFromPaste",true)};this.onSegmentFocus=event=>{event.stopPropagation();const target=event.target;this.activeSegment=target.dataset["segment"]??this.activeSegment;const related=event.relatedTarget;if(containsElement(this.renderRoot.querySelector('[part="input"]'),related))return;relayNativeEvent(this,event);this.emit("lr-focus")};this.onSegmentBlur=event=>{event.stopPropagation();const related=event.relatedTarget;if(containsElement(this.renderRoot.querySelector('[part="input"]'),related))return;if(!this.effectiveDisabled)this.touched=true;this.resetDigitBuffer();relayNativeEvent(this,event);this.emit("lr-blur")};this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];if(isElementNode(target)&&composedContains(this,target))return;void this.requestVisibility(false,true,false)};this.onExpand=()=>{if(this.open)void this.hide();else void this.show()};this.onClear=()=>{if(this.effectiveDisabled||this.readonly||!this.draftHasAny&&this.value==="")return;this.touched=true;this.commitUserValue("","deleteContentBackward",true);this.emit("lr-clear");this.focus()};this.onNow=()=>{if(this.effectiveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;if(this.includeSeconds)value+=`:${pad(now.getSeconds())}`;this.commitUserValue(value)};this.onPopupPointerDown=event=>{event.preventDefault()};this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget;const normalized=normalizeTimeValue(input.value);if(!normalized||this.readonly||this.effectiveDisabled)return;this.value=normalized;dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"});this.emit("lr-input",{value:this.value})};this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget;const normalized=normalizeTimeValue(input.value);if(!normalized||this.readonly||this.effectiveDisabled)return;this.value=normalized;dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})};this.addEventListener("invalid",()=>{this.touched=true})}get open(){return this._open}set open(next){void this.requestVisibility(Boolean(next),this.isConnected&&this.hasUpdated,true)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=Boolean(next);this.toggleAttribute("readonly",this._readonly);this.updateValidity();this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any"){this._step=next}else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}if(this.numericStep<60)this.secondsVisible=true;this.updateValidity();this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next;if(next)this.forceClose(false);this.syncComponentStates()}get value(){return super.value}set value(next){let normalized=normalizeTimeValue(next);if(normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"){normalized+=":00"}this.partial=false;this.resetDigitBuffer();this.syncDraft(normalized);super.value=normalized;this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond);return result}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get pattern(){return localeTimePattern(this.effectiveLocale,this.hourFormat,this.includeSeconds)}get segmentOrder(){return this.pattern.filter(part=>part.type!=="literal").map(part=>part.type)}get usesTwelveHour(){return this.segmentOrder.includes("dayPeriod")}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft();this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"};this.secondsVisible=this.numericStep<60||parsed.precision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value==="");setCustomState(this.internals,"disabled",this.effectiveDisabled);setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){try{return getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:false}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}segmentNumericValue(name){if(name==="hour"){if(this.draft.hour===null)return null;return this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour}if(name==="minute")return this.draft.minute;if(name==="second")return this.draft.second;return this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer){return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length)}if(name==="dayPeriod"){const labels=dayPeriodLabels(this.effectiveLocale);return this.draft.dayPeriod?labels[this.draft.dayPeriod]:"--"}const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){if(name==="hour")return this.usesTwelveHour?{min:1,max:12}:{min:0,max:23};if(name==="dayPeriod")return{min:0,max:1};return{min:0,max:59}}setDraftSegment(name,value,user=true){if(this.effectiveDisabled||user&&this.readonly)return;if(name==="hour"){if(value===null){this.draft.hour=null}else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else{this.draft[name]=value===null?null:Number(value)}if(!user){this.requestUpdate();return}this.publishDraftEdit()}publishDraftEdit(){const before=super.value;const next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete;super.value=next;this.syncComponentStates();dispatchNativeInputEvent(this,{inputType:"insertReplacementText"});this.emit("lr-input",{value:this.value});if(next!==""&&next!==before){dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})}this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=false){const before=this.value;this.value=value;dispatchNativeInputEvent(this,{inputType});this.emit("lr-input",{value:this.value});if(forceChange||this.value!==before){dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})}}resetDigitBuffer(){this.digitBuffer="";this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder;const current=Math.max(0,order.indexOf(from));const next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour";this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;if(this.digitSegment!==name){this.digitSegment=name;this.digitBuffer=""}const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2);let candidate=Number(candidateText);if(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min){candidateText=digit;candidate=Number(digit)}this.digitBuffer=candidateText;if(candidate>=bounds.min&&candidate<=bounds.max)this.setDraftSegment(name,candidate);else this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;if(candidateText.length===2||cannotAcceptAnother){this.resetDigitBuffer();this.moveSegment(name,1)}}stepSegment(name,delta){const bounds=this.segmentBounds(name);const current=this.segmentNumericValue(name);const next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;if(name==="dayPeriod")this.setDraftSegment(name,next===0?"am":"pm");else this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){const order=this.segmentOrder;if(!order.includes(this.activeSegment))this.activeSegment=order[0]??"hour";this.segmentElement(this.activeSegment)?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;if(active&&typeof active.blur==="function"){active.blur()}}click(){if(!this.effectiveDisabled)this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next;this.syncComponentStates();this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){if(this._open===next)return this.visibilityPromise;if(next&&this.effectiveDisabled){this.syncOpenAttribute();return Promise.resolve()}if(announce){const event=this.emit(next?"lr-show":"lr-hide",void 0,{cancelable:true});if(event.defaultPrevented){this.syncOpenAttribute();return Promise.resolve()}}this.restoreFocusOnClose=restoreFocus;this.setOpen(next);this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve();return this.visibilityPromise}show(){return this.requestVisibility(true,true,true)}hide(){return this.requestVisibility(false,true,true)}forceClose(restoreFocus){if(!this._open)return;this.restoreFocusOnClose=restoreFocus;this.setOpen(false)}async settleTransition(event){const token=++this.transitionToken;await this.updateComplete;if(this.transitionToken!==token)return;if(this.isConnected){const view=this.ownerDocument.defaultView;if(view)await new Promise(resolve=>view.requestAnimationFrame(()=>resolve()));if(this.transitionToken!==token)return;const popup=this.renderRoot.querySelector('[part="popup"]');const animations=popup?.getAnimations({subtree:true})??[];await Promise.all(animations.map(animation=>animation.finished.catch(()=>void 0)));if(this.transitionToken!==token)return}this.emit(event)}positionPopup(){this.cleanupPositioner?.();this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]');const popup=this.renderRoot.querySelector('[part="popup"]');if(!anchor||!popup)return;this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"})}activatePopup(){if(!this.isConnected)return;this.positionPopup();this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>void this.hide(),restoreFocusTo:this.segmentElement(this.activeSegment),modal:false,trapFocus:false});this.lightDismissDocument=this.ownerDocument;this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,true);this.updateComplete.then(()=>{this.renderRoot.querySelector('[part~="column-item-selected"]')?.scrollIntoView({block:"center"})})}teardownPopup(){this.cleanupPositioner?.();this.cleanupPositioner=void 0;this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose});this.overlayHandle=void 0;this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,true);this.lightDismissDocument=void 0;this.restoreFocusOnClose=true}onColumnSelect(name,value){if(this.readonly||this.effectiveDisabled)return;this.resetDigitBuffer();this.setDraftSegment(name,value);this.activeSegment=name;this.updateComplete.then(()=>this.segmentElement(name)?.focus())}updateSlotState(event){const slot=event.currentTarget;const present=slot.assignedNodes({flatten:true}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);if(slot.name==="label")this.hasLabelSlot=present;else if(slot.name==="hint")this.hasHintSlot=present;else if(slot.name==="error")this.hasErrorSlot=present;else if(slot.name==="start")this.hasStartSlot=present;else if(slot.name==="end")this.hasEndSlot=present;else if(slot.name==="footer")this.hasFooterSlot=present}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";if(this.required&&this.value==="")flags.valueMissing=true;if(this.partial)flags.badInput=true;const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed)flags.badInput=true;if(parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min);const parsedMax=parseTimeValue(this.max);if(parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds){flags.rangeUnderflow=true;message=this.localize("timeInputRangeMessage",void 0,{min:this.min,max:this.max})}else if(parsedMin&&parsed.milliseconds<parsedMin.milliseconds){flags.rangeUnderflow=true;message=this.localize("timeInputMinMessage",void 0,{min:this.min})}else{flags.rangeOverflow=true;message=this.localize("timeInputMaxMessage",void 0,{max:this.max})}}if(parsed&&hasTimeStepMismatch(this.value,this.step,this.min)){flags.stepMismatch=true;message||=this.localize("timeInputStepMessage")}if(flags.badInput)message=this.localize("timeInputInvalid");else if(flags.valueMissing)message=this.localize("fieldRequired");this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){this.updateValidity();return super.checkValidity()}reportValidity(){this.touched=true;this.updateValidity();return super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegment)}formResetCallback(){super.formResetCallback();this.touched=false;this.partial=false;this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){const slots=Array.from(this.children).map(element=>element.getAttribute("slot"));this.hasLabelSlot=slots.includes("label");this.hasHintSlot=slots.includes("hint");this.hasErrorSlot=slots.includes("error");this.hasStartSlot=slots.includes("start");this.hasEndSlot=slots.includes("end");this.hasFooterSlot=slots.includes("footer")}if(this.open&&this.effectiveDisabled)this.forceClose(false);const order=this.segmentOrder;const orderKey=order.join("|");if(orderKey!==this.segmentOrderKey||!order.includes(this.activeSegment)){this.activeSegment=order[0]??"hour"}this.segmentOrderKey=orderKey}updated(changed){super.updated(changed);if(changed.has("open")){if(this.open)this.activatePopup();else this.teardownPopup()}else if(this.open&&(changed.has("placement")||changed.has("distance"))){this.positionPopup()}if(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step")){this.updateValidity()}this.syncComponentStates();this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid)}disconnectedCallback(){this.transitionToken++;this.teardownPopup();this._open=false;this.syncOpenAttribute();this.partial=false;this.resetDigitBuffer();super.disconnectedCallback()}renderSegment(name){const value=this.segmentNumericValue(name);const bounds=this.segmentBounds(name);const empty=value===null;return html`
2
2
  <span
3
3
  part="segment"
4
4
  role="spinbutton"
@@ -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--)if(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{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.locales=[];this.showFlags=true;this.label="";this.hint="";this.errorText="";this.open=false;this.size="m";this.activeIndex=-1;this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.registryTick=0;this.listId=nextId("locale-picker-list");this.controlId=nextId("locale-picker-control");this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{event.stopPropagation();this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onTriggerFocus=event=>{event.stopPropagation();this.emit("focus")};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onKeyDown=e=>{const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commit(activeRow.tag)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break;default:if(e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey){this.typeAhead(e.key)}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const tag=optionEl?.dataset["value"];if(tag===void 0)return;this.commit(tag)};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals.setFormValue("")}focus(options){this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.triggerElement?.click()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1});if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.stopRegistrySubscription?.();this.stopRegistrySubscription=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error");this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label")}}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){if(this.isBarred()){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("localePickerRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid);this.requestUpdate()}get normalizedEntries(){const raw=this.locales;if(raw&&raw.length>0){return raw.map(entry=>typeof entry==="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country})}return getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.cleanup?.();this.cleanup=void 0;if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.cleanup=place(anchor,listbox)}updated(changed){super.updated(changed);const reposition=changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick"));if(reposition){this.syncPopup()}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}commit(tag){const previousValue=this._value;this.value=tag;this.hide();const event=this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:true});if(!event.defaultPrevented)setLyraLocale(tag)}typeAhead(char){this.clearTypeAheadTimer();this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow;this.typeAheadTimer=ownerWindow.setTimeout(()=>{if(this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0;this.typeAheadBuffer=""},500)}const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag;const currentIndex=rows.findIndex(r=>r.tag===currentTag);const n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else{this.commit(row.tag)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.tag===this._value;return html`<div
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--)if(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{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{getLyraLocaleDirection,getRegisteredLyraLocales,subscribeLyraLocaleRegistry,setLyraLocale}from"../../../internal/localization-runtime.js";import{localeNativeName}from"../../media/flag/language-map.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./locale-picker.styles.js";import{trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";function createInternalsSafely(host){if(typeof host.attachInternals!=="function")return createNoopInternals();try{return host.attachInternals()}catch{return createNoopInternals()}}function createNoopInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue(){},setValidity(){},checkValidity(){return true},reportValidity(){return true}}}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},name:{reflect:true,noAccessor:true}}}constructor(){super();this.locales=[];this.showFlags=true;this.label="";this.hint="";this.errorText="";this.open=false;this.size="m";this.activeIndex=-1;this.touched=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasLabelSlot=false;this.registryTick=0;this.listId=nextId("locale-picker-list");this.controlId=nextId("locale-picker-control");this._value="";this._fieldsetDisabled=false;this._name="";this._disabled=false;this._required=false;this._defaultValue="";this._valueDirty=false;this.settingDefaultValue=false;this.reflectingDefaultValue=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this.onDocPointer=e=>{if(!e.composedPath().includes(this))this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;this.open?this.hide():this.show()};this.onTriggerBlur=event=>{event.stopPropagation();if(!this.effectiveDisabled)this.touched=true;this.syncCustomStates();this.hide();this.emit("blur")};this.onTriggerFocus=event=>{event.stopPropagation();this.emit("focus")};this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:true}).length>0};this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};this.onKeyDown=e=>{const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.min(rows.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(!this.open)return this.show();this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];if(this.activeIndex>=0&&activeRow){this.commit(activeRow.tag)}else{this.hide()}}break;case"Escape":if(this.open){e.preventDefault();this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=rows.length-1}break;default:if(e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey){this.typeAhead(e.key)}break}};this.onListboxMouseDown=e=>{if(e.target.closest('[part="option"]'))e.preventDefault()};this.onListboxClick=e=>{if(this.effectiveDisabled)return;const optionEl=e.target.closest('[part="option"]');const tag=optionEl?.dataset["value"];if(tag===void 0)return;this.commit(tag)};this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals.setFormValue("")}focus(options){this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.triggerElement?.click()}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part="trigger"]')??null}connectedCallback(){super.connectedCallback();this.updateValidity();this.stopRegistrySubscription=subscribeLyraLocaleRegistry(()=>{this.registryTick+=1});if(this.hasUpdated&&this.open)queueMicrotask(()=>this.syncPopup())}disconnectedCallback(){super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.stopRegistrySubscription?.();this.stopRegistrySubscription=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed);if(!this.hasUpdated){this.hasHintSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="error");this.hasLabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="label")}}get value(){return this._value}set value(next){const old=this._value;if(!this.settingDefaultValue)this._valueDirty=true;this._value=next??"";this.internals.setFormValue(this._value);this.updateValidity();this.requestUpdate("value",old)}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"";this.reflectingDefaultValue=true;try{if(this._defaultValue)this.setAttribute("value",this._defaultValue);else this.removeAttribute("value")}finally{this.reflectingDefaultValue=false}if(!this._valueDirty)this.restoreLiveValueFromDefault();this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"";if(this._name){this.setAttribute("name",this._name)}else{this.removeAttribute("name")}this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)this.hide();this.updateValidity();this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.updateValidity();this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){if(this.isBarred()){this.validityController.setValidity({})}else if(this.required&&!this._value){this.validityController.setValidity({valueMissing:true},this.localize("localePickerRequired"))}else{this.validityController.setValidity({})}this.syncCustomStates()}isBarred(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.isBarred()})}formResetCallback(){this.touched=false;this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=true;try{this.value=this._defaultValue}finally{this.settingDefaultValue=false}this._valueDirty=false}formStateRestoreCallback(state2,_mode){this.value=typeof state2==="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.touched=true;this.syncCustomStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid);this.requestUpdate()}get normalizedEntries(){const raw=this.locales;if(raw&&raw.length>0){return raw.map(entry=>typeof entry==="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country})}return getRegisteredLyraLocales().map(tag=>({tag,label:localeNativeName(tag)}))}get previewTag(){return this._value||this.effectiveLocale}entryFor(tag){return this.normalizedEntries.find(e=>e.tag===tag)}labelFor(tag){return this.entryFor(tag)?.label??localeNativeName(tag)}show(){if(this.open||this.effectiveDisabled)return;this.open=true}hide(){if(!this.open)return;this.open=false;this.activeIndex=-1}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{if(this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument;this.pointerListener=listener;ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){if(this.pointerListenerDocument&&this.pointerListener){this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener)}this.pointerListenerDocument=void 0;this.pointerListener=void 0}syncPopup(){this.cleanup?.();this.cleanup=void 0;if(!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox)this.cleanup=place(anchor,listbox)}updated(changed){super.updated(changed);const reposition=changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick"));if(reposition){this.syncPopup()}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}commit(tag){const previousValue=this._value;this.value=tag;this.hide();const event=this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:true});if(!event.defaultPrevented)setLyraLocale(tag)}typeAhead(char){this.clearTypeAheadTimer();this.typeAheadBuffer+=char.toLocaleLowerCase(this.effectiveLocale);const ownerWindow=this.ownerDocument.defaultView;if(this.isConnected&&ownerWindow){const generation=this.typeAheadTimerGeneration;this.typeAheadTimerWindow=ownerWindow;this.typeAheadTimer=ownerWindow.setTimeout(()=>{if(this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow){return}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0;this.typeAheadBuffer=""},500)}const rows=this.normalizedEntries;if(!rows.length)return;const currentTag=this.open?rows[this.activeIndex]?.tag:this.previewTag;const currentIndex=rows.findIndex(r=>r.tag===currentTag);const n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else{this.commit(row.tag)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`;const selected=entry.tag===this._value;return html`<div
2
2
  part="option"
3
3
  id=${id}
4
4
  role="option"
@@ -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--)if(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{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{findImplicitSubmitter,isNativeSubmitter,submitOnEnter}from"../../../internal/submit-on-enter.js";import{styles}from"./otp-input.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";const ACCEPTED={numeric:/[0-9]/,alpha:/[a-zA-Z]/,alphanumeric:/[a-zA-Z0-9]/};const DEFAULT_LENGTH=6;const MAX_LENGTH=32;class LyraOtpInputBase extends LyraElement{static{this.styles=[LyraElement.styles,contextualSizes,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){constructor(){super(...arguments);this.label="";this.hint="";this.errorText="";this.appearance="outlined";this.autofocus=false;this.autosubmit=false;this.size="m";this.length=DEFAULT_LENGTH;this.format="";this.type="numeric";this.case="preserve";this.mask=false;this.withMask=false;this.readonly=false;this.autocomplete="one-time-code";this.focused=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.touched=false;this.labelId=nextId("otp-input-label");this.hintId=nextId("otp-input-hint");this.errorId=nextId("otp-input-error");this.activeSegmentIndex=0;this.segmentValues=[];this.segmentEditPendingChange=false;this.autosubmitToken=0;this.onInput=event=>{if(event.isComposing===true){event.stopPropagation();return}const raw=event.target.value;const next=this.sanitize(raw);const previous=this.value;const previousFilled=this.filledSegmentCount;const packed=Array.from({length:this.segmentCount},(_,index)=>next[index]??"");const layoutChanged=packed.some((value,index)=>value!==this.segmentValues[index]);if(this.control&&this.control.value!==next)this.control.value=next;if(next===this.value&&!layoutChanged){event.stopImmediatePropagation();return}this.touched=true;this.value=next;relayNativeEvent(this,event);if(previous&&!next)this.emit("lr-clear");this.completeIfTransition(previousFilled)};this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;const delta=this.effectiveDirection==="rtl"?-physical:physical;this.setActiveSegment(this.activeSegmentIndex+delta);return}if(event.key==="Enter"){if(!this.readonly)submitOnEnter(this,event,{beforeSubmit:()=>this.flushPendingChange()});return}if(this.readonly||event.isComposing)return;const selection=this.selectedSegmentRange;if(event.key==="Backspace"||event.key==="Delete"){event.preventDefault();const values2=this.normalizedSegmentValues();if(selection){for(const index of selection.indices)values2[index]="";this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward");this.setActiveSegment(selection.first);return}const changed=Boolean(values2[this.activeSegmentIndex]);values2[this.activeSegmentIndex]="";if(changed){this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward")}if(event.key==="Backspace")this.setActiveSegment(this.activeSegmentIndex-1);return}if(event.ctrlKey||event.metaKey||event.altKey||event.key.length!==1)return;event.preventDefault();const accepted=this.sanitize(event.key).slice(0,1);if(!accepted)return;const values=this.normalizedSegmentValues();const targetIndex=selection?.first??this.activeSegmentIndex;if(selection){for(const index of selection.indices)values[index]=""}values[targetIndex]=accepted;this.commitSegmentEdit(values,"insertText",accepted);this.setActiveSegment(targetIndex+1)};this.onPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=this.sanitize(event.clipboardData?.getData("text")??"");event.preventDefault();if(!pasted)return;const values=Array.from({length:this.segmentCount},(_,index)=>pasted[index]??"");this.commitSegmentEdit(values,"insertFromPaste",pasted);this.setActiveSegment(Math.min(pasted.length,this.segmentCount-1))};this.onChange=event=>{this.segmentEditPendingChange=false;relayNativeEvent(this,event)};this.onFocus=event=>{this.focused=true;relayNativeEvent(this,event);this.emit("lr-focus")};this.onBlur=event=>{this.focused=false;this.touched=true;this.flushPendingChange();relayNativeEvent(this,event);this.emit("lr-blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedNodes({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedNodes({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedNodes({flatten:true}).length>0}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,otpInputIncomplete:LYRA_DEFAULT_otpInputIncomplete,otpInputLabel:LYRA_DEFAULT_otpInputLabel,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}get input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){const normalized=this.sanitize(next??"");this.packSegmentValues(normalized);super.value=normalized}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;this.parsedFormatSource=this.format;if(!this.format){this.parsedFormatCells=null;return null}const cells=[];let segments=0;let literal="";const flushLiteral=()=>{if(!literal)return;cells.push({kind:"separator",text:literal});literal=""};for(const char of this.format){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral();cells.push({kind:"segment"});segments+=1}flushLiteral();this.parsedFormatCells=segments>0?cells:null;return this.parsedFormatCells}get segmentCount(){const formatted=this.formattedCells;if(formatted)return formatted.filter(cell=>cell.kind==="segment").length;return Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.segmentCount}get cells(){return this.formattedCells??Array.from({length:this.segmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric;let out=[...raw??""].filter(char=>accepted.test(char)).join("");if(this.case==="upper")out=out.toUpperCase();else if(this.case==="lower")out=out.toLowerCase();return out.slice(0,this.segmentCount)}packSegmentValues(value){const count=this.segmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??"");this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){if(!Array.isArray(this.segmentValues))return this.value.length;return this.segmentValues.reduce((count,value)=>count+(value?1:0),0)}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.segmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.segmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret);void this.updateComplete.then(()=>{const segment=this.renderRoot.querySelectorAll('[part~="segment"]')[next];segment?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();if(!form)return;const submitter=findImplicitSubmitter(form);if(!submitter)form.requestSubmit();else if(isNativeSubmitter(submitter)){form.requestSubmit(submitter)}else{submitter.click()}}completeIfTransition(previousFilled){if(previousFilled>=this.segmentCount||this.filledSegmentCount!==this.segmentCount)return;const completeEvent=this.emit("lr-complete",{value:this.value},{cancelable:true});if(!this.autosubmit)return;const token=this.autosubmitToken+=1;setTimeout(()=>{if(token!==this.autosubmitToken||completeEvent.defaultPrevented)return;if(!this.isConnected||!this.autosubmit)return;if(this.filledSegmentCount!==this.segmentCount)return;this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){const previousValue=this.value;const previousFilled=this.filledSegmentCount;this.segmentValues=this.normalizedSegmentValues(values);const nextValue=this.segmentValues.join("");super.value=nextValue;if(this.control)this.control.value=nextValue;this.touched=true;dispatchNativeInputEvent(this,{data,inputType});this.segmentEditPendingChange=true;if(previousValue&&!nextValue)this.emit("lr-clear");this.completeIfTransition(previousFilled);this.requestUpdate()}get selectedSegmentRange(){const start=this.control?.selectionStart;const end=this.control?.selectionEnd;if(start===void 0||start===null||end===void 0||end===null||start===end){return null}const occupiedIndices=this.normalizedSegmentValues().map((value,index)=>value?index:-1).filter(index=>index>=0);const indices=occupiedIndices.slice(start,end);const first=indices[0];return first===void 0?null:{indices,first}}focus(options){if(!this.effectiveDisabled)this.control?.focus(options)}blur(){this.control?.blur()}click(){if(!this.effectiveDisabled)this.control?.click()}select(){this.control?.select()}clear(){const hadValue=this.value.length>0;this.value="";if(this.control)this.control.value="";this.focus();if(hadValue)this.emit("lr-clear")}formResetCallback(){super.formResetCallback();this.touched=false;this.segmentEditPendingChange=false}reportValidity(){this.touched=true;return super.reportValidity()}firstUpdated(){if(this.autofocus)this.scheduleAfterUpdate(()=>this.focus(),"otp-autofocus")}willUpdate(changed){super.willUpdate?.(changed);if(changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.value);if(next!==this.value)this.value=next;else this.packSegmentValues(next)}if(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format")){this.updateValidity()}this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"--blank",this.value.length===0);setCustomState(this.internals,"--filled",this.filledSegmentCount===this.segmentCount);setCustomState(this.internals,"disabled",this.effectiveDisabled);setCustomState(this.internals,"readonly",this.readonly)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const total=this.segmentCount;const filled=this.filledSegmentCount;const complete=filled===total;if(this.required&&filled===0){this[SET_ANCHORED_VALIDITY]({valueMissing:true},this.localize("fieldRequired"));return}if(filled>0&&!complete){this[SET_ANCHORED_VALIDITY]({tooShort:true},this.localize("otpInputIncomplete",void 0,{total}));return}this[SET_ANCHORED_VALIDITY]({})}flushPendingChange(){if(!this.segmentEditPendingChange)return;this.segmentEditPendingChange=false;dispatchNativeEvent(this,"change")}renderSegment(index,invalid){const char=this.segmentValues[index]??"";const filled=char!=="";const active=this.focused&&!this.effectiveDisabled&&!this.readonly&&index===this.activeSegmentIndex;const masked=filled&&this.mask;const placeholderMask=!filled&&this.withMask;const parts=["segment"];if(active)parts.push("active");if(masked)parts.push("masked");if(placeholderMask)parts.push("placeholder-mask");if(invalid)parts.push("invalid");return html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=Boolean(this.label)||this.hasLabelSlot;const hasHint=Boolean(this.hint)||this.hasHintSlot;const hasError=Boolean(this.errorText)||this.hasErrorSlot;const intrinsicInvalid=this.touched&&!this.validity.valid;const ariaInvalid=hasError||intrinsicInvalid;const describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" ");let segmentIndex=-1;return html`
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--)if(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{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{findImplicitSubmitter,isNativeSubmitter,submitOnEnter}from"../../../internal/submit-on-enter.js";import{styles}from"./otp-input.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel,LYRA_DEFAULT_restore,LYRA_DEFAULT_search}from"../../../internal/default-strings.generated.js";const ACCEPTED={numeric:/[0-9]/,alpha:/[a-zA-Z]/,alphanumeric:/[a-zA-Z0-9]/};const DEFAULT_LENGTH=6;const MAX_LENGTH=32;class LyraOtpInputBase extends LyraElement{static{this.styles=[LyraElement.styles,contextualSizes,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){constructor(){super(...arguments);this.label="";this.hint="";this.errorText="";this.appearance="outlined";this.autofocus=false;this.autosubmit=false;this.size="m";this.length=DEFAULT_LENGTH;this.format="";this.type="numeric";this.case="preserve";this.mask=false;this.withMask=false;this.readonly=false;this.autocomplete="one-time-code";this.focused=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.touched=false;this.labelId=nextId("otp-input-label");this.hintId=nextId("otp-input-hint");this.errorId=nextId("otp-input-error");this.activeSegmentIndex=0;this.segmentValues=[];this.segmentEditPendingChange=false;this.autosubmitToken=0;this.onInput=event=>{if(event.isComposing===true){event.stopPropagation();return}const raw=event.target.value;const next=this.sanitize(raw);const previous=this.value;const previousFilled=this.filledSegmentCount;const packed=Array.from({length:this.segmentCount},(_,index)=>next[index]??"");const layoutChanged=packed.some((value,index)=>value!==this.segmentValues[index]);if(this.control&&this.control.value!==next)this.control.value=next;if(next===this.value&&!layoutChanged){event.stopImmediatePropagation();return}this.touched=true;this.value=next;relayNativeEvent(this,event);if(previous&&!next)this.emit("lr-clear");this.completeIfTransition(previousFilled)};this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;const delta=this.effectiveDirection==="rtl"?-physical:physical;this.setActiveSegment(this.activeSegmentIndex+delta);return}if(event.key==="Enter"){if(!this.readonly)submitOnEnter(this,event,{beforeSubmit:()=>this.flushPendingChange()});return}if(this.readonly||event.isComposing)return;const selection=this.selectedSegmentRange;if(event.key==="Backspace"||event.key==="Delete"){event.preventDefault();const values2=this.normalizedSegmentValues();if(selection){for(const index of selection.indices)values2[index]="";this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward");this.setActiveSegment(selection.first);return}const changed=Boolean(values2[this.activeSegmentIndex]);values2[this.activeSegmentIndex]="";if(changed){this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward")}if(event.key==="Backspace")this.setActiveSegment(this.activeSegmentIndex-1);return}if(event.ctrlKey||event.metaKey||event.altKey||event.key.length!==1)return;event.preventDefault();const accepted=this.sanitize(event.key).slice(0,1);if(!accepted)return;const values=this.normalizedSegmentValues();const targetIndex=selection?.first??this.activeSegmentIndex;if(selection){for(const index of selection.indices)values[index]=""}values[targetIndex]=accepted;this.commitSegmentEdit(values,"insertText",accepted);this.setActiveSegment(targetIndex+1)};this.onPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=this.sanitize(event.clipboardData?.getData("text")??"");event.preventDefault();if(!pasted)return;const values=Array.from({length:this.segmentCount},(_,index)=>pasted[index]??"");this.commitSegmentEdit(values,"insertFromPaste",pasted);this.setActiveSegment(Math.min(pasted.length,this.segmentCount-1))};this.onChange=event=>{this.segmentEditPendingChange=false;relayNativeEvent(this,event)};this.onFocus=event=>{this.focused=true;relayNativeEvent(this,event);this.emit("lr-focus")};this.onBlur=event=>{this.focused=false;if(!this.effectiveDisabled)this.touched=true;this.flushPendingChange();relayNativeEvent(this,event);this.emit("lr-blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedNodes({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedNodes({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedNodes({flatten:true}).length>0}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,otpInputIncomplete:LYRA_DEFAULT_otpInputIncomplete,otpInputLabel:LYRA_DEFAULT_otpInputLabel,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search}}get input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){const normalized=this.sanitize(next??"");this.packSegmentValues(normalized);super.value=normalized}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;this.parsedFormatSource=this.format;if(!this.format){this.parsedFormatCells=null;return null}const cells=[];let segments=0;let literal="";const flushLiteral=()=>{if(!literal)return;cells.push({kind:"separator",text:literal});literal=""};for(const char of this.format){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral();cells.push({kind:"segment"});segments+=1}flushLiteral();this.parsedFormatCells=segments>0?cells:null;return this.parsedFormatCells}get segmentCount(){const formatted=this.formattedCells;if(formatted)return formatted.filter(cell=>cell.kind==="segment").length;return Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.segmentCount}get cells(){return this.formattedCells??Array.from({length:this.segmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric;let out=[...raw??""].filter(char=>accepted.test(char)).join("");if(this.case==="upper")out=out.toUpperCase();else if(this.case==="lower")out=out.toLowerCase();return out.slice(0,this.segmentCount)}packSegmentValues(value){const count=this.segmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??"");this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){if(!Array.isArray(this.segmentValues))return this.value.length;return this.segmentValues.reduce((count,value)=>count+(value?1:0),0)}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.segmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.segmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret);void this.updateComplete.then(()=>{const segment=this.renderRoot.querySelectorAll('[part~="segment"]')[next];segment?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();if(!form)return;const submitter=findImplicitSubmitter(form);if(!submitter)form.requestSubmit();else if(isNativeSubmitter(submitter)){form.requestSubmit(submitter)}else{submitter.click()}}completeIfTransition(previousFilled){if(previousFilled>=this.segmentCount||this.filledSegmentCount!==this.segmentCount)return;const completeEvent=this.emit("lr-complete",{value:this.value},{cancelable:true});if(!this.autosubmit)return;const token=this.autosubmitToken+=1;setTimeout(()=>{if(token!==this.autosubmitToken||completeEvent.defaultPrevented)return;if(!this.isConnected||!this.autosubmit)return;if(this.filledSegmentCount!==this.segmentCount)return;this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){const previousValue=this.value;const previousFilled=this.filledSegmentCount;this.segmentValues=this.normalizedSegmentValues(values);const nextValue=this.segmentValues.join("");super.value=nextValue;if(this.control)this.control.value=nextValue;this.touched=true;dispatchNativeInputEvent(this,{data,inputType});this.segmentEditPendingChange=true;if(previousValue&&!nextValue)this.emit("lr-clear");this.completeIfTransition(previousFilled);this.requestUpdate()}get selectedSegmentRange(){const start=this.control?.selectionStart;const end=this.control?.selectionEnd;if(start===void 0||start===null||end===void 0||end===null||start===end){return null}const occupiedIndices=this.normalizedSegmentValues().map((value,index)=>value?index:-1).filter(index=>index>=0);const indices=occupiedIndices.slice(start,end);const first=indices[0];return first===void 0?null:{indices,first}}focus(options){if(!this.effectiveDisabled)this.control?.focus(options)}blur(){this.control?.blur()}click(){if(!this.effectiveDisabled)this.control?.click()}select(){this.control?.select()}clear(){const hadValue=this.value.length>0;this.value="";if(this.control)this.control.value="";this.focus();if(hadValue)this.emit("lr-clear")}formResetCallback(){super.formResetCallback();this.touched=false;this.segmentEditPendingChange=false}reportValidity(){this.touched=true;return super.reportValidity()}firstUpdated(){if(this.autofocus)this.scheduleAfterUpdate(()=>this.focus(),"otp-autofocus")}willUpdate(changed){super.willUpdate?.(changed);if(changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.value);if(next!==this.value)this.value=next;else this.packSegmentValues(next)}if(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format")){this.updateValidity()}this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"--blank",this.value.length===0);setCustomState(this.internals,"--filled",this.filledSegmentCount===this.segmentCount);setCustomState(this.internals,"disabled",this.effectiveDisabled);setCustomState(this.internals,"readonly",this.readonly)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const total=this.segmentCount;const filled=this.filledSegmentCount;const complete=filled===total;if(this.required&&filled===0){this[SET_ANCHORED_VALIDITY]({valueMissing:true},this.localize("fieldRequired"));return}if(filled>0&&!complete){this[SET_ANCHORED_VALIDITY]({tooShort:true},this.localize("otpInputIncomplete",void 0,{total}));return}this[SET_ANCHORED_VALIDITY]({})}flushPendingChange(){if(!this.segmentEditPendingChange)return;this.segmentEditPendingChange=false;dispatchNativeEvent(this,"change")}renderSegment(index,invalid){const char=this.segmentValues[index]??"";const filled=char!=="";const active=this.focused&&!this.effectiveDisabled&&!this.readonly&&index===this.activeSegmentIndex;const masked=filled&&this.mask;const placeholderMask=!filled&&this.withMask;const parts=["segment"];if(active)parts.push("active");if(masked)parts.push("masked");if(placeholderMask)parts.push("placeholder-mask");if(invalid)parts.push("invalid");return html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=Boolean(this.label)||this.hasLabelSlot;const hasHint=Boolean(this.hint)||this.hasHintSlot;const hasError=Boolean(this.errorText)||this.hasErrorSlot;const intrinsicInvalid=this.touched&&!this.validity.valid;const ariaInvalid=hasError||intrinsicInvalid;const describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" ");let segmentIndex=-1;return html`
2
2
  <div part="base form-control">
3
3
  <label part="label form-control-label" id=${this.labelId} for="control" ?hidden=${!hasLabel}>
4
4
  ${this.label}<slot