@aceshooting/lyra-ui 12.0.0 → 12.1.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.
- package/CHANGELOG.md +29 -0
- package/custom-elements.json +1 -1
- package/dist/autoloader.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +0 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +1 -1
- package/dist/components/charts/chart/histogram-bin.d.ts +0 -1
- package/dist/components/charts/chart/histogram-bin.js +1 -1
- package/dist/components/charts/chart/lite-chart.class.d.ts +22 -9
- package/dist/components/charts/chart/lite-chart.class.js +6 -6
- package/dist/components/conversation/code-block/code-block-shared.d.ts +4 -54
- package/dist/components/conversation/code-block/code-block-shared.js +1 -1
- package/dist/components/conversation/code-block/shiki-types.d.ts +2 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +1 -1
- package/dist/components/conversation/model-select/model-select.class.d.ts +0 -3
- package/dist/components/conversation/model-select/model-select.class.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.d.ts +0 -1
- package/dist/components/conversation/voice-picker/voice-picker.class.js +1 -1
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +0 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +4 -1
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/table/table.class.d.ts +18 -4
- package/dist/components/data/table/table.class.js +2 -2
- package/dist/components/data/table/table.styles.js +2 -1
- package/dist/components/data/timeline/timeline-cluster.d.ts +1 -0
- package/dist/components/data/timeline/timeline-cluster.js +1 -0
- package/dist/components/data/timeline/timeline-item.class.d.ts +17 -2
- package/dist/components/data/timeline/timeline-item.class.js +13 -2
- package/dist/components/data/timeline/timeline-item.styles.js +65 -0
- package/dist/components/data/timeline/timeline.class.d.ts +83 -27
- package/dist/components/data/timeline/timeline.class.js +3 -3
- package/dist/components/data/timeline/timeline.d.ts +1 -0
- package/dist/components/data/timeline/timeline.js +1 -1
- package/dist/components/data/timeline/timeline.styles.js +14 -0
- package/dist/components/forms/button/button.class.js +1 -1
- package/dist/components/forms/checkbox/checkbox.class.d.ts +0 -1
- package/dist/components/forms/checkbox/checkbox.class.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.d.ts +0 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/color-picker/color-picker.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.d.ts +7 -1
- package/dist/components/forms/combobox/combobox.class.js +3 -2
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-data-loader.d.ts +0 -1
- package/dist/components/forms/input/native-time-input.class.js +1 -1
- package/dist/components/forms/input/time-input-shared.d.ts +2 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/locale-picker/locale-picker.class.d.ts +0 -1
- package/dist/components/forms/locale-picker/locale-picker.class.js +1 -1
- package/dist/components/forms/radio/radio-button.styles.d.ts +0 -1
- package/dist/components/forms/radio/radio-button.styles.js +1 -1
- package/dist/components/forms/radio/radio-group.class.d.ts +0 -1
- package/dist/components/forms/radio/radio-group.class.js +1 -1
- package/dist/components/forms/radio/radio.class.d.ts +0 -1
- package/dist/components/forms/radio/radio.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +0 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +0 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +0 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/switch/switch.class.d.ts +0 -1
- package/dist/components/forms/switch/switch.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.d.ts +0 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/forms/token-input/token-input.class.d.ts +0 -1
- package/dist/components/forms/token-input/token-input.class.js +1 -1
- package/dist/components/layout/dashboard-grid/layout-internal.d.ts +0 -1
- package/dist/components/layout/dashboard-grid/layout-internal.js +1 -1
- package/dist/components/layout/details/accordion-owner.d.ts +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/menu/menu-item.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/av-player/av-metadata.d.ts +0 -2
- package/dist/components/media/av-player/av-metadata.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +0 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +4 -1
- package/dist/components/media/map/map.class.d.ts +50 -12
- package/dist/components/media/map/map.class.js +2 -2
- package/dist/components/overlays/overlay/popover.class.d.ts +7 -1
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/overlays/overlay/tooltip.class.d.ts +1 -0
- package/dist/components/overlays/overlay/tooltip.class.js +1 -1
- package/dist/components/overlays/progress/progress-shared.d.ts +0 -2
- package/dist/components/overlays/progress/progress-shared.js +1 -1
- package/dist/components/overlays/rating/rating.class.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.d.ts +10 -9
- package/dist/components/retrieval/mind-map/mind-map-layout.d.ts +0 -4
- package/dist/components/retrieval/mind-map/mind-map-layout.js +1 -1
- package/dist/components/utility/format/format-options.d.ts +0 -2
- package/dist/components/utility/format/format-options.js +1 -1
- package/dist/components/utility/icon/icon-resource.d.ts +0 -2
- package/dist/components/utility/icon/icon-resource.js +1 -1
- package/dist/components/viewers/archive-viewer/zip-resource-guard.d.ts +2 -1
- package/dist/components/viewers/docx-viewer/docx-resource-guard.d.ts +0 -3
- package/dist/components/viewers/docx-viewer/docx-resource-guard.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-loader.d.ts +2 -1
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.d.ts +0 -3
- package/dist/components/viewers/ebook-viewer/epub-resource-guard.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-loader.d.ts +2 -2
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +2 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.d.ts +0 -2
- package/dist/components/viewers/pptx-viewer/pptx-resource-guard.js +1 -1
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.d.ts +0 -5
- package/dist/components/viewers/spreadsheet-viewer/xlsx-resource-guard.js +1 -1
- package/dist/custom-elements-jsx.d.ts +4 -4
- package/dist/events.d.ts +15 -0
- package/dist/internal/accessibility-visibility.d.ts +1 -1
- package/dist/internal/anchor-target.d.ts +1 -3
- package/dist/internal/anchor-target.js +2 -2
- package/dist/internal/anchored-overlay-runtime.d.ts +7 -0
- package/dist/internal/anchored-overlay-runtime.js +1 -0
- package/dist/internal/announcement-text.d.ts +1 -1
- package/dist/internal/ansi.d.ts +0 -4
- package/dist/internal/ansi.js +1 -1
- package/dist/internal/aria-ownership.d.ts +2 -1
- package/dist/internal/default-strings.generated.d.ts +1 -0
- package/dist/internal/default-strings.generated.js +1 -1
- package/dist/internal/focus-navigation.d.ts +3 -2
- package/dist/internal/form-associated.d.ts +0 -1
- package/dist/internal/form-associated.js +1 -1
- package/dist/internal/form-control-labels.d.ts +0 -3
- package/dist/internal/form-control-labels.js +1 -1
- package/dist/internal/localization-runtime.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/lyra-element.d.ts +0 -13
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/nonmodal-overlay-manager.d.ts +9 -0
- package/dist/internal/nonmodal-overlay-manager.js +1 -0
- package/dist/internal/overlay-manager.d.ts +4 -20
- package/dist/internal/overlay-manager.js +1 -1
- package/dist/internal/overlay-stack.d.ts +66 -0
- package/dist/internal/overlay-stack.js +1 -0
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.js +1 -1
- package/dist/internal/text-quote.d.ts +1 -1
- package/dist/lyra.d.ts +2 -3
- package/dist/svelte.d.ts +4 -4
- package/dist/translations/ar.js +1 -1
- package/dist/translations/de.js +1 -1
- package/dist/translations/es.js +1 -1
- package/dist/translations/fa.js +1 -1
- package/dist/translations/fr.js +1 -1
- package/dist/translations/he.js +1 -1
- package/dist/translations/ja.js +1 -1
- package/dist/translations/pt-BR.js +1 -1
- package/dist/translations/ru.js +1 -1
- package/dist/translations/zh-CN.js +1 -1
- package/dist/utilities/localization.js +1 -1
- package/dist/vue.d.ts +4 -4
- package/llms/components/lr-combobox.md +42 -0
- package/llms/components/lr-date-input.md +1 -1
- package/llms/components/lr-date-picker.md +1 -1
- package/llms/components/lr-filter-bar.md +2 -2
- package/llms/components/lr-heatmap.md +4 -1
- package/llms/components/lr-lite-chart.md +20 -8
- package/llms/components/lr-map.md +52 -22
- package/llms/components/lr-option.md +42 -0
- package/llms/components/lr-popover.md +39 -0
- package/llms/components/lr-table.md +7 -3
- package/llms/components/lr-timeline-item.md +49 -24
- package/llms/components/lr-timeline.md +49 -24
- package/llms-full.txt +224 -60
- package/package.json +3 -4
- package/vscode-css-data.json +21 -0
- package/vscode-html-data.json +12 -6
- package/web-types.json +47 -16
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon,calendarIcon,chevronIcon}from"../../../internal/icons.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{isDateObject}from"../../../internal/dom-guards.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dateTimeFormat,parseISO,formatISO,localDate,utcDate,normalizeCalendarMonths,normalizeWeekdayFormat}from"./calendar-core.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./date-input.styles.js";import"./date-picker.class.js";import"./date-picker.class.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_chooseDate,LYRA_DEFAULT_clear,LYRA_DEFAULT_date,LYRA_DEFAULT_dateInputFutureDisabled,LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_dateInputPastDisabled,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_openCalendar}from"../../../internal/default-strings.generated.js";function localeDateOrder(locale){try{const order=dateTimeFormat(locale,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2)).filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}const BIDI_FORMATTING_MARKS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function normalizeLocalizedDateText(raw,locale){let normalized=raw.replace(BIDI_FORMATTING_MARKS,"");try{const formatter=getNumberFormat(locale||void 0,{useGrouping:!1});for(let digit=0;digit<=9;digit++){const localized=formatter.format(digit).replace(BIDI_FORMATTING_MARKS,"");localized&&localized!==String(digit)&&(normalized=normalized.split(localized).join(String(digit)))}}catch{}return normalized.trim()}const monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths},weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizeDateInputAppearance(value){return value==="filled"||value==="filled-outlined"?value:"outlined"}const appearanceConverter={fromAttribute:normalizeDateInputAppearance,toAttribute:normalizeDateInputAppearance},placements=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function normalizeDateInputPlacement(value){return typeof value=="string"&&placements.has(value)?value:"bottom-start"}const placementConverter={fromAttribute:normalizeDateInputPlacement,toAttribute:normalizeDateInputPlacement};function normalizeDateInputPageBy(value){return value==="single"?"single":"months"}const pageByConverter={fromAttribute:normalizeDateInputPageBy,toAttribute:normalizeDateInputPageBy},VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}class LyraDateInputBase extends LyraElement{}class LyraDateInput extends FormAssociated(LyraDateInputBase){static{this.defaultStrings={...super.defaultStrings,chooseDate:LYRA_DEFAULT_chooseDate,clear:LYRA_DEFAULT_clear,date:LYRA_DEFAULT_date,dateInputFutureDisabled:LYRA_DEFAULT_dateInputFutureDisabled,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,dateInputPastDisabled:LYRA_DEFAULT_dateInputPastDisabled,fieldRequired:LYRA_DEFAULT_fieldRequired,openCalendar:LYRA_DEFAULT_openCalendar}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={mode:{reflect:!0,noAccessor:!0},min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},disablePast:{type:Boolean,attribute:"disable-past",reflect:!0,noAccessor:!0},disableFuture:{type:Boolean,attribute:"disable-future",reflect:!0,noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!this.readonly&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get appliedPreset(){return this._appliedPreset}constructor(){super(),this.appearance="outlined",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.size="m",this.pill=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.accessibleLabel=null,this.locale="",this.months=1,this.firstDayOfWeek="auto",this.weekdayFormat="short",this.presets=Object.freeze([]),this.withOutsideDays=!1,this.withWeekNumbers=!1,this.disabledDates="",this.disabledDaysOfWeek="",this.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.distance=0,this.placement="bottom-start",this.assumeInteractionOn=["input"],this.validators=[],this.clearLabel="",this.openLabel="",this.dialogLabel="Choose date",this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.restorePopupFocusOnClose=!1,this.transitionToken=0,this.transitionWaiters=new Map,this.interactionListeners=new Map,this.inputId=nextId("date-input"),this.popupId=nextId("date-popup"),this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.validityRevision=0,this._mode="single",this._min="",this._max="",this._open=!1,this._readonly=!1,this._disablePast=!1,this._disableFuture=!1,this.typedBadInput=!1,this.now=()=>new Date,this.onVisibilityChange=()=>{this.ownerDocument.visibilityState==="visible"&&(this.updateValidity(),this.validityRevision++)},this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide(!1)},this.onInputChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const raw=e.target.value;if(this.enterCommittedText!==null&&(raw===this.enterCommittedText||raw===this.displayText))return;this.enterCommittedText=null,this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)):this.inputRelayedSinceCommit=!1},this.onInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.inputRelayedSinceCommit=!0,relayNativeEvent(this,event))},this.onInputKey=e=>{if(e.altKey&&e.key==="ArrowDown"){e.preventDefault(),this.show();return}if(this.liveDisabled||this.readonly||!isImplicitSubmission(e))return;const input=this.inputElement;if(input&&input.value!==this.displayText){const raw=input.value;this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,dispatchNativeEvent(this,"change")):this.inputRelayedSinceCommit=!1,this.enterCommittedText=raw}submitOnEnter(this,e)},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:!0}).length>0},this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:!0}).length>0},this.onPickerInput=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,this._appliedPreset=picker.appliedPreset,this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)},this.onPickerChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,this._appliedPreset=picker.appliedPreset,relayNativeEvent(this,e),this.hide(!0)},this.addEventListener("invalid",()=>{this.touched=!0})}get mode(){return this._mode}set mode(next){const old=this._mode;this._mode=next==="range"?"range":"single",this.internals.setFormValue(this.isIncompleteRangeValue(this.value)?"":this.value),this.updateValidity(),this.syncCustomStates(),this.requestUpdate("mode",old)}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.hide(),this.updateValidity(),this.requestUpdate("readonly",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.hide(),this.syncCustomStates()}get disablePast(){return this._disablePast}set disablePast(next){const old=this._disablePast;this._disablePast=!!next,this.updateValidity(),this.requestUpdate("disablePast",old)}get disableFuture(){return this._disableFuture}set disableFuture(next){const old=this._disableFuture;this._disableFuture=!!next,this.updateValidity(),this.requestUpdate("disableFuture",old)}get input(){return this.inputElement}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){this.inputElement&&(this.inputElement.selectionStart=value??0)}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){this.inputElement&&(this.inputElement.selectionEnd=value??0)}get selectionDirection(){return this.inputElement?.selectionDirection??null}set selectionDirection(value){this.inputElement&&(this.inputElement.selectionDirection=value??"none")}get value(){return super.value}set value(next){this.setTypedBadInput(!1);const normalized=this.normalizeCommittedValue(next??"");super.value=normalized,this.internals.setFormValue(this.isIncompleteRangeValue(normalized)?"":normalized),this.syncCustomStates()}get valueAsDate(){return this.mode==="single"?this.parseStrictISO(this.value):null}set valueAsDate(next){this.value=isDateObject(next)&&Number.isFinite(next.getTime())?formatISO(next):""}get valueAsRange(){if(this.mode!=="range")return{from:null,to:null};const[from="",to=""]=this.value.split("/");return{from:this.parseStrictISO(from),to:this.parseStrictISO(to)}}set valueAsRange(next){let from=isDateObject(next?.from)&&Number.isFinite(next.from.getTime())?next.from:null,to=isDateObject(next?.to)&&Number.isFinite(next.to.getTime())?next.to:null;from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get validationTarget(){return this.validationTargetOverride??this.inputElement}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}setTypedBadInput(next){const old=this.typedBadInput;this.typedBadInput=next,old!==next&&this.requestUpdate("typedBadInput",old)}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}normalizeCommittedValue(value){if(value==="")return"";const parts=value.split("/");if(parts.length!==1&&parts.length!==2)return"";const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?"":parts.length===2&&dates[0]>dates[1]?`${parts[1]}/${parts[0]}`:value}isIncompleteRangeValue(value){return this.mode==="range"&&value!==""&&!value.includes("/")}valueDates(value){const parts=value.split("/"),expectedParts=this.mode==="range"&&parts.length===2?2:1;if(parts.length!==expectedParts)return null;const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?null:dates}configuredDisabledDateKeys(){const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return new Set(values.map(value=>isDateObject(value)?value:parseISO(String(value))).filter(value=>isDateObject(value)&&Number.isFinite(value.getTime())).map(value=>formatISO(value)))}configuredDisabledWeekdays(){const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6};return new Set(String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0))}rangeLength(from,to){const fromUtc=utcDate(from.getFullYear(),from.getMonth(),from.getDate()).getTime(),toUtc=utcDate(to.getFullYear(),to.getMonth(),to.getDate()).getTime();return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("dateInputInvalid")}}result=typeof validator=="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:!0},message:this.localize("dateInputInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("dateInputInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("dateInputInvalid")}}}return{}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let underflowMessage="",overflowMessage="";const incompleteRange=this.isIncompleteRangeValue(this.value);if(this.required&&(this.value===""||incompleteRange)&&(flags.valueMissing=!0),this.typedBadInput&&(flags.badInput=!0),this.value!==""){const dates=this.valueDates(this.value);if(!dates)flags.badInput=!0;else{const min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max),now=this.parseStrictISO(this.today)??this.now(),today=localDate(now.getFullYear(),now.getMonth(),now.getDate());min!==null&&dates.some(date=>date<min)&&(flags.rangeUnderflow=!0,underflowMessage=this.localize("dateInputMinMessage",void 0,{min:this.min})),this.disablePast&&dates.some(date=>date<today)&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputPastDisabled")),max!==null&&dates.some(date=>date>max)&&(flags.rangeOverflow=!0,overflowMessage=this.localize("dateInputMaxMessage",void 0,{max:this.max})),this.disableFuture&&dates.some(date=>date>today)&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputFutureDisabled"));const disabledDates=this.configuredDisabledDateKeys(),disabledWeekdays=this.configuredDisabledWeekdays();let configuredDisabled=dates.some(date=>disabledDates.has(formatISO(date))||disabledWeekdays.has(date.getDay()));if(!configuredDisabled&&this.isDateDisabled)try{configuredDisabled=dates.some(date=>!!this.isDateDisabled?.(new Date(date.getTime())))}catch{configuredDisabled=!1}if(configuredDisabled&&(flags.customError=!0),this.mode==="range"&&dates.length===2){const length=this.rangeLength(dates[0],dates[1]),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);minimum>0&&length<minimum&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputInvalid")),maximum>0&&length>maximum&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputInvalid"))}}}const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags);let message="";configured.message?message=configured.message:flags.badInput||flags.customError?message=this.localize("dateInputInvalid"):flags.rangeUnderflow?message=underflowMessage:flags.rangeOverflow?message=overflowMessage:flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.updateValidity(),super.reportValidity()}bindVisibilityListener(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.visibilityListenerDocument===ownerDocument&&this.visibilityListener)return;this.unbindVisibilityListener();const listener=()=>{this.visibilityListener!==listener||this.visibilityListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onVisibilityChange()};this.visibilityListenerDocument=ownerDocument,this.visibilityListener=listener,ownerDocument.addEventListener("visibilitychange",listener)}unbindVisibilityListener(){this.visibilityListenerDocument&&this.visibilityListener&&this.visibilityListenerDocument.removeEventListener("visibilitychange",this.visibilityListener),this.visibilityListenerDocument=void 0,this.visibilityListener=void 0}get displayText(){const parts=this.value.split("/"),from=parseISO(parts[0]),to=parseISO(parts[1]??"");if(!from)return"";const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"}),fmt=d=>formatter.format(d);if(this.mode!=="range"||!to)return fmt(from);try{return formatter.formatRange(from,to)}catch{return`${fmt(from)} \u2013 ${fmt(to)}`}}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasStartSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="end")),changed.has("open")&&(this.open&&this.isConnected?this.bindDocumentPointer():this.unbindDocumentPointer())}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}show(){if(this.open||this.liveDisabled||this.readonly||this.emit("lr-show",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,this.settleTransition("lr-after-show"),settled}hide(restoreFocus=!1){if(!this.open||this.emit("lr-hide",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.restorePopupFocusOnClose||=restoreFocus,this.open=!1,this.settleTransition("lr-after-hide"),settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.bindDocumentPointer(),this.cleanupFn?.();const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)},modal:!1,trapFocus:!1}))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}connectedCallback(){super.connectedCallback(),this.bindVisibilityListener(),this.syncInteractionListeners(),this.syncValidatorAttributeObserver(),this.syncCustomStates(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}clear(){!this.value||this.liveDisabled||this.readonly||(this.touched=!0,this._appliedPreset=void 0,this.value="",this.emit("lr-clear"),this.inputRelayedSinceCommit=!1,dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),dispatchNativeEvent(this,"change"))}syncInteractionListeners(){const requested=new Set((Array.isArray(this.assumeInteractionOn)?this.assumeInteractionOn:[]).filter(name=>typeof name=="string"&&name.length>0));for(const[name,listener]of this.interactionListeners)requested.has(name)||(this.removeEventListener(name,listener),this.interactionListeners.delete(name));for(const name of requested){if(this.interactionListeners.has(name))continue;const listener=()=>{this.touched=!0,this.syncCustomStates()};this.addEventListener(name,listener),this.interactionListeners.set(name,listener)}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}syncCustomStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open),setCustomState(this.internals,"range",this.mode==="range")}disconnectedCallback(){this.transitionToken++,this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver(),this.restorePopupFocusOnClose=!1,this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide");for(const[name,listener]of this.interactionListeners)this.removeEventListener(name,listener);this.interactionListeners.clear(),this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.open=!1,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver()}updated(changed){if(super.updated(changed),(changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("isDateDisabled")||changed.has("minRange")||changed.has("maxRange")||changed.has("today")||changed.has("validators"))&&this.updateValidity(),(changed.has("open")||this.open&&(changed.has("placement")||changed.has("distance")))&&(this.cleanupFn?.(),this.cleanupFn=void 0,this.open&&this.isConnected)){const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');anchor&&popup&&(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}))}if(changed.has("open")){if(this.open&&this.isConnected)this.renderRoot.querySelector('[part="popup"]')&&(this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)},modal:!1,trapFocus:!1}));else if(!this.open){const popup=this.renderRoot.querySelector('[part="popup"]'),focusWasInsidePopup=popup!==null&&composedContains(popup,deepActiveElement(this.ownerDocument));this.overlayHandle?.deactivate({restoreFocus:this.restorePopupFocusOnClose||focusWasInsidePopup}),this.overlayHandle=void 0,this.restorePopupFocusOnClose=!1}}changed.has("assumeInteractionOn")&&this.syncInteractionListeners(),changed.has("validators")&&this.syncValidatorAttributeObserver(),this.syncCustomStates(),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("mode")||changed.has("min")||changed.has("max")||changed.has("readonly")||changed.has("disablePast")||changed.has("disableFuture")||changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("minRange")||changed.has("maxRange")||changed.has("validators")||changed.has("typedBadInput")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}applyTypedText(raw){this.enterCommittedText=null;const trimmed=raw.trim();if(!trimmed)return this.value!==""&&(this._appliedPreset=void 0),this.value="",!0;const parsed=this.mode==="range"?this.parseRangeText(trimmed):this.parseSingleText(trimmed);return parsed?(parsed!==this.value&&(this._appliedPreset=void 0),this.value=parsed,!0):(this.inputElement&&(this.inputElement.value=this.displayText),this.setTypedBadInput(!0),this.updateValidity(),!1)}parseOneDate(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),/^\d{4}-\d{2}-\d{2}$/.test(raw))return parseISO(raw);const ambiguous=/^(\d{1,4})[/.-](\d{1,4})[/.-](\d{1,4})$/.exec(raw);if(ambiguous){const[,g1,g2,g3]=ambiguous;if(g1.length===4)return parseISO(`${g1}-${g2.padStart(2,"0")}-${g3.padStart(2,"0")}`);const order=localeDateOrder(this.effectiveLocale),values=[Number(g1),Number(g2),Number(g3)],fields={};if(order.forEach((type,i)=>{fields[type]=values[i]}),fields.day!=null&&fields.month!=null&&fields.year!=null){const year=fields.year<100?2e3+fields.year:fields.year;return parseISO(`${String(year).padStart(4,"0")}-${String(fields.month).padStart(2,"0")}-${String(fields.day).padStart(2,"0")}`)}}const timestamp=Date.parse(raw);return Number.isNaN(timestamp)?null:new Date(timestamp)}parseSingleText(raw){const parsed=this.parseOneDate(raw);return parsed?formatISO(parsed):null}localizedRangeSeparator(){const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"});try{const parts=formatter.formatRangeToParts(localDate(2026,0,2),localDate(2026,0,3)),firstEnd=parts.findIndex(part=>part.source==="endRange");let lastStart=-1;for(let index=0;index<firstEnd;index++)parts[index]?.source==="startRange"&&(lastStart=index);const separator=parts.slice(lastStart+1,firstEnd).map(part=>part.value).join("");return normalizeLocalizedDateText(separator,this.effectiveLocale)||"\u2013"}catch{return"\u2013"}}parseRangeText(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),raw===normalizeLocalizedDateText(this.displayText,this.effectiveLocale)&&this.value.includes("/"))return this.normalizeCommittedValue(this.value);if(/^\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}$/.test(raw)){const[a,b]=raw.split("/"),from2=parseISO(a),to2=parseISO(b);return!from2||!to2?null:from2<=to2?raw:`${b}/${a}`}const separator=this.localizedRangeSeparator(),idx=raw.indexOf(separator);if(idx===-1)return null;const from=this.parseOneDate(raw.slice(0,idx).trim()),to=this.parseOneDate(raw.slice(idx+separator.length).trim());return!from||!to?null:from<=to?`${formatISO(from)}/${formatISO(to)}`:`${formatISO(to)}/${formatISO(from)}`}click(){this.liveDisabled||this.inputElement?.click()}focus(options){this.liveDisabled||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;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.applyTypedText(input.value))}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formResetCallback(){super.formResetCallback(),this.touched=!1,this._appliedPreset=void 0}formDisabledCallback(disabled){Object.getPrototypeOf(LyraDateInput.prototype).formDisabledCallback.call(this,disabled),disabled&&this.hide(),this.syncCustomStates()}render(){const hasValue=this.value.length>0,hasHint=this.withHint||this.hasHintSlot||this.hint.length>0,hasError=this.hasErrorSlot||this.errorText.length>0,hasLabel=this.withLabel||this.hasLabelSlot||this.label.length>0,invalid=this.touched&&!this.internals.validity.valid,describedBy=[hasError?"date-input-error":"",hasHint?"date-input-hint":""].filter(Boolean).join(" "),dynamicDaySlots=[...new Set(Array.from(this.children??[]).map(child=>child.getAttribute("slot")??"").filter(name=>/^day-\d{4}-\d{2}-\d{2}$/.test(name)))];return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon,calendarIcon,chevronIcon}from"../../../internal/icons.js";import{activateNonmodalOverlay,composedContains,deepActiveElement}from"../../../internal/nonmodal-overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{isDateObject}from"../../../internal/dom-guards.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dateTimeFormat,parseISO,formatISO,localDate,utcDate,normalizeCalendarMonths,normalizeWeekdayFormat}from"./calendar-core.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./date-input.styles.js";import"./date-picker.class.js";import"./date-picker.class.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_chooseDate,LYRA_DEFAULT_clear,LYRA_DEFAULT_date,LYRA_DEFAULT_dateInputFutureDisabled,LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_dateInputPastDisabled,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_openCalendar}from"../../../internal/default-strings.generated.js";function localeDateOrder(locale){try{const order=dateTimeFormat(locale,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2)).filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}const BIDI_FORMATTING_MARKS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function normalizeLocalizedDateText(raw,locale){let normalized=raw.replace(BIDI_FORMATTING_MARKS,"");try{const formatter=getNumberFormat(locale||void 0,{useGrouping:!1});for(let digit=0;digit<=9;digit++){const localized=formatter.format(digit).replace(BIDI_FORMATTING_MARKS,"");localized&&localized!==String(digit)&&(normalized=normalized.split(localized).join(String(digit)))}}catch{}return normalized.trim()}const monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths},weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizeDateInputAppearance(value){return value==="filled"||value==="filled-outlined"?value:"outlined"}const appearanceConverter={fromAttribute:normalizeDateInputAppearance,toAttribute:normalizeDateInputAppearance},placements=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function normalizeDateInputPlacement(value){return typeof value=="string"&&placements.has(value)?value:"bottom-start"}const placementConverter={fromAttribute:normalizeDateInputPlacement,toAttribute:normalizeDateInputPlacement};function normalizeDateInputPageBy(value){return value==="single"?"single":"months"}const pageByConverter={fromAttribute:normalizeDateInputPageBy,toAttribute:normalizeDateInputPageBy},VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}class LyraDateInputBase extends LyraElement{}class LyraDateInput extends FormAssociated(LyraDateInputBase){static{this.defaultStrings={...super.defaultStrings,chooseDate:LYRA_DEFAULT_chooseDate,clear:LYRA_DEFAULT_clear,date:LYRA_DEFAULT_date,dateInputFutureDisabled:LYRA_DEFAULT_dateInputFutureDisabled,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,dateInputPastDisabled:LYRA_DEFAULT_dateInputPastDisabled,fieldRequired:LYRA_DEFAULT_fieldRequired,openCalendar:LYRA_DEFAULT_openCalendar}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={mode:{reflect:!0,noAccessor:!0},min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},disablePast:{type:Boolean,attribute:"disable-past",reflect:!0,noAccessor:!0},disableFuture:{type:Boolean,attribute:"disable-future",reflect:!0,noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!this.readonly&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get appliedPreset(){return this._appliedPreset}constructor(){super(),this.appearance="outlined",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.size="m",this.pill=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.accessibleLabel=null,this.locale="",this.months=1,this.firstDayOfWeek="auto",this.weekdayFormat="short",this.presets=Object.freeze([]),this.withOutsideDays=!1,this.withWeekNumbers=!1,this.disabledDates="",this.disabledDaysOfWeek="",this.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.distance=0,this.placement="bottom-start",this.assumeInteractionOn=["input"],this.validators=[],this.clearLabel="",this.openLabel="",this.dialogLabel="Choose date",this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.restorePopupFocusOnClose=!1,this.transitionToken=0,this.transitionWaiters=new Map,this.interactionListeners=new Map,this.inputId=nextId("date-input"),this.popupId=nextId("date-popup"),this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.validityRevision=0,this._mode="single",this._min="",this._max="",this._open=!1,this._readonly=!1,this._disablePast=!1,this._disableFuture=!1,this.typedBadInput=!1,this.now=()=>new Date,this.onVisibilityChange=()=>{this.ownerDocument.visibilityState==="visible"&&(this.updateValidity(),this.validityRevision++)},this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide(!1)},this.onInputChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const raw=e.target.value;if(this.enterCommittedText!==null&&(raw===this.enterCommittedText||raw===this.displayText))return;this.enterCommittedText=null,this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)):this.inputRelayedSinceCommit=!1},this.onInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.inputRelayedSinceCommit=!0,relayNativeEvent(this,event))},this.onInputKey=e=>{if(e.altKey&&e.key==="ArrowDown"){e.preventDefault(),this.show();return}if(this.liveDisabled||this.readonly||!isImplicitSubmission(e))return;const input=this.inputElement;if(input&&input.value!==this.displayText){const raw=input.value;this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,dispatchNativeEvent(this,"change")):this.inputRelayedSinceCommit=!1,this.enterCommittedText=raw}submitOnEnter(this,e)},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:!0}).length>0},this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:!0}).length>0},this.onPickerInput=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,this._appliedPreset=picker.appliedPreset,this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)},this.onPickerChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,this._appliedPreset=picker.appliedPreset,relayNativeEvent(this,e),this.hide(!0)},this.addEventListener("invalid",()=>{this.touched=!0})}get mode(){return this._mode}set mode(next){const old=this._mode;this._mode=next==="range"?"range":"single",this.internals.setFormValue(this.isIncompleteRangeValue(this.value)?"":this.value),this.updateValidity(),this.syncCustomStates(),this.requestUpdate("mode",old)}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.hide(),this.updateValidity(),this.requestUpdate("readonly",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.hide(),this.syncCustomStates()}get disablePast(){return this._disablePast}set disablePast(next){const old=this._disablePast;this._disablePast=!!next,this.updateValidity(),this.requestUpdate("disablePast",old)}get disableFuture(){return this._disableFuture}set disableFuture(next){const old=this._disableFuture;this._disableFuture=!!next,this.updateValidity(),this.requestUpdate("disableFuture",old)}get input(){return this.inputElement}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){this.inputElement&&(this.inputElement.selectionStart=value??0)}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){this.inputElement&&(this.inputElement.selectionEnd=value??0)}get selectionDirection(){return this.inputElement?.selectionDirection??null}set selectionDirection(value){this.inputElement&&(this.inputElement.selectionDirection=value??"none")}get value(){return super.value}set value(next){this.setTypedBadInput(!1);const normalized=this.normalizeCommittedValue(next??"");super.value=normalized,this.internals.setFormValue(this.isIncompleteRangeValue(normalized)?"":normalized),this.syncCustomStates()}get valueAsDate(){return this.mode==="single"?this.parseStrictISO(this.value):null}set valueAsDate(next){this.value=isDateObject(next)&&Number.isFinite(next.getTime())?formatISO(next):""}get valueAsRange(){if(this.mode!=="range")return{from:null,to:null};const[from="",to=""]=this.value.split("/");return{from:this.parseStrictISO(from),to:this.parseStrictISO(to)}}set valueAsRange(next){let from=isDateObject(next?.from)&&Number.isFinite(next.from.getTime())?next.from:null,to=isDateObject(next?.to)&&Number.isFinite(next.to.getTime())?next.to:null;from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get validationTarget(){return this.validationTargetOverride??this.inputElement}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}setTypedBadInput(next){const old=this.typedBadInput;this.typedBadInput=next,old!==next&&this.requestUpdate("typedBadInput",old)}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}normalizeCommittedValue(value){if(value==="")return"";const parts=value.split("/");if(parts.length!==1&&parts.length!==2)return"";const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?"":parts.length===2&&dates[0]>dates[1]?`${parts[1]}/${parts[0]}`:value}isIncompleteRangeValue(value){return this.mode==="range"&&value!==""&&!value.includes("/")}valueDates(value){const parts=value.split("/"),expectedParts=this.mode==="range"&&parts.length===2?2:1;if(parts.length!==expectedParts)return null;const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?null:dates}configuredDisabledDateKeys(){const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return new Set(values.map(value=>isDateObject(value)?value:parseISO(String(value))).filter(value=>isDateObject(value)&&Number.isFinite(value.getTime())).map(value=>formatISO(value)))}configuredDisabledWeekdays(){const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6};return new Set(String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0))}rangeLength(from,to){const fromUtc=utcDate(from.getFullYear(),from.getMonth(),from.getDate()).getTime(),toUtc=utcDate(to.getFullYear(),to.getMonth(),to.getDate()).getTime();return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("dateInputInvalid")}}result=typeof validator=="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:!0},message:this.localize("dateInputInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("dateInputInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("dateInputInvalid")}}}return{}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let underflowMessage="",overflowMessage="";const incompleteRange=this.isIncompleteRangeValue(this.value);if(this.required&&(this.value===""||incompleteRange)&&(flags.valueMissing=!0),this.typedBadInput&&(flags.badInput=!0),this.value!==""){const dates=this.valueDates(this.value);if(!dates)flags.badInput=!0;else{const min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max),now=this.parseStrictISO(this.today)??this.now(),today=localDate(now.getFullYear(),now.getMonth(),now.getDate());min!==null&&dates.some(date=>date<min)&&(flags.rangeUnderflow=!0,underflowMessage=this.localize("dateInputMinMessage",void 0,{min:this.min})),this.disablePast&&dates.some(date=>date<today)&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputPastDisabled")),max!==null&&dates.some(date=>date>max)&&(flags.rangeOverflow=!0,overflowMessage=this.localize("dateInputMaxMessage",void 0,{max:this.max})),this.disableFuture&&dates.some(date=>date>today)&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputFutureDisabled"));const disabledDates=this.configuredDisabledDateKeys(),disabledWeekdays=this.configuredDisabledWeekdays();let configuredDisabled=dates.some(date=>disabledDates.has(formatISO(date))||disabledWeekdays.has(date.getDay()));if(!configuredDisabled&&this.isDateDisabled)try{configuredDisabled=dates.some(date=>!!this.isDateDisabled?.(new Date(date.getTime())))}catch{configuredDisabled=!1}if(configuredDisabled&&(flags.customError=!0),this.mode==="range"&&dates.length===2){const length=this.rangeLength(dates[0],dates[1]),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);minimum>0&&length<minimum&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputInvalid")),maximum>0&&length>maximum&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputInvalid"))}}}const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags);let message="";configured.message?message=configured.message:flags.badInput||flags.customError?message=this.localize("dateInputInvalid"):flags.rangeUnderflow?message=underflowMessage:flags.rangeOverflow?message=overflowMessage:flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.updateValidity(),super.reportValidity()}bindVisibilityListener(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.visibilityListenerDocument===ownerDocument&&this.visibilityListener)return;this.unbindVisibilityListener();const listener=()=>{this.visibilityListener!==listener||this.visibilityListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onVisibilityChange()};this.visibilityListenerDocument=ownerDocument,this.visibilityListener=listener,ownerDocument.addEventListener("visibilitychange",listener)}unbindVisibilityListener(){this.visibilityListenerDocument&&this.visibilityListener&&this.visibilityListenerDocument.removeEventListener("visibilitychange",this.visibilityListener),this.visibilityListenerDocument=void 0,this.visibilityListener=void 0}get displayText(){const parts=this.value.split("/"),from=parseISO(parts[0]),to=parseISO(parts[1]??"");if(!from)return"";const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"}),fmt=d=>formatter.format(d);if(this.mode!=="range"||!to)return fmt(from);try{return formatter.formatRange(from,to)}catch{return`${fmt(from)} \u2013 ${fmt(to)}`}}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasStartSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="end")),changed.has("open")&&(this.open&&this.isConnected?this.bindDocumentPointer():this.unbindDocumentPointer())}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}show(){if(this.open||this.liveDisabled||this.readonly||this.emit("lr-show",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,this.settleTransition("lr-after-show"),settled}hide(restoreFocus=!1){if(!this.open||this.emit("lr-hide",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.restorePopupFocusOnClose||=restoreFocus,this.open=!1,this.settleTransition("lr-after-hide"),settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.bindDocumentPointer(),this.cleanupFn?.();const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)}}))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}connectedCallback(){super.connectedCallback(),this.bindVisibilityListener(),this.syncInteractionListeners(),this.syncValidatorAttributeObserver(),this.syncCustomStates(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}clear(){!this.value||this.liveDisabled||this.readonly||(this.touched=!0,this._appliedPreset=void 0,this.value="",this.emit("lr-clear"),this.inputRelayedSinceCommit=!1,dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),dispatchNativeEvent(this,"change"))}syncInteractionListeners(){const requested=new Set((Array.isArray(this.assumeInteractionOn)?this.assumeInteractionOn:[]).filter(name=>typeof name=="string"&&name.length>0));for(const[name,listener]of this.interactionListeners)requested.has(name)||(this.removeEventListener(name,listener),this.interactionListeners.delete(name));for(const name of requested){if(this.interactionListeners.has(name))continue;const listener=()=>{this.touched=!0,this.syncCustomStates()};this.addEventListener(name,listener),this.interactionListeners.set(name,listener)}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}syncCustomStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open),setCustomState(this.internals,"range",this.mode==="range")}disconnectedCallback(){this.transitionToken++,this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver(),this.restorePopupFocusOnClose=!1,this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide");for(const[name,listener]of this.interactionListeners)this.removeEventListener(name,listener);this.interactionListeners.clear(),this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.open=!1,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver()}updated(changed){if(super.updated(changed),(changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("isDateDisabled")||changed.has("minRange")||changed.has("maxRange")||changed.has("today")||changed.has("validators"))&&this.updateValidity(),(changed.has("open")||this.open&&(changed.has("placement")||changed.has("distance")))&&(this.cleanupFn?.(),this.cleanupFn=void 0,this.open&&this.isConnected)){const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');anchor&&popup&&(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}))}if(changed.has("open")){if(this.open&&this.isConnected)this.renderRoot.querySelector('[part="popup"]')&&(this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)}}));else if(!this.open){const popup=this.renderRoot.querySelector('[part="popup"]'),focusWasInsidePopup=popup!==null&&composedContains(popup,deepActiveElement(this.ownerDocument));this.overlayHandle?.deactivate({restoreFocus:this.restorePopupFocusOnClose||focusWasInsidePopup}),this.overlayHandle=void 0,this.restorePopupFocusOnClose=!1}}changed.has("assumeInteractionOn")&&this.syncInteractionListeners(),changed.has("validators")&&this.syncValidatorAttributeObserver(),this.syncCustomStates(),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("mode")||changed.has("min")||changed.has("max")||changed.has("readonly")||changed.has("disablePast")||changed.has("disableFuture")||changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("minRange")||changed.has("maxRange")||changed.has("validators")||changed.has("typedBadInput")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}applyTypedText(raw){this.enterCommittedText=null;const trimmed=raw.trim();if(!trimmed)return this.value!==""&&(this._appliedPreset=void 0),this.value="",!0;const parsed=this.mode==="range"?this.parseRangeText(trimmed):this.parseSingleText(trimmed);return parsed?(parsed!==this.value&&(this._appliedPreset=void 0),this.value=parsed,!0):(this.inputElement&&(this.inputElement.value=this.displayText),this.setTypedBadInput(!0),this.updateValidity(),!1)}parseOneDate(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),/^\d{4}-\d{2}-\d{2}$/.test(raw))return parseISO(raw);const ambiguous=/^(\d{1,4})[/.-](\d{1,4})[/.-](\d{1,4})$/.exec(raw);if(ambiguous){const[,g1,g2,g3]=ambiguous;if(g1.length===4)return parseISO(`${g1}-${g2.padStart(2,"0")}-${g3.padStart(2,"0")}`);const order=localeDateOrder(this.effectiveLocale),values=[Number(g1),Number(g2),Number(g3)],fields={};if(order.forEach((type,i)=>{fields[type]=values[i]}),fields.day!=null&&fields.month!=null&&fields.year!=null){const year=fields.year<100?2e3+fields.year:fields.year;return parseISO(`${String(year).padStart(4,"0")}-${String(fields.month).padStart(2,"0")}-${String(fields.day).padStart(2,"0")}`)}}const timestamp=Date.parse(raw);return Number.isNaN(timestamp)?null:new Date(timestamp)}parseSingleText(raw){const parsed=this.parseOneDate(raw);return parsed?formatISO(parsed):null}localizedRangeSeparator(){const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"});try{const parts=formatter.formatRangeToParts(localDate(2026,0,2),localDate(2026,0,3)),firstEnd=parts.findIndex(part=>part.source==="endRange");let lastStart=-1;for(let index=0;index<firstEnd;index++)parts[index]?.source==="startRange"&&(lastStart=index);const separator=parts.slice(lastStart+1,firstEnd).map(part=>part.value).join("");return normalizeLocalizedDateText(separator,this.effectiveLocale)||"\u2013"}catch{return"\u2013"}}parseRangeText(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),raw===normalizeLocalizedDateText(this.displayText,this.effectiveLocale)&&this.value.includes("/"))return this.normalizeCommittedValue(this.value);if(/^\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}$/.test(raw)){const[a,b]=raw.split("/"),from2=parseISO(a),to2=parseISO(b);return!from2||!to2?null:from2<=to2?raw:`${b}/${a}`}const separator=this.localizedRangeSeparator(),idx=raw.indexOf(separator);if(idx===-1)return null;const from=this.parseOneDate(raw.slice(0,idx).trim()),to=this.parseOneDate(raw.slice(idx+separator.length).trim());return!from||!to?null:from<=to?`${formatISO(from)}/${formatISO(to)}`:`${formatISO(to)}/${formatISO(from)}`}click(){this.liveDisabled||this.inputElement?.click()}focus(options){this.liveDisabled||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;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.applyTypedText(input.value))}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formResetCallback(){super.formResetCallback(),this.touched=!1,this._appliedPreset=void 0}formDisabledCallback(disabled){Object.getPrototypeOf(LyraDateInput.prototype).formDisabledCallback.call(this,disabled),disabled&&this.hide(),this.syncCustomStates()}render(){const hasValue=this.value.length>0,hasHint=this.withHint||this.hasHintSlot||this.hint.length>0,hasError=this.hasErrorSlot||this.errorText.length>0,hasLabel=this.withLabel||this.hasLabelSlot||this.label.length>0,invalid=this.touched&&!this.internals.validity.valid,describedBy=[hasError?"date-input-error":"",hasHint?"date-input-hint":""].filter(Boolean).join(" "),dynamicDaySlots=[...new Set(Array.from(this.children??[]).map(child=>child.getAttribute("slot")??"").filter(name=>/^day-\d{4}-\d{2}-\d{2}$/.test(name)))];return html`
|
|
2
2
|
<div part="date-input">
|
|
3
3
|
<div part="base">
|
|
4
4
|
<div part="form-control">
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import type { EmojiPickerGroup } from './emoji-types.js';
|
|
2
|
-
export type EmojiDataApi = unknown;
|
|
3
2
|
/**
|
|
4
3
|
* Loads the optional peer dependency `emoji-picker-element-data` and adapts its JSON export into
|
|
5
4
|
* this component's own `EmojiPickerGroup[]` shape via `adaptEmojiPickerElementData()` below. Never
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{property}from"lit/decorators.js";import{LyraInput}from"./input.class.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";const timeBoundConverter={fromAttribute:value=>value??void 0
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{property}from"lit/decorators.js";import{LyraInput}from"./input.class.js";import{LYRA_DEFAULT_fieldRequired}from"../../../internal/default-strings.generated.js";const timeBoundConverter={fromAttribute:value=>value??void 0};class LyraNativeTimeInput extends LyraInput{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired}}get inputWrapperParts(){return`${super.inputWrapperParts} time-input`}constructor(){super(),this.appearance="filled-outlined",this.type="time"}connectedCallback(){super.connectedCallback(),this.type="time"}}__decorate([property({reflect:!0})],LyraNativeTimeInput.prototype,"appearance",void 0),__decorate([property({converter:timeBoundConverter})],LyraNativeTimeInput.prototype,"min",void 0),__decorate([property({converter:timeBoundConverter})],LyraNativeTimeInput.prototype,"max",void 0);export{LyraNativeTimeInput};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
type TimePrecision = 'minute' | 'second' | 'millisecond';
|
|
2
2
|
export interface ParsedTimeValue {
|
|
3
3
|
hour: number;
|
|
4
4
|
minute: number;
|
|
@@ -45,3 +45,4 @@ export declare function dayPeriodLabels(locale: string): {
|
|
|
45
45
|
pm: string;
|
|
46
46
|
};
|
|
47
47
|
export declare function wrapTimeMilliseconds(value: number): number;
|
|
48
|
+
export {};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{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{acquireAriaDescription}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{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,timeValueFromMilliseconds,timeStepBaseMilliseconds,to24Hour}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_popover,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)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,popover:LYRA_DEFAULT_popover,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 get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.hasFooterSlot=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.digitBuffer="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.transitionToken=0,this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);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),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}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const focusedSegment=event.target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus){queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&(this.activeSegment=focusedSegment)});return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(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,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncRequiredDescription()}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!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}const parsedValue=parseTimeValue(this.value);this.secondsVisible=this.numericStep<60||parsedValue!==void 0&&parsedValue.precision!=="minute",this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){let normalized=normalizeTimeValue(next);normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"&&(normalized+=":00"),this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}set valueAsNumber(next){this.value=timeValueFromMilliseconds(next)}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}set valueAsDate(next){this.value=normalizeTimeValue(next)}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 liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}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:!1}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;try{const formatter=getNumberFormat(this.effectiveLocale,{useGrouping:!1});for(let value=0;value<=9;value++)if(formatter.formatToParts(value).find(part=>part.type==="integer")?.value===key)return String(value)}catch{}}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=dayPeriodLabels(this.effectiveLocale);return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second: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){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){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,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}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(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,current=Math.max(0,order.indexOf(from)),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;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||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){return this._open===next?this.visibilityPromise:next&&this.liveDisabled?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event)}}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"}))}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment),modal:!1,trapFocus:!1}),this.lightDismissDocument=this.ownerDocument,this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,!0),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,!0),this.lightDismissDocument=void 0,this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateSlotState(event){const slot=event.currentTarget,present=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="label"?this.hasLabelSlot=present:slot.name==="hint"?this.hasHintSlot=present:slot.name==="error"?this.hasErrorSlot=present:slot.name==="start"?this.hasStartSlot=present:slot.name==="end"?this.hasEndSlot=present:slot.name==="footer"&&(this.hasFooterSlot=present)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){if(super.willUpdate(changed),!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")}this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focusedSegment=orderKey!==this.segmentOrderKey?this.shadowRoot?.activeElement?.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(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),this.syncRequiredDescription();const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}syncRequiredDescription(){const target=this.renderRoot.querySelector('[part~="input"]'),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),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--)(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{acquireAriaDescription}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteNumber}from"../../../internal/numbers.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateNonmodalOverlay,composedContains}from"../../../internal/nonmodal-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,timeValueFromMilliseconds,timeStepBaseMilliseconds,to24Hour}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_popover,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)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,popover:LYRA_DEFAULT_popover,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 get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.hasFooterSlot=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.digitBuffer="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.transitionToken=0,this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);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),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}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const focusedSegment=event.target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus){queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&(this.activeSegment=focusedSegment)});return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(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,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncRequiredDescription()}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!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}const parsedValue=parseTimeValue(this.value);this.secondsVisible=this.numericStep<60||parsedValue!==void 0&&parsedValue.precision!=="minute",this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){let normalized=normalizeTimeValue(next);normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"&&(normalized+=":00"),this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}set valueAsNumber(next){this.value=timeValueFromMilliseconds(next)}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}set valueAsDate(next){this.value=normalizeTimeValue(next)}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 liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}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:!1}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;try{const formatter=getNumberFormat(this.effectiveLocale,{useGrouping:!1});for(let value=0;value<=9;value++)if(formatter.formatToParts(value).find(part=>part.type==="integer")?.value===key)return String(value)}catch{}}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=dayPeriodLabels(this.effectiveLocale);return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second: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){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){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,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}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(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,current=Math.max(0,order.indexOf(from)),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;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||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){return this._open===next?this.visibilityPromise:next&&this.liveDisabled?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event)}}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"}))}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateNonmodalOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment)}),this.lightDismissDocument=this.ownerDocument,this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,!0),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,!0),this.lightDismissDocument=void 0,this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateSlotState(event){const slot=event.currentTarget,present=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="label"?this.hasLabelSlot=present:slot.name==="hint"?this.hasHintSlot=present:slot.name==="error"?this.hasErrorSlot=present:slot.name==="start"?this.hasStartSlot=present:slot.name==="end"?this.hasEndSlot=present:slot.name==="footer"&&(this.hasFooterSlot=present)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){if(super.willUpdate(changed),!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")}this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focusedSegment=orderKey!==this.segmentOrderKey?this.shadowRoot?.activeElement?.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(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),this.syncRequiredDescription();const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}syncRequiredDescription(){const target=this.renderRoot.querySelector('[part~="input"]'),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="segment"
|
|
4
4
|
role="spinbutton"
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type TemplateResult, type PropertyValues } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
-
import '../../../internal/form-control-labels.js';
|
|
4
3
|
import type { LyraLocaleDirection } from '../../../internal/localization.js';
|
|
5
4
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
6
5
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.js";import{place}from"../../../internal/positioner.js";import{hostAriaLabel,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{declaredDefaultConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired}from"../../../internal/default-strings.generated.js";const MAX_LOCALE_ENTRIES=512;function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get locales(){return this._locales}set locales(next){const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1),this.requestUpdate("open",old)}constructor(){super(),this.showFlags=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.registryTick=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeAheadBuffer="",this.typeAheadTimerGeneration=0,this.activeScrollGeneration=0,this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onKeyDown=e=>{if(this.liveDisabled)return;const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.min(rows.length-1,this.activeIndex+1));break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.max(0,this.activeIndex-1));break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(rows.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.liveDisabled||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}),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.activeScrollGeneration+=1,this.typeAheadBuffer="",this.open=!1}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed),this.open&&(changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.normalizedEntries.length-1),this.queueActiveScroll()),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;this.settingDefaultValue||(this._valueDirty=!0),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=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.isBarred()?this.validityController.setValidity({}):this.required&&!this._value?this.validityController.setValidity({valueMissing:!0},this.localize("localePickerRequired")):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=!1,this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.syncCustomStates(),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;return raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country}):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(){this.open||this.liveDisabled||(this.open=!0)}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox))}updated(changed){super.updated(changed),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")))&&this.syncPopup(),(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(),this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:!0}).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(()=>{this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||(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,currentIndex=rows.findIndex(r=>r.tag===currentTag),n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){this.open?this.setActiveIndex(idx):this.commit(row.tag);return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1,this.typeAheadTimer!==void 0&&this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer),this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0}setActiveIndex(index){const last=this.normalizedEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index||this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`)?.scrollIntoView({block:"nearest"})})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,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--)(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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{place}from"../../../internal/positioner.js";import{hostAriaLabel,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{declaredDefaultConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_localePickerLabel,LYRA_DEFAULT_localePickerRequired}from"../../../internal/default-strings.generated.js";const MAX_LOCALE_ENTRIES=512;function snapshotLocaleCatalog(source){if(!Array.isArray(source))return Object.freeze([]);const rows=[];for(let index=0;index<Math.min(source.length,MAX_LOCALE_ENTRIES);index+=1)try{const raw=source[index];if(typeof raw=="string"){raw.length>0&&rows.push(raw);continue}if(raw===null||typeof raw!="object")continue;const candidate=raw,tag=candidate.tag,label=candidate.label,country=candidate.country;if(typeof tag!="string"||tag.length===0||label!==void 0&&typeof label!="string"||country!==void 0&&typeof country!="string")continue;rows.push(Object.freeze({tag,...label===void 0?{}:{label},...country===void 0?{}:{country}}))}catch{}return Object.freeze(rows)}class LyraLocalePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,localePickerLabel:LYRA_DEFAULT_localePickerLabel,localePickerRequired:LYRA_DEFAULT_localePickerRequired}}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0}}}get locales(){return this._locales}set locales(next){const previous=this._locales;this._locales=next===void 0?void 0:snapshotLocaleCatalog(next),this.requestUpdate("locales",previous)}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this._open||(this.activeIndex=-1),this.requestUpdate("open",old)}constructor(){super(),this.showFlags=!0,this.label="",this.hint="",this.errorText="",this.size="m",this.activeIndex=-1,this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.registryTick=0,this.listId=nextId("locale-picker-list"),this.controlId=nextId("locale-picker-control"),this._value="",this._open=!1,this._fieldsetDisabled=!1,this._name="",this._disabled=!1,this._required=!1,this._defaultValue="",this._valueDirty=!1,this.settingDefaultValue=!1,this.reflectingDefaultValue=!1,this.typeAheadBuffer="",this.typeAheadTimerGeneration=0,this.activeScrollGeneration=0,this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide()},this.onTriggerClick=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onTriggerBlur=event=>{this.liveDisabled||(this.touched=!0),this.syncCustomStates(),this.hide(),relayNativeEvent(this,event)},this.onTriggerFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onKeyDown=e=>{if(this.liveDisabled)return;const rows=this.normalizedEntries;switch(e.key){case"ArrowDown":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.min(rows.length-1,this.activeIndex+1));break;case"ArrowUp":if(e.preventDefault(),!this.open)return this.show();this.setActiveIndex(Math.max(0,this.activeIndex-1));break;case"Enter":case" ":if(this.open){e.preventDefault();const activeRow=rows[this.activeIndex];this.activeIndex>=0&&activeRow?this.commit(activeRow.tag):this.hide()}break;case"Escape":this.open&&(e.preventDefault(),this.hide());break;case"Home":this.open&&(e.preventDefault(),this.setActiveIndex(0));break;case"End":this.open&&(e.preventDefault(),this.setActiveIndex(rows.length-1));break;default:e.key.length===1&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&this.typeAhead(e.key);break}},this.onListboxMouseDown=e=>{e.target.closest('[part="option"]')&&e.preventDefault()},this.onListboxClick=e=>{if(this.liveDisabled)return;const tag=e.target.closest('[part="option"]')?.dataset.value;tag!==void 0&&this.commit(tag)},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue("")}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}focus(options){this.liveDisabled||this.triggerElement?.focus(options)}blur(){this.triggerElement?.blur()}click(){this.liveDisabled||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}),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.activeScrollGeneration+=1,this.typeAheadBuffer="",this.open=!1}adoptedCallback(){super.adoptedCallback(),this.cleanup?.(),this.cleanup=void 0,this.unbindDocumentPointer(),this.clearTypeAheadTimer()}willUpdate(changed){super.willUpdate(changed),this.open&&(changed.has("locales")||changed.has("registryTick"))&&this.activeIndex>=0&&(this.activeIndex=Math.min(this.activeIndex,this.normalizedEntries.length-1),this.queueActiveScroll()),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;this.settingDefaultValue||(this._valueDirty=!0),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=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||this.restoreLiveValueFromDefault(),this.requestUpdate("defaultValue",old)}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.requestUpdate("name",old)}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&this.hide(),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}updateValidity(){this.isBarred()?this.validityController.setValidity({}):this.required&&!this._value?this.validityController.setValidity({valueMissing:!0},this.localize("localePickerRequired")):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=!1,this.restoreLiveValueFromDefault()}restoreLiveValueFromDefault(){this.settingDefaultValue=!0;try{this.value=this._defaultValue}finally{this.settingDefaultValue=!1}this._valueDirty=!1}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&this.hide(),this.updateValidity(),this.requestUpdate()}checkValidity(){return this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.syncCustomStates(),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;return raw!==void 0?raw.map(entry=>typeof entry=="string"?{tag:entry,label:localeNativeName(entry)}:{tag:entry.tag,label:entry.label??localeNativeName(entry.tag),country:entry.country}):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(){this.open||this.liveDisabled||(this.open=!0)}hide(){this.open&&(this.open=!1,this.setActiveIndex(-1))}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}syncPopup(){if(this.cleanup?.(),this.cleanup=void 0,!this.open||!this.isConnected){this.unbindDocumentPointer();return}this.bindDocumentPointer();const anchor=this.renderRoot.querySelector('[part="trigger"]'),listbox=this.renderRoot.querySelector('[part="listbox"]');anchor&&listbox&&(this.cleanup=place(anchor,listbox))}updated(changed){super.updated(changed),(changed.has("open")||this.open&&(changed.has("locales")||changed.has("registryTick")))&&this.syncPopup(),(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(),this.emit("lr-change",{value:tag,previousValue,direction:getLyraLocaleDirection(tag)},{cancelable:!0}).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(()=>{this.typeAheadTimerGeneration!==generation||!this.isConnected||this.ownerDocument.defaultView!==ownerWindow||(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,currentIndex=rows.findIndex(r=>r.tag===currentTag),n=rows.length;for(let step=1;step<=n;step++){const idx=(currentIndex+step+n)%n,row=rows[idx];if(row&&row.label.toLocaleLowerCase(this.effectiveLocale).startsWith(this.typeAheadBuffer)){this.open?this.setActiveIndex(idx):this.commit(row.tag);return}}}clearTypeAheadTimer(){this.typeAheadTimerGeneration+=1,this.typeAheadTimer!==void 0&&this.typeAheadTimerWindow?.clearTimeout(this.typeAheadTimer),this.typeAheadTimer=void 0,this.typeAheadTimerWindow=void 0}setActiveIndex(index){const last=this.normalizedEntries.length-1,next=last<0||index<0?-1:Math.min(last,index);this.activeIndex=next,this.queueActiveScroll()}queueActiveScroll(){const generation=++this.activeScrollGeneration,index=this.activeIndex;index<0||!this.open||this.updateComplete.then(()=>{generation!==this.activeScrollGeneration||!this.isConnected||!this.open||this.activeIndex!==index||this.shadowRoot?.getElementById(`${this.listId}-opt-${index}`)?.scrollIntoView({block:"nearest"})})}renderRows(rows,activeId){return rows.map((entry,i)=>{const id=`${this.listId}-opt-${i}`,selected=entry.tag===this._value;return html`<div
|
|
2
2
|
part="option"
|
|
3
3
|
id=${id}
|
|
4
4
|
role="option"
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type PropertyValues, type TemplateResult } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
-
import '../../../internal/form-control-labels.js';
|
|
4
3
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
5
4
|
import type { LyraRadio } from './radio.class.js';
|
|
6
5
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import"../../../internal/form-control-labels.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{declaredDefaultConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["radio"]),"lr-change":Object.freeze(["radio"])})}static get validators(){return[currentValidityValidator("required","disabled","value")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},orientation:{reflect:!0,converter:declaredDefaultConverter("vertical")},form:{noAccessor:!0}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormState(),this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=!0,this.selectValue(next??"")}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||(this.selectValue(this._defaultValue),this._valueDirty=!1),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get required(){return this._required}set required(next){const old=this._required;this._required=!!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=!!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=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,this.labelId=nextId("radio-group-label"),this.hintId=nextId("radio-group-hint"),this.errorId=nextId("radio-group-error"),this.managedRadios=new Set,this.syncingRadios=!1,this.membershipObserverGeneration=0,this._name="",this._value="",this._defaultValue="",this._valueDirty=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this.hasInteracted=!1,this.hadShoelaceDefaultValue=!1,this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target)))return;this.emit("lr-invalid",null,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onKeyDown=event=>{if(![...this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"],"Home","End"].includes(event.key)||this.effectiveDisabled)return;const radios=this.radios().filter(radio=>this.isRadioAvailable(radio)),current=event.target;if(!this.isRadioAvailable(current))return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl",forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight",backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft",nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index,next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onSlotChange=event=>{const slot=event.target,elements=slot.assignedElements({flatten:!0});slot.name==="label"&&(this.hasLabelSlot=elements.length>0),slot.name==="hint"&&(this.hasHintSlot=elements.length>0),slot.name==="help-text"&&(this.hasHelpTextSlot=elements.length>0),slot.name==="error"&&(this.hasErrorSlot=elements.length>0)},this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument,generation=this.membershipObserverGeneration,ownerWindow=ownerDocument?.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{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,!0),this.syncFormState(),this.updateValidity()}connectedCallback(){super.connectedCallback(),this.syncSupportSlots(),this.syncRadios(),this.armMembershipObserver(),this.armRunResizeObserver(),this.scheduleRunProjection()}armRunResizeObserver(){this.runResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerDocument?.defaultView?.ResizeObserver;if(!(!ResizeObserverCtor||!this.isConnected)){this.runResizeObserver=new ResizeObserverCtor(()=>this.scheduleRunProjection()),this.runResizeObserver.observe(this);for(const radio of this.radios())this.runResizeObserver.observe(radio)}}scheduleRunProjection(){const ownerWindow=this.ownerDocument?.defaultView;!ownerWindow||!this.isConnected||this.runProjectionFrame!==void 0||(this.runProjectionFrame=ownerWindow.requestAnimationFrame(()=>{this.runProjectionFrame=void 0,this.isConnected&&this.projectButtonRuns()}))}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}areActuallyAdjacent(first,second){const firstRect=first.getBoundingClientRect(),secondRect=second.getBoundingClientRect();if(firstRect.width<=0||firstRect.height<=0||secondRect.width<=0||secondRect.height<=0||!(Math.abs(firstRect.top-secondRect.top)<=1&&Math.abs(firstRect.bottom-secondRect.bottom)<=1))return!1;const gap=getComputedStyle(this).direction==="rtl"?firstRect.left-secondRect.right:secondRect.left-firstRect.right;return gap>=-2&&gap<=1}projectButtonRuns(){const radios=this.radios(),joinsPrevious=radios.map(()=>!1);if(this.orientation==="horizontal")for(let index=1;index<radios.length;index+=1){const previous=radios[index-1],current=radios[index];joinsPrevious[index]=this.isButtonRadio(previous)&&this.isButtonRadio(current)&&this.areActuallyAdjacent(previous,current)}for(let index=0;index<radios.length;index+=1){const joinsBefore=joinsPrevious[index]??!1,joinsAfter=joinsPrevious[index+1]??!1,position=joinsBefore?joinsAfter?"middle":"end":joinsAfter?"start":"standalone";radios[index].setButtonRunPosition(position)}}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument?.defaultView,MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||ownerWindow.queueMicrotask(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.syncRadios()})});this.membershipObserver=observer,this.membershipObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["slot","checked","disabled","value","size","appearance","hidden","inert","aria-hidden","aria-disabled","class","style"]})}disconnectedCallback(){this.resetMembershipObserver(),this.runResizeObserver?.disconnect(),this.runResizeObserver=void 0;const ownerWindow=this.ownerDocument?.defaultView;ownerWindow&&this.runProjectionFrame!==void 0&&ownerWindow.cancelAnimationFrame(this.runProjectionFrame),this.runProjectionFrame=void 0,this.releaseRadios(this.managedRadios),this.managedRadios.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed),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;for(;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;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner=="function")}isRadioAvailable(radio){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))return!1;if(current===this)break}return!0}selectValue(next){const desired=next??"",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=!0;try{for(const radio of radios)radio.checked=radio===match}finally{this.syncingRadios=!1}this.pendingSelection=void 0,this.syncRadios(match)}syncRadios(preferred){if(!this.syncingRadios){this.syncingRadios=!0;try{const radios=this.radios(),current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios)radio.setGroupOwner(this);this.managedRadios=current,this.armRunResizeObserver();for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>this.isRadioAvailable(radio));let checked=radios.filter(radio=>radio.checked),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&¤t.has(preferred)?preferred:checked[checked.length-1];for(const radio of checked)radio!==checkedRadio&&(radio.checked=!1);const tabbableRadio=checkedRadio&&this.isRadioAvailable(checkedRadio)?checkedRadio:enabled[0];for(const radio of radios)radio.setGroupSize(this.size),radio.setGroupRequired(this.required&&!this.effectiveDisabled),radio.setGroupTabbable(radio===tabbableRadio);const oldValue=this._value;this._value=checkedRadio?.value??"",this.syncFormState(),this.updateValidity(),oldValue!==this._value&&this.requestUpdate("value",oldValue),this.scheduleRunProjection()}finally{this.syncingRadios=!1}}}releaseRadios(radios){for(const radio of radios)radio.releaseGroupOwner(this),radio.setButtonRunPosition("standalone")}reconcileRadio(radio){return this.ownsRadio(radio)?(this.syncRadios(radio.checked?radio:void 0),!0):!1}releaseRadio(radio){this.managedRadios.has(radio)&&(this.releaseRadios([radio]),this.managedRadios.delete(radio),this.syncRadios())}radioCheckedChanged(radio){this.syncingRadios||!this.ownsRadio(radio)||(this._valueDirty=!0,this.syncRadios(radio.checked?radio:void 0))}selectRadio(radio){if(this.effectiveDisabled||!this.ownsRadio(radio)||!this.isRadioAvailable(radio))return!1;this._valueDirty=!0,this.hasInteracted=!0,this.syncingRadios=!0;try{for(const candidate of this.radios())candidate.checked=candidate===radio}finally{this.syncingRadios=!1}return this.syncRadios(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:radio.value,radio}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:radio.value,radio}),!0}focus(options){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}blur(){this.radios().find(radio=>radio.matches(":focus-within"))?.blur()}click(){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){this.internals&&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:!0}:{},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(){return this.hasInteracted=!0,this.updateValidity(),this.internals.reportValidity()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.reflectValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message=""){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity()}formResetCallback(){this._valueDirty=!1,this.pendingSelection=void 0,this.syncingRadios=!0;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=!1}this.defaultValue&&(this.pendingSelection=this.defaultValue),this.hasInteracted=!1,this.syncRadios()}formStateRestoreCallback(state2,reason){this._valueDirty=!0,this.hasInteracted=!1,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||!!this.label||this.withLabel,hasAccessibleLabel=this.hasAttribute("aria-label")||!!this.accessibleLabel,hasHint=this.hasHintSlot||this.hasHelpTextSlot||!!(this.hint||this.helpText)||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,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--)(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{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();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{declaredDefaultConverter,omittedEmptyStringConverter}from"../../../internal/converters.js";import{isAccessibilitySubtreeExcluded,isAriaTrue}from"../../../internal/accessibility-visibility.js";import{composedParentElement}from"../../../internal/active-element.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_radioRequired}from"../../../internal/default-strings.generated.js";const RADIO_TAGS=()=>[tag("radio"),tag("radio-button")];class LyraRadioGroup extends LyraElement{static{this.defaultStrings={...super.defaultStrings,radioRequired:LYRA_DEFAULT_radioRequired}}static{this.immutableEventDetails=Object.freeze(["lr-input","lr-change"])}static{this.identityEventDetailProperties=Object.freeze({"lr-input":Object.freeze(["radio"]),"lr-change":Object.freeze(["radio"])})}static get validators(){return[currentValidityValidator("required","disabled","value")]}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,groupStyles]}static{this.properties={name:{reflect:!0,noAccessor:!0,converter:omittedEmptyStringConverter},value:{attribute:!1,noAccessor:!0},defaultValue:{attribute:"value",reflect:!0,useDefault:!0,noAccessor:!0},customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},orientation:{reflect:!0,converter:declaredDefaultConverter("vertical")},form:{noAccessor:!0}}}get name(){return this._name}set name(next){const old=this._name;this._name=next??"",this._name?this.setAttribute("name",this._name):this.removeAttribute("name"),this.syncFormState(),this.requestUpdate("name",old)}get value(){return this._value}set value(next){this._valueDirty=!0,this.selectValue(next??"")}get defaultValue(){return this._defaultValue}set defaultValue(next){if(this.reflectingDefaultValue)return;const old=this._defaultValue;this._defaultValue=next??"",this.reflectingDefaultValue=!0;try{this._defaultValue?this.setAttribute("value",this._defaultValue):this.removeAttribute("value")}finally{this.reflectingDefaultValue=!1}this._valueDirty||(this.selectValue(this._defaultValue),this._valueDirty=!1),this.requestUpdate("defaultValue",old)}get customError(){return this.validityController?.customValidityMessage||null}set customError(next){this.reflectingCustomError||this.commitCustomValidity(next)}get required(){return this._required}set required(next){const old=this._required;this._required=!!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=!!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=!1,this.withHint=!1,this.errorText="",this.accessibleLabel="",this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasHelpTextSlot=!1,this.hasErrorSlot=!1,this.labelId=nextId("radio-group-label"),this.hintId=nextId("radio-group-hint"),this.errorId=nextId("radio-group-error"),this.managedRadios=new Set,this.syncingRadios=!1,this.membershipObserverGeneration=0,this._name="",this._value="",this._defaultValue="",this._valueDirty=!1,this.reflectingDefaultValue=!1,this.reflectingCustomError=!1,this._required=!1,this._disabled=!1,this._fieldsetDisabled=!1,this.hasInteracted=!1,this.hadShoelaceDefaultValue=!1,this.onInvalid=event=>{const target=event.target;if(target!==this&&!(target?.nodeType===1&&this.ownsRadio(target)))return;this.emit("lr-invalid",null,{cancelable:!0}).defaultPrevented&&event.preventDefault()},this.onKeyDown=event=>{if(![...this.orientation==="horizontal"?["ArrowRight","ArrowLeft"]:["ArrowDown","ArrowUp"],"Home","End"].includes(event.key)||this.effectiveDisabled)return;const radios=this.radios().filter(radio=>this.isRadioAvailable(radio)),current=event.target;if(!this.isRadioAvailable(current))return;const index=radios.indexOf(current);if(index<0||radios.length===0)return;event.preventDefault();const rtl=this.effectiveDirection==="rtl",forward=this.orientation==="vertical"?event.key==="ArrowDown":rtl?event.key==="ArrowLeft":event.key==="ArrowRight",backward=this.orientation==="vertical"?event.key==="ArrowUp":rtl?event.key==="ArrowRight":event.key==="ArrowLeft",nextIndex=event.key==="Home"?0:event.key==="End"?radios.length-1:forward?(index+1)%radios.length:backward?(index-1+radios.length)%radios.length:index,next=radios[nextIndex];next.focus(),next.activateFromGroup()},this.onSlotChange=event=>{const slot=event.target,elements=slot.assignedElements({flatten:!0});slot.name==="label"&&(this.hasLabelSlot=elements.length>0),slot.name==="hint"&&(this.hasHintSlot=elements.length>0),slot.name==="help-text"&&(this.hasHelpTextSlot=elements.length>0),slot.name==="error"&&(this.hasErrorSlot=elements.length>0)},this.onRadioSlotChange=()=>{this.syncRadios();const ownerDocument=this.ownerDocument,generation=this.membershipObserverGeneration,ownerWindow=ownerDocument?.defaultView;ownerWindow&&ownerWindow.queueMicrotask(()=>{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,!0),this.syncFormState(),this.updateValidity()}connectedCallback(){super.connectedCallback(),this.syncSupportSlots(),this.syncRadios(),this.armMembershipObserver(),this.armRunResizeObserver(),this.scheduleRunProjection()}armRunResizeObserver(){this.runResizeObserver?.disconnect();const ResizeObserverCtor=this.ownerDocument?.defaultView?.ResizeObserver;if(!(!ResizeObserverCtor||!this.isConnected)){this.runResizeObserver=new ResizeObserverCtor(()=>this.scheduleRunProjection()),this.runResizeObserver.observe(this);for(const radio of this.radios())this.runResizeObserver.observe(radio)}}scheduleRunProjection(){const ownerWindow=this.ownerDocument?.defaultView;!ownerWindow||!this.isConnected||this.runProjectionFrame!==void 0||(this.runProjectionFrame=ownerWindow.requestAnimationFrame(()=>{this.runProjectionFrame=void 0,this.isConnected&&this.projectButtonRuns()}))}isButtonRadio(radio){return radio.localName===tag("radio-button")||radio.appearance==="button"}areActuallyAdjacent(first,second){const firstRect=first.getBoundingClientRect(),secondRect=second.getBoundingClientRect();if(firstRect.width<=0||firstRect.height<=0||secondRect.width<=0||secondRect.height<=0||!(Math.abs(firstRect.top-secondRect.top)<=1&&Math.abs(firstRect.bottom-secondRect.bottom)<=1))return!1;const gap=getComputedStyle(this).direction==="rtl"?firstRect.left-secondRect.right:secondRect.left-firstRect.right;return gap>=-2&&gap<=1}projectButtonRuns(){const radios=this.radios(),joinsPrevious=radios.map(()=>!1);if(this.orientation==="horizontal")for(let index=1;index<radios.length;index+=1){const previous=radios[index-1],current=radios[index];joinsPrevious[index]=this.isButtonRadio(previous)&&this.isButtonRadio(current)&&this.areActuallyAdjacent(previous,current)}for(let index=0;index<radios.length;index+=1){const joinsBefore=joinsPrevious[index]??!1,joinsAfter=joinsPrevious[index+1]??!1,position=joinsBefore?joinsAfter?"middle":"end":joinsAfter?"start":"standalone";radios[index].setButtonRunPosition(position)}}armMembershipObserver(){const ownerDocument=this.ownerDocument;if(!this.isConnected||this.membershipObserver&&this.membershipObserverDocument===ownerDocument)return;this.resetMembershipObserver();const ownerWindow=ownerDocument?.defaultView,MutationObserverCtor=ownerWindow?.MutationObserver;if(!ownerWindow||!MutationObserverCtor)return;const generation=this.membershipObserverGeneration,observer=new MutationObserverCtor(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||ownerWindow.queueMicrotask(()=>{this.membershipObserver!==observer||this.membershipObserverDocument!==ownerDocument||this.membershipObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.syncRadios()})});this.membershipObserver=observer,this.membershipObserverDocument=ownerDocument,observer.observe(this,{attributes:!0,childList:!0,subtree:!0,attributeFilter:["slot","checked","disabled","value","size","appearance","hidden","inert","aria-hidden","aria-disabled","class","style"]})}disconnectedCallback(){this.resetMembershipObserver(),this.runResizeObserver?.disconnect(),this.runResizeObserver=void 0;const ownerWindow=this.ownerDocument?.defaultView;ownerWindow&&this.runProjectionFrame!==void 0&&ownerWindow.cancelAnimationFrame(this.runProjectionFrame),this.runProjectionFrame=void 0,this.releaseRadios(this.managedRadios),this.managedRadios.clear(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetMembershipObserver()}resetMembershipObserver(){this.membershipObserverGeneration+=1,this.membershipObserver?.disconnect(),this.membershipObserver=void 0,this.membershipObserverDocument=void 0}willUpdate(changed){super.willUpdate(changed),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;for(;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;return typeof querySelectorAll!="function"?[]:[...querySelectorAll.call(this,RADIO_TAGS().join(","))].filter(radio=>this.ownsRadio(radio)&&typeof radio.setGroupOwner=="function")}isRadioAvailable(radio){if(radio.effectiveDisabled||radio.matches(":disabled"))return!1;for(let current=radio;current;current=composedParentElement(current)){if(isAccessibilitySubtreeExcluded(current)||isAriaTrue(current.getAttribute("aria-disabled")))return!1;if(current===this)break}return!0}selectValue(next){const desired=next??"",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=!0;try{for(const radio of radios)radio.checked=radio===match}finally{this.syncingRadios=!1}this.pendingSelection=void 0,this.syncRadios(match)}syncRadios(preferred){if(!this.syncingRadios){this.syncingRadios=!0;try{const radios=this.radios(),current=new Set(radios);this.releaseRadios([...this.managedRadios].filter(radio=>!current.has(radio)));for(const radio of radios)radio.setGroupOwner(this);this.managedRadios=current,this.armRunResizeObserver();for(const radio of radios)radio.setGroupDisabled(this.effectiveDisabled);const enabled=radios.filter(radio=>this.isRadioAvailable(radio));let checked=radios.filter(radio=>radio.checked),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&¤t.has(preferred)?preferred:checked[checked.length-1];for(const radio of checked)radio!==checkedRadio&&(radio.checked=!1);const tabbableRadio=checkedRadio&&this.isRadioAvailable(checkedRadio)?checkedRadio:enabled[0];for(const radio of radios)radio.setGroupSize(this.size),radio.setGroupRequired(this.required&&!this.effectiveDisabled),radio.setGroupTabbable(radio===tabbableRadio);const oldValue=this._value;this._value=checkedRadio?.value??"",this.syncFormState(),this.updateValidity(),oldValue!==this._value&&this.requestUpdate("value",oldValue),this.scheduleRunProjection()}finally{this.syncingRadios=!1}}}releaseRadios(radios){for(const radio of radios)radio.releaseGroupOwner(this),radio.setButtonRunPosition("standalone")}reconcileRadio(radio){return this.ownsRadio(radio)?(this.syncRadios(radio.checked?radio:void 0),!0):!1}releaseRadio(radio){this.managedRadios.has(radio)&&(this.releaseRadios([radio]),this.managedRadios.delete(radio),this.syncRadios())}radioCheckedChanged(radio){this.syncingRadios||!this.ownsRadio(radio)||(this._valueDirty=!0,this.syncRadios(radio.checked?radio:void 0))}selectRadio(radio){if(this.effectiveDisabled||!this.ownsRadio(radio)||!this.isRadioAvailable(radio))return!1;this._valueDirty=!0,this.hasInteracted=!0,this.syncingRadios=!0;try{for(const candidate of this.radios())candidate.checked=candidate===radio}finally{this.syncingRadios=!1}return this.syncRadios(),dispatchNativeInputEvent(this),this.emit("lr-input",{value:radio.value,radio}),dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:radio.value,radio}),!0}focus(options){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.focus(options)}blur(){this.radios().find(radio=>radio.matches(":focus-within"))?.blur()}click(){if(this.effectiveDisabled||this.matches(":disabled"))return;const enabled=this.radios().filter(radio=>this.isRadioAvailable(radio));(enabled.find(radio=>radio.checked)??enabled[0])?.click()}[VALIDITY_ANCHOR](){return this.renderRoot?.querySelector('[part~="base"]')??null}syncFormState(){this.internals&&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:!0}:{},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(){return this.hasInteracted=!0,this.updateValidity(),this.internals.reportValidity()}commitCustomValidity(message){const old=this.customError,normalized=message??"";this.validityController.setCustomValidity(normalized),this.reflectValidityStates(),this.reflectingCustomError=!0;try{normalized?this.setAttribute("custom-error",normalized):this.removeAttribute("custom-error")}finally{this.reflectingCustomError=!1}this.requestUpdate("customError",old)}setCustomValidity(message=""){this.commitCustomValidity(message)}resetValidity(){this.commitCustomValidity(""),this.updateValidity()}formResetCallback(){this._valueDirty=!1,this.pendingSelection=void 0,this.syncingRadios=!0;try{for(const radio of this.radios())radio.resetFromGroup()}finally{this.syncingRadios=!1}this.defaultValue&&(this.pendingSelection=this.defaultValue),this.hasInteracted=!1,this.syncRadios()}formStateRestoreCallback(state2,reason){this._valueDirty=!0,this.hasInteracted=!1,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||!!this.label||this.withLabel,hasAccessibleLabel=this.hasAttribute("aria-label")||!!this.accessibleLabel,hasHint=this.hasHintSlot||this.hasHelpTextSlot||!!(this.hint||this.helpText)||this.withHint,hasError=this.hasErrorSlot||!!this.errorText,described=[hasHint?this.hintId:"",hasError?this.errorId:""].filter(Boolean).join(" ")||nothing;return html`
|
|
2
2
|
<div part="base" role="radiogroup"
|
|
3
3
|
aria-label=${hasAccessibleLabel?this.accessibleLabel:nothing}
|
|
4
4
|
aria-labelledby=${!hasAccessibleLabel&&hasLabel?this.labelId:nothing}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { type TemplateResult } from 'lit';
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
|
-
import '../../../internal/form-control-labels.js';
|
|
4
3
|
import type { LyraSize } from '../../../internal/variants.js';
|
|
5
4
|
import { type FormOwnerValue } from '../../../internal/form-associated.js';
|
|
6
5
|
import { type LyraFormValidator } from '../form-validator.js';
|