@aceshooting/lyra-ui 8.2.0 → 8.2.2
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.
- package/CHANGELOG.md +34 -0
- package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/input/input.class.d.ts +9 -0
- package/dist/components/forms/input/input.class.js +4 -3
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/phone-input/phone-input.class.js +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/localization-runtime.d.ts +13 -0
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/lyra-element.d.ts +15 -0
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/testing/happy-dom-shims.d.ts +1 -1
- package/dist/testing/happy-dom-shims.js +1 -1
- package/llms/components/lr-input.md +6 -0
- package/llms-full.txt +6 -0
- package/package.json +2 -2
- 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}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
|
|
@@ -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{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./phone-input.styles.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_phoneInputIncomplete,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";async function loadLibphonenumberAdapter(loader){const module=await loader();const countries=module.getCountries().map(code=>({code:normalizeCountry(code),callingCode:module.getCountryCallingCode(code)}));return{countries,parse(input,country){const raw=input.trim();if(!raw)return{status:"empty"};const normalizedCountry=country?normalizeCountry(country):void 0;const phone=module.parsePhoneNumberFromString(raw,normalizedCountry);if(!phone){const length2=module.validatePhoneNumberLength?.(raw,normalizedCountry);return{status:length2==="TOO_SHORT"||isDialLike(raw)?"incomplete":"invalid",formatted:raw}}const formatted=raw.startsWith("+")?phone.formatInternational():phone.formatNational();if(phone.isValid()){return{status:"valid",e164:phone.number,formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}const length=module.validatePhoneNumberLength?.(raw,normalizedCountry);return{status:length==="TOO_SHORT"||!length&&!phone.isPossible()?"incomplete":"invalid",formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}}}class LyraPhoneInputBase extends LyraElement{}const E164_RE=/^\+[1-9]\d{1,14}$/;const DIAL_LIKE_RE=/^[+\d\s().-]+$/;function normalizeCountry(country){return country.trim().toUpperCase()}function isDialLike(value){return DIAL_LIKE_RE.test(value.trim())}function digitsBefore(value,index){let count=0;for(let i=0;i<index&&i<value.length;i++){if(/\d/.test(value[i]))count++}return count}function indexAfterDigits(value,digitCount){if(digitCount<=0)return 0;let count=0;for(let i=0;i<value.length;i++){if(/\d/.test(value[i])){count++;if(count===digitCount)return i+1}}return value.length}function fallbackParse(input){const raw=input.trim();if(!raw)return{status:"empty"};const compact=raw.replace(/[\s().-]/g,"");if(E164_RE.test(compact))return{status:"valid",e164:compact,formatted:raw};if(isDialLike(raw))return{status:"incomplete",formatted:raw};return{status:"invalid",formatted:raw}}class LyraPhoneInput extends FormAssociated(LyraPhoneInputBase){constructor(){super(...arguments);this.flags=false;this.countries=[];this.defaultCountry="";this.label="";this.hint="";this.errorText="";this.placeholder="";this.size="m";this.pill=false;this.accessibleLabel=null;this.countryLabel="Select";this.phoneLabel="";this.incompleteText="This phone number is incomplete.";this.invalidText="The value is invalid.";this.autocomplete="tel";this.inputmode="tel";this.enterkeyhint="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.editableValue="";this.status="empty";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasCountryPrefixSlot=false;this.inputId=nextId("phone-input");this.hintId=nextId("phone-hint");this.errorId=nextId("phone-error");this.explicitCountry="";this.catalogCountryResolved=false;this.onInput=event=>{event.stopPropagation();const input=event.currentTarget;const caret=input.selectionStart;const digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value));this.syncFormattedValue(input,digitsBeforeCaret);this.emit("input",this.eventDetail)};this.onChange=event=>{event.stopPropagation();this.touched=true;this.emit("change",this.eventDetail)};this.onCountryChange=event=>{event.stopPropagation();this.country=normalizeCountry(event.currentTarget.value);this.applyParsed(this.editableValue,this.parse(this.editableValue));this.emit("input",this.eventDetail);this.emit("change",this.eventDetail)};this.onKeyDown=event=>{if(this.effectiveDisabled)return;submitOnEnter(this,event)};this.onFocus=event=>{event.stopPropagation();this.emit("focus")};this.onBlur=event=>{event.stopPropagation();this.touched=true;this.emit("blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onCountryPrefixSlotChange=event=>{this.hasCountryPrefixSlot=event.currentTarget.assignedElements({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,phoneInputIncomplete:LYRA_DEFAULT_phoneInputIncomplete,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={country:{noAccessor:true}}}get country(){if(this.catalogCountryResolved)return normalizeCountry(this.explicitCountry);const firstCountry=this.countries[0]?.code??this.adapter?.countries?.[0]?.code??"";return normalizeCountry(this.explicitCountry||this.defaultCountry||firstCountry)}set country(next){const old=this.country;this.catalogCountryResolved=false;this.explicitCountry=normalizeCountry(next??"");this.requestUpdate("country",old)}get input(){return this.inputElement}get inputValue(){return this.editableValue}get phoneStatus(){return this.status}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}set selectionDirection(value){if(this.inputElement)this.inputElement.selectionDirection=value??"none"}[VALIDITY_ANCHOR](){return this.inputElement??null}get value(){return super.value}set value(next){const raw=next??"";const parsed=this.parse(raw);this.applyParsed(raw,parsed)}get availableCountries(){const source=this.countries.length?this.countries:this.adapter?.countries??[];const seen=new Set;const rows=[];for(const item of source){const code=normalizeCountry(item.code);if(!/^[A-Z]{2}$/.test(code)||seen.has(code))continue;seen.add(code);rows.push({...item,code,callingCode:item.callingCode.replace(/^\+/,"")})}if(rows.length===0&&this.country){rows.push({code:this.country,callingCode:""})}return rows}parse(input){if(!this.adapter)return fallbackParse(input);try{const parsed=this.adapter.parse(input,this.country||void 0);if(parsed.status==="valid"&&(!parsed.e164||!E164_RE.test(parsed.e164))){return{status:"invalid",formatted:parsed.formatted??input,country:parsed.country}}return parsed}catch{return fallbackParse(input)}}reconcileCountryCatalog(){const source=this.countries.length?this.countries:this.adapter?.countries??[];const codes=source.map(item=>normalizeCountry(item.code)).filter((code,index,values)=>/^[A-Z]{2}$/.test(code)&&values.indexOf(code)===index);const old=this.country;const preferred=normalizeCountry(this.defaultCountry);const next=codes.includes(old)?old:codes.includes(preferred)?preferred:codes[0]??"";this.explicitCountry=next;this.catalogCountryResolved=true;if(old!==next)this.requestUpdate("country",old)}applyParsed(raw,parsed){this.editableValue=parsed.formatted??raw;this.status=parsed.status;if(parsed.country)this.country=normalizeCountry(parsed.country);super.value=parsed.status==="valid"?parsed.e164:"";this.setAttribute("data-phone-status",parsed.status)}syncFormattedValue(input,digitsBeforeCaret){if(input.value===this.editableValue)return;input.value=this.editableValue;if(digitsBeforeCaret!=null){const position=indexAfterDigits(this.editableValue,digitsBeforeCaret);input.setSelectionRange(position,position)}}get eventDetail(){return{value:super.value,inputValue:this.editableValue,country:this.country,valid:this.internals.validity.valid,status:this.status}}get effectiveCountryLabel(){return this.localize("select",this.countryLabel==="Select"?void 0:this.countryLabel)}get effectivePhoneLabel(){return this.accessibleLabel||this.phoneLabel||this.label||this.placeholder||void 0}get incompleteMessage(){return this.localize("phoneInputIncomplete",this.incompleteText==="This phone number is incomplete."?void 0:this.incompleteText)}get invalidMessage(){return this.localize("valueInvalid",this.invalidText==="The value is invalid."?void 0:this.invalidText)}countryName(row){if(row.label)return row.label;try{return getDisplayNames(this.effectiveLocale,{type:"region"}).of(row.code)??row.code}catch{return row.code}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";if(this.required&&this.status==="empty"){flags.valueMissing=true;message=this.localize("fieldRequired")}else if(this.status==="incomplete"){flags.badInput=true;message=this.incompleteMessage}else if(this.status==="invalid"){flags.typeMismatch=true;message=this.invalidMessage}this[SET_ANCHORED_VALIDITY](flags,message)}willUpdate(changed){super.willUpdate(changed);if(this.flags&&!LyraPhoneInput.flagRegistration){LyraPhoneInput.flagRegistration=import("../../media/flag/flag.js").catch(error=>{console.warn("<lr-phone-input> failed to register <lr-flag> for its flags option:",error)})}if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="error");this.hasCountryPrefixSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="country-prefix")}if(this.hasUpdated&&(changed.has("countries")||changed.has("adapter"))){this.reconcileCountryCatalog()}if((changed.has("adapter")||changed.has("countries")||changed.has("country")||changed.has("defaultCountry"))&&this.editableValue){this.applyParsed(this.editableValue,this.parse(this.editableValue))}}updated(changed){super.updated(changed);if(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("status")){const invalid=this.touched&&!this.internals.validity.valid;this.toggleAttribute("data-invalid",invalid);if(invalid)this.setAttribute("aria-invalid","true");else this.removeAttribute("aria-invalid")}}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)}const caret=input.selectionStart;const digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value));this.syncFormattedValue(input,digitsBeforeCaret)}formResetCallback(){this.country=normalizeCountry(this.defaultCountry||this.availableCountries[0]?.code||"");super.formResetCallback();this.touched=false}render(){const hasLabel=Boolean(this.label||this.hasLabelSlot);const validationError=this.touched?this.validationMessage:"";const renderedError=this.errorText||validationError;const hasHint=Boolean(this.hint||this.hasHintSlot);const hasError=Boolean(renderedError||this.hasErrorSlot);const describedBy=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ");const rows=this.availableCountries;const current=rows.find(row=>row.code===this.country);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{nextId}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./phone-input.styles.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_phoneInputIncomplete,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";async function loadLibphonenumberAdapter(loader){const module=await loader();const countries=module.getCountries().map(code=>({code:normalizeCountry(code),callingCode:module.getCountryCallingCode(code)}));return{countries,parse(input,country){const raw=input.trim();if(!raw)return{status:"empty"};const normalizedCountry=country?normalizeCountry(country):void 0;const phone=module.parsePhoneNumberFromString(raw,normalizedCountry);if(!phone){const length2=module.validatePhoneNumberLength?.(raw,normalizedCountry);return{status:length2==="TOO_SHORT"||isDialLike(raw)?"incomplete":"invalid",formatted:raw}}const formatted=raw.startsWith("+")?phone.formatInternational():phone.formatNational();if(phone.isValid()){return{status:"valid",e164:phone.number,formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}const length=module.validatePhoneNumberLength?.(raw,normalizedCountry);return{status:length==="TOO_SHORT"||!length&&!phone.isPossible()?"incomplete":"invalid",formatted,country:phone.country?normalizeCountry(phone.country):normalizedCountry}}}}class LyraPhoneInputBase extends LyraElement{}const E164_RE=/^\+[1-9]\d{1,14}$/;const DIAL_LIKE_RE=/^[+\d\s().-]+$/;function normalizeCountry(country){return country.trim().toUpperCase()}function isDialLike(value){return DIAL_LIKE_RE.test(value.trim())}function digitsBefore(value,index){let count=0;for(let i=0;i<index&&i<value.length;i++){if(/\d/.test(value[i]))count++}return count}function indexAfterDigits(value,digitCount){if(digitCount<=0)return 0;let count=0;for(let i=0;i<value.length;i++){if(/\d/.test(value[i])){count++;if(count===digitCount)return i+1}}return value.length}function fallbackParse(input){const raw=input.trim();if(!raw)return{status:"empty"};const compact=raw.replace(/[\s().-]/g,"");if(E164_RE.test(compact))return{status:"valid",e164:compact,formatted:raw};if(isDialLike(raw))return{status:"incomplete",formatted:raw};return{status:"invalid",formatted:raw}}class LyraPhoneInput extends FormAssociated(LyraPhoneInputBase){constructor(){super(...arguments);this.flags=false;this.countries=[];this.defaultCountry="";this.label="";this.hint="";this.errorText="";this.placeholder="";this.size="m";this.pill=false;this.accessibleLabel=null;this.countryLabel="Select";this.phoneLabel="";this.incompleteText="This phone number is incomplete.";this.invalidText="The value is invalid.";this.autocomplete="tel";this.inputmode="tel";this.enterkeyhint="";this.spellcheck=true;this.autocapitalize="";this.autoCorrect="";this.editableValue="";this.status="empty";this.touched=false;this.hasLabelSlot=false;this.hasHintSlot=false;this.hasErrorSlot=false;this.hasCountryPrefixSlot=false;this.inputId=nextId("phone-input");this.hintId=nextId("phone-hint");this.errorId=nextId("phone-error");this.explicitCountry="";this.catalogCountryResolved=false;this.onInput=event=>{event.stopPropagation();const input=event.currentTarget;const caret=input.selectionStart;const digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value));this.syncFormattedValue(input,digitsBeforeCaret);this.emit("input",this.eventDetail)};this.onChange=event=>{event.stopPropagation();this.touched=true;this.emit("change",this.eventDetail)};this.onCountryChange=event=>{event.stopPropagation();this.country=normalizeCountry(event.currentTarget.value);this.applyParsed(this.editableValue,this.parse(this.editableValue));this.emit("input",this.eventDetail);this.emit("change",this.eventDetail)};this.onKeyDown=event=>{if(this.effectiveDisabled)return;submitOnEnter(this,event)};this.onFocus=event=>{event.stopPropagation();this.emit("focus")};this.onBlur=event=>{event.stopPropagation();if(!this.effectiveDisabled)this.touched=true;this.emit("blur")};this.onLabelSlotChange=event=>{this.hasLabelSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onHintSlotChange=event=>{this.hasHintSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=event=>{this.hasErrorSlot=event.currentTarget.assignedElements({flatten:true}).length>0};this.onCountryPrefixSlotChange=event=>{this.hasCountryPrefixSlot=event.currentTarget.assignedElements({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,phoneInputIncomplete:LYRA_DEFAULT_phoneInputIncomplete,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={country:{noAccessor:true}}}get country(){if(this.catalogCountryResolved)return normalizeCountry(this.explicitCountry);const firstCountry=this.countries[0]?.code??this.adapter?.countries?.[0]?.code??"";return normalizeCountry(this.explicitCountry||this.defaultCountry||firstCountry)}set country(next){const old=this.country;this.catalogCountryResolved=false;this.explicitCountry=normalizeCountry(next??"");this.requestUpdate("country",old)}get input(){return this.inputElement}get inputValue(){return this.editableValue}get phoneStatus(){return this.status}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}set selectionDirection(value){if(this.inputElement)this.inputElement.selectionDirection=value??"none"}[VALIDITY_ANCHOR](){return this.inputElement??null}get value(){return super.value}set value(next){const raw=next??"";const parsed=this.parse(raw);this.applyParsed(raw,parsed)}get availableCountries(){const source=this.countries.length?this.countries:this.adapter?.countries??[];const seen=new Set;const rows=[];for(const item of source){const code=normalizeCountry(item.code);if(!/^[A-Z]{2}$/.test(code)||seen.has(code))continue;seen.add(code);rows.push({...item,code,callingCode:item.callingCode.replace(/^\+/,"")})}if(rows.length===0&&this.country){rows.push({code:this.country,callingCode:""})}return rows}parse(input){if(!this.adapter)return fallbackParse(input);try{const parsed=this.adapter.parse(input,this.country||void 0);if(parsed.status==="valid"&&(!parsed.e164||!E164_RE.test(parsed.e164))){return{status:"invalid",formatted:parsed.formatted??input,country:parsed.country}}return parsed}catch{return fallbackParse(input)}}reconcileCountryCatalog(){const source=this.countries.length?this.countries:this.adapter?.countries??[];const codes=source.map(item=>normalizeCountry(item.code)).filter((code,index,values)=>/^[A-Z]{2}$/.test(code)&&values.indexOf(code)===index);const old=this.country;const preferred=normalizeCountry(this.defaultCountry);const next=codes.includes(old)?old:codes.includes(preferred)?preferred:codes[0]??"";this.explicitCountry=next;this.catalogCountryResolved=true;if(old!==next)this.requestUpdate("country",old)}applyParsed(raw,parsed){this.editableValue=parsed.formatted??raw;this.status=parsed.status;if(parsed.country)this.country=normalizeCountry(parsed.country);super.value=parsed.status==="valid"?parsed.e164:"";this.setAttribute("data-phone-status",parsed.status)}syncFormattedValue(input,digitsBeforeCaret){if(input.value===this.editableValue)return;input.value=this.editableValue;if(digitsBeforeCaret!=null){const position=indexAfterDigits(this.editableValue,digitsBeforeCaret);input.setSelectionRange(position,position)}}get eventDetail(){return{value:super.value,inputValue:this.editableValue,country:this.country,valid:this.internals.validity.valid,status:this.status}}get effectiveCountryLabel(){return this.localize("select",this.countryLabel==="Select"?void 0:this.countryLabel)}get effectivePhoneLabel(){return this.accessibleLabel||this.phoneLabel||this.label||this.placeholder||void 0}get incompleteMessage(){return this.localize("phoneInputIncomplete",this.incompleteText==="This phone number is incomplete."?void 0:this.incompleteText)}get invalidMessage(){return this.localize("valueInvalid",this.invalidText==="The value is invalid."?void 0:this.invalidText)}countryName(row){if(row.label)return row.label;try{return getDisplayNames(this.effectiveLocale,{type:"region"}).of(row.code)??row.code}catch{return row.code}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";if(this.required&&this.status==="empty"){flags.valueMissing=true;message=this.localize("fieldRequired")}else if(this.status==="incomplete"){flags.badInput=true;message=this.incompleteMessage}else if(this.status==="invalid"){flags.typeMismatch=true;message=this.invalidMessage}this[SET_ANCHORED_VALIDITY](flags,message)}willUpdate(changed){super.willUpdate(changed);if(this.flags&&!LyraPhoneInput.flagRegistration){LyraPhoneInput.flagRegistration=import("../../media/flag/flag.js").catch(error=>{console.warn("<lr-phone-input> failed to register <lr-flag> for its flags option:",error)})}if(!this.hasUpdated){this.hasLabelSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="hint");this.hasErrorSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="error");this.hasCountryPrefixSlot=Array.from(this.children).some(child=>child.getAttribute("slot")==="country-prefix")}if(this.hasUpdated&&(changed.has("countries")||changed.has("adapter"))){this.reconcileCountryCatalog()}if((changed.has("adapter")||changed.has("countries")||changed.has("country")||changed.has("defaultCountry"))&&this.editableValue){this.applyParsed(this.editableValue,this.parse(this.editableValue))}}updated(changed){super.updated(changed);if(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("status")){const invalid=this.touched&&!this.internals.validity.valid;this.toggleAttribute("data-invalid",invalid);if(invalid)this.setAttribute("aria-invalid","true");else this.removeAttribute("aria-invalid")}}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)}const caret=input.selectionStart;const digitsBeforeCaret=caret==null?null:digitsBefore(input.value,caret);this.applyParsed(input.value,this.parse(input.value));this.syncFormattedValue(input,digitsBeforeCaret)}formResetCallback(){this.country=normalizeCountry(this.defaultCountry||this.availableCountries[0]?.code||"");super.formResetCallback();this.touched=false}render(){const hasLabel=Boolean(this.label||this.hasLabelSlot);const validationError=this.touched?this.validationMessage:"";const renderedError=this.errorText||validationError;const hasHint=Boolean(this.hint||this.hasHintSlot);const hasError=Boolean(renderedError||this.hasErrorSlot);const describedBy=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ");const rows=this.availableCountries;const current=rows.find(row=>row.code===this.country);return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<label part="form-control-label" for=${this.inputId} ?hidden=${!hasLabel}>
|
|
4
4
|
<slot name="label" @slotchange=${this.onLabelSlotChange}>${this.label}</slot>
|
|
@@ -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{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{LyraOption}from"../combobox/option.class.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_select,LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}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 LyraSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},multiple:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:true},defaultValue:{attribute:"default-value",noAccessor:true}}}focus(options){if(!this.effectiveDisabled)this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){if(!this.effectiveDisabled)this.triggerElement?.click()}constructor(){super();this.placeholder="";this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.autofocus=false;this.title="";this.open=false;this.size="m";this.appearance="outlined";this.pill=false;this.placement="bottom";this.hoist=false;this.filled=false;this.withClear=false;this.clearable=false;this.autoCommitSingleOption=false;this.activeIndex=-1;this.options=[];this.touched=false;this.hasInteracted=false;this.slotPresence=new SlotPresenceController(this);this._fieldsetDisabled=false;this.listId=nextId("select-list");this.triggerId=nextId("select-trigger");this._isFirstUpdate=true;this.openVetoed=false;this.transitionToken=0;this.transitionWaiters=new Map;this._selected=[];this._selectedOptions=[];this._multiple=false;this._disabled=false;this._required=false;this._defaultSelected=[];this._defaultSelectedOptions=[];this._defaultCaptured=false;this._valueDirty=false;this._restoredStateActive=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this._name="";this._maxOptionsVisible=3;this.collectOptions=e=>{const slot=e.target;const previous=new Set(this.options);this.options=slot.assignedElements({flatten:true}).filter(el=>el instanceof LyraOption);if(!this._defaultCaptured){this._defaultCaptured=true;const hasDefaultValue=this.hasAttribute("default-value");const allDefaults=this.options.filter(option=>option.defaultSelected);const defaults=this.multiple?allDefaults:allDefaults.slice(0,1);const allLive=this.options.filter(option=>option.selected);const live=this.multiple?allLive:allLive.slice(0,1);const initialLive=this.options.filter(option=>wasOptionInitiallySelected(option));const optionDirty=this.options.some(option=>isOptionSelectedDirty(option));const dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(!hasDefaultValue){const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value);this._defaultSelectedOptions=[...resetOptions]}else{this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected)}const fromDefaults=hasDefaultValue||defaults.length>0;const initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:hasDefaultValue?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){if(!fromDefaults||optionDirty)this._valueDirty=true;this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty)this._valueDirty=true;if(hasDefaultValue&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}else{const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected);const newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...!this._restoredStateActive?newLive:[]];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1);const occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;if(newLive.length>0)this._valueDirty=true;this.setSelection(occurrences.map(option=>option.value),occurrences);return}}this.reflectSelected()};this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults();this.reflectSelected();this.options=[...this.options]})};this.onDocPointer=e=>{if(!e.composedPath().includes(this))void this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;if(this.onlyOption)return this.selectOption(this.onlyOption);if(this.open)void this.hide();else void this.show()};this.onTriggerBlur=event=>{this.touched=true;this.hasInteracted=true;this.reflectValidityStates();void this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onTriggerFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onKeyDown=e=>{const navigable=this.navigableOptions();switch(e.key){case"ArrowDown":e.preventDefault();if(this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){void this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){void this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];if(this.activeIndex>=0&&active){this.selectOption(active)}else{void this.hide()}}break;case"Escape":if(this.open){e.preventDefault();void this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=navigable.length-1}break;case"Backspace":case"Delete":if(this.multiple&&this._selected.length>0){e.preventDefault();this.removeValue(this._selected[this._selected.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=>{const optionEl=e.target.closest('[part="option"]');const index=Number(optionEl?.dataset["index"]);if(!Number.isInteger(index))return;const option=this.options[index];if(option)this.selectOption(option)};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormValue()}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();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){super.willUpdate(changed);this._isFirstUpdate=!this.hasUpdated;this.announceOpenTransition(changed)}announceOpenTransition(changed){this.openVetoed=false;if(!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}if(!this.emit(name,void 0,{cancelable:true}).defaultPrevented)return;this.openVetoed=true;this.open=!this.open;this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show")}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.syncFormValue();this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=Boolean(next);this.toggleAttribute("multiple",this._multiple);if(!this._multiple&&this._selected.length>1){this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1))}else{this.syncFormValue()}this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3);this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)void 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 value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this._restoredStateActive=false;this._valueDirty=true;const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value==="string");this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"";const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value==="string");this._defaultSelected=this.multiple?[...new Set(values)]:values.slice(0,1);this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);if(!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){this._restoredStateActive=false;this._valueDirty=true;const candidates=Array.isArray(next)?next:[];const live=candidates.filter((option,index)=>option instanceof LyraOption&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index);const selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}setSelection(next,preferred=[]){const values=this.multiple?[...new Set(next)]:next.slice(0,1);const previousValues=this._selected;const previousOptions=this._selectedOptions;const old=this.multiple?[...previousValues]:previousValues[0]??"";this._selected=values;this._selectedOptions=this.resolveOccurrences(values,preferred);this.syncFormValue();this.reflectSelected();this.updateValidity();this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]);const sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);if(sameValues&&!sameOptions)this.requestUpdate()}resolveOccurrences(values,preferred=[]){const claimed=new Set;const resolved=[];values.forEach((value,index)=>{const hint=preferred[index];const match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));if(!match)return;claimed.add(match);resolved.push(match)});return resolved}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&this._selected.length===0){this.validityController.setValidity({valueMissing:true},this.localize("selectValueMissing"))}else{this.validityController.setValidity({})}this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation});if(this._selected.length===0)this.internals.states?.add("blank");else this.internals.states?.delete("blank")}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=false;this.hasInteracted=false;this._restoredStateActive=false;this._valueDirty=false;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));if(this._defaultSelectedOptions.length===0&&resetOptions.length>0){this._defaultSelectedOptions=[...resetOptions];this._defaultSelected=resetOptions.map(option=>option.value)}const defaults=new Set(resetOptions);for(const option of this.options){option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option))}this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){void reason;if(!this.multiple){this.value=typeof state2==="string"?state2:""}else{let restored=[];if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(Array.isArray(parsed)&&parsed.every(entry=>typeof entry==="string"))restored=parsed}catch{}}this.value=restored}this._restoredStateActive=true;this._valueDirty=true}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)void this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){this.updateValidity();return this.internals.checkValidity()}reportValidity(){this.updateValidity();this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.transitionToken++;super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.unbindDocumentPointer();this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}refreshOptionDefaults(){if(this.hasAttribute("default-value"))return;const declared=this.options.filter(option=>option.defaultSelected);const defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value);this._defaultSelectedOptions=[...defaults];if(!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions);const chosen=new Set(this._selectedOptions);for(const option of this.options){option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}}labelFor(value){return this._selectedOptions.find(option=>option.value===value)?.label??this.options.find(option=>option.value===value)?.label??value}get onlyOption(){if(!this.autoCommitSingleOption)return void 0;const navigable=this.navigableOptions();return navigable.length===1?navigable[0]:void 0}navigableOptions(options=this.options){return options.filter(o=>!o.disabled&&!o.inert&&!o.closest("[inert]"))}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;return settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.open=false;this.activeIndex=-1;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.cleanup?.();this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"})}}updated(changed){super.updated(changed);if(changed.has("open")&&!this.openVetoed){this.cleanup?.();this.cleanup=void 0;if(this.open&&this.isConnected){this.bindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-show")}const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"})}}else if(!this.open){this.unbindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-hide")}}else{this.unbindDocumentPointer()}}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}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 listbox=this.renderRoot.querySelector('[part="listbox"]');const animations=listbox?.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()}emitValueEvents(){dispatchNativeInputEvent(this);this.emit("lr-input",{value:this.value});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})}selectOption(option){if(this.effectiveDisabled||option.disabled)return;this.hasInteracted=true;this._restoredStateActive=false;this._valueDirty=true;if(this.multiple){const selected=this._selected.includes(option.value);const occurrences=selected?this._selectedOptions.filter(candidate=>candidate.value!==option.value):[...this._selectedOptions,option];const values=selected?this._selected.filter(value=>value!==option.value):[...this._selected,option.value];this.setSelection(values,occurrences);this.emitValueEvents();return}const changed=option!==this._selectedOptions[0]||option.value!==this._selected[0];this.setSelection([option.value],[option]);void this.hide();if(changed)this.emitValueEvents()}removeValue(value){if(this.effectiveDisabled||!this._selected.includes(value))return;this._restoredStateActive=false;this._valueDirty=true;this.setSelection(this._selected.filter(candidate=>candidate!==value),this._selectedOptions.filter(option=>option.value!==value));this.emitValueEvents()}clear(){if(this.effectiveDisabled||this._selected.length===0)return;this._restoredStateActive=false;this._valueDirty=true;this.setSelection([],[]);this.emitValueEvents();this.emit("lr-clear")}removeTag(value,index,event){event.stopPropagation();this.removeValue(value);void this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.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 navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1];const currentIndex=navigable.indexOf(currentOption);const n=navigable.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const candidate=navigable[idx];if(candidate===void 0)continue;if(candidate.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else if(!(this.multiple&&this._selected.includes(candidate.value))){this.selectOption(candidate)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(options,activeId){const out=[];const chosen=new Set(this._selectedOptions);let currentGroup;options.forEach((o,i)=>{if(o.group!==currentGroup){currentGroup=o.group;if(currentGroup)out.push(html`<div class="group-label" part="group-label">${currentGroup}</div>`)}const id=`${this.listId}-opt-${i}`;const selected=chosen.has(o);out.push(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{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{nextId}from"../../../internal/a11y.js";import{chevronIcon,closeIcon}from"../../../internal/icons.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{styles}from"./select.styles.js";import{sizes}from"../../../internal/sizes.styles.js";import{LyraOption}from"../combobox/option.class.js";import"../combobox/option.class.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{isOptionSelectedDirty,wasOptionInitiallySelected,RESET_OPTION_SELECTED_FROM_OWNER,SET_OPTION_SELECTED_FROM_OWNER}from"../../../internal/option-selection.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_select,LYRA_DEFAULT_selectSelectedOverflow,LYRA_DEFAULT_selectValueMissing}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 LyraSelect extends LyraElement{static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,select:LYRA_DEFAULT_select,selectSelectedOverflow:LYRA_DEFAULT_selectSelectedOverflow,selectValueMissing:LYRA_DEFAULT_selectValueMissing}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},multiple:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},value:{noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},maxOptionsVisible:{type:Number,attribute:"max-options-visible",noAccessor:true},defaultValue:{attribute:"default-value",noAccessor:true}}}focus(options){if(!this.effectiveDisabled)this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){if(!this.effectiveDisabled)this.triggerElement?.click()}constructor(){super();this.placeholder="";this.label="";this.hint="";this.helpText="";this.withLabel=false;this.withHint=false;this.errorText="";this.autofocus=false;this.title="";this.open=false;this.size="m";this.appearance="outlined";this.pill=false;this.placement="bottom";this.hoist=false;this.filled=false;this.withClear=false;this.clearable=false;this.autoCommitSingleOption=false;this.activeIndex=-1;this.options=[];this.touched=false;this.hasInteracted=false;this.slotPresence=new SlotPresenceController(this);this._fieldsetDisabled=false;this.listId=nextId("select-list");this.triggerId=nextId("select-trigger");this._isFirstUpdate=true;this.openVetoed=false;this.transitionToken=0;this.transitionWaiters=new Map;this._selected=[];this._selectedOptions=[];this._multiple=false;this._disabled=false;this._required=false;this._defaultSelected=[];this._defaultSelectedOptions=[];this._defaultCaptured=false;this._valueDirty=false;this._restoredStateActive=false;this.typeAheadBuffer="";this.typeAheadTimerGeneration=0;this._name="";this._maxOptionsVisible=3;this.collectOptions=e=>{const slot=e.target;const previous=new Set(this.options);this.options=slot.assignedElements({flatten:true}).filter(el=>el instanceof LyraOption);if(!this._defaultCaptured){this._defaultCaptured=true;const hasDefaultValue=this.hasAttribute("default-value");const allDefaults=this.options.filter(option=>option.defaultSelected);const defaults=this.multiple?allDefaults:allDefaults.slice(0,1);const allLive=this.options.filter(option=>option.selected);const live=this.multiple?allLive:allLive.slice(0,1);const initialLive=this.options.filter(option=>wasOptionInitiallySelected(option));const optionDirty=this.options.some(option=>isOptionSelectedDirty(option));const dirtySelected=this.options.filter(option=>isOptionSelectedDirty(option)&&option.selected);if(!hasDefaultValue){const resetOptions=defaults.length>0?defaults:initialLive.length>0?initialLive:live;this._defaultSelected=resetOptions.map(option=>option.value);this._defaultSelectedOptions=[...resetOptions]}else{this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected)}const fromDefaults=hasDefaultValue||defaults.length>0;const initial=optionDirty?this.multiple?allLive:dirtySelected.slice(-1)[0]?dirtySelected.slice(-1):live:hasDefaultValue?this._defaultSelectedOptions:fromDefaults?defaults:live;if(initial.length>0&&!this._restoredStateActive&&!this._valueDirty){if(!fromDefaults||optionDirty)this._valueDirty=true;this.setSelection(initial.map(option=>option.value),[...initial]);return}if(optionDirty)this._valueDirty=true;if(hasDefaultValue&&!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions]);return}}else{const newDefaults=this.options.filter(option=>!previous.has(option)&&option.defaultSelected);const newLive=this.options.filter(option=>!previous.has(option)&&option.selected&&!option.defaultSelected);this.refreshOptionDefaults();const eligible=[...!this._restoredStateActive&&!this._valueDirty?newDefaults:[],...!this._restoredStateActive?newLive:[]];if(eligible.length>0){const added=this.multiple?eligible:eligible.slice(-1);const occurrences=this.multiple?[...new Set([...this._selectedOptions,...added])]:added;if(newLive.length>0)this._valueDirty=true;this.setSelection(occurrences.map(option=>option.value),occurrences);return}}this.reflectSelected()};this.onOptionChange=()=>{queueMicrotask(()=>{this.refreshOptionDefaults();this.reflectSelected();this.options=[...this.options]})};this.onDocPointer=e=>{if(!e.composedPath().includes(this))void this.hide()};this.onTriggerClick=()=>{if(this.effectiveDisabled)return;if(this.onlyOption)return this.selectOption(this.onlyOption);if(this.open)void this.hide();else void this.show()};this.onTriggerBlur=event=>{if(!this.effectiveDisabled){this.touched=true;this.hasInteracted=true;this.reflectValidityStates()}void this.hide();relayNativeEvent(this,event);this.emit("lr-blur")};this.onTriggerFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onKeyDown=e=>{const navigable=this.navigableOptions();switch(e.key){case"ArrowDown":e.preventDefault();if(this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){void this.show();return}this.activeIndex=Math.min(navigable.length-1,this.activeIndex+1);break;case"ArrowUp":e.preventDefault();if(this.onlyOption)return this.selectOption(this.onlyOption);if(!this.open){void this.show();return}this.activeIndex=Math.max(0,this.activeIndex-1);break;case"Enter":case" ":if(this.open){e.preventDefault();const active=navigable[this.activeIndex];if(this.activeIndex>=0&&active){this.selectOption(active)}else{void this.hide()}}break;case"Escape":if(this.open){e.preventDefault();void this.hide()}break;case"Home":if(this.open){e.preventDefault();this.activeIndex=0}break;case"End":if(this.open){e.preventDefault();this.activeIndex=navigable.length-1}break;case"Backspace":case"Delete":if(this.multiple&&this._selected.length>0){e.preventDefault();this.removeValue(this._selected[this._selected.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=>{const optionEl=e.target.closest('[part="option"]');const index=Number(optionEl?.dataset["index"]);if(!Number.isInteger(index))return;const option=this.options[index];if(option)this.selectOption(option)};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormValue()}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();if(this.hasUpdated&&this.open)queueMicrotask(()=>this.reconnectOpenPopup())}willUpdate(changed){super.willUpdate(changed);this._isFirstUpdate=!this.hasUpdated;this.announceOpenTransition(changed)}announceOpenTransition(changed){this.openVetoed=false;if(!changed.has("open")||this._isFirstUpdate)return;const name=this.open?"lr-show":"lr-hide";if(!this.isConnected){this.emit("lr-hide");return}if(!this.emit(name,void 0,{cancelable:true}).defaultPrevented)return;this.openVetoed=true;this.open=!this.open;this.resolveTransitionWaiters(this.open?"lr-after-hide":"lr-after-show")}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.syncFormValue();this.requestUpdate("name",old)}get multiple(){return this._multiple}set multiple(next){const old=this._multiple;this._multiple=Boolean(next);this.toggleAttribute("multiple",this._multiple);if(!this._multiple&&this._selected.length>1){this.setSelection(this._selected.slice(0,1),this._selectedOptions.slice(0,1))}else{this.syncFormValue()}this.requestUpdate("multiple",old)}get maxOptionsVisible(){return this._maxOptionsVisible}set maxOptionsVisible(next){const old=this._maxOptionsVisible;this._maxOptionsVisible=finiteCount(next,3);this.requestUpdate("maxOptionsVisible",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);if(this._disabled)void 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 value(){return this.multiple?[...this._selected]:this._selected[0]??""}set value(next){this._restoredStateActive=false;this._valueDirty=true;const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value==="string");this.setSelection(values,values.map(value=>this.options.find(option=>option.value===value)))}get defaultValue(){return this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??""}set defaultValue(next){const old=this.multiple?[...this._defaultSelected]:this._defaultSelected[0]??"";const values=(Array.isArray(next)?next:next?[next]:[]).filter(value=>typeof value==="string");this._defaultSelected=this.multiple?[...new Set(values)]:values.slice(0,1);this._defaultSelectedOptions=this.resolveOccurrences(this._defaultSelected);if(!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}this.requestUpdate("defaultValue",old)}get selectedOptions(){return[...this._selectedOptions]}set selectedOptions(next){this._restoredStateActive=false;this._valueDirty=true;const candidates=Array.isArray(next)?next:[];const live=candidates.filter((option,index)=>option instanceof LyraOption&&this.contains(option)&&this.options.includes(option)&&candidates.indexOf(option)===index);const selected=this.multiple?live:live.slice(0,1);this.setSelection(selected.map(option=>option.value),selected)}setSelection(next,preferred=[]){const values=this.multiple?[...new Set(next)]:next.slice(0,1);const previousValues=this._selected;const previousOptions=this._selectedOptions;const old=this.multiple?[...previousValues]:previousValues[0]??"";this._selected=values;this._selectedOptions=this.resolveOccurrences(values,preferred);this.syncFormValue();this.reflectSelected();this.updateValidity();this.requestUpdate("value",old);const sameValues=previousValues.length===values.length&&previousValues.every((value,i)=>value===values[i]);const sameOptions=previousOptions.length===this._selectedOptions.length&&previousOptions.every((option,i)=>option===this._selectedOptions[i]);if(sameValues&&!sameOptions)this.requestUpdate()}resolveOccurrences(values,preferred=[]){const claimed=new Set;const resolved=[];values.forEach((value,index)=>{const hint=preferred[index];const match=hint&&hint.value===value&&this.options.includes(hint)&&!claimed.has(hint)?hint:this.options.find(option=>option.value===value&&!claimed.has(option));if(!match)return;claimed.add(match);resolved.push(match)});return resolved}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&this._selected.length===0){this.validityController.setValidity({valueMissing:true},this.localize("selectValueMissing"))}else{this.validityController.setValidity({})}this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation});if(this._selected.length===0)this.internals.states?.add("blank");else this.internals.states?.delete("blank")}syncFormValue(){if(!this.multiple){this.internals.setFormValue(this._selected[0]??"");return}const state2=JSON.stringify(this._selected);if(!this.name){this.internals.setFormValue(null,state2);return}const data=new FormData;for(const value of this._selected)data.append(this.name,value);this.internals.setFormValue(data,state2)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}formResetCallback(){this.touched=false;this.hasInteracted=false;this._restoredStateActive=false;this._valueDirty=false;const resetOptions=this._defaultSelectedOptions.length>0?this._defaultSelectedOptions:this.options.filter(option=>wasOptionInitiallySelected(option));if(this._defaultSelectedOptions.length===0&&resetOptions.length>0){this._defaultSelectedOptions=[...resetOptions];this._defaultSelected=resetOptions.map(option=>option.value)}const defaults=new Set(resetOptions);for(const option of this.options){option[RESET_OPTION_SELECTED_FROM_OWNER](defaults.has(option))}this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}formStateRestoreCallback(state2,reason){void reason;if(!this.multiple){this.value=typeof state2==="string"?state2:""}else{let restored=[];if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(Array.isArray(parsed)&&parsed.every(entry=>typeof entry==="string"))restored=parsed}catch{}}this.value=restored}this._restoredStateActive=true;this._valueDirty=true}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;if(disabled)void this.hide();this.updateValidity();this.requestUpdate()}checkValidity(){this.updateValidity();return this.internals.checkValidity()}reportValidity(){this.updateValidity();this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates()}resetValidity(){this.setCustomValidity("")}disconnectedCallback(){this.transitionToken++;super.disconnectedCallback();this.cleanup?.();this.cleanup=void 0;this.clearTypeAheadTimer();this.typeAheadBuffer="";this.unbindDocumentPointer();this.resolveTransitionWaiters("lr-after-show");this.resolveTransitionWaiters("lr-after-hide");this.open=false}adoptedCallback(){this.cleanup?.();this.cleanup=void 0;this.unbindDocumentPointer();this.clearTypeAheadTimer()}refreshOptionDefaults(){if(this.hasAttribute("default-value"))return;const declared=this.options.filter(option=>option.defaultSelected);const defaults=this.multiple?declared:declared.slice(0,1);this._defaultSelected=defaults.map(option=>option.value);this._defaultSelectedOptions=[...defaults];if(!this._valueDirty&&!this._restoredStateActive){this.setSelection([...this._defaultSelected],[...this._defaultSelectedOptions])}}reflectSelected(){this._selectedOptions=this.resolveOccurrences(this._selected,this._selectedOptions);const chosen=new Set(this._selectedOptions);for(const option of this.options){option[SET_OPTION_SELECTED_FROM_OWNER](chosen.has(option))}}labelFor(value){return this._selectedOptions.find(option=>option.value===value)?.label??this.options.find(option=>option.value===value)?.label??value}get onlyOption(){if(!this.autoCommitSingleOption)return void 0;const navigable=this.navigableOptions();return navigable.length===1?navigable[0]:void 0}navigableOptions(options=this.options){return options.filter(o=>!o.disabled&&!o.inert&&!o.closest("[inert]"))}show(){if(this.open||this.effectiveDisabled)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");this.open=true;return settled}hide(){if(!this.open)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");this.open=false;this.activeIndex=-1;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.cleanup?.();this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"})}}updated(changed){super.updated(changed);if(changed.has("open")&&!this.openVetoed){this.cleanup?.();this.cleanup=void 0;if(this.open&&this.isConnected){this.bindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-show")}const anchor=this.renderRoot.querySelector('[part="trigger"]');const listbox=this.renderRoot.querySelector('[part="listbox"]');if(anchor&&listbox){this.cleanup=place(anchor,listbox,{placement:rtlAwarePlacement(this.placement,this),strategy:this.hoist?"fixed":"absolute"})}}else if(!this.open){this.unbindDocumentPointer();if(!this._isFirstUpdate){void this.settleTransition("lr-after-hide")}}else{this.unbindDocumentPointer()}}if(changed.has("touched")||changed.has("required")||changed.has("value")){this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}}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 listbox=this.renderRoot.querySelector('[part="listbox"]');const animations=listbox?.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()}emitValueEvents(){dispatchNativeInputEvent(this);this.emit("lr-input",{value:this.value});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:this.value})}selectOption(option){if(this.effectiveDisabled||option.disabled)return;this.hasInteracted=true;this._restoredStateActive=false;this._valueDirty=true;if(this.multiple){const selected=this._selected.includes(option.value);const occurrences=selected?this._selectedOptions.filter(candidate=>candidate.value!==option.value):[...this._selectedOptions,option];const values=selected?this._selected.filter(value=>value!==option.value):[...this._selected,option.value];this.setSelection(values,occurrences);this.emitValueEvents();return}const changed=option!==this._selectedOptions[0]||option.value!==this._selected[0];this.setSelection([option.value],[option]);void this.hide();if(changed)this.emitValueEvents()}removeValue(value){if(this.effectiveDisabled||!this._selected.includes(value))return;this._restoredStateActive=false;this._valueDirty=true;this.setSelection(this._selected.filter(candidate=>candidate!==value),this._selectedOptions.filter(option=>option.value!==value));this.emitValueEvents()}clear(){if(this.effectiveDisabled||this._selected.length===0)return;this._restoredStateActive=false;this._valueDirty=true;this.setSelection([],[]);this.emitValueEvents();this.emit("lr-clear")}removeTag(value,index,event){event.stopPropagation();this.removeValue(value);void this.updateComplete.then(()=>{const buttons=[...this.renderRoot.querySelectorAll('[part~="tag__remove-button"]')];(buttons[Math.min(index,buttons.length-1)]??this.triggerElement)?.focus()})}typeAhead(char){this.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 navigable=this.navigableOptions();if(!navigable.length)return;const currentOption=this.open?navigable[this.activeIndex]:this._selectedOptions[this._selectedOptions.length-1];const currentIndex=navigable.indexOf(currentOption);const n=navigable.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n;const candidate=navigable[idx];if(candidate===void 0)continue;if(candidate.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){if(this.open){this.activeIndex=idx}else if(!(this.multiple&&this._selected.includes(candidate.value))){this.selectOption(candidate)}return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1;if(this.typeAheadTimer!==void 0){this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer)}this.typeAheadTimer=void 0;this.typeAheadTimerWindow=void 0}renderRows(options,activeId){const out=[];const chosen=new Set(this._selectedOptions);let currentGroup;options.forEach((o,i)=>{if(o.group!==currentGroup){currentGroup=o.group;if(currentGroup)out.push(html`<div class="group-label" part="group-label">${currentGroup}</div>`)}const id=`${this.listId}-opt-${i}`;const selected=chosen.has(o);out.push(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,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_switchRequired}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 LyraSwitch extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,switchRequired:LYRA_DEFAULT_switchRequired}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.formAssociated=true}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},checked:{attribute:false,noAccessor:true},defaultChecked:{attribute:"checked",type:Boolean,reflect:true,useDefault:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},value:{reflect:true,noAccessor:true}}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get checked(){return this._checked}set checked(next){const old=this._checked;if(!this.settingDefaultChecked)this._checkedDirty=true;this._checked=Boolean(next);this.syncFormState();this.requestUpdate("checked",old)}get defaultChecked(){return this._defaultChecked}set defaultChecked(next){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=Boolean(next);this.reflectingDefaultChecked=true;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=false}if(!this._checkedDirty)this.restoreCheckedFromDefault();this.requestUpdate("defaultChecked",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.updateValidity();this.requestUpdate("disabled",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 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 value(){return this._value}set value(next){const old=this._value;this._value=next??"on";if(next==null){if(this.hasAttribute("value"))this.removeAttribute("value")}else if(this.getAttribute("value")!==this._value){this.setAttribute("value",this._value)}this.syncFormState();this.requestUpdate("value",old,{reflect:false})}constructor(){super();this.size="m";this.hint="";this.helpText="";this.withHint=false;this.shoelaceDefaultChecked=false;this.errorText="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.hasErrorSlot=false;this.touched=false;this.hasInteracted=false;this._defaultChecked=false;this._checkedDirty=false;this.settingDefaultChecked=false;this.reflectingDefaultChecked=false;this.hadShoelaceDefaultChecked=false;this._fieldsetDisabled=false;this._name="";this._checked=false;this._disabled=false;this._required=false;this._value="on";this.onClick=()=>{this.setFromUser(!this.checked)};this.onBlur=event=>{this.touched=true;this.hasInteracted=true;this.reflectValidityStates();relayNativeEvent(this,event);this.emit("lr-blur")};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key===" "||e.key==="Spacebar"){e.preventDefault();this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}};this.onLabelSlotChange=event=>this.handleLabelSlotChange(event);this.onSlotChange=event=>this.handleLabelSlotChange(event);this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onHelpTextSlotChange=e=>{this.hasHelpTextSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormState()}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~="base"]')??null}click(){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.click()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}connectedCallback(){super.connectedCallback();this.updateValidity();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}):void 0;this.addEventListener("slotchange",this.onLabelSlotChange);this.bindLabelObserverTargets();if(this.hasUpdated){this.recomputeLightDomSlotState()}else{this.seedFirstRenderState(()=>this.recomputeLightDomSlotState())}}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange);this.labelObserver?.disconnect();this.labelObserver=void 0;super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultChecked")&&(this.hasAttribute("default-checked")||this.hadShoelaceDefaultChecked)){this.defaultChecked=this.shoelaceDefaultChecked;this.hadShoelaceDefaultChecked=this.hasAttribute("default-checked")}}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this.checked){this.validityController.setValidity({valueMissing:true},this.localize("switchRequired"))}else{this.validityController.setValidity({})}this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation});setCustomState(this.internals,"checked",this.checked);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked");this.updateValidity()}formResetCallback(){this.touched=false;this.hasInteracted=false;this.restoreCheckedFromDefault();this.reflectValidityStates()}formStateRestoreCallback(state2,reason){void reason;this.checked=state2==="checked"}restoreCheckedFromDefault(){this.settingDefaultChecked=true;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=false}this._checkedDirty=false}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}resetValidity(){this.setCustomValidity("")}setFromUser(next){if(this.effectiveDisabled)return;if(this.checked===next)return;this.hasInteracted=true;this.checked=next;dispatchNativeInputEvent(this);this.emit("lr-input",{checked:this.checked});dispatchNativeEvent(this,"change");this.emit("lr-change",{checked:this.checked})}isDefaultLabelNode(node){if(node.nodeType!==1)return true;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;while(top.parentNode&&top.parentNode!==this)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}observeLabelNode(node){if(!this.labelObserver)return;if(node.nodeType===3){this.labelObserver.observe(node,{characterData:true});return}if(node.nodeType!==1)return;this.labelObserver.observe(node,{attributes:true,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:true,characterData:true,subtree:true})}bindLabelObserverTargets(){if(!this.labelObserver)return;this.labelObserver.disconnect();this.observeLabelNode(this);for(const slot of this.labelForwardingSlots()){if(slot.assignedNodes().length===0)continue;for(const assigned of slot.assignedNodes({flatten:true}))this.observeLabelNode(assigned)}}recomputeHasLabelSlot(){const renderRoot=this.renderRoot;const childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])");const nodes=slot?slot.assignedNodes({flatten:true}):Array.from(childNodes).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:true}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}recomputeLightDomSlotState(){this.recomputeHasLabelSlot();const children=this.children;if(!children)return;this.hasHintSlot=Array.from(children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(children).some(element=>element.getAttribute("slot")==="help-text");this.hasErrorSlot=Array.from(children).some(element=>element.getAttribute("slot")==="error")}handleLabelSlotChange(event){const target=event.target;if(target?.nodeType!==1||target.localName!=="slot")return;if(target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target))return;this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}render(){const hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||this.hint.length>0||this.helpText.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"switch-error":"",hasHint?"switch-hint":""].filter(Boolean).join(" ");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{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./switch.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{hasRealContent}from"../../../internal/a11y.js";import{getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_switchRequired}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 LyraSwitch extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,switchRequired:LYRA_DEFAULT_switchRequired}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.formAssociated=true}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},checked:{attribute:false,noAccessor:true},defaultChecked:{attribute:"checked",type:Boolean,reflect:true,useDefault:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},required:{type:Boolean,reflect:true,noAccessor:true},size:{reflect:true},value:{reflect:true,noAccessor:true}}}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get checked(){return this._checked}set checked(next){const old=this._checked;if(!this.settingDefaultChecked)this._checkedDirty=true;this._checked=Boolean(next);this.syncFormState();this.requestUpdate("checked",old)}get defaultChecked(){return this._defaultChecked}set defaultChecked(next){if(this.reflectingDefaultChecked)return;const old=this._defaultChecked;this._defaultChecked=Boolean(next);this.reflectingDefaultChecked=true;try{this.toggleAttribute("checked",this._defaultChecked)}finally{this.reflectingDefaultChecked=false}if(!this._checkedDirty)this.restoreCheckedFromDefault();this.requestUpdate("defaultChecked",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.updateValidity();this.requestUpdate("disabled",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 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 value(){return this._value}set value(next){const old=this._value;this._value=next??"on";if(next==null){if(this.hasAttribute("value"))this.removeAttribute("value")}else if(this.getAttribute("value")!==this._value){this.setAttribute("value",this._value)}this.syncFormState();this.requestUpdate("value",old,{reflect:false})}constructor(){super();this.size="m";this.hint="";this.helpText="";this.withHint=false;this.shoelaceDefaultChecked=false;this.errorText="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.hasErrorSlot=false;this.touched=false;this.hasInteracted=false;this._defaultChecked=false;this._checkedDirty=false;this.settingDefaultChecked=false;this.reflectingDefaultChecked=false;this.hadShoelaceDefaultChecked=false;this._fieldsetDisabled=false;this._name="";this._checked=false;this._disabled=false;this._required=false;this._value="on";this.onClick=()=>{this.setFromUser(!this.checked)};this.onBlur=event=>{if(!this.effectiveDisabled)this.touched=true;this.hasInteracted=true;this.reflectValidityStates();relayNativeEvent(this,event);this.emit("lr-blur")};this.onFocus=event=>{relayNativeEvent(this,event);this.emit("lr-focus")};this.onKeyDown=e=>{if(this.effectiveDisabled)return;if(e.key===" "||e.key==="Spacebar"){e.preventDefault();this.setFromUser(!this.checked);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){e.preventDefault();const turnsOn=this.effectiveDirection==="rtl"?e.key==="ArrowLeft":e.key==="ArrowRight";this.setFromUser(turnsOn)}};this.onLabelSlotChange=event=>this.handleLabelSlotChange(event);this.onSlotChange=event=>this.handleLabelSlotChange(event);this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:true}).length>0};this.onHelpTextSlotChange=e=>{this.hasHelpTextSlot=e.target.assignedElements({flatten:true}).length>0};this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:true}).length>0};installInvalidEventAlias(this,init=>this.emit("lr-invalid",void 0,init));this.internals=createInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);this.syncFormState()}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~="base"]')??null}click(){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.click()}focus(options){if(!this.effectiveDisabled)this[VALIDITY_ANCHOR]()?.focus(options)}blur(){this[VALIDITY_ANCHOR]()?.blur()}connectedCallback(){super.connectedCallback();this.updateValidity();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;this.labelObserver=MutationObserverCtor?new MutationObserverCtor(()=>{this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}):void 0;this.addEventListener("slotchange",this.onLabelSlotChange);this.bindLabelObserverTargets();if(this.hasUpdated){this.recomputeLightDomSlotState()}else{this.seedFirstRenderState(()=>this.recomputeLightDomSlotState())}}disconnectedCallback(){this.removeEventListener("slotchange",this.onLabelSlotChange);this.labelObserver?.disconnect();this.labelObserver=void 0;super.disconnectedCallback()}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultChecked")&&(this.hasAttribute("default-checked")||this.hadShoelaceDefaultChecked)){this.defaultChecked=this.shoelaceDefaultChecked;this.hadShoelaceDefaultChecked=this.hasAttribute("default-checked")}}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({})}else if(this.required&&!this.checked){this.validityController.setValidity({valueMissing:true},this.localize("switchRequired"))}else{this.validityController.setValidity({})}this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation});setCustomState(this.internals,"checked",this.checked);setCustomState(this.internals,"disabled",this.effectiveDisabled)}syncFormState(){this.internals.setFormValue(this.checked?this.value:null,this.checked?"checked":"unchecked");this.updateValidity()}formResetCallback(){this.touched=false;this.hasInteracted=false;this.restoreCheckedFromDefault();this.reflectValidityStates()}formStateRestoreCallback(state2,reason){void reason;this.checked=state2==="checked"}restoreCheckedFromDefault(){this.settingDefaultChecked=true;try{this.checked=this._defaultChecked}finally{this.settingDefaultChecked=false}this._checkedDirty=false}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.updateValidity();this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.reflectValidityStates();return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}resetValidity(){this.setCustomValidity("")}setFromUser(next){if(this.effectiveDisabled)return;if(this.checked===next)return;this.hasInteracted=true;this.checked=next;dispatchNativeInputEvent(this);this.emit("lr-input",{checked:this.checked});dispatchNativeEvent(this,"change");this.emit("lr-change",{checked:this.checked})}isDefaultLabelNode(node){if(node.nodeType!==1)return true;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;while(top.parentNode&&top.parentNode!==this)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}observeLabelNode(node){if(!this.labelObserver)return;if(node.nodeType===3){this.labelObserver.observe(node,{characterData:true});return}if(node.nodeType!==1)return;this.labelObserver.observe(node,{attributes:true,attributeFilter:["aria-hidden","aria-label","class","hidden","inert","slot","style"],childList:true,characterData:true,subtree:true})}bindLabelObserverTargets(){if(!this.labelObserver)return;this.labelObserver.disconnect();this.observeLabelNode(this);for(const slot of this.labelForwardingSlots()){if(slot.assignedNodes().length===0)continue;for(const assigned of slot.assignedNodes({flatten:true}))this.observeLabelNode(assigned)}}recomputeHasLabelSlot(){const renderRoot=this.renderRoot;const childNodes=this.childNodes;if(!renderRoot||!childNodes)return;const slot=renderRoot.querySelector("slot:not([name])");const nodes=slot?slot.assignedNodes({flatten:true}):Array.from(childNodes).filter(node=>this.isDefaultLabelNode(node)).flatMap(node=>{if(node.nodeType!==1||node.localName!=="slot")return[node];const forwardingSlot=node;return forwardingSlot.assignedNodes().length>0?forwardingSlot.assignedNodes({flatten:true}):Array.from(forwardingSlot.childNodes)});this.hasLabelSlot=hasRealContent(nodes)}recomputeLightDomSlotState(){this.recomputeHasLabelSlot();const children=this.children;if(!children)return;this.hasHintSlot=Array.from(children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(children).some(element=>element.getAttribute("slot")==="help-text");this.hasErrorSlot=Array.from(children).some(element=>element.getAttribute("slot")==="error")}handleLabelSlotChange(event){const target=event.target;if(target?.nodeType!==1||target.localName!=="slot")return;if(target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target))return;this.bindLabelObserverTargets();this.recomputeHasLabelSlot()}render(){const hasHint=this.withHint||this.hasHintSlot||this.hasHelpTextSlot||this.hint.length>0||this.helpText.length>0;const hasError=this.hasErrorSlot||this.errorText.length>0;const describedBy=[hasError?"switch-error":"",hasHint?"switch-hint":""].filter(Boolean).join(" ");return html`
|
|
2
2
|
<div part="form-control">
|
|
3
3
|
<span
|
|
4
4
|
part="base switch wrapper"
|