@aceshooting/lyra-ui 8.1.0 → 8.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/custom-elements.json +1 -1
  3. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +5 -0
  4. package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
  5. package/dist/components/charts/chart/chart.class.js +1 -1
  6. package/dist/components/conversation/chat-composer/chat-composer.class.js +1 -1
  7. package/dist/components/conversation/model-select/model-select.class.js +1 -1
  8. package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
  9. package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +4 -0
  10. package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
  11. package/dist/components/forms/checkbox/checkbox.class.js +1 -1
  12. package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +3 -0
  13. package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
  14. package/dist/components/forms/code-editor/code-editor.class.js +1 -1
  15. package/dist/components/forms/combobox/combobox.class.js +1 -1
  16. package/dist/components/forms/date-picker/date-input.class.js +1 -1
  17. package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
  18. package/dist/components/forms/input/input.class.js +1 -1
  19. package/dist/components/forms/input/time-input.class.js +1 -1
  20. package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
  21. package/dist/components/forms/otp-input/otp-input.class.js +1 -1
  22. package/dist/components/forms/phone-input/phone-input.class.js +1 -1
  23. package/dist/components/forms/radio/radio-group.class.d.ts +3 -0
  24. package/dist/components/forms/radio/radio-group.class.js +1 -1
  25. package/dist/components/forms/rubric-form/rubric-form.class.d.ts +3 -0
  26. package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
  27. package/dist/components/forms/select/select.class.js +1 -1
  28. package/dist/components/forms/switch/switch.class.js +1 -1
  29. package/dist/components/forms/textarea/textarea.class.js +1 -1
  30. package/dist/components/forms/token-input/token-input.class.js +1 -1
  31. package/dist/components/media/file-input/file-input.class.js +1 -1
  32. package/dist/components/utility/known-date/known-date.class.js +1 -1
  33. package/dist/internal/form-associated.js +1 -1
  34. package/dist/internal/localization-runtime.d.ts +13 -0
  35. package/dist/internal/localization-runtime.js +1 -1
  36. package/dist/internal/lyra-element.d.ts +15 -0
  37. package/dist/internal/lyra-element.js +1 -1
  38. package/dist/internal/package-metadata.d.ts +1 -1
  39. package/dist/internal/package-metadata.js +1 -1
  40. package/dist/testing/happy-dom-shims.d.ts +1 -1
  41. package/dist/testing/happy-dom-shims.js +1 -1
  42. package/llms/components/lr-checkbox-group.md +2 -0
  43. package/llms/components/lr-graph-query-builder.md +3 -1
  44. package/llms/components/lr-radio-group.md +3 -1
  45. package/llms/components/lr-rubric-form.md +2 -0
  46. package/llms/components/lr-tool-param-form.md +3 -0
  47. package/llms/peers.md +1 -1
  48. package/llms-full.txt +13 -2
  49. package/package.json +4 -4
  50. 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>
@@ -193,6 +193,9 @@ export declare class LyraRadioGroup extends LyraElement<LyraRadioGroupEventMap>
193
193
  private onRadioSlotChange;
194
194
  /** Moves focus to the selected enabled option, or the first enabled option when empty. */
195
195
  focus(options?: FocusOptions): void;
196
+ /** Activates the selected/first enabled option, matching host click semantics on the internal
197
+ * radio collection rather than leaving `<lr-radio-group>` a no-op. */
198
+ click(): void;
196
199
  private syncFormState;
197
200
  /** Shared with every other form control: disabled (own or fieldset-cascaded) bars validation. */
198
201
  private get barredFromValidation();
@@ -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{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_radioRequired,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,radioRequired:LYRA_DEFAULT_radioRequired,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},customError:{attribute:"custom-error",reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},orientation:{reflect:true},form:{noAccessor:true}}}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.syncFormState();this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=true;this.selectValue(next??"")}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.selectValue(this._defaultValue);this._valueDirty=false}this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){if(this.reflectingCustomError)return;const old=this.customError;const message=next??"";this.reflectingCustomError=true;try{if(next==null)this.removeAttribute("custom-error");else this.setAttribute("custom-error",message)}finally{this.reflectingCustomError=false}this.setCustomValidity(message);this.requestUpdate("customError",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.syncRadios();this.updateValidity();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.syncRadios();this.updateValidity();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}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}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.helpText="";this.shoelaceDefaultValue="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.hasErrorSlot=false;this.labelId=nextId("radio-group-label");this.hintId=nextId("radio-group-hint");this.errorId=nextId("radio-group-error");this.managedRadios=new Set;this.authorNames=new Map;this.syncingRadios=false;this.membershipObserverGeneration=0;this._name="";this._value="";this._defaultValue="";this._valueDirty=false;this.reflectingDefaultValue=false;this.reflectingCustomError=false;this._required=false;this._disabled=false;this._fieldsetDisabled=false;this.hasInteracted=false;this.hadShoelaceDefaultValue=false;this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target))){return}const alias=this.emit("lr-invalid",void 0,{cancelable:true});if(alias.defaultPrevented)event.preventDefault()};this.onKeyDown=event=>{const arrows=this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"];if(![...arrows,"Home","End"].includes(event.key))return;if(this.effectiveDisabled)return;const radios=this.radios().filter(radio=>!radio.effectiveDisabled);const current=event.target;if(current.effectiveDisabled)return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl";const forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight";const backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft";const nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index;const next=radios[nextIndex];next.focus();next.activateFromGroup()};this.onSlotChange=event=>{const slot=event.target;const elements=slot.assignedElements({flatten:true});if(slot.name==="label")this.hasLabelSlot=elements.length>0;if(slot.name==="hint")this.hasHintSlot=elements.length>0;if(slot.name==="help-text")this.hasHelpTextSlot=elements.length>0;if(slot.name==="error")this.hasErrorSlot=elements.length>0};this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument;const generation=this.membershipObserverGeneration;const ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;ownerWindow.queueMicrotask(()=>{if(this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument){this.syncRadios()}})};this.internals=attachInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());this.addEventListener("invalid",this.onInvalid,true);this.syncFormState();this.updateValidity()}connectedCallback(){super.connectedCallback();this.syncSupportSlots();this.syncRadios();this.armMembershipObserver()}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument.defaultView;const MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration;const observer=new MutationObserverCtor(()=>{if(this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}ownerWindow.queueMicrotask(()=>{if(this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.syncRadios()})});this.membershipObserver=observer;this.membershipObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["slot","checked","disabled","value","size"]})}disconnectedCallback(){this.resetMembershipObserver();this.releaseRadios(this.managedRadios);this.managedRadios.clear();super.disconnectedCallback()}adoptedCallback(){this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1;this.membershipObserver?.disconnect();this.membershipObserver=void 0;this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)){this.defaultValue=this.shoelaceDefaultValue;this.hadShoelaceDefaultValue=this.hasAttribute("default-value")}}updated(changed){super.updated(changed);this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="help-text");this.hasErrorSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="error")}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;while(topLevelChild.parentElement&&topLevelChild.parentElement!==group){topLevelChild=topLevelChild.parentElement}if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner==="function")}selectValue(next){const desired=next??"";const radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired;this.pendingSelection=desired;this.syncFormState();this.updateValidity();this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=true;try{for(const radio of radios)radio.checked=radio===match}finally{this.syncingRadios=false}this.pendingSelection=void 0;this.syncRadios(match)}syncRadios(preferred){if(this.syncingRadios)return;this.syncingRadios=true;try{const radios=this.radios();const current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios){radio.setGroupOwner(this);if(!this.managedRadios.has(radio)){this.authorNames.set(radio,radio.name)}}this.managedRadios=current;for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>!radio.effectiveDisabled);let checked=radios.filter(radio=>radio.checked);let checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked=radio===checkedRadio;checked=checkedRadio?[checkedRadio]:[];this.pendingSelection=void 0}else{checkedRadio=preferred?.checked&&current.has(preferred)?preferred:checked[checked.length-1]}for(const radio of checked){if(radio!==checkedRadio)radio.checked=false}const tabbableRadio=checkedRadio&&!checkedRadio.effectiveDisabled?checkedRadio:enabled[0];for(const radio of radios){radio.name=this.name||this.authorNames.get(radio)||"";radio.size=this.size;radio.setGroupRequired(this.required&&!this.effectiveDisabled);radio.setGroupTabbable(radio===tabbableRadio)}const oldValue=this._value;this._value=checkedRadio?.value??"";this.syncFormState();this.updateValidity();if(oldValue!==this._value)this.requestUpdate("value",oldValue)}finally{this.syncingRadios=false}}releaseRadios(radios){for(const radio of radios){const authorName=this.authorNames.get(radio)??radio.name;this.authorNames.delete(radio);radio.releaseGroupOwner(this,authorName)}}reconcileRadio(radio){if(!this.ownsRadio(radio))return false;this.syncRadios(radio.checked?radio:void 0);return true}releaseRadio(radio){if(!this.managedRadios.has(radio)&&!this.authorNames.has(radio))return;this.releaseRadios([radio]);this.managedRadios.delete(radio);this.syncRadios()}radioCheckedChanged(radio){if(this.syncingRadios||!this.ownsRadio(radio))return;this._valueDirty=true;this.syncRadios(radio.checked?radio:void 0)}selectRadio(radio){if(this.effectiveDisabled||radio.effectiveDisabled||!this.ownsRadio(radio))return false;this._valueDirty=true;this.hasInteracted=true;this.syncingRadios=true;try{for(const candidate of this.radios())candidate.checked=candidate===radio}finally{this.syncingRadios=false}this.syncRadios();dispatchNativeInputEvent(this);this.emit("lr-input",{value:radio.value,radio});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:radio.value,radio});return true}focus(options){const enabled=this.radios().filter(radio=>!radio.effectiveDisabled);(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){if(!this.internals)return;this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:true}:{},missing?this.localize("radioRequired"):"");this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.updateValidity();return this.internals.reportValidity()}setCustomValidity(message=""){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity();this.requestUpdate()}formResetCallback(){this._valueDirty=false;this.pendingSelection=void 0;this.syncingRadios=true;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=false}if(this.defaultValue)this.pendingSelection=this.defaultValue;this.hasInteracted=false;this.syncRadios()}formStateRestoreCallback(state2,reason){void reason;this._valueDirty=true;this.hasInteracted=false;this.pendingSelection=typeof state2==="string"?state2:"";this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncRadios();this.updateValidity();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||this.hasHelpTextSlot||Boolean(this.hint||this.helpText)||this.withHint;const hasError=this.hasErrorSlot||Boolean(this.errorText);const described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;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{nextId}from"../../../internal/a11y.js";import{tag}from"../../../internal/prefix.js";import{sizes}from"../../../internal/sizes.styles.js";import{groupStyles}from"./radio-group.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{omittedEmptyStringConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_open,LYRA_DEFAULT_radioRequired,LYRA_DEFAULT_restore}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,open:LYRA_DEFAULT_open,radioRequired:LYRA_DEFAULT_radioRequired,restore:LYRA_DEFAULT_restore}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:true,noAccessor:true,converter:omittedEmptyStringConverter},value:{attribute:false,noAccessor:true},defaultValue:{attribute:"value",reflect:true,useDefault:true,noAccessor:true},customError:{attribute:"custom-error",reflect:true,noAccessor:true},required:{type:Boolean,reflect:true,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true},orientation:{reflect:true},form:{noAccessor:true}}}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.syncFormState();this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=true;this.selectValue(next??"")}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.selectValue(this._defaultValue);this._valueDirty=false}this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){if(this.reflectingCustomError)return;const old=this.customError;const message=next??"";this.reflectingCustomError=true;try{if(next==null)this.removeAttribute("custom-error");else this.setAttribute("custom-error",message)}finally{this.reflectingCustomError=false}this.setCustomValidity(message);this.requestUpdate("customError",old)}get required(){return this._required}set required(next){const old=this._required;this._required=Boolean(next);this.toggleAttribute("required",this._required);this.syncRadios();this.updateValidity();this.requestUpdate("required",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=Boolean(next);this.toggleAttribute("disabled",this._disabled);this.syncRadios();this.updateValidity();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}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}constructor(){super();this.size="m";this.orientation="vertical";this.label="";this.hint="";this.helpText="";this.shoelaceDefaultValue="";this.withLabel=false;this.withHint=false;this.errorText="";this.accessibleLabel="";this.hasLabelSlot=false;this.hasHintSlot=false;this.hasHelpTextSlot=false;this.hasErrorSlot=false;this.labelId=nextId("radio-group-label");this.hintId=nextId("radio-group-hint");this.errorId=nextId("radio-group-error");this.managedRadios=new Set;this.authorNames=new Map;this.syncingRadios=false;this.membershipObserverGeneration=0;this._name="";this._value="";this._defaultValue="";this._valueDirty=false;this.reflectingDefaultValue=false;this.reflectingCustomError=false;this._required=false;this._disabled=false;this._fieldsetDisabled=false;this.hasInteracted=false;this.hadShoelaceDefaultValue=false;this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target))){return}const alias=this.emit("lr-invalid",void 0,{cancelable:true});if(alias.defaultPrevented)event.preventDefault()};this.onKeyDown=event=>{const arrows=this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"];if(![...arrows,"Home","End"].includes(event.key))return;if(this.effectiveDisabled)return;const radios=this.radios().filter(radio=>!radio.effectiveDisabled);const current=event.target;if(current.effectiveDisabled)return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl";const forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight";const backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft";const nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index;const next=radios[nextIndex];next.focus();next.activateFromGroup()};this.onSlotChange=event=>{const slot=event.target;const elements=slot.assignedElements({flatten:true});if(slot.name==="label")this.hasLabelSlot=elements.length>0;if(slot.name==="hint")this.hasHintSlot=elements.length>0;if(slot.name==="help-text")this.hasHelpTextSlot=elements.length>0;if(slot.name==="error")this.hasErrorSlot=elements.length>0};this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument;const generation=this.membershipObserverGeneration;const ownerWindow=ownerDocument.defaultView;if(!ownerWindow)return;ownerWindow.queueMicrotask(()=>{if(this.membershipObserverGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument){this.syncRadios()}})};this.internals=attachInternalsSafely(this);this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());this.addEventListener("invalid",this.onInvalid,true);this.syncFormState();this.updateValidity()}connectedCallback(){super.connectedCallback();this.syncSupportSlots();this.syncRadios();this.armMembershipObserver()}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected)return;if(this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument.defaultView;const MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration;const observer=new MutationObserverCtor(()=>{if(this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}ownerWindow.queueMicrotask(()=>{if(this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument){return}this.syncRadios()})});this.membershipObserver=observer;this.membershipObserverDocument=ownerDocument;observer.observe(this,{attributes:true,childList:true,subtree:true,attributeFilter:["slot","checked","disabled","value","size"]})}disconnectedCallback(){this.resetMembershipObserver();this.releaseRadios(this.managedRadios);this.managedRadios.clear();super.disconnectedCallback()}adoptedCallback(){this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1;this.membershipObserver?.disconnect();this.membershipObserver=void 0;this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed);if(changed.has("shoelaceDefaultValue")&&(this.hasAttribute("default-value")||this.hadShoelaceDefaultValue)){this.defaultValue=this.shoelaceDefaultValue;this.hadShoelaceDefaultValue=this.hasAttribute("default-value")}}updated(changed){super.updated(changed);this.syncRadios()}syncSupportSlots(){this.hasLabelSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="label");this.hasHintSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="hint");this.hasHelpTextSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="help-text");this.hasErrorSlot=Array.from(this.children).some(element=>element.getAttribute("slot")==="error")}radioGroupOwner(element){const group=element.closest(tag("radio-group"));if(!group)return null;let topLevelChild=element;while(topLevelChild.parentElement&&topLevelChild.parentElement!==group){topLevelChild=topLevelChild.parentElement}if(topLevelChild.parentElement!==group)return null;const slot=topLevelChild.getAttribute("slot");return slot==="label"||slot==="hint"||slot==="help-text"||slot==="error"?null:group}ownsRadio(element){return RADIO_TAGS().includes(element.localName)&&this.radioGroupOwner(element)===this}radios(){const querySelectorAll=this.querySelectorAll;if(typeof querySelectorAll!=="function")return[];return[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner==="function")}selectValue(next){const desired=next??"";const radios=this.radios();if(radios.length===0){const old=this._value;this._value=desired;this.pendingSelection=desired;this.syncFormState();this.updateValidity();this.requestUpdate("value",old);return}const match=radios.find(radio=>radio.value===desired);this.syncingRadios=true;try{for(const radio of radios)radio.checked=radio===match}finally{this.syncingRadios=false}this.pendingSelection=void 0;this.syncRadios(match)}syncRadios(preferred){if(this.syncingRadios)return;this.syncingRadios=true;try{const radios=this.radios();const current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios){radio.setGroupOwner(this);if(!this.managedRadios.has(radio)){this.authorNames.set(radio,radio.name)}}this.managedRadios=current;for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>!radio.effectiveDisabled);let checked=radios.filter(radio=>radio.checked);let checkedRadio;if(this.pendingSelection!==void 0&&radios.length>0){checkedRadio=radios.find(radio=>radio.value===this.pendingSelection);for(const radio of radios)radio.checked=radio===checkedRadio;checked=checkedRadio?[checkedRadio]:[];this.pendingSelection=void 0}else{checkedRadio=preferred?.checked&&current.has(preferred)?preferred:checked[checked.length-1]}for(const radio of checked){if(radio!==checkedRadio)radio.checked=false}const tabbableRadio=checkedRadio&&!checkedRadio.effectiveDisabled?checkedRadio:enabled[0];for(const radio of radios){radio.name=this.name||this.authorNames.get(radio)||"";radio.size=this.size;radio.setGroupRequired(this.required&&!this.effectiveDisabled);radio.setGroupTabbable(radio===tabbableRadio)}const oldValue=this._value;this._value=checkedRadio?.value??"";this.syncFormState();this.updateValidity();if(oldValue!==this._value)this.requestUpdate("value",oldValue)}finally{this.syncingRadios=false}}releaseRadios(radios){for(const radio of radios){const authorName=this.authorNames.get(radio)??radio.name;this.authorNames.delete(radio);radio.releaseGroupOwner(this,authorName)}}reconcileRadio(radio){if(!this.ownsRadio(radio))return false;this.syncRadios(radio.checked?radio:void 0);return true}releaseRadio(radio){if(!this.managedRadios.has(radio)&&!this.authorNames.has(radio))return;this.releaseRadios([radio]);this.managedRadios.delete(radio);this.syncRadios()}radioCheckedChanged(radio){if(this.syncingRadios||!this.ownsRadio(radio))return;this._valueDirty=true;this.syncRadios(radio.checked?radio:void 0)}selectRadio(radio){if(this.effectiveDisabled||radio.effectiveDisabled||!this.ownsRadio(radio))return false;this._valueDirty=true;this.hasInteracted=true;this.syncingRadios=true;try{for(const candidate of this.radios())candidate.checked=candidate===radio}finally{this.syncingRadios=false}this.syncRadios();dispatchNativeInputEvent(this);this.emit("lr-input",{value:radio.value,radio});dispatchNativeEvent(this,"change");this.emit("lr-change",{value:radio.value,radio});return true}focus(options){const enabled=this.radios().filter(radio=>!radio.effectiveDisabled);(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}click(){if(this.effectiveDisabled)return;const enabled=this.radios().filter(radio=>!radio.effectiveDisabled);(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){if(!this.internals)return;this.internals.setFormValue(this.name&&this.value?this.value:null,this.value)}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}updateValidity(){if(!this.validityController)return;const missing=!this.barredFromValidation&&this.required&&!this.value;this.validityController.setValidity(missing?{valueMissing:true}:{},missing?this.localize("radioRequired"):"");this.reflectValidityStates()}reflectValidityStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.hasInteracted,barred:this.barredFromValidation})}checkValidity(){return this.internals.checkValidity()}reportValidity(){this.hasInteracted=true;this.updateValidity();return this.internals.reportValidity()}setCustomValidity(message=""){this.validityController.setCustomValidity(message??"");this.reflectValidityStates();this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity("");this.updateValidity();this.requestUpdate()}formResetCallback(){this._valueDirty=false;this.pendingSelection=void 0;this.syncingRadios=true;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=false}if(this.defaultValue)this.pendingSelection=this.defaultValue;this.hasInteracted=false;this.syncRadios()}formStateRestoreCallback(state2,reason){void reason;this._valueDirty=true;this.hasInteracted=false;this.pendingSelection=typeof state2==="string"?state2:"";this.selectValue(this.pendingSelection)}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncRadios();this.updateValidity();this.requestUpdate()}render(){const hasLabel=this.hasLabelSlot||Boolean(this.label)||this.withLabel;const hasHint=this.hasHintSlot||this.hasHelpTextSlot||Boolean(this.hint||this.helpText)||this.withHint;const hasError=this.hasErrorSlot||Boolean(this.errorText);const described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`
2
2
  <div part="base" role="radiogroup"
3
3
  aria-label=${this.accessibleLabel||nothing}
4
4
  aria-labelledby=${!this.accessibleLabel&&hasLabel?this.labelId:nothing}
@@ -258,6 +258,9 @@ export declare class LyraRubricForm extends LyraElement<LyraRubricFormEventMap>
258
258
  private submit;
259
259
  private skip;
260
260
  private focusFirstControl;
261
+ /** Forwards host clicks to the first rendered field, so programmatic and `<label>`-driven
262
+ * interactions target the active rubric field. */
263
+ click(): void;
261
264
  protected updated(changed: PropertyValues): void;
262
265
  private renderScoreControl;
263
266
  private renderCategoryControl;
@@ -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{state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.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_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings.generated.js";const EMPTY_KEYS=[];const EMPTY_VALUE={};class LyraRubricForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},keys:{attribute:false,noAccessor:true},value:{attribute:false,noAccessor:true},itemId:{attribute:"item-id",reflect:true,noAccessor:true},hasNext:{type:Boolean,attribute:"has-next",noAccessor:true},skippable:{type:Boolean,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this._errors={};this.touchedFields=new Set;this.baseId=nextId("rubric-form");this._fieldsetDisabled=false;this._name="";this._keys=EMPTY_KEYS;this._value=EMPTY_VALUE;this._itemId="";this._hasNext=false;this._skippable=false;this._disabled=false;this.pendingFocusFirst=false;this.onFormKeyDown=e=>{if(e.key==="Enter"&&(e.ctrlKey||e.metaKey)){e.preventDefault();this.submit()}};this.stopChildEvent=event=>{event.stopPropagation()};this.internals=this.safeAttachInternals();this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.addEventListener("keydown",this.onFormKeyDown);this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals==="undefined"){return this.inertInternals()}try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>true,reportValidity:()=>true,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get keys(){return this._keys}set keys(next){const old=this._keys;this._keys=next??EMPTY_KEYS;this.syncFormState();this.requestUpdate("keys",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??EMPTY_VALUE;this.syncFormState();this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"";if(old!==this._itemId){this.touchedFields=new Set;if(this.hasUpdated)this.pendingFocusFirst=true}if(this._itemId)this.setAttribute("item-id",this._itemId);else this.removeAttribute("item-id");this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=Boolean(next);this.toggleAttribute("has-next",this._hasNext);this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=Boolean(next);this.requestUpdate("skippable",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.validityController)this.syncFormState();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}fieldElement(key){const root=this.renderRoot;const ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape==="function"){try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];if(!firstInvalidKey||!this.renderRoot)return void 0;const field=this.fieldElement(firstInvalidKey);return field?.querySelector(".control")??void 0}isSegmentedScore(k){const min=k.min??0;const max=k.max??5;const step=k.step??1;if(step<=0||!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return false;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}scoreValues(k){if(!this.isSegmentedScore(k))return[];const min=k.min??0;const max=k.max??5;const step=k.step??1;const count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors={};const flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){errors[k.key]=this.localize("unsupportedFieldType",void 0,{type:String(k.type)});flags.customError=true;continue}if(!k.required)continue;const v=this._value[k.key];const present=k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="";if(!present){errors[k.key]=this.localize("fieldRequired");flags.valueMissing=true}}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}this.internals.setFormValue(formValue,formValue);if(this.barredFromValidation||Object.keys(flags).length===0){this.validityController.setValidity({})}else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>Boolean(key.required)),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]);this.syncCustomStates()}return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.requestUpdate()}formResetCallback(){this.value={};this.touchedFields=new Set;this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed))restored=parsed}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncFormState();this.requestUpdate()}setFieldValue(key,val){if(this.effectiveDisabled)return;this.value={...this._value,[key]:val};this.emit("lr-input",{value:{...this._value}})}markTouched(key){if(this.touchedFields.has(key))return;this.touchedFields=new Set(this.touchedFields).add(key);this.syncCustomStates()}submit(){if(this.effectiveDisabled)return;if(!this.reportValidity())return;this.emit("lr-submit",{value:{...this._value},itemId:this.itemId})}skip(){if(this.effectiveDisabled)return;this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(){const firstKey=this._keys[0];if(!firstKey)return;const field=this.fieldElement(firstKey.key);const control=field?.querySelector(".control");if(!control)return;if(firstKey.type==="score"&&this.isSegmentedScore(firstKey)){control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus()}else if(firstKey.type==="score"){control.shadowRoot?.querySelector('[part="thumb"]')?.focus()}else if(firstKey.type==="category"&&firstKey.multiple){control.querySelector("lr-checkbox")?.focus()}else{control.focus()}}updated(changed){super.updated(changed);if(changed.has("value")||changed.has("keys")||changed.has("_errors")){const valid=Object.keys(this._errors).length===0;const key=JSON.stringify({valid,errors:this._errors});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}}if(this.pendingFocusFirst){this.pendingFocusFirst=false;this.focusFirstControl()}}renderScoreControl(k,fieldId,current,hasError){const min=k.min??0;const max=k.max??5;const step=k.step??1;const disabled=this.effectiveDisabled;const accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>Boolean(value)).join(". ");if(this.isSegmentedScore(k)){const items=this.scoreValues(k).map(score=>({value:String(score),label:String(score),disabled}));const value=typeof current==="number"?String(current):"";return html`<lr-segmented
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{state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId}from"../../../internal/a11y.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{syncValidityStates}from"../../../internal/custom-states.js";import{styles}from"./rubric-form.styles.js";import"../../layout/segmented/segmented.class.js";import"../slider/slider.class.js";import"../select/select.class.js";import"../combobox/option.class.js";import"../checkbox/checkbox.class.js";import"../checkbox-group/checkbox-group.class.js";import"../textarea/textarea.class.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_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_restore,LYRA_DEFAULT_rubricSkip,LYRA_DEFAULT_rubricSubmit,LYRA_DEFAULT_rubricSubmitAndNext,LYRA_DEFAULT_unsupportedFieldType}from"../../../internal/default-strings.generated.js";const EMPTY_KEYS=[];const EMPTY_VALUE={};class LyraRubricForm extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,noData:LYRA_DEFAULT_noData,open:LYRA_DEFAULT_open,restore:LYRA_DEFAULT_restore,rubricSkip:LYRA_DEFAULT_rubricSkip,rubricSubmit:LYRA_DEFAULT_rubricSubmit,rubricSubmitAndNext:LYRA_DEFAULT_rubricSubmitAndNext,unsupportedFieldType:LYRA_DEFAULT_unsupportedFieldType}}static{this.formAssociated=true}static{this.styles=[LyraElement.styles,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:true,noAccessor:true},name:{reflect:true,noAccessor:true},keys:{attribute:false,noAccessor:true},value:{attribute:false,noAccessor:true},itemId:{attribute:"item-id",reflect:true,noAccessor:true},hasNext:{type:Boolean,attribute:"has-next",noAccessor:true},skippable:{type:Boolean,noAccessor:true},disabled:{type:Boolean,reflect:true,noAccessor:true}}}constructor(){super();this._errors={};this.touchedFields=new Set;this.baseId=nextId("rubric-form");this._fieldsetDisabled=false;this._name="";this._keys=EMPTY_KEYS;this._value=EMPTY_VALUE;this._itemId="";this._hasNext=false;this._skippable=false;this._disabled=false;this.pendingFocusFirst=false;this.onFormKeyDown=e=>{if(e.key==="Enter"&&(e.ctrlKey||e.metaKey)){e.preventDefault();this.submit()}};this.stopChildEvent=event=>{event.stopPropagation()};this.internals=this.safeAttachInternals();this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]());installCustomErrorProperty(this,()=>this.validityController.customValidityMessage);installInvalidEventAlias(this,()=>this.emit("lr-invalid"));this.addEventListener("keydown",this.onFormKeyDown);this.syncFormState()}safeAttachInternals(){if(typeof globalThis.ElementInternals==="undefined"){return this.inertInternals()}try{return this.attachInternals()}catch{return this.inertInternals()}}inertInternals(){return{form:null,labels:[],validity:{},validationMessage:"",willValidate:false,setFormValue:()=>{},setValidity:()=>{},checkValidity:()=>true,reportValidity:()=>true,states:new Set}}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get keys(){return this._keys}set keys(next){const old=this._keys;this._keys=next??EMPTY_KEYS;this.syncFormState();this.requestUpdate("keys",old)}get value(){return this._value}set value(next){const old=this._value;this._value=next??EMPTY_VALUE;this.syncFormState();this.requestUpdate("value",old)}get itemId(){return this._itemId}set itemId(next){const old=this._itemId;this._itemId=next??"";if(old!==this._itemId){this.touchedFields=new Set;if(this.hasUpdated)this.pendingFocusFirst=true}if(this._itemId)this.setAttribute("item-id",this._itemId);else this.removeAttribute("item-id");this.requestUpdate("itemId",old)}get hasNext(){return this._hasNext}set hasNext(next){const old=this._hasNext;this._hasNext=Boolean(next);this.toggleAttribute("has-next",this._hasNext);this.requestUpdate("hasNext",old)}get skippable(){return this._skippable}set skippable(next){const old=this._skippable;this._skippable=Boolean(next);this.requestUpdate("skippable",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.validityController)this.syncFormState();this.requestUpdate("disabled",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get errors(){return{...this._errors}}fieldElement(key){const root=this.renderRoot;const ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape==="function"){try{const candidate=root.querySelector(`[part="field"][data-key="${ownerCss.escape(key)}"]`);if(candidate?.getAttribute("data-key")===key)return candidate}catch{}}return Array.from(root.querySelectorAll('[part="field"][data-key]')).find(candidate=>candidate.getAttribute("data-key")===key)??null}[VALIDITY_ANCHOR](){const firstInvalidKey=Object.keys(this._errors)[0];if(!firstInvalidKey||!this.renderRoot)return void 0;const field=this.fieldElement(firstInvalidKey);return field?.querySelector(".control")??void 0}isSegmentedScore(k){const min=k.min??0;const max=k.max??5;const step=k.step??1;if(step<=0||!Number.isInteger(min)||!Number.isInteger(max)||!Number.isInteger(step))return false;const count=(max-min)/step;return Number.isInteger(count)&&count>=0&&count<=10}scoreValues(k){if(!this.isSegmentedScore(k))return[];const min=k.min??0;const max=k.max??5;const step=k.step??1;const count=Math.round((max-min)/step);return Array.from({length:count+1},(_,index)=>index===count?max:min+index*step)}computeValidation(){const errors={};const flags={};for(const k of this._keys){if(k.type!=="score"&&k.type!=="category"&&k.type!=="comment"){errors[k.key]=this.localize("unsupportedFieldType",void 0,{type:String(k.type)});flags.customError=true;continue}if(!k.required)continue;const v=this._value[k.key];const present=k.type==="category"&&k.multiple?Array.isArray(v)&&v.length>0:v!==void 0&&v!=="";if(!present){errors[k.key]=this.localize("fieldRequired");flags.valueMissing=true}}return{errors,flags}}syncFormState(){const{errors,flags}=this.computeValidation();this._errors=errors;let formValue=null;try{formValue=JSON.stringify(this._value)}catch{formValue=null}this.internals.setFormValue(formValue,formValue);if(this.barredFromValidation||Object.keys(flags).length===0){this.validityController.setValidity({})}else{const message=Object.values(errors)[0]??"";this.validityController.setValidity(flags,message)}this.syncCustomStates()}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}syncCustomStates(){syncValidityStates(this.internals,{required:this._keys.some(key=>Boolean(key.required)),hasInteracted:this.touchedFields.size>0,barred:this.barredFromValidation})}checkValidity(){this.syncFormState();return this.internals.checkValidity()}reportValidity(){this.syncFormState();if(Object.keys(this._errors).length>0){this.touchedFields=new Set([...this.touchedFields,...Object.keys(this._errors)]);this.syncCustomStates()}return this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??"");this.syncCustomStates();this.requestUpdate()}formResetCallback(){this.value={};this.touchedFields=new Set;this.syncCustomStates()}formStateRestoreCallback(state2,_mode){let restored={};if(typeof state2==="string"){try{const parsed=JSON.parse(state2);if(parsed!==null&&typeof parsed==="object"&&!Array.isArray(parsed))restored=parsed}catch{}}this.value=restored}formDisabledCallback(disabled){this._fieldsetDisabled=disabled;this.syncFormState();this.requestUpdate()}setFieldValue(key,val){if(this.effectiveDisabled)return;this.value={...this._value,[key]:val};this.emit("lr-input",{value:{...this._value}})}markTouched(key){if(this.touchedFields.has(key))return;this.touchedFields=new Set(this.touchedFields).add(key);this.syncCustomStates()}submit(){if(this.effectiveDisabled)return;if(!this.reportValidity())return;this.emit("lr-submit",{value:{...this._value},itemId:this.itemId})}skip(){if(this.effectiveDisabled)return;this.emit("lr-skip",{itemId:this.itemId})}focusFirstControl(){const firstKey=this._keys[0];if(!firstKey)return;const field=this.fieldElement(firstKey.key);const control=field?.querySelector(".control");if(!control)return;if(firstKey.type==="score"&&this.isSegmentedScore(firstKey)){control.shadowRoot?.querySelector('[part="segment"][tabindex="0"]')?.focus()}else if(firstKey.type==="score"){control.shadowRoot?.querySelector('[part="thumb"]')?.focus()}else if(firstKey.type==="category"&&firstKey.multiple){control.querySelector("lr-checkbox")?.focus()}else{control.focus()}}click(){if(this.effectiveDisabled)return;this.focusFirstControl()}updated(changed){super.updated(changed);if(changed.has("value")||changed.has("keys")||changed.has("_errors")){const valid=Object.keys(this._errors).length===0;const key=JSON.stringify({valid,errors:this._errors});if(key!==this.lastValidityKey){this.lastValidityKey=key;this.emit("lr-validity-change",{valid,errors:{...this._errors}})}}if(this.pendingFocusFirst){this.pendingFocusFirst=false;this.focusFirstControl()}}renderScoreControl(k,fieldId,current,hasError){const min=k.min??0;const max=k.max??5;const step=k.step??1;const disabled=this.effectiveDisabled;const accessibleLabel=[k.label??k.key,k.description,hasError?this._errors[k.key]:void 0].filter(value=>Boolean(value)).join(". ");if(this.isSegmentedScore(k)){const items=this.scoreValues(k).map(score=>({value:String(score),label:String(score),disabled}));const value=typeof current==="number"?String(current):"";return html`<lr-segmented
2
2
  id=${fieldId}
3
3
  class="control"
4
4
  part="scale"