@aceshooting/lyra-ui 14.3.1 → 15.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +127 -0
- package/custom-elements.json +1 -1
- package/design-tokens.json +1 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +4 -0
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +3 -3
- package/dist/components/agent-tools/approval-queue/approval-queue.class.js +3 -2
- package/dist/components/agent-tools/artifact-panel/artifact-panel.styles.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.styles.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.styles.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +8 -3
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.d.ts +3 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +10 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.styles.js +1 -1
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.d.ts +19 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +4 -4
- package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.d.ts +5 -0
- package/dist/components/agent-tools/task-list/task-list.class.js +3 -3
- package/dist/components/agent-tools/terminal/terminal.class.d.ts +1 -1
- package/dist/components/agent-tools/terminal/terminal.styles.js +1 -1
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +10 -7
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +15 -14
- package/dist/components/agent-tools/tool-param-form/tool-param-form.d.ts +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.styles.js +1 -1
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.d.ts +5 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.d.ts +3 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +9 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.styles.js +1 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +64 -4
- package/dist/components/charts/chart/box-plot.class.js +5 -5
- package/dist/components/charts/chart/chart-colors.d.ts +10 -0
- package/dist/components/charts/chart/chart-colors.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +35 -10
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart.class.d.ts +10 -2
- package/dist/components/charts/chart/lite-chart.styles.js +1 -1
- package/dist/components/conversation/markdown/markdown.class.d.ts +9 -1
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +18 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +4 -4
- package/dist/components/conversation/model-select/model-select.class.d.ts +6 -2
- package/dist/components/conversation/model-select/model-select.class.js +3 -3
- package/dist/components/conversation/prompt-input/prompt-input.styles.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/data/calendar/calendar.class.js +2 -2
- package/dist/components/data/context-meter/context-meter.styles.js +1 -1
- package/dist/components/data/data-grid/data-grid-types.d.ts +8 -2
- package/dist/components/data/data-grid/data-grid.class.d.ts +16 -3
- package/dist/components/data/data-grid/data-grid.class.js +3 -2
- package/dist/components/data/env-list/env-list.styles.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +22 -2
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +12 -4
- package/dist/components/data/flow-minimap/flow-minimap.class.js +2 -2
- package/dist/components/data/flow-minimap/flow-minimap.styles.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +5 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +12 -1
- package/dist/components/data/heatmap/heatmap.class.js +3 -3
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/date-picker/date-picker.class.d.ts +12 -1
- package/dist/components/forms/date-picker/date-picker.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +27 -5
- package/dist/components/forms/icon-button/icon-button.class.js +7 -3
- package/dist/components/forms/input/input.styles.js +1 -1
- package/dist/components/forms/input/time-input.class.d.ts +13 -2
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.d.ts +8 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +4 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.d.ts +9 -4
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +7 -2
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/card/card.class.js +2 -2
- package/dist/components/layout/card/card.styles.js +1 -1
- package/dist/components/layout/control-group/control-group.class.js +1 -1
- package/dist/components/layout/dashboard-grid/dashboard-grid.styles.js +1 -1
- package/dist/components/layout/details/details.styles.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.d.ts +13 -3
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/menu/dropdown-item.class.d.ts +2 -0
- package/dist/components/layout/menu/menu-item.class.d.ts +28 -1
- package/dist/components/layout/menu/menu-item.class.js +45 -35
- package/dist/components/layout/menu/menu-item.styles.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +12 -2
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/page/page.class.js +2 -1
- package/dist/components/layout/page/page.styles.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +2 -2
- package/dist/components/layout/responsive-panel/responsive-panel.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.class.js +2 -2
- package/dist/components/layout/tab-group/tab-group.class.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.js +2 -2
- package/dist/components/layout/widget/widget.class.d.ts +12 -2
- package/dist/components/layout/widget/widget.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/file-icon/file-icon.class.d.ts +3 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.styles.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.class.d.ts +5 -5
- package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.styles.js +1 -1
- package/dist/components/media/lightbox/lightbox.styles.js +1 -1
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.styles.js +1 -1
- package/dist/components/overlays/alert/alert.class.d.ts +6 -0
- package/dist/components/overlays/alert/alert.styles.js +1 -1
- package/dist/components/overlays/badge/tag.class.js +1 -1
- package/dist/components/overlays/chip/chip.class.js +1 -1
- package/dist/components/overlays/empty/empty.class.js +2 -2
- package/dist/components/overlays/kbd/kbd.styles.js +1 -1
- package/dist/components/overlays/progress/progress-ring.class.d.ts +4 -1
- package/dist/components/overlays/progress/progress.styles.js +1 -1
- package/dist/components/overlays/toast/toast.styles.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +10 -3
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/graph/graph.styles.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +6 -6
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +2 -2
- package/dist/components/retrieval/mind-map/mind-map.styles.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +3 -3
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/node-palette/node-palette.class.d.ts +7 -1
- package/dist/components/retrieval/node-palette/node-palette.class.js +23 -13
- package/dist/components/retrieval/node-palette/node-palette.styles.js +1 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +4 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +4 -3
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-list/source-list.class.d.ts +7 -1
- package/dist/components/retrieval/source-list/source-list.class.js +1 -1
- package/dist/components/utility/export-button/export-button.class.d.ts +14 -2
- package/dist/components/utility/export-button/export-button.class.js +3 -3
- package/dist/components/utility/export-button/export-button.styles.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.d.ts +4 -2
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.d.ts +9 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +4 -4
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.d.ts +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +4 -4
- package/dist/components/viewers/document-compare/document-compare.class.d.ts +5 -0
- package/dist/components/viewers/document-compare/document-compare.class.js +9 -4
- package/dist/components/viewers/document-compare/document-compare.styles.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.d.ts +9 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +2 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.d.ts +5 -0
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +5 -0
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.d.ts +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +3 -3
- package/dist/components/viewers/xml-viewer/xml-viewer.styles.js +1 -1
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +5 -4
- package/dist/internal/accessibility-visibility.d.ts +13 -2
- package/dist/internal/accessibility-visibility.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-alert.md +11 -3
- package/llms/components/lr-box-plot.md +21 -4
- package/llms/components/lr-chart.md +13 -4
- package/llms/components/lr-code-block.md +5 -4
- package/llms/components/lr-data-grid.md +24 -10
- package/llms/components/lr-document-compare.md +5 -0
- package/llms/components/lr-dropdown-item.md +31 -0
- package/llms/components/lr-eval-dataset.md +5 -4
- package/llms/components/lr-export-button.md +10 -5
- package/llms/components/lr-filter-bar.md +4 -1
- package/llms/components/lr-flow-minimap.md +7 -1
- package/llms/components/lr-icon-button.md +6 -1
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-markdown.md +2 -2
- package/llms/components/lr-menu-item.md +31 -0
- package/llms/components/lr-menu.md +31 -0
- package/llms/components/lr-message-parts.md +7 -0
- package/llms/components/lr-model-settings-panel.md +4 -1
- package/llms/components/lr-node-palette.md +5 -4
- package/llms/components/lr-pdf-viewer.md +7 -0
- package/llms/components/lr-responsive-panel.md +2 -2
- package/llms/components/lr-subagent-panel.md +17 -2
- package/llms/components/lr-thinking-panel.md +4 -0
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +1 -1
- package/llms/components/lr-tool-select-dialog.md +4 -3
- package/llms/components/lr-virtual-list.md +11 -11
- package/llms-full.txt +212 -59
- package/package.json +3 -3
- package/vscode-css-data.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(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{observeReactivePropertyWrites}from"../../../internal/reactive-property-writes.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{chevronIcon}from"../../../internal/icons.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{isRtl}from"../../../internal/rtl.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{activeElementIn}from"../../../internal/active-element.js";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{styles}from"./date-picker.styles.js";import{monthMatrix,weekdayLabels,monthTitle,formatISO,parseISO,isSameDay,addMonths,addMonthsClampingDay,clampDate,dateTimeFormat,localDate,utcDate,normalizeCalendarMode,normalizeCalendarMonths,normalizeWeekdayFormat,resolveFirstDayOfWeek}from"./calendar-core.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_nextMonth,LYRA_DEFAULT_previousMonth}from"../../../internal/default-strings.generated.js";const MAX_VIEW_PERIOD_DAYS=366*10,modeConverter={fromAttribute:normalizeCalendarMode,toAttribute:normalizeCalendarMode},monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths},weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizePageBy(value){return value==="single"?"single":"months"}function normalizeView(value){return value==="months"||value==="years"||value==="decades"?value:"days"}const pageByConverter={fromAttribute:normalizePageBy,toAttribute:normalizePageBy},viewConverter={fromAttribute:normalizeView,toAttribute:normalizeView},canonicalPresetSnapshots=new WeakMap;function isSafeArray(value){try{return Array.isArray(value)}catch{return!1}}function isSafeNonArrayObject(value){if(value===null||typeof value!="object")return!1;try{return!Array.isArray(value)}catch{return!1}}function projectDateRangePreset(value){if(!isSafeNonArrayObject(value))return;const label=getOwnDataDescriptor(value,"label"),start=getOwnDataDescriptor(value,"start"),end=getOwnDataDescriptor(value,"end");if(!(label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||typeof label.value!="string"||label.value.trim().length===0||start===UNSAFE_OWN_DATA_DESCRIPTOR||end===UNSAFE_OWN_DATA_DESCRIPTOR)&&!(start!==MISSING_OWN_DATA_DESCRIPTOR&&start.value!==void 0&&typeof start.value!="string"||end!==MISSING_OWN_DATA_DESCRIPTOR&&end.value!==void 0&&typeof end.value!="string"))return Object.freeze({source:value,label:label.value,start:start===MISSING_OWN_DATA_DESCRIPTOR?void 0:start.value,end:end===MISSING_OWN_DATA_DESCRIPTOR?void 0:end.value})}function canonicalDateRangePresets(values){const cached=canonicalPresetSnapshots.get(values);if(cached)return cached;const projected=[];for(const value of values){const preset=projectDateRangePreset(value);preset&&projected.push(preset)}const snapshot=Object.freeze(projected);return canonicalPresetSnapshots.set(values,snapshot),snapshot}function copyNativeDate(value){if(value===null||typeof value!="object")return null;try{const epoch=Date.prototype.getTime.call(value);return Number.isFinite(epoch)?new Date(epoch):null}catch{return null}}const MAX_DISABLED_DATE_ENTRIES=1e4;function projectDisabledDateKeys(value){if(typeof value=="string")return Object.freeze(value.split(/[\s,]+/).map(entry=>parseISO(entry)).filter(entry=>entry!==null).map(entry=>formatISO(entry)));if(!isSafeArray(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const dates=[];for(let index=0;index<Math.min(length.value,MAX_DISABLED_DATE_ENTRIES);index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const date=typeof entry.value=="string"?parseISO(entry.value):copyNativeDate(entry.value);date&&dates.push(formatISO(date))}return Object.freeze(dates)}class LyraDatePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,nextMonth:LYRA_DEFAULT_nextMonth,previousMonth:LYRA_DEFAULT_previousMonth}}static{this.styles=[LyraElement.styles,styles]}static{this.ownedCollectionProperties=Object.freeze(["presets"])}static{this.identityCollectionProperties=Object.freeze(["presets"])}get presets(){return this._presets}set presets(next){const old=this._presets;this._presets=isSafeArray(next)?next:Object.freeze([]),this.requestUpdate("presets",old)}get appliedPreset(){return this._appliedPreset}resolvePresetRange(preset){const bound=(own,fallback)=>{const text=typeof own=="string"&&own.trim()?own:fallback;return text?parseISO(text):null},min=parseISO(this.min),max=parseISO(this.max);if(min&&max&&min>max)return null;const start=bound(preset.start,this.min),end=bound(preset.end,this.max);if(!start||!end)return null;let from=clampDate(start,min,max),to=clampDate(end,min,max);return to<from&&([from,to]=[to,from]),this.admitsRange(from,to,min,max,this.resolvedToday())?{from,to}:null}static get observedAttributes(){const attributes=super.observedAttributes;return observeReactivePropertyWrites(this.prototype,["previousLabel","nextLabel"],(instance,name,value)=>{const authored=value!=null;let ownershipChanged=!1;switch(name){case"previousLabel":if(instance.previousLabelAuthored===void 0)return;ownershipChanged=authored!==instance.previousLabelAuthored,instance.previousLabelAuthored=authored;break;case"nextLabel":if(instance.nextLabelAuthored===void 0)return;ownershipChanged=authored!==instance.nextLabelAuthored,instance.nextLabelAuthored=authored;break}ownershipChanged&&instance.requestUpdate()}),attributes}constructor(){super(),this.value="",this.mode="single",this.min="",this.max="",this.disabled=!1,this.readonly=!1,this.months=1,this.size="m",this.locale="",this.firstDayOfWeek="auto",this.weekdayFormat="short",this.disablePast=!1,this.disableFuture=!1,this.withOutsideDays=!1,this.withWeekNumbers=!1,this.disabledDates="",this.disabledDaysOfWeek="",this._presets=Object.freeze([]),this.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.focusedDate="",this.view="days",this.previousLabel="Previous month",this.previousLabelAuthored=!1,this.nextLabel="Next month",this.nextLabelAuthored=!1,this.viewDate=localDate(new Date().getFullYear(),new Date().getMonth(),1),this.rangePreview=null,this.focusedViewStart="",this.focusPending=!1,this.viewFocusPending=!1,this.restoringViewFocus=!1,this.internals=attachInternalsSafely(this),this.disabledDatesCache=new Set,this.disabledWeekdaysCache=new Set,this.viewPeriodAvailabilityCache=new Map,this.titleIds=[nextId("date-picker-title"),nextId("date-picker-title")],this.onViewGridKey=event=>{const view=this.effectiveView;if(view==="days")return;const periods=this.viewPeriods(view),source=event.composedPath().find(node=>node instanceof HTMLElement&&node.hasAttribute("data-view-start")),currentSource=parseISO(source?.getAttribute("data-view-start")??"")??this.resolveViewFocus(periods);if(!currentSource)return;const current=this.viewPeriodStart(currentSource,view),span=this.viewPeriodMonths(view),rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=null;switch(event.key){case backwardKey:next=this.firstEnabledViewPeriod(addMonths(current,-span),-1);break;case forwardKey:next=this.firstEnabledViewPeriod(addMonths(current,span),1);break;case"ArrowUp":next=this.firstEnabledViewPeriod(addMonths(current,-4*span),-1);break;case"ArrowDown":next=this.firstEnabledViewPeriod(addMonths(current,4*span),1);break;case"Home":next=periods.find(period=>!this.viewPeriodDisabled(period.start,period.end))?.start??null;break;case"End":next=[...periods].reverse().find(period=>!this.viewPeriodDisabled(period.start,period.end))?.start??null;break;case"Enter":case" ":event.preventDefault(),this.pickViewItem(current);return;default:return}event.preventDefault(),next&&(this.viewDate=localDate(next.getFullYear(),next.getMonth(),1),this.focusViewPeriod(next,view))},this.onGridKey=e=>{const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday(),current=this.focusedDateValue??this.selection.from??this.firstEnabledDate(min,max,today)??localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),step=(base,days)=>localDate(base.getFullYear(),base.getMonth(),base.getDate()+days),firstEnabledFrom=(base,dayStep)=>{let d=base;for(let i=0;i<366;i++){if(d.getFullYear()<0||d.getFullYear()>9999)return null;if(!this.isDisabled(d,min,max,today))return d;d=step(d,dayStep)}return null},rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=null;switch(e.key){case backwardKey:next=firstEnabledFrom(step(current,-1),-1);break;case forwardKey:next=firstEnabledFrom(step(current,1),1);break;case"ArrowUp":next=firstEnabledFrom(step(current,-7),-1);break;case"ArrowDown":next=firstEnabledFrom(step(current,7),1);break;case"PageUp":next=firstEnabledFrom(addMonthsClampingDay(current,-1),1);break;case"PageDown":next=firstEnabledFrom(addMonthsClampingDay(current,1),1);break;case"Home":next=firstEnabledFrom(localDate(current.getFullYear(),current.getMonth(),1),1);break;case"End":next=firstEnabledFrom(localDate(current.getFullYear(),current.getMonth()+1,0),-1);break;case"Enter":case" ":e.preventDefault(),this.selectDate(current);return;default:return}e.preventDefault(),next&&(this.setFocusedDate(next),this.viewDate=this.viewDateForFocus(next),this.focusPending=!0)},observeScrollOverflow(this,()=>this.renderRoot.querySelectorAll(".calendar-scroll")[0]),observeScrollOverflow(this,()=>this.renderRoot.querySelectorAll(".calendar-scroll")[1])}get effectiveMode(){return normalizeCalendarMode(this.mode)}get visibleMonths(){return normalizeCalendarMonths(this.months)}get effectiveWeekdayFormat(){return normalizeWeekdayFormat(this.weekdayFormat)}get effectiveView(){return normalizeView(this.view)}get selection(){const parts=(this.value??"").split("/");return{from:parseISO(parts[0]??""),to:parseISO(parts[1]??"")}}set selection(next){this.valueAsRange=next}get valueAsDate(){return this.effectiveMode==="single"?this.selection.from:null}set valueAsDate(next){const date=copyNativeDate(next);if(!date){this.value="";return}this.value=formatISO(date)}get valueAsRange(){return this.effectiveMode==="range"?this.selection:{from:null,to:null}}set valueAsRange(next){let from=copyNativeDate(next?.from),to=copyNativeDate(next?.to);from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get focusedDateValue(){return parseISO(this.focusedDate)}setFocusedDate(date){this.focusedDate=date?formatISO(date):""}resolvedToday(){const today=parseISO(this.today)??new Date;return localDate(today.getFullYear(),today.getMonth(),today.getDate())}syncCustomStates(){setCustomState(this.internals,"disabled",this.disabled),setCustomState(this.internals,"range",this.effectiveMode==="range"),setCustomState(this.internals,"readonly",this.readonly)}willUpdate(changed){super.willUpdate(changed),this.viewPeriodAvailabilityCache.clear();const activeElement=activeElementIn(this.renderRoot),activeViewStart=activeElement?.matches('[part~="view-item"]')?parseISO(activeElement.getAttribute("data-view-start")??""):null;if(changed.has("value")){const external=this.committedValue!==this.value;if(this.committedValue=void 0,external&&(this._appliedPreset=void 0),external&&this.value){const from=this.selection.from;from&&(this.viewDate=localDate(from.getFullYear(),from.getMonth(),1))}}if(changed.has("focusedDate")){const focused=this.focusedDateValue;focused&&!this.isVisibleDate(focused)&&(this.viewDate=this.viewDateForFocus(focused))}const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday();if(this.viewDate=this.clampViewAnchor(this.viewDate),this.normalizeFocusedDate(min,max,today),this.clampViewDateToEnabledPeriod(),this.syncCustomStates(),activeViewStart&&this.effectiveView!=="days"){const next=this.resolveViewFocus(this.viewPeriods());next&&!isSameDay(activeViewStart,next)&&(this.setFocusedViewStart(next),this.viewFocusPending=!0)}}get fdow(){return resolveFirstDayOfWeek(this.firstDayOfWeek,this.effectiveLocale)}get disabledDateKeys(){return this.disabledDatesCacheSource===this.disabledDates?this.disabledDatesCache:(this.disabledDatesCacheSource=this.disabledDates,this.disabledDatesCache=new Set(projectDisabledDateKeys(this.disabledDates)),this.disabledDatesCache)}get disabledWeekdays(){if(this.disabledWeekdaysCacheSource===this.disabledDaysOfWeek)return this.disabledWeekdaysCache;this.disabledWeekdaysCacheSource=this.disabledDaysOfWeek;const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6},parsed=String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0);return this.disabledWeekdaysCache=new Set(parsed),this.disabledWeekdaysCache}rangeLength(from,to){const fromUtc=utcDate(from.getFullYear(),from.getMonth(),from.getDate()).getTime(),toUtc=utcDate(to.getFullYear(),to.getMonth(),to.getDate()).getTime();return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}isDisabled(d,min,max,today,pendingRange=!0){if(!Number.isFinite(d.getTime())||d.getFullYear()<0||d.getFullYear()>9999||this.disabled||this.readonly||min&&d<min||max&&d>max||this.disablePast&&d<today||this.disableFuture&&d>today||this.disabledDateKeys.has(formatISO(d))||this.disabledWeekdays.has(d.getDay()))return!0;try{if(this.isDateDisabled?.(new Date(d.getTime())))return!0}catch{}if(pendingRange&&this.effectiveMode==="range"){const{from,to}=this.selection;if(from&&!to&&!isSameDay(from,d)){const length=this.rangeLength(from,d),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);if(minimum>0&&length<minimum||maximum>0&&length>maximum)return!0}}return!1}nearestEnabledDate(anchor,min,max,today){let lower=min??localDate(0),upper=max??localDate(9999,11,31);if(this.disablePast&&today>lower&&(lower=today),this.disableFuture&&today<upper&&(upper=today),lower>upper)return null;if(anchor=clampDate(anchor,lower,upper),!this.isDisabled(anchor,min,max,today))return new Date(anchor.getTime());for(let distance=1;distance<=732;distance++){const before=localDate(anchor.getFullYear(),anchor.getMonth(),anchor.getDate()-distance);if(!this.isDisabled(before,min,max,today))return before;const after=localDate(anchor.getFullYear(),anchor.getMonth(),anchor.getDate()+distance);if(!this.isDisabled(after,min,max,today))return after}return null}isVisibleDate(date){const start=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),end=addMonths(start,this.visibleMonths);return date>=start&&date<end}normalizeFocusedDate(min,max,today){const anchor=this.focusedDateValue??this.selection.from??(this.effectiveView==="days"?this.viewDate:null);if(!anchor)return;const disabled=this.isDisabled(anchor,min,max,today);if(!disabled&&this.isVisibleDate(anchor))return;const next=disabled?this.nearestEnabledDate(anchor,min,max,today):this.firstEnabledDate(min,max,today);if(!next){this.setFocusedDate(null),this.focusPending=!1;return}this.setFocusedDate(next),this.viewDate=this.viewDateForFocus(next);const active=activeElementIn(this.renderRoot);disabled&&active?.matches('[part~="day"]')&&(this.constraintFocusOwner=active,this.focusPending=!0)}firstEnabledDate(min,max,today){let d=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1);const lastVisibleMonth=addMonths(d,this.visibleMonths-1),boundEnd=localDate(lastVisibleMonth.getFullYear(),lastVisibleMonth.getMonth()+1,0);for(let i=0;i<732&&d<=boundEnd;i++){if(!this.isDisabled(d,min,max,today))return d;d=localDate(d.getFullYear(),d.getMonth(),d.getDate()+1)}return null}admitsRange(from,to,min,max,today){if(this.isDisabled(from,min,max,today,!1)||this.isDisabled(to,min,max,today,!1))return!1;const length=this.rangeLength(from,to),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);return(minimum===0||length>=minimum)&&(maximum===0||length<=maximum)}commit(from,to,fire){const next=this.effectiveMode==="range"?from&&to?`${formatISO(from)}/${formatISO(to)}`:from?formatISO(from):"":from?formatISO(from):"";next!==this.value&&(this.committedValue=next),this.value=next,dispatchNativeInputEvent(this),fire&&dispatchNativeEvent(this,"change")}selectDate(date){const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday();if(this.isDisabled(date,min,max,today))return;const pending=this.selection;if(!(this.effectiveMode==="range"&&pending.from&&!pending.to&&!this.admitsRange(pending.from,date,min,max,today)))if(this._appliedPreset=void 0,this.setFocusedDate(date),this.effectiveMode==="range"){const{from,to}=this.selection;if(!from||from&&to)this.commit(date,null,!1);else{let a=from,b=date;b<a&&([a,b]=[b,a]),this.commit(a,b,!0)}}else this.commit(date,null,!0)}clear(){this._appliedPreset=void 0,this.commit(null,null,!0)}goToToday(){this.goToDate(this.resolvedToday())}goToDate(date){const d=typeof date=="string"?parseISO(date):date;if(!d||!Number.isFinite(d.getTime()))return;const midnight=localDate(d.getFullYear(),d.getMonth(),d.getDate()),clamped=clampDate(midnight,parseISO(this.min)??localDate(0),parseISO(this.max)??localDate(9999,11,31));this.viewDate=localDate(clamped.getFullYear(),clamped.getMonth(),1),this.setFocusedDate(clamped),this.focusPending=!0}clampViewAnchor(date){return clampDate(date,localDate(0),localDate(9999,12-this.visibleMonths,1))}nav(delta){const page=this.pageBy==="single"?1:this.visibleMonths;this.viewDate=this.clampViewAnchor(addMonths(this.viewDate,delta*page))}focus(options){this.renderRoot?.querySelector('[part~="day"][tabindex="0"], [part~="view-item"][tabindex="0"]:not(:disabled)')?.focus(options)}viewPeriodMonths(view=this.effectiveView){return view==="years"?12:view==="decades"?120:1}viewPeriodStart(date,view=this.effectiveView){return view==="years"?localDate(date.getFullYear(),0,1):view==="decades"?localDate(Math.floor(date.getFullYear()/10)*10,0,1):localDate(date.getFullYear(),date.getMonth(),1)}viewPageStart(view=this.effectiveView){const year=this.viewDate.getFullYear();return view==="months"?localDate(year,0,1):view==="years"?localDate(Math.floor(year/12)*12,0,1):localDate(Math.floor(year/120)*120,0,1)}viewPeriods(view=this.effectiveView){const pageStart=this.viewPageStart(view),span=this.viewPeriodMonths(view);return Array.from({length:12},(_,index)=>{const start=addMonths(pageStart,index*span);return{start,end:clampDate(localDate(start.getFullYear(),start.getMonth()+span,0),null,localDate(9999,11,31))}}).filter(period=>period.start.getFullYear()<=9999)}clampViewDateToEnabledPeriod(view=this.effectiveView){if(view==="days")return null;const periods=this.viewPeriods(view);if(this.disabled||this.readonly||periods.some(period=>!this.viewPeriodDisabled(period.start,period.end)))return null;const first=periods[0],last=periods[periods.length-1],span=this.viewPeriodMonths(view),min=parseISO(this.min),max=parseISO(this.max),forward=min&&last.end<min,backward=max&&first.start>max,next=forward?this.firstEnabledViewPeriod(this.viewPeriodStart(min),1):backward?this.firstEnabledViewPeriod(this.viewPeriodStart(max),-1):this.firstEnabledViewPeriod(addMonths(last.start,span),1)??this.firstEnabledViewPeriod(addMonths(first.start,-span),-1);return next?(this.viewDate=localDate(next.getFullYear(),next.getMonth(),1),next):null}resolveViewFocus(periods){const inView=candidate=>{if(!candidate)return null;const start=this.viewPeriodStart(candidate),period=periods.find(item=>isSameDay(item.start,start));return period&&!this.viewPeriodDisabled(period.start,period.end)?period.start:null},fallback=periods.find(period=>!this.viewPeriodDisabled(period.start,period.end));return inView(parseISO(this.focusedViewStart))??inView(this.selection.from)??inView(this.viewDate)??fallback?.start??null}setFocusedViewStart(date,view=this.effectiveView,requestUpdate=!1){const next=formatISO(this.viewPeriodStart(date,view));this.focusedViewStart!==next&&(this.focusedViewStart=next,requestUpdate&&this.requestUpdate())}onViewItemFocus(start){this.restoringViewFocus||this.setFocusedViewStart(start,this.effectiveView,!0)}firstEnabledViewPeriod(start,direction){const span=this.viewPeriodMonths();let candidate=this.viewPeriodStart(start);for(let index=0;index<366;index++){if(candidate.getFullYear()<0||candidate.getFullYear()>9999)return null;const end=localDate(candidate.getFullYear(),candidate.getMonth()+span,0);if(!this.viewPeriodDisabled(candidate,end))return candidate;candidate=addMonths(candidate,direction*span)}return null}focusViewPeriod(date,view=this.effectiveView){this.setFocusedViewStart(date,view),this.viewFocusPending=!0}setView(next,date=this.viewDate){next!==this.view&&(this.view=next,this.emit("lr-view-change",{view:next,date:new Date(date.getTime())}))}advanceView(){const next={days:"months",months:"years",years:"decades",decades:"decades"},current=this.effectiveView,nextView=next[current];if(nextView===current)return;const focused=current==="days"?this.focusedDateValue??this.selection.from??this.viewDate:this.resolveViewFocus(this.viewPeriods(current))??this.viewDate;this.focusViewPeriod(focused,nextView),this.setView(nextView)}onDayFocus(date){this.setFocusedDate(date),this.emit("lr-focus-day",{date:new Date(date.getTime())})}viewDateForFocus(next){const firstMonth=this.clampViewAnchor(localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1)),nextMonth=localDate(next.getFullYear(),next.getMonth(),1),lastMonth=addMonths(firstMonth,this.visibleMonths-1);return nextMonth<firstMonth?nextMonth:nextMonth>lastMonth?addMonths(nextMonth,-(this.visibleMonths-1)):firstMonth}updated(changed){super.updated(changed);const focusedDate=this.focusedDateValue,repairOwner=this.constraintFocusOwner;this.constraintFocusOwner=void 0;const active=activeElementIn(this.renderRoot);if(repairOwner&&active!==repairOwner&&(active!==null||activeElementIn(this.ownerDocument)!==this.ownerDocument.body)&&(this.focusPending=!1),this.focusPending&&focusedDate){this.focusPending=!1;const iso=formatISO(focusedDate);this.renderRoot.querySelector(`[data-date="${iso}"][tabindex="0"]`)?.focus()}if(this.viewFocusPending){this.viewFocusPending=!1;const item=this.renderRoot.querySelector('[part~="view-item"][tabindex="0"]:not(:disabled)');if(item){this.restoringViewFocus=!0;try{item.focus()}finally{this.restoringViewFocus=!1}}}}renderDay(date,shownMonth,selection,min,max,today,rowHasVisibleDay,fallbackFocusDate,dayLabelFmt){const outside=date.getMonth()!==shownMonth;if(date.getFullYear()<0||date.getFullYear()>9999||outside&&!this.withOutsideDays)return html`<span
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{observeReactivePropertyWrites}from"../../../internal/reactive-property-writes.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{chevronIcon}from"../../../internal/icons.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{isRtl}from"../../../internal/rtl.js";import{attachInternalsSafely}from"../../../internal/form-associated.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{activeElementIn}from"../../../internal/active-element.js";import{MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR,getOwnDataDescriptor}from"../../../internal/data-descriptors.js";import{dispatchNativeEvent,dispatchNativeInputEvent}from"../../../internal/native-event-relay.js";import{styles}from"./date-picker.styles.js";import{monthMatrix,weekdayLabels,monthTitle,formatISO,parseISO,isSameDay,addMonths,addMonthsClampingDay,clampDate,dateTimeFormat,localDate,utcDate,normalizeCalendarMode,normalizeCalendarMonths,normalizeWeekdayFormat,resolveFirstDayOfWeek}from"./calendar-core.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_nextMonth,LYRA_DEFAULT_previousMonth}from"../../../internal/default-strings.generated.js";const MAX_VIEW_PERIOD_DAYS=366*10,modeConverter={fromAttribute:normalizeCalendarMode,toAttribute:normalizeCalendarMode},monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths},weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizePageBy(value){return value==="single"?"single":"months"}function normalizeView(value){return value==="months"||value==="years"||value==="decades"?value:"days"}const pageByConverter={fromAttribute:normalizePageBy,toAttribute:normalizePageBy},viewConverter={fromAttribute:normalizeView,toAttribute:normalizeView},canonicalPresetSnapshots=new WeakMap;function isSafeArray(value){try{return Array.isArray(value)}catch{return!1}}function isSafeNonArrayObject(value){if(value===null||typeof value!="object")return!1;try{return!Array.isArray(value)}catch{return!1}}function projectDateRangePreset(value){if(!isSafeNonArrayObject(value))return;const label=getOwnDataDescriptor(value,"label"),start=getOwnDataDescriptor(value,"start"),end=getOwnDataDescriptor(value,"end");if(!(label===MISSING_OWN_DATA_DESCRIPTOR||label===UNSAFE_OWN_DATA_DESCRIPTOR||typeof label.value!="string"||label.value.trim().length===0||start===UNSAFE_OWN_DATA_DESCRIPTOR||end===UNSAFE_OWN_DATA_DESCRIPTOR)&&!(start!==MISSING_OWN_DATA_DESCRIPTOR&&start.value!==void 0&&typeof start.value!="string"||end!==MISSING_OWN_DATA_DESCRIPTOR&&end.value!==void 0&&typeof end.value!="string"))return Object.freeze({source:value,label:label.value,start:start===MISSING_OWN_DATA_DESCRIPTOR?void 0:start.value,end:end===MISSING_OWN_DATA_DESCRIPTOR?void 0:end.value})}function canonicalDateRangePresets(values){const cached=canonicalPresetSnapshots.get(values);if(cached)return cached;const projected=[];for(const value of values){const preset=projectDateRangePreset(value);preset&&projected.push(preset)}const snapshot=Object.freeze(projected);return canonicalPresetSnapshots.set(values,snapshot),snapshot}function copyNativeDate(value){if(value===null||typeof value!="object")return null;try{const epoch=Date.prototype.getTime.call(value);return Number.isFinite(epoch)?new Date(epoch):null}catch{return null}}const MAX_DISABLED_DATE_ENTRIES=1e4;function projectDisabledDateKeys(value){if(typeof value=="string")return Object.freeze(value.split(/[\s,]+/).map(entry=>parseISO(entry)).filter(entry=>entry!==null).map(entry=>formatISO(entry)));if(!isSafeArray(value))return Object.freeze([]);const length=getOwnDataDescriptor(value,"length");if(length===MISSING_OWN_DATA_DESCRIPTOR||length===UNSAFE_OWN_DATA_DESCRIPTOR||typeof length.value!="number"||!Number.isSafeInteger(length.value)||length.value<0)return Object.freeze([]);const dates=[];for(let index=0;index<Math.min(length.value,MAX_DISABLED_DATE_ENTRIES);index+=1){const entry=getOwnDataDescriptor(value,String(index));if(entry===MISSING_OWN_DATA_DESCRIPTOR||entry===UNSAFE_OWN_DATA_DESCRIPTOR)continue;const date=typeof entry.value=="string"?parseISO(entry.value):copyNativeDate(entry.value);date&&dates.push(formatISO(date))}return Object.freeze(dates)}class LyraDatePicker extends LyraElement{static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,nextMonth:LYRA_DEFAULT_nextMonth,previousMonth:LYRA_DEFAULT_previousMonth}}static{this.styles=[LyraElement.styles,styles]}static{this.ownedCollectionProperties=Object.freeze(["presets"])}static{this.identityCollectionProperties=Object.freeze(["presets"])}get presets(){return this._presets}set presets(next){const old=this._presets;this._presets=isSafeArray(next)?next:Object.freeze([]),this.requestUpdate("presets",old)}get appliedPreset(){return this._appliedPreset}resolvePresetRange(preset){const bound=(own,fallback)=>{const text=typeof own=="string"&&own.trim()?own:fallback;return text?parseISO(text):null},min=parseISO(this.min),max=parseISO(this.max);if(min&&max&&min>max)return null;const start=bound(preset.start,this.min),end=bound(preset.end,this.max);if(!start||!end)return null;let from=clampDate(start,min,max),to=clampDate(end,min,max);return to<from&&([from,to]=[to,from]),this.admitsRange(from,to,min,max,this.resolvedToday())?{from,to}:null}static get observedAttributes(){const attributes=super.observedAttributes;return observeReactivePropertyWrites(this.prototype,["previousLabel","nextLabel"],(instance,name,value)=>{const authored=value!=null;let ownershipChanged=!1;switch(name){case"previousLabel":if(instance.previousLabelAuthored===void 0)return;ownershipChanged=authored!==instance.previousLabelAuthored,instance.previousLabelAuthored=authored;break;case"nextLabel":if(instance.nextLabelAuthored===void 0)return;ownershipChanged=authored!==instance.nextLabelAuthored,instance.nextLabelAuthored=authored;break}ownershipChanged&&instance.requestUpdate()}),attributes}constructor(){super(),this.value="",this.mode="single",this.min="",this.max="",this.disabled=!1,this.readonly=!1,this.months=1,this.size="m",this.locale="",this.firstDayOfWeek="auto",this.weekdayFormat="short",this.disablePast=!1,this.disableFuture=!1,this.withOutsideDays=!1,this.withWeekNumbers=!1,this.disabledDates="",this.disabledDaysOfWeek="",this._presets=Object.freeze([]),this.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.focusedDate="",this.view="days",this.previousLabel="Previous month",this.previousLabelAuthored=!1,this.nextLabel="Next month",this.nextLabelAuthored=!1,this.viewDate=localDate(new Date().getFullYear(),new Date().getMonth(),1),this.rangePreview=null,this.focusedViewStart="",this.focusPending=!1,this.viewFocusPending=!1,this.restoringViewFocus=!1,this.internals=attachInternalsSafely(this),this.disabledDatesCache=new Set,this.disabledWeekdaysCache=new Set,this.viewPeriodAvailabilityCache=new Map,this.titleIds=[nextId("date-picker-title"),nextId("date-picker-title")],this.onViewGridKey=event=>{const view=this.effectiveView;if(view==="days")return;const periods=this.viewPeriods(view),source=event.composedPath().find(node=>node instanceof HTMLElement&&node.hasAttribute("data-view-start")),currentSource=parseISO(source?.getAttribute("data-view-start")??"")??this.resolveViewFocus(periods);if(!currentSource)return;const current=this.viewPeriodStart(currentSource,view),span=this.viewPeriodMonths(view),rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=null;switch(event.key){case backwardKey:next=this.firstEnabledViewPeriod(addMonths(current,-span),-1);break;case forwardKey:next=this.firstEnabledViewPeriod(addMonths(current,span),1);break;case"ArrowUp":next=this.firstEnabledViewPeriod(addMonths(current,-4*span),-1);break;case"ArrowDown":next=this.firstEnabledViewPeriod(addMonths(current,4*span),1);break;case"Home":next=periods.find(period=>!this.viewPeriodDisabled(period.start,period.end))?.start??null;break;case"End":next=[...periods].reverse().find(period=>!this.viewPeriodDisabled(period.start,period.end))?.start??null;break;case"Enter":case" ":event.preventDefault(),this.pickViewItem(current);return;default:return}event.preventDefault(),next&&(this.viewDate=localDate(next.getFullYear(),next.getMonth(),1),this.focusViewPeriod(next,view))},this.onGridKey=e=>{const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday(),current=this.focusedDateValue??this.selection.from??this.firstEnabledDate(min,max,today)??localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),step=(base,days)=>localDate(base.getFullYear(),base.getMonth(),base.getDate()+days),firstEnabledFrom=(base,dayStep)=>{let d=base;for(let i=0;i<366;i++){if(d.getFullYear()<0||d.getFullYear()>9999)return null;if(!this.isDisabled(d,min,max,today))return d;d=step(d,dayStep)}return null},rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=null;switch(e.key){case backwardKey:next=firstEnabledFrom(step(current,-1),-1);break;case forwardKey:next=firstEnabledFrom(step(current,1),1);break;case"ArrowUp":next=firstEnabledFrom(step(current,-7),-1);break;case"ArrowDown":next=firstEnabledFrom(step(current,7),1);break;case"PageUp":next=firstEnabledFrom(addMonthsClampingDay(current,-1),1);break;case"PageDown":next=firstEnabledFrom(addMonthsClampingDay(current,1),1);break;case"Home":next=firstEnabledFrom(localDate(current.getFullYear(),current.getMonth(),1),1);break;case"End":next=firstEnabledFrom(localDate(current.getFullYear(),current.getMonth()+1,0),-1);break;case"Enter":case" ":e.preventDefault(),this.selectDate(current);return;default:return}e.preventDefault(),next&&(this.setFocusedDate(next),this.viewDate=this.viewDateForFocus(next),this.focusPending=!0)},observeScrollOverflow(this,()=>this.renderRoot.querySelectorAll(".calendar-scroll")[0]),observeScrollOverflow(this,()=>this.renderRoot.querySelectorAll(".calendar-scroll")[1])}get effectiveMode(){return normalizeCalendarMode(this.mode)}get visibleMonths(){return normalizeCalendarMonths(this.months)}get effectiveWeekdayFormat(){return normalizeWeekdayFormat(this.weekdayFormat)}get effectiveView(){return normalizeView(this.view)}get selection(){const parts=(this.value??"").split("/");return{from:parseISO(parts[0]??""),to:parseISO(parts[1]??"")}}set selection(next){this.valueAsRange=next}get valueAsDate(){return this.effectiveMode==="single"?this.selection.from:null}set valueAsDate(next){const date=copyNativeDate(next);if(!date){this.value="";return}this.value=formatISO(date)}get valueAsRange(){return this.effectiveMode==="range"?this.selection:{from:null,to:null}}set valueAsRange(next){let from=copyNativeDate(next?.from),to=copyNativeDate(next?.to);from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get focusedDateValue(){return parseISO(this.focusedDate)}setFocusedDate(date){this.focusedDate=date?formatISO(date):""}resolvedToday(){const today=parseISO(this.today)??new Date;return localDate(today.getFullYear(),today.getMonth(),today.getDate())}syncCustomStates(){setCustomState(this.internals,"disabled",this.disabled),setCustomState(this.internals,"range",this.effectiveMode==="range"),setCustomState(this.internals,"readonly",this.readonly)}willUpdate(changed){super.willUpdate(changed),this.viewPeriodAvailabilityCache.clear();const activeElement=activeElementIn(this.renderRoot),activeViewStart=activeElement?.matches('[part~="view-item"]')?parseISO(activeElement.getAttribute("data-view-start")??""):null;if(changed.has("value")){const external=this.committedValue!==this.value;if(this.committedValue=void 0,external&&(this._appliedPreset=void 0),external&&this.value){const from=this.selection.from;from&&(this.viewDate=localDate(from.getFullYear(),from.getMonth(),1))}}if(changed.has("focusedDate")){const focused=this.focusedDateValue;focused&&!this.isVisibleDate(focused)&&(this.viewDate=this.viewDateForFocus(focused))}const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday();if(this.viewDate=this.clampViewAnchor(this.viewDate),this.normalizeFocusedDate(min,max,today),this.clampViewDateToEnabledPeriod(),this.syncCustomStates(),activeViewStart&&this.effectiveView!=="days"){const next=this.resolveViewFocus(this.viewPeriods());next&&!isSameDay(activeViewStart,next)&&(this.setFocusedViewStart(next),this.viewFocusPending=!0)}}get fdow(){return resolveFirstDayOfWeek(this.firstDayOfWeek,this.effectiveLocale)}get disabledDateKeys(){return this.disabledDatesCacheSource===this.disabledDates?this.disabledDatesCache:(this.disabledDatesCacheSource=this.disabledDates,this.disabledDatesCache=new Set(projectDisabledDateKeys(this.disabledDates)),this.disabledDatesCache)}get disabledWeekdays(){if(this.disabledWeekdaysCacheSource===this.disabledDaysOfWeek)return this.disabledWeekdaysCache;this.disabledWeekdaysCacheSource=this.disabledDaysOfWeek;const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6},parsed=String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0);return this.disabledWeekdaysCache=new Set(parsed),this.disabledWeekdaysCache}rangeLength(from,to){const fromUtc=utcDate(from.getFullYear(),from.getMonth(),from.getDate()).getTime(),toUtc=utcDate(to.getFullYear(),to.getMonth(),to.getDate()).getTime();return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}isDisabled(d,min,max,today,pendingRange=!0){if(!Number.isFinite(d.getTime())||d.getFullYear()<0||d.getFullYear()>9999||this.disabled||this.readonly||min&&d<min||max&&d>max||this.disablePast&&d<today||this.disableFuture&&d>today||this.disabledDateKeys.has(formatISO(d))||this.disabledWeekdays.has(d.getDay()))return!0;try{if(this.isDateDisabled?.(new Date(d.getTime())))return!0}catch{}if(pendingRange&&this.effectiveMode==="range"){const{from,to}=this.selection;if(from&&!to&&!isSameDay(from,d)){const length=this.rangeLength(from,d),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);if(minimum>0&&length<minimum||maximum>0&&length>maximum)return!0}}return!1}nearestEnabledDate(anchor,min,max,today){let lower=min??localDate(0),upper=max??localDate(9999,11,31);if(this.disablePast&&today>lower&&(lower=today),this.disableFuture&&today<upper&&(upper=today),lower>upper)return null;if(anchor=clampDate(anchor,lower,upper),!this.isDisabled(anchor,min,max,today))return new Date(anchor.getTime());for(let distance=1;distance<=732;distance++){const before=localDate(anchor.getFullYear(),anchor.getMonth(),anchor.getDate()-distance);if(!this.isDisabled(before,min,max,today))return before;const after=localDate(anchor.getFullYear(),anchor.getMonth(),anchor.getDate()+distance);if(!this.isDisabled(after,min,max,today))return after}return null}isVisibleDate(date){const start=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1),end=addMonths(start,this.visibleMonths);return date>=start&&date<end}normalizeFocusedDate(min,max,today){const anchor=this.focusedDateValue??this.selection.from??(this.effectiveView==="days"?this.viewDate:null);if(!anchor)return;const disabled=this.isDisabled(anchor,min,max,today);if(!disabled&&this.isVisibleDate(anchor))return;const next=disabled?this.nearestEnabledDate(anchor,min,max,today):this.firstEnabledDate(min,max,today);if(!next){this.setFocusedDate(null),this.focusPending=!1;return}this.setFocusedDate(next),this.viewDate=this.viewDateForFocus(next);const active=activeElementIn(this.renderRoot);disabled&&active?.matches('[part~="day"]')&&(this.constraintFocusOwner=active,this.focusPending=!0)}firstEnabledDate(min,max,today){let d=localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1);const lastVisibleMonth=addMonths(d,this.visibleMonths-1),boundEnd=localDate(lastVisibleMonth.getFullYear(),lastVisibleMonth.getMonth()+1,0);for(let i=0;i<732&&d<=boundEnd;i++){if(!this.isDisabled(d,min,max,today))return d;d=localDate(d.getFullYear(),d.getMonth(),d.getDate()+1)}return null}admitsRange(from,to,min,max,today){if(this.isDisabled(from,min,max,today,!1)||this.isDisabled(to,min,max,today,!1))return!1;const length=this.rangeLength(from,to),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);return(minimum===0||length>=minimum)&&(maximum===0||length<=maximum)}commit(from,to,fire){const next=this.effectiveMode==="range"?from&&to?`${formatISO(from)}/${formatISO(to)}`:from?formatISO(from):"":from?formatISO(from):"";next!==this.value&&(this.committedValue=next),this.value=next,dispatchNativeInputEvent(this),fire&&dispatchNativeEvent(this,"change")}selectDate(date){const min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday();if(this.isDisabled(date,min,max,today))return;const pending=this.selection;if(!(this.effectiveMode==="range"&&pending.from&&!pending.to&&!this.admitsRange(pending.from,date,min,max,today)))if(this._appliedPreset=void 0,this.setFocusedDate(date),this.effectiveMode==="range"){const{from,to}=this.selection;if(!from||from&&to)this.commit(date,null,!1);else{let a=from,b=date;b<a&&([a,b]=[b,a]),this.commit(a,b,!0)}}else this.commit(date,null,!0)}clear(){this._appliedPreset=void 0,this.commit(null,null,!0)}goToToday(){this.goToDate(this.resolvedToday())}goToDate(date){const d=typeof date=="string"?parseISO(date):date;if(!d||!Number.isFinite(d.getTime()))return;const midnight=localDate(d.getFullYear(),d.getMonth(),d.getDate()),clamped=clampDate(midnight,parseISO(this.min)??localDate(0),parseISO(this.max)??localDate(9999,11,31));this.viewDate=localDate(clamped.getFullYear(),clamped.getMonth(),1),this.setFocusedDate(clamped),this.focusPending=!0}clampViewAnchor(date){return clampDate(date,localDate(0),localDate(9999,12-this.visibleMonths,1))}nav(delta){const page=this.pageBy==="single"?1:this.visibleMonths;this.viewDate=this.clampViewAnchor(addMonths(this.viewDate,delta*page))}get rovingTarget(){return this.renderRoot?.querySelector('[part~="day"][tabindex="0"], [part~="view-item"][tabindex="0"]:not(:disabled)')??null}focus(options){this.rovingTarget?.focus(options)}blur(){this.rovingTarget?.blur()}click(){this.rovingTarget?.click()}viewPeriodMonths(view=this.effectiveView){return view==="years"?12:view==="decades"?120:1}viewPeriodStart(date,view=this.effectiveView){return view==="years"?localDate(date.getFullYear(),0,1):view==="decades"?localDate(Math.floor(date.getFullYear()/10)*10,0,1):localDate(date.getFullYear(),date.getMonth(),1)}viewPageStart(view=this.effectiveView){const year=this.viewDate.getFullYear();return view==="months"?localDate(year,0,1):view==="years"?localDate(Math.floor(year/12)*12,0,1):localDate(Math.floor(year/120)*120,0,1)}viewPeriods(view=this.effectiveView){const pageStart=this.viewPageStart(view),span=this.viewPeriodMonths(view);return Array.from({length:12},(_,index)=>{const start=addMonths(pageStart,index*span);return{start,end:clampDate(localDate(start.getFullYear(),start.getMonth()+span,0),null,localDate(9999,11,31))}}).filter(period=>period.start.getFullYear()<=9999)}clampViewDateToEnabledPeriod(view=this.effectiveView){if(view==="days")return null;const periods=this.viewPeriods(view);if(this.disabled||this.readonly||periods.some(period=>!this.viewPeriodDisabled(period.start,period.end)))return null;const first=periods[0],last=periods[periods.length-1],span=this.viewPeriodMonths(view),min=parseISO(this.min),max=parseISO(this.max),forward=min&&last.end<min,backward=max&&first.start>max,next=forward?this.firstEnabledViewPeriod(this.viewPeriodStart(min),1):backward?this.firstEnabledViewPeriod(this.viewPeriodStart(max),-1):this.firstEnabledViewPeriod(addMonths(last.start,span),1)??this.firstEnabledViewPeriod(addMonths(first.start,-span),-1);return next?(this.viewDate=localDate(next.getFullYear(),next.getMonth(),1),next):null}resolveViewFocus(periods){const inView=candidate=>{if(!candidate)return null;const start=this.viewPeriodStart(candidate),period=periods.find(item=>isSameDay(item.start,start));return period&&!this.viewPeriodDisabled(period.start,period.end)?period.start:null},fallback=periods.find(period=>!this.viewPeriodDisabled(period.start,period.end));return inView(parseISO(this.focusedViewStart))??inView(this.selection.from)??inView(this.viewDate)??fallback?.start??null}setFocusedViewStart(date,view=this.effectiveView,requestUpdate=!1){const next=formatISO(this.viewPeriodStart(date,view));this.focusedViewStart!==next&&(this.focusedViewStart=next,requestUpdate&&this.requestUpdate())}onViewItemFocus(start){this.restoringViewFocus||this.setFocusedViewStart(start,this.effectiveView,!0)}firstEnabledViewPeriod(start,direction){const span=this.viewPeriodMonths();let candidate=this.viewPeriodStart(start);for(let index=0;index<366;index++){if(candidate.getFullYear()<0||candidate.getFullYear()>9999)return null;const end=localDate(candidate.getFullYear(),candidate.getMonth()+span,0);if(!this.viewPeriodDisabled(candidate,end))return candidate;candidate=addMonths(candidate,direction*span)}return null}focusViewPeriod(date,view=this.effectiveView){this.setFocusedViewStart(date,view),this.viewFocusPending=!0}setView(next,date=this.viewDate){next!==this.view&&(this.view=next,this.emit("lr-view-change",{view:next,date:new Date(date.getTime())}))}advanceView(){const next={days:"months",months:"years",years:"decades",decades:"decades"},current=this.effectiveView,nextView=next[current];if(nextView===current)return;const focused=current==="days"?this.focusedDateValue??this.selection.from??this.viewDate:this.resolveViewFocus(this.viewPeriods(current))??this.viewDate;this.focusViewPeriod(focused,nextView),this.setView(nextView)}onDayFocus(date){this.setFocusedDate(date),this.emit("lr-focus-day",{date:new Date(date.getTime())})}viewDateForFocus(next){const firstMonth=this.clampViewAnchor(localDate(this.viewDate.getFullYear(),this.viewDate.getMonth(),1)),nextMonth=localDate(next.getFullYear(),next.getMonth(),1),lastMonth=addMonths(firstMonth,this.visibleMonths-1);return nextMonth<firstMonth?nextMonth:nextMonth>lastMonth?addMonths(nextMonth,-(this.visibleMonths-1)):firstMonth}updated(changed){super.updated(changed);const focusedDate=this.focusedDateValue,repairOwner=this.constraintFocusOwner;this.constraintFocusOwner=void 0;const active=activeElementIn(this.renderRoot);if(repairOwner&&active!==repairOwner&&(active!==null||activeElementIn(this.ownerDocument)!==this.ownerDocument.body)&&(this.focusPending=!1),this.focusPending&&focusedDate){this.focusPending=!1;const iso=formatISO(focusedDate);this.renderRoot.querySelector(`[data-date="${iso}"][tabindex="0"]`)?.focus()}if(this.viewFocusPending){this.viewFocusPending=!1;const item=this.renderRoot.querySelector('[part~="view-item"][tabindex="0"]:not(:disabled)');if(item){this.restoringViewFocus=!0;try{item.focus()}finally{this.restoringViewFocus=!1}}}}renderDay(date,shownMonth,selection,min,max,today,rowHasVisibleDay,fallbackFocusDate,dayLabelFmt){const outside=date.getMonth()!==shownMonth;if(date.getFullYear()<0||date.getFullYear()>9999||outside&&!this.withOutsideDays)return html`<span
|
|
2
2
|
part="day-placeholder"
|
|
3
3
|
role="gridcell"
|
|
4
4
|
aria-hidden=${rowHasVisibleDay?"true":nothing}
|
|
@@ -11,7 +11,11 @@ import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from
|
|
|
11
11
|
* slotted `<lr-flag>`) is never run through it.
|
|
12
12
|
*
|
|
13
13
|
* Host `aria-haspopup` and `aria-expanded` values are forwarded reactively to the shadow-internal
|
|
14
|
-
* native button.
|
|
14
|
+
* native button. `aria-pressed` (`true`, `false`, `mixed`) supports icon-only toggle actions (mute,
|
|
15
|
+
* favorite, pin); `aria-current` (`page`, `step`, `location`, `date`, `time`, `true`, `false`)
|
|
16
|
+
* supports current-item icon buttons. Both follow attribute changes, removal and button/link
|
|
17
|
+
* replacement without changing the native role; empty or unsupported tokens are omitted. Host
|
|
18
|
+
* `aria-describedby` IDREFs are resolved through `ariaDescribedByElements`.
|
|
15
19
|
* Description targets follow same-ID replacement, removal, reinsertion, reconnection and document
|
|
16
20
|
* adoption, including transitions between the native button and anchor.
|
|
17
21
|
* When host `aria-controls` names elements in the host's own root, the controls relationship is
|
|
@@ -32,9 +36,10 @@ import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from
|
|
|
32
36
|
* renders no glyph unless a matching library is registered, including through
|
|
33
37
|
* `registerIconLibrary('default', { resolver })`.
|
|
34
38
|
*
|
|
35
|
-
* A safe `href` switches the interactive root to a native anchor. `
|
|
36
|
-
*
|
|
37
|
-
*
|
|
39
|
+
* A safe `href` switches the interactive root to a native anchor. `rel` is independently
|
|
40
|
+
* settable (no default); `opener` is always stripped and any `target` force-adds the
|
|
41
|
+
* non-removable `noopener noreferrer` guard. `download` narrows URL validation to downloadable
|
|
42
|
+
* schemes. A disabled link keeps the anchor anatomy but removes `href`, so it cannot navigate.
|
|
38
43
|
*
|
|
39
44
|
* Component-scoped theme inputs remain undeclared on the host, so values inherited from an
|
|
40
45
|
* ancestor theme wrapper override the built-in fallback. A value set directly on the icon button
|
|
@@ -43,6 +48,10 @@ import{type PropertyValues,type TemplateResult}from'lit';import{LyraElement}from
|
|
|
43
48
|
* @customElement lr-icon-button
|
|
44
49
|
* @event focus - Native focus relayed once from the internal button.
|
|
45
50
|
* @event blur - Native blur relayed once from the internal button.
|
|
51
|
+
* @attr aria-pressed - Toggle state forwarded reactively to the internal control: true, false or mixed.
|
|
52
|
+
* @attr aria-current - Current-item state forwarded reactively to the internal control: page, step, location, date, time, true or false.
|
|
53
|
+
* @attr rel - Independently settable author relationship tokens (no default). `opener` is always
|
|
54
|
+
* stripped, and any `target` force-adds the non-removable `noopener noreferrer` guard.
|
|
46
55
|
* @slot - Optional custom icon content, rendered beside (not inside) the `icon` glyph.
|
|
47
56
|
* @csspart base - Shoelace compatibility name for the interactive native control; use `button`.
|
|
48
57
|
* @csspart button - Native button, or the native anchor in safe link mode. The same node also
|
|
@@ -92,17 +101,30 @@ get name():string;set name(next:string|undefined);
|
|
|
92
101
|
/** Icon-library name forwarded to the nested `<lr-icon>`. */
|
|
93
102
|
library?:string;
|
|
94
103
|
/** Remote SVG URL forwarded to the nested `<lr-icon>` and handled by its guarded loader. */
|
|
95
|
-
src?:string;accessibleLabel:string;private triggerHasPopup;private triggerExpanded;private triggerControls;private triggerDescribedBy;label:string;
|
|
104
|
+
src?:string;accessibleLabel:string;private triggerHasPopup;private triggerExpanded;private triggerControls;private triggerDescribedBy;private triggerPressed;private triggerCurrent;label:string;
|
|
96
105
|
/** Safe link URL. When valid, the native root is an anchor rather than a button. */
|
|
97
106
|
href?:string;
|
|
98
107
|
/** Native anchor target. A non-empty target always derives a safe `rel`. */
|
|
99
108
|
target?:string;
|
|
109
|
+
/** Author relationship tokens for the rendered anchor, e.g. `nofollow me license` -- mirrors
|
|
110
|
+
* `wa-icon-button`/`sl-icon-button`'s own `rel`, so values a migrating consumer already relies
|
|
111
|
+
* on survive a `wa-`/`sl-` -> `lr-` rename instead of being silently dropped. Two rules are
|
|
112
|
+
* enforced regardless of what an author writes: `opener` is always stripped (the one token that
|
|
113
|
+
* re-opens the reverse-tabnabbing vector), and `noopener noreferrer` is force-added whenever
|
|
114
|
+
* `target` is set. With no `target` there is no new browsing context to protect, so a same-tab
|
|
115
|
+
* link renders exactly the author's tokens. Deliberately left with no default, matching
|
|
116
|
+
* `<lr-button>`'s own `rel`. */
|
|
117
|
+
rel?:string;
|
|
100
118
|
/** Native anchor download filename; also selects the stricter download URL allowlist. */
|
|
101
119
|
download?:string;private baseEl?;private slotEl?;private fallbackSvgEl?;
|
|
102
120
|
/** Only ever true when `icon` is unset and at least one top-level slotted element is bare SVG
|
|
103
121
|
* geometry with no SVG parent of its own -- see `needsSvgNamespaceFallback`. Mounts the internal
|
|
104
122
|
* `[part="fallback"]` SVG, which `updated()` then populates via `syncFallbackGeometry()`. */
|
|
105
123
|
private hasBareGeometry;
|
|
124
|
+
/** Resolved `rel` for the rendered anchor: author tokens minus `opener`, plus the
|
|
125
|
+
* `noopener noreferrer` guard whenever `target` is set. `undefined` when nothing remains, so the
|
|
126
|
+
* attribute is omitted rather than rendered empty. Mirrors `<lr-button>`'s own `resolvedRel`. */
|
|
127
|
+
private get resolvedRel();
|
|
106
128
|
/** Activates the internal native action or link. */
|
|
107
129
|
click():void;focus(options?:FocusOptions):void;blur():void;private onFocus;private onBlur;private onSlotChange;connectedCallback():void;disconnectedCallback():void;adoptedCallback():void;protected updated(changed:PropertyValues):void;private syncDescribedByElements;private releaseExternalDescription;
|
|
108
130
|
/** Mirrors `<lr-icon>`'s own `syncCustomNodes()`: repopulates `[part="fallback"]` from scratch
|
|
@@ -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{syncAriaControlsElements,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{styles}from"./icon-button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute}from"../../../internal/safe-svg.js";import{LYRA_DEFAULT_iconButtonLabel}from"../../../internal/default-strings.generated.js";const BARE_SVG_GEOMETRY_TAGS=new Set(["path","circle","rect","line","polygon","polyline","ellipse","g","use"]),SVG_NAMESPACE="http://www.w3.org/2000/svg";function needsSvgNamespaceFallback(node){return BARE_SVG_GEOMETRY_TAGS.has(node.localName)&&node.namespaceURI!==SVG_NAMESPACE}function cloneToSvgNamespace(node){if(node.localName.includes("-"))return null;const copy=node.ownerDocument.createElementNS(SVG_NAMESPACE,node.localName);for(const attribute of node.attributes)isUnsafeSvgCloneAttribute(attribute.name)||copy.setAttribute(attribute.name,attribute.value);for(const child of node.childNodes)if(child.nodeType===3)copy.append(child.cloneNode(!0));else if(child.nodeType===1){const childCopy=cloneToSvgNamespace(child);childCopy&©.append(childCopy)}return copy}class LyraIconButton extends LyraElement{constructor(){super(...arguments),this._disabled=!1,this.icon="",this.accessibleLabel="",this.triggerHasPopup=null,this.triggerExpanded=null,this.triggerControls=null,this.triggerDescribedBy=null,this.label="",this.hasBareGeometry=!1,this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{relayNativeEvent(this,event)},this.onSlotChange=()=>{const assigned=this.slotEl?.assignedElements({flatten:!0})??[];this.hasBareGeometry=assigned.some(el=>needsSvgNamespaceFallback(el))}}static{this.defaultStrings={...super.defaultStrings,iconButtonLabel:LYRA_DEFAULT_iconButtonLabel}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this._disabled}get name(){return this.icon}set name(next){this.icon=next??""}click(){this.effectiveDisabled||this.baseEl?.click()}focus(options){this.effectiveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements()}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}updated(changed){super.updated(changed),this.syncFallbackGeometry(),syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements()}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}syncFallbackGeometry(){const svgEl=this.fallbackSvgEl;if(!svgEl)return;svgEl.replaceChildren();const assigned=this.slotEl?.assignedElements({flatten:!0})??[];for(const el of assigned){if(!needsSvgNamespaceFallback(el))continue;const copy=cloneToSvgNamespace(el);copy&&svgEl.append(copy)}}render(){const label=this.accessibleLabel||this.label||this.localize("iconButtonLabel"),content=html`${this.icon||this.src?html`<lr-icon
|
|
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{syncAriaControlsElements,acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{styles}from"./icon-button.styles.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{safeDownloadHref,safeLinkHref}from"../../../internal/safe-url.js";import{isUnsafeSvgCloneAttribute}from"../../../internal/safe-svg.js";import{LYRA_DEFAULT_iconButtonLabel}from"../../../internal/default-strings.generated.js";const BARE_SVG_GEOMETRY_TAGS=new Set(["path","circle","rect","line","polygon","polyline","ellipse","g","use"]),SVG_NAMESPACE="http://www.w3.org/2000/svg";function needsSvgNamespaceFallback(node){return BARE_SVG_GEOMETRY_TAGS.has(node.localName)&&node.namespaceURI!==SVG_NAMESPACE}function cloneToSvgNamespace(node){if(node.localName.includes("-"))return null;const copy=node.ownerDocument.createElementNS(SVG_NAMESPACE,node.localName);for(const attribute of node.attributes)isUnsafeSvgCloneAttribute(attribute.name)||copy.setAttribute(attribute.name,attribute.value);for(const child of node.childNodes)if(child.nodeType===3)copy.append(child.cloneNode(!0));else if(child.nodeType===1){const childCopy=cloneToSvgNamespace(child);childCopy&©.append(childCopy)}return copy}class LyraIconButton extends LyraElement{constructor(){super(...arguments),this._disabled=!1,this.icon="",this.accessibleLabel="",this.triggerHasPopup=null,this.triggerExpanded=null,this.triggerControls=null,this.triggerDescribedBy=null,this.triggerPressed=null,this.triggerCurrent=null,this.label="",this.hasBareGeometry=!1,this.onFocus=event=>{relayNativeEvent(this,event)},this.onBlur=event=>{relayNativeEvent(this,event)},this.onSlotChange=()=>{const assigned=this.slotEl?.assignedElements({flatten:!0})??[];this.hasBareGeometry=assigned.some(el=>needsSvgNamespaceFallback(el))}}static{this.defaultStrings={...super.defaultStrings,iconButtonLabel:LYRA_DEFAULT_iconButtonLabel}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={disabled:{type:Boolean,reflect:!0,noAccessor:!0}}}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this.requestUpdate("disabled",old)}get effectiveDisabled(){return this._disabled}get name(){return this.icon}set name(next){this.icon=next??""}get resolvedRel(){const authored=(this.rel??"").split(/\s+/).filter(token=>token!==""&&token.toLowerCase()!=="opener"),tokens=new Set(authored);return this.target&&(tokens.add("noopener"),tokens.add("noreferrer")),tokens.size>0?[...tokens].join(" "):void 0}click(){this.effectiveDisabled||this.baseEl?.click()}focus(options){this.effectiveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncDescribedByElements()}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.isConnected&&this.hasUpdated&&this.syncDescribedByElements()}updated(changed){super.updated(changed),this.syncFallbackGeometry(),syncAriaControlsElements(this,this.baseEl,this.triggerControls),this.syncDescribedByElements()}syncDescribedByElements(){const target=this.isConnected?this.baseEl:void 0;if(!target){this.releaseExternalDescription();return}this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby")}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}syncFallbackGeometry(){const svgEl=this.fallbackSvgEl;if(!svgEl)return;svgEl.replaceChildren();const assigned=this.slotEl?.assignedElements({flatten:!0})??[];for(const el of assigned){if(!needsSvgNamespaceFallback(el))continue;const copy=cloneToSvgNamespace(el);copy&&svgEl.append(copy)}}render(){const pressed=["true","false","mixed"].includes(this.triggerPressed??"")?this.triggerPressed:nothing,current=["page","step","location","date","time","true","false"].includes(this.triggerCurrent??"")?this.triggerCurrent:nothing,label=this.accessibleLabel||this.label||this.localize("iconButtonLabel"),content=html`${this.icon||this.src?html`<lr-icon
|
|
2
2
|
name=${this.icon||nothing}
|
|
3
3
|
library=${this.library||nothing}
|
|
4
4
|
src=${this.src||nothing}
|
|
@@ -6,11 +6,13 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
6
6
|
part="base button"
|
|
7
7
|
href=${disabled?nothing:href}
|
|
8
8
|
target=${this.target||nothing}
|
|
9
|
-
rel=${this.
|
|
9
|
+
rel=${this.resolvedRel??nothing}
|
|
10
10
|
download=${hasDownload?this.download??"":nothing}
|
|
11
11
|
aria-label=${label}
|
|
12
12
|
aria-haspopup=${this.triggerHasPopup??nothing}
|
|
13
13
|
aria-expanded=${this.triggerExpanded??nothing}
|
|
14
|
+
aria-pressed=${pressed}
|
|
15
|
+
aria-current=${current}
|
|
14
16
|
aria-controls=${this.triggerControls||nothing}
|
|
15
17
|
aria-describedby=${this.triggerDescribedBy||nothing}
|
|
16
18
|
aria-disabled=${disabled?"true":"false"}
|
|
@@ -24,8 +26,10 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
24
26
|
aria-label=${label}
|
|
25
27
|
aria-haspopup=${this.triggerHasPopup??nothing}
|
|
26
28
|
aria-expanded=${this.triggerExpanded??nothing}
|
|
29
|
+
aria-pressed=${pressed}
|
|
30
|
+
aria-current=${current}
|
|
27
31
|
aria-controls=${this.triggerControls||nothing}
|
|
28
32
|
aria-describedby=${this.triggerDescribedBy||nothing}
|
|
29
33
|
@focus=${this.onFocus}
|
|
30
34
|
@blur=${this.onBlur}
|
|
31
|
-
>${content}</button>`}}__decorate([property()],LyraIconButton.prototype,"icon",void 0),__decorate([property()],LyraIconButton.prototype,"name",null),__decorate([property()],LyraIconButton.prototype,"library",void 0),__decorate([property()],LyraIconButton.prototype,"src",void 0),__decorate([property({attribute:"aria-label"})],LyraIconButton.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"aria-haspopup"})],LyraIconButton.prototype,"triggerHasPopup",void 0),__decorate([property({attribute:"aria-expanded"})],LyraIconButton.prototype,"triggerExpanded",void 0),__decorate([property({attribute:"aria-controls"})],LyraIconButton.prototype,"triggerControls",void 0),__decorate([property({attribute:"aria-describedby"})],LyraIconButton.prototype,"triggerDescribedBy",void 0),__decorate([property()],LyraIconButton.prototype,"label",void 0),__decorate([property()],LyraIconButton.prototype,"href",void 0),__decorate([property()],LyraIconButton.prototype,"target",void 0),__decorate([property()],LyraIconButton.prototype,"download",void 0),__decorate([query('[part~="button"]')],LyraIconButton.prototype,"baseEl",void 0),__decorate([query("slot")],LyraIconButton.prototype,"slotEl",void 0),__decorate([query('[part="fallback"]')],LyraIconButton.prototype,"fallbackSvgEl",void 0),__decorate([state()],LyraIconButton.prototype,"hasBareGeometry",void 0);export{LyraIconButton};
|
|
35
|
+
>${content}</button>`}}__decorate([property()],LyraIconButton.prototype,"icon",void 0),__decorate([property()],LyraIconButton.prototype,"name",null),__decorate([property()],LyraIconButton.prototype,"library",void 0),__decorate([property()],LyraIconButton.prototype,"src",void 0),__decorate([property({attribute:"aria-label"})],LyraIconButton.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"aria-haspopup"})],LyraIconButton.prototype,"triggerHasPopup",void 0),__decorate([property({attribute:"aria-expanded"})],LyraIconButton.prototype,"triggerExpanded",void 0),__decorate([property({attribute:"aria-controls"})],LyraIconButton.prototype,"triggerControls",void 0),__decorate([property({attribute:"aria-describedby"})],LyraIconButton.prototype,"triggerDescribedBy",void 0),__decorate([property({attribute:"aria-pressed"})],LyraIconButton.prototype,"triggerPressed",void 0),__decorate([property({attribute:"aria-current"})],LyraIconButton.prototype,"triggerCurrent",void 0),__decorate([property()],LyraIconButton.prototype,"label",void 0),__decorate([property()],LyraIconButton.prototype,"href",void 0),__decorate([property()],LyraIconButton.prototype,"target",void 0),__decorate([property()],LyraIconButton.prototype,"rel",void 0),__decorate([property()],LyraIconButton.prototype,"download",void 0),__decorate([query('[part~="button"]')],LyraIconButton.prototype,"baseEl",void 0),__decorate([query("slot")],LyraIconButton.prototype,"slotEl",void 0),__decorate([query('[part="fallback"]')],LyraIconButton.prototype,"fallbackSvgEl",void 0),__decorate([state()],LyraIconButton.prototype,"hasBareGeometry",void 0);export{LyraIconButton};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: block; --_lr-input-padding-block-default: var(--lr-form-control-padding-block); --_lr-input-padding-inline-default: var(--lr-form-control-padding-inline); --_lr-input-font-size-default: var(--lr-form-control-font-size); --_lr-input-control-min-height-default: var(--lr-form-control-height); --_lr-input-gap-default: var(--lr-space-xs); --_lr-input-radius-default: var(--lr-form-control-radius); --_lr-input-fill-default: transparent; --_lr-input-border-color-default: var(--lr-color-border); } :host([appearance='filled-outlined']) { --_lr-input-fill-default: var(--lr-color-surface); --_lr-input-border-color-default: var(--lr-color-border); } :host([appearance='outlined']) { --_lr-input-fill-default: transparent; --_lr-input-border-color-default: var(--lr-color-border); } :host([appearance='filled']) { --_lr-input-fill-default: var(--lr-color-surface-raised); --_lr-input-border-color-default: transparent; } :host([filled]) { --_lr-input-fill-default: var(--lr-color-surface-raised); --_lr-input-border-color-default: transparent; } :host([appearance='plain']) { --_lr-input-fill-default: transparent; --_lr-input-border-color-default: transparent; } :host([appearance='accent']) { --_lr-input-fill-default: var(--lr-color-brand-quiet); --_lr-input-border-color-default: var(--lr-color-brand); } :host([pill]) { --_lr-input-radius-default: var(--lr-radius-pill); } [part='form-control-label'] { display: block; margin-block-end: var(--lr-space-xs); font-size: var(--lr-font-size-md-sm); font-weight: var(--lr-font-weight-semibold); } [part='form-control-label'][hidden] { display: none; } ${formControlRequiredMarker} [part~='input-wrapper'] { display: flex; align-items: center; gap: var(--lr-input-gap, var(--_lr-input-gap-default)); inline-size: 100%; box-sizing: border-box; min-block-size: var(--lr-input-control-height, var(--lr-input-control-min-height, var(--_lr-input-control-min-height-default))); block-size: var(--lr-input-control-height, auto); padding-inline: var(--lr-input-padding-inline, var(--_lr-input-padding-inline-default)); border: var(--lr-border-width-thin) solid var(--lr-input-border-color, var(--_lr-input-border-color-default)); border-radius: var(--lr-input-radius, var(--_lr-input-radius-default)); background: var(--lr-input-fill, var(--_lr-input-fill-default)); } [part~='input-wrapper']:focus-within { border-color: var(--lr-input-focus-border-color, var(--lr-color-brand)); } :host(:disabled) [part~='input-wrapper'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='input'] { flex: 1 1 auto; min-inline-size: 0; box-sizing: border-box; padding-block: var(--lr-input-padding-block, var(--_lr-input-padding-block-default)); border: none; outline: none; background: transparent; color: var(--lr-color-text); font: inherit; font-size: var(--lr-input-font-size, var(--_lr-input-font-size-default)); } [part='input']::placeholder { color: var(--lr-input-action-color, var(--lr-color-text-quiet)); } [part='input'][type='search']::-webkit-search-cancel-button, [part='input'][type='search']::-webkit-search-decoration { appearance: none; } [part='input'][type='number'][data-without-spin-buttons] { appearance: textfield; } [part='input'][type='number'][data-without-spin-buttons]::-webkit-outer-spin-button, [part='input'][type='number'][data-without-spin-buttons]::-webkit-inner-spin-button { appearance: none; margin: 0; } [part='input'][type='time']::-webkit-calendar-picker-indicator { cursor: pointer; border-radius: var(--lr-radius-xs); background-color: transparent; outline: var(--lr-focus-ring-width) solid transparent; outline-offset: var(--lr-focus-ring-offset); } [part='input'][type='time']:not(:disabled):hover::-webkit-calendar-picker-indicator { background-color: var(--lr-input-time-picker-hover-bg, var(--lr-color-brand-quiet)); } [part='input'][type='time']:not(:disabled):active::-webkit-calendar-picker-indicator { background-color: var(--lr-input-time-picker-active-bg, var(--lr-color-brand)); } [part='input'][type='time']:not(:disabled):focus-visible::-webkit-calendar-picker-indicator { background-color: var(--lr-input-time-picker-focus-bg, var(--lr-color-brand-quiet)); outline-color: var(--lr-input-time-picker-focus-ring, var(--lr-focus-ring-color)); } [part='start'], [part='end'] { flex: 0 1 auto; display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 50%; overflow: hidden; color: var(--lr-color-text-quiet); } [part='start'] slot, [part='end'] slot, [part='start'] slot::slotted(*), [part='end'] slot::slotted(*) { min-inline-size: 0; max-inline-size: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='start'][hidden], [part='end'][hidden] { display: none; } [part='password-toggle'], [part='clear-button'] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; border: none; border-radius: var(--lr-radius); background: none; cursor: pointer; color: var(--lr-input-action-color, var(--lr-color-text-quiet)); padding: var(--lr-space-xs); min-inline-size: min(var(--lr-icon-button-size), var(--lr-form-control-height)); min-block-size: min(var(--lr-icon-button-size), var(--lr-form-control-height)); line-height: var(--lr-line-height-none); font-size: var(--lr-font-size-m); } [part='password-toggle']:not(:disabled):hover { color: var(--lr-input-action-hover-color, var(--lr-color-text)); } [part='clear-button']:not(:disabled):hover { color: var(--lr-input-action-hover-color, var(--lr-color-text)); } [part='password-toggle']:not(:disabled):active, [part='clear-button']:not(:disabled):active { color: var(--lr-input-action-active-color, var(--lr-input-action-hover-color, var(--lr-color-text))); background: var( --lr-input-action-active-bg, color-mix(in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active)) ); } [part='password-toggle']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part='clear-button']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part~='hint'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-text-quiet); } [part~='hint'][hidden] { display: none; } [part='error'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-danger); } [part='error'][hidden] { display: none; } [part='form-control'], [part='form-control-label'], [part~='hint'], [part='error'] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } `;export{styles};
|
|
1
|
+
import{css}from"lit";import{formControlRequiredMarker}from"../../../internal/form-control.styles.js";const styles=css` :host { display: block; --_lr-input-padding-block-default: var(--lr-form-control-padding-block); --_lr-input-padding-inline-default: var(--lr-form-control-padding-inline); --_lr-input-font-size-default: var(--lr-form-control-font-size); --_lr-input-control-min-height-default: var(--lr-form-control-height); --_lr-input-gap-default: var(--lr-space-xs); --_lr-input-radius-default: var(--lr-form-control-radius); --_lr-input-fill-default: transparent; --_lr-input-border-color-default: var(--lr-color-border); } :host([appearance='filled-outlined']) { --_lr-input-fill-default: var(--lr-color-surface); --_lr-input-border-color-default: var(--lr-color-border); } :host([appearance='outlined']) { --_lr-input-fill-default: transparent; --_lr-input-border-color-default: var(--lr-color-border); } :host([appearance='filled']) { --_lr-input-fill-default: var(--lr-color-surface-raised); --_lr-input-border-color-default: transparent; } :host([filled]) { --_lr-input-fill-default: var(--lr-color-surface-raised); --_lr-input-border-color-default: transparent; } :host([appearance='plain']) { --_lr-input-fill-default: transparent; --_lr-input-border-color-default: transparent; } :host([appearance='accent']) { --_lr-input-fill-default: var(--lr-color-brand-quiet); --_lr-input-border-color-default: var(--lr-color-brand); } :host([pill]) { --_lr-input-radius-default: var(--lr-radius-pill); } [part='form-control-label'] { display: block; margin-block-end: var(--lr-space-xs); font-size: var(--lr-font-size-md-sm); font-weight: var(--lr-font-weight-semibold); } [part='form-control-label'][hidden] { display: none; } ${formControlRequiredMarker} [part~='input-wrapper'] { display: flex; align-items: center; gap: var(--lr-input-gap, var(--_lr-input-gap-default)); inline-size: 100%; box-sizing: border-box; min-block-size: var(--lr-input-control-height, var(--lr-input-control-min-height, var(--_lr-input-control-min-height-default))); block-size: var(--lr-input-control-height, auto); padding-inline: var(--lr-input-padding-inline, var(--_lr-input-padding-inline-default)); border: var(--lr-border-width-thin) solid var(--lr-input-border-color, var(--_lr-input-border-color-default)); border-radius: var(--lr-input-radius, var(--_lr-input-radius-default)); background: var(--lr-input-fill, var(--_lr-input-fill-default)); } [part~='input-wrapper']:focus-within { border-color: var(--lr-input-focus-border-color, var(--lr-color-brand)); } :host(:disabled) [part~='input-wrapper'] { opacity: var(--lr-opacity-disabled); cursor: not-allowed; } [part='input'] { flex: 1 1 auto; min-inline-size: 0; box-sizing: border-box; padding-block: var(--lr-input-padding-block, var(--_lr-input-padding-block-default)); border: none; outline: none; background: transparent; color: var(--lr-color-text); font: inherit; font-size: var(--lr-input-font-size, var(--_lr-input-font-size-default)); } [part='input']::placeholder { color: var(--lr-input-action-color, var(--lr-color-text-quiet)); } [part='input'][type='search']::-webkit-search-cancel-button, [part='input'][type='search']::-webkit-search-decoration { appearance: none; } [part='input'][type='number'][data-without-spin-buttons] { appearance: textfield; } [part='input'][type='number'][data-without-spin-buttons]::-webkit-outer-spin-button, [part='input'][type='number'][data-without-spin-buttons]::-webkit-inner-spin-button { appearance: none; margin: 0; } [part='input'][type='time']::-webkit-calendar-picker-indicator { cursor: pointer; border-radius: var(--lr-radius-xs); background-color: transparent; outline: var(--lr-focus-ring-width) solid transparent; outline-offset: var(--lr-focus-ring-offset); } [part='input'][type='time']:not(:disabled):hover::-webkit-calendar-picker-indicator { background-color: var(--lr-input-time-picker-hover-bg, var(--lr-color-brand-quiet)); } [part='input'][type='time']:not(:disabled):active::-webkit-calendar-picker-indicator { background-color: var(--lr-input-time-picker-active-bg, var(--lr-color-brand)); } [part='input'][type='time']:not(:disabled):focus-visible::-webkit-calendar-picker-indicator { background-color: var(--lr-input-time-picker-focus-bg, var(--lr-color-brand-quiet)); outline-color: var(--lr-input-time-picker-focus-ring, var(--lr-focus-ring-color)); } [part='start'], [part='end'] { flex: 0 1 auto; display: inline-flex; align-items: center; min-inline-size: 0; max-inline-size: 50%; overflow: hidden; color: var(--lr-color-text-quiet); } [part='start'] slot, [part='end'] slot, [part='start'] slot::slotted(*), [part='end'] slot::slotted(*) { min-inline-size: 0; max-inline-size: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } [part='start'][hidden], [part='end'][hidden] { display: none; } [part='password-toggle'], [part='clear-button'] { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; border: none; border-radius: var(--lr-radius); background: none; cursor: pointer; color: var(--lr-input-action-color, var(--lr-color-text-quiet)); padding: var(--lr-space-xs); min-inline-size: max(var(--lr-size-24px), min(var(--lr-icon-button-size), var(--lr-form-control-height))); min-block-size: max(var(--lr-size-24px), min(var(--lr-icon-button-size), var(--lr-form-control-height))); line-height: var(--lr-line-height-none); font-size: var(--lr-font-size-m); } [part='password-toggle']:not(:disabled):hover { color: var(--lr-input-action-hover-color, var(--lr-color-text)); } [part='clear-button']:not(:disabled):hover { color: var(--lr-input-action-hover-color, var(--lr-color-text)); } [part='password-toggle']:not(:disabled):active, [part='clear-button']:not(:disabled):active { color: var(--lr-input-action-active-color, var(--lr-input-action-hover-color, var(--lr-color-text))); background: var( --lr-input-action-active-bg, color-mix(in oklab, var(--lr-color-surface), var(--lr-color-mix-partner) var(--lr-color-mix-active)) ); } [part='password-toggle']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part='clear-button']:focus-visible { outline: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color); outline-offset: var(--lr-focus-ring-offset); } [part~='hint'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-text-quiet); } [part~='hint'][hidden] { display: none; } [part='error'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-danger); } [part='error'][hidden] { display: none; } [part='form-control'], [part='form-control-label'], [part~='hint'], [part='error'] { min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } `;export{styles};
|
|
@@ -127,7 +127,12 @@ import{type ComplexAttributeConverter,type PropertyValues,type TemplateResult}fr
|
|
|
127
127
|
*/
|
|
128
128
|
export declare class LyraTimeInput extends LyraTimeInput_base{
|
|
129
129
|
/** Public WA-compatible intrinsic validator catalog. */
|
|
130
|
-
static get validators():LyraFormValidator<LyraTimeInput>[];static styles:import("lit").CSSResultGroup[];static properties:{open:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};readonly:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};step:{converter:ComplexAttributeConverter<LyraTimeInputStep,unknown>;reflect:boolean;noAccessor:boolean;};};appearance:LyraAppearance;autocomplete:string;distance:number;hint:string;hourFormat:LyraTimeInputHourFormat;label:string;min:string;max:string;pill:boolean;placement:LyraTimeInputPlacement;size:LyraSize;withClear:boolean;withHint:boolean;withLabel:boolean;withNow:boolean;errorText:string;private activeSegment;private touched;private hasLabelSlot;private hasHintSlot;private hasErrorSlot;private hasStartSlot;private hasEndSlot;private hasFooterSlot;private _open;private _readonly;private _step;private draft;private partial;private secondsVisible;
|
|
130
|
+
static get validators():LyraFormValidator<LyraTimeInput>[];static styles:import("lit").CSSResultGroup[];static properties:{open:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};readonly:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};step:{converter:ComplexAttributeConverter<LyraTimeInputStep,unknown>;reflect:boolean;noAccessor:boolean;};};appearance:LyraAppearance;autocomplete:string;distance:number;hint:string;hourFormat:LyraTimeInputHourFormat;label:string;min:string;max:string;pill:boolean;placement:LyraTimeInputPlacement;size:LyraSize;withClear:boolean;withHint:boolean;withLabel:boolean;withNow:boolean;errorText:string;private activeSegment;private touched;private hasLabelSlot;private hasHintSlot;private hasErrorSlot;private hasStartSlot;private hasEndSlot;private hasFooterSlot;private _open;private _readonly;private _step;private draft;private partial;private secondsVisible;
|
|
131
|
+
/** The last explicitly assigned/typed value, normalized but never step-padded. The committed
|
|
132
|
+
* `value` is always re-derived from this (see `committedValue`), so second-precision padding
|
|
133
|
+
* applies and reverts consistently regardless of `value`/`step` assignment order instead of
|
|
134
|
+
* depending on which was assigned first. */
|
|
135
|
+
private genuineValue;private digitBuffer;private digitSegment?;private pendingSegmentFocus?;private restoringSegmentFocus;private cleanupPositioner?;private overlayHandle?;private lightDismissDocument?;private restoreFocusOnClose;private transitionToken;private visibilityPromise;private segmentOrderKey;private pickerGridKey;private pickerGridMilliseconds;private inputId;private labelId;private hintId;private errorId;private requiredDescriptionId;private popupId;private externalDescriptionLease?;private requiredDescriptionLease?;private requiredDescriptionTarget?;
|
|
131
136
|
/** Clock seam for deterministic local-time tests. */
|
|
132
137
|
private now;constructor();connectedCallback():void;
|
|
133
138
|
/** Whether the column picker is open.
|
|
@@ -150,7 +155,13 @@ get valueAsNumber():number;set valueAsNumber(next:number);
|
|
|
150
155
|
*
|
|
151
156
|
* Assigning reads the same local clock fields back off the given Date, so it round-trips with
|
|
152
157
|
* the getter; `null` or an invalid Date clears the field. Assignment is silent. */
|
|
153
|
-
get valueAsDate():Date|null;set valueAsDate(next:Date|null);private get numericStep();
|
|
158
|
+
get valueAsDate():Date|null;set valueAsDate(next:Date|null);private get numericStep();
|
|
159
|
+
/** Pads a canonical time string to second precision when the step currently in effect requires
|
|
160
|
+
* it, so the committed `value` string is identical no matter which of `value`/`step` was
|
|
161
|
+
* assigned first. */
|
|
162
|
+
private padToStepPrecision;
|
|
163
|
+
/** `genuineValue` padded for the step currently in effect -- what `value` actually commits to. */
|
|
164
|
+
private get committedValue();private get includeSeconds();private get pattern();private get segmentOrder();
|
|
154
165
|
/** Reads component state plus the UA's synchronous fieldset cascade when a browser selector
|
|
155
166
|
* predicate exists. Lit's server element shim has no callable `matches()`, so SSR falls back to
|
|
156
167
|
* the reactive authority instead of aborting public-state application before the first render. */
|
|
@@ -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,acquireResolvedAriaRelationship}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{activeElementIn}from"../../../internal/active-element.js";import{deferredPlaceReady as place,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.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(),this.syncExternalDescription())}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=activeElementIn(this.shadowRoot);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(event==="lr-after-show"){const positioned=await waitForDeferredPlacement(()=>this.cleanupPositioner);if(this.transitionToken!==token||!this.open)return;if(!positioned){this.forceClose(!1);return}if(await this.updateComplete,this.transitionToken!==token)return}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("|"),focused=orderKey!==this.segmentOrderKey?activeElementIn(this.shadowRoot):null,focusedSegment=typeof focused?.getAttribute=="function"?focused.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(),this.syncExternalDescription();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.releaseExternalDescription(),this.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.releaseRequiredDescription(),this.isConnected&&this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}syncExternalDescription(){const target=this.renderRoot.querySelector('[part~="input"]');if(!target){this.releaseExternalDescription();return}if(!this.externalDescriptionLease){this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby");return}this.externalDescriptionLease.update(target)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}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,acquireResolvedAriaRelationship}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{activeElementIn}from"../../../internal/active-element.js";import{deferredPlaceReady as place,waitForDeferredPlacement}from"../../../internal/anchored-overlay-runtime.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.genuineValue="",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(),this.syncExternalDescription())}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 genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="minute";const committed=this.committedValue;committed!==this.value&&(super.value=committed),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){this.genuineValue=normalizeTimeValue(next);const normalized=this.committedValue;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)}padToStepPrecision(value){return value&&this.numericStep<60&&parseTimeValue(value)?.precision==="minute"?`${value}:00`:value}get committedValue(){return this.padToStepPrecision(this.genuineValue)}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"};const genuinePrecision=parseTimeValue(this.genuineValue)?.precision;this.secondsVisible=this.numericStep<60||genuinePrecision!==void 0&&genuinePrecision!=="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,this.genuineValue=next,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=activeElementIn(this.shadowRoot);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(event==="lr-after-show"){const positioned=await waitForDeferredPlacement(()=>this.cleanupPositioner);if(this.transitionToken!==token||!this.open)return;if(!positioned){this.forceClose(!1);return}if(await this.updateComplete,this.transitionToken!==token)return}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("|"),focused=orderKey!==this.segmentOrderKey?activeElementIn(this.shadowRoot):null,focusedSegment=typeof focused?.getAttribute=="function"?focused.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(),this.syncExternalDescription();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.releaseExternalDescription(),this.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.releaseRequiredDescription(),this.isConnected&&this.hasUpdated&&(this.syncRequiredDescription(),this.syncExternalDescription())}syncExternalDescription(){const target=this.renderRoot.querySelector('[part~="input"]');if(!target){this.releaseExternalDescription();return}if(!this.externalDescriptionLease){this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby");return}this.externalDescriptionLease.update(target)}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}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"
|
|
@@ -166,7 +166,14 @@ readonly:boolean;
|
|
|
166
166
|
/** Native autofill hint. Defaults to the SMS one-time-code value. */
|
|
167
167
|
autocomplete:string;private focused;private hasLabelSlot;private hasHintSlot;private hasErrorSlot;
|
|
168
168
|
/** Intrinsic invalid styling is only shown once the user has actually engaged with the field. */
|
|
169
|
-
private touched;private control?;private readonly labelId;private readonly hintId;private readonly errorId;private activeSegmentIndex;private segmentValues;
|
|
169
|
+
private touched;private control?;private readonly labelId;private readonly hintId;private readonly errorId;private activeSegmentIndex;private segmentValues;
|
|
170
|
+
/** The last raw string passed to the `value` setter, before length/format-dependent truncation.
|
|
171
|
+
* `willUpdate()` re-derives the live value from this (not from the already-truncated `value`)
|
|
172
|
+
* whenever `type`/`case`/`length`/`format` changes, so a `value` assignment that lands in the
|
|
173
|
+
* same batched update as a widening `length`/`format` (e.g. `el.value = '12345678'; el.length =
|
|
174
|
+
* 8;`, or the same template-binding order) never permanently loses the characters truncated
|
|
175
|
+
* against the stale, not-yet-updated segment count. */
|
|
176
|
+
private rawValue;private segmentEditPendingChange;
|
|
170
177
|
/** Invalidates a deferred autosubmission whose completion has since been superseded. */
|
|
171
178
|
private autosubmitToken;private parsedFormatSource?;private parsedFormatCells?;
|
|
172
179
|
/** The real native input used for focus, selection, autofill, and IME. */
|
|
@@ -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{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{findImplicitSubmitter,isNativeSubmitter,submitOnEnter}from"../../../internal/submit-on-enter.js";import{styles}from"./otp-input.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{currentValidityValidator}from"../form-validator.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel}from"../../../internal/default-strings.generated.js";const ACCEPTED={numeric:/[0-9]/,alpha:/[a-zA-Z]/,alphanumeric:/[a-zA-Z0-9]/},DEFAULT_LENGTH=6,MAX_LENGTH=32,MAX_FORMAT_SOURCE_LENGTH=4096,MAX_VALUE_SOURCE_LENGTH=4096;class LyraOtpInputBase extends LyraElement{static{this.styles=[LyraElement.styles,contextualSizes,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){constructor(){super(...arguments),this.label="",this.hint="",this.errorText="",this.appearance="outlined",this.autofocus=!1,this.autosubmit=!1,this.size="m",this.length=DEFAULT_LENGTH,this.format="",this.type="numeric",this.case="preserve",this.mask=!1,this.withMask=!1,this.readonly=!1,this.autocomplete="one-time-code",this.focused=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.touched=!1,this.labelId=nextId("otp-input-label"),this.hintId=nextId("otp-input-hint"),this.errorId=nextId("otp-input-error"),this.activeSegmentIndex=0,this.segmentValues=[],this.segmentEditPendingChange=!1,this.autosubmitToken=0,this.onInput=event=>{if(event.isComposing===!0){event.stopPropagation();return}const raw=event.target.value,next=this.sanitize(raw),previous=this.value,previousFilled=this.filledSegmentCount,layoutChanged=Array.from({length:this.renderedSegmentCount},(_,index)=>next[index]??"").some((value,index)=>value!==this.segmentValues[index]);if(this.control&&this.control.value!==next&&(this.control.value=next),next===this.value&&!layoutChanged){event.stopImmediatePropagation();return}this.touched=!0,this.value=next,relayNativeEvent(this,event),previous&&!next&&this.emit("lr-clear"),this.completeIfTransition(previousFilled)},this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1,delta=this.effectiveDirection==="rtl"?-physical:physical;this.setActiveSegment(this.activeSegmentIndex+delta);return}if(event.key==="Enter"){this.readonly||submitOnEnter(this,event,{beforeSubmit:()=>this.flushPendingChange()});return}if(this.readonly||event.isComposing)return;const selection=this.selectedSegmentRange;if(event.key==="Backspace"||event.key==="Delete"){event.preventDefault();const values2=this.normalizedSegmentValues();if(selection){for(const index of selection.indices)values2[index]="";this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),this.setActiveSegment(selection.first);return}const changed=!!values2[this.activeSegmentIndex];values2[this.activeSegmentIndex]="",changed&&this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),event.key==="Backspace"&&this.setActiveSegment(this.activeSegmentIndex-1);return}if(event.ctrlKey||event.metaKey||event.altKey||event.key.length!==1)return;event.preventDefault();const accepted=this.sanitize(event.key).slice(0,1);if(!accepted)return;const values=this.normalizedSegmentValues(),targetIndex=selection?.first??this.activeSegmentIndex;if(selection)for(const index of selection.indices)values[index]="";values[targetIndex]=accepted,this.commitSegmentEdit(values,"insertText",accepted),this.setActiveSegment(targetIndex+1)},this.onPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=this.sanitize(event.clipboardData?.getData("text")??"");if(event.preventDefault(),!pasted)return;const values=Array.from({length:this.renderedSegmentCount},(_,index)=>pasted[index]??"");this.commitSegmentEdit(values,"insertFromPaste",pasted),this.setActiveSegment(Math.min(pasted.length,this.renderedSegmentCount-1))},this.onChange=event=>{this.segmentEditPendingChange=!1,relayNativeEvent(this,event)},this.onFocus=event=>{this.focused=!0,relayNativeEvent(this,event)},this.onBlur=event=>{this.focused=!1,this.effectiveDisabled||(this.touched=!0),this.flushPendingChange(),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedNodes({flatten:!0}).length>0}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,otpInputIncomplete:LYRA_DEFAULT_otpInputIncomplete,otpInputLabel:LYRA_DEFAULT_otpInputLabel}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","length","pattern")]}get input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){this.autosubmitToken+=1;const normalized=this.sanitize(next??"");this.packSegmentValues(normalized),super.value=normalized}get defaultValue(){return super.defaultValue}set defaultValue(next){this.autosubmitToken+=1,super.defaultValue=next}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;if(this.parsedFormatSource=this.format,!this.format)return this.parsedFormatCells=null,null;const cells=[];let segments=0,literal="";const flushLiteral=()=>{literal&&(cells.push({kind:"separator",text:literal}),literal="")};for(const char of this.format.slice(0,MAX_FORMAT_SOURCE_LENGTH)){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral(),cells.push({kind:"segment"}),segments+=1}return flushLiteral(),this.parsedFormatCells=segments>0?cells:null,this.parsedFormatCells}get renderedSegmentCount(){const formatted=this.formattedCells;return formatted?formatted.filter(cell=>cell.kind==="segment").length:Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.renderedSegmentCount}get cells(){return this.formattedCells??Array.from({length:this.renderedSegmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric,limit=this.renderedSegmentCount;let out="";for(const char of(raw??"").slice(0,MAX_VALUE_SOURCE_LENGTH))if(accepted.test(char)&&(out+=char),out.length>=limit)break;return this.case==="upper"?out=out.toUpperCase():this.case==="lower"&&(out=out.toLowerCase()),out.slice(0,limit)}packSegmentValues(value){const count=this.renderedSegmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??""),this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){return Array.isArray(this.segmentValues)?this.segmentValues.reduce((count,value)=>count+(value?1:0),0):this.value.length}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.renderedSegmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.renderedSegmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret),this.updateComplete.then(()=>{this.renderRoot.querySelectorAll('[part~="segment"]')[next]?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();if(!form)return;const submitter=findImplicitSubmitter(form);submitter?isNativeSubmitter(submitter)?form.requestSubmit(submitter):submitter.click():form.requestSubmit()}completeIfTransition(previousFilled){if(previousFilled>=this.renderedSegmentCount||this.filledSegmentCount!==this.renderedSegmentCount)return;const completionValue=this.value,token=this.autosubmitToken,completeEvent=this.emit("lr-complete",{value:completionValue},{cancelable:!0});this.autosubmit&&setTimeout(()=>{token!==this.autosubmitToken||completeEvent.defaultPrevented||!this.isConnected||!this.autosubmit||this.value!==completionValue||this.filledSegmentCount!==this.renderedSegmentCount||this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){this.autosubmitToken+=1;const previousValue=this.value,previousFilled=this.filledSegmentCount;this.segmentValues=this.normalizedSegmentValues(values);const nextValue=this.segmentValues.join("");super.value=nextValue,this.control&&(this.control.value=nextValue),this.touched=!0,dispatchNativeInputEvent(this,{data,inputType}),this.segmentEditPendingChange=!0,previousValue&&!nextValue&&this.emit("lr-clear"),this.completeIfTransition(previousFilled),this.requestUpdate()}get selectedSegmentRange(){const start=this.control?.selectionStart,end=this.control?.selectionEnd;if(start==null||end===void 0||end===null||start===end)return null;const indices=this.normalizedSegmentValues().map((value,index)=>value?index:-1).filter(index=>index>=0).slice(start,end),first=indices[0];return first===void 0?null:{indices,first}}segmentIndexAtCompactOffset(offset){const values=this.normalizedSegmentValues();let occupied=0;for(let index=0;index<values.length;index+=1){if(occupied>=offset)return index;values[index]&&(occupied+=1)}return Math.max(0,values.length-1)}syncActiveSegmentFromSelection(){const control=this.control;if(!control||control.selectionStart===null)return;const selected=this.selectedSegmentRange;this.activeSegmentIndex=selected?.first??this.segmentIndexAtCompactOffset(control.selectionStart)}get selectionStart(){return this.control?.selectionStart??null}set selectionStart(value){this.control&&(this.control.selectionStart=value,this.syncActiveSegmentFromSelection())}get selectionEnd(){return this.control?.selectionEnd??null}set selectionEnd(value){this.control&&(this.control.selectionEnd=value,this.syncActiveSegmentFromSelection())}get selectionDirection(){return this.control?.selectionDirection??null}set selectionDirection(value){this.control&&(this.control.selectionDirection=value)}focus(options){this.effectiveDisabled||this.control?.focus(options)}blur(){this.control?.blur()}click(){this.effectiveDisabled||this.control?.click()}select(){this.control?.select()}setSelectionRange(start,end,direction){this.control&&(this.control.setSelectionRange(start,end,direction),this.syncActiveSegmentFromSelection())}setRangeText(replacement,start,end,selectMode){const control=this.control;if(!control)return;const selectionPrefixLength=(value,offset)=>{if(offset===null)return null;const boundedOffset=Math.min(MAX_VALUE_SOURCE_LENGTH,Math.max(0,offset));return this.sanitize(value.slice(0,boundedOffset)).length},currentRaw=control.value,currentSelectionStart=selectionPrefixLength(currentRaw,control.selectionStart),currentSelectionEnd=selectionPrefixLength(currentRaw,control.selectionEnd),currentSelectionDirection=control.selectionDirection,boundedCurrent=this.sanitize(currentRaw);currentRaw!==boundedCurrent&&(control.value=boundedCurrent,currentSelectionStart!==null&¤tSelectionEnd!==null&&control.setSelectionRange(currentSelectionStart,currentSelectionEnd,currentSelectionDirection??void 0));const boundedReplacement=this.sanitize(replacement);start===void 0||end===void 0?control.setRangeText(boundedReplacement):control.setRangeText(boundedReplacement,start,end,selectMode);const raw=control.value,selectionStart=selectionPrefixLength(raw,control.selectionStart),selectionEnd=selectionPrefixLength(raw,control.selectionEnd),selectionDirection=control.selectionDirection,normalized=this.sanitize(raw);this.value=normalized,control.value=normalized,selectionStart!==null&&selectionEnd!==null&&control.setSelectionRange(selectionStart,selectionEnd,selectionDirection??void 0),this.syncActiveSegmentFromSelection()}clear(){const hadValue=this.value.length>0;this.value="",this.control&&(this.control.value=""),this.focus(),hadValue&&this.emit("lr-clear")}formResetCallback(){this.autosubmitToken+=1,super.formResetCallback(),this.touched=!1,this.segmentEditPendingChange=!1}formStateRestoreCallback(state2,reason){this.autosubmitToken+=1,super.formStateRestoreCallback(state2,reason)}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback(),this.autosubmitToken+=1}reportValidity(){return this.touched=!0,super.reportValidity()}firstUpdated(changed){super.firstUpdated(changed),this.autofocus&&this.scheduleAfterUpdate(()=>this.focus(),"otp-autofocus")}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const target=this.control??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.value);next!==this.value?this.value=next:this.packSegmentValues(next)}(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format"))&&this.updateValidity(),this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"--blank",this.value.length===0),setCustomState(this.internals,"--filled",this.filledSegmentCount===this.renderedSegmentCount),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"readonly",this.readonly)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const total=this.renderedSegmentCount,filled=this.filledSegmentCount,complete=filled===total;if(this.required&&filled===0){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}if(filled>0&&!complete){this[SET_ANCHORED_VALIDITY]({tooShort:!0},this.localize("otpInputIncomplete",void 0,{total}));return}this[SET_ANCHORED_VALIDITY]({})}flushPendingChange(){this.segmentEditPendingChange&&(this.segmentEditPendingChange=!1,dispatchNativeEvent(this,"change"))}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&index===this.activeSegmentIndex,masked=filled&&this.mask,placeholderMask=!filled&&this.withMask,parts=["segment"];return active&&parts.push("active"),masked&&parts.push("masked"),placeholderMask&&parts.push("placeholder-mask"),invalid&&parts.push("invalid"),html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=!!this.label||this.hasLabelSlot,hasHint=!!this.hint||this.hasHintSlot,hasError=!!this.errorText||this.hasErrorSlot,intrinsicInvalid=this.touched&&!this.validity.valid,ariaInvalid=hasError||intrinsicInvalid,describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" "),labelledBy=hasLabel&&!this.getAttribute("aria-label")?this.labelId:nothing;let segmentIndex=-1;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(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{acquireResolvedAriaRelationship}from"../../../internal/aria-controls.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY}from"../../../internal/anchored-validity.js";import{hostAriaLabel,nextId}from"../../../internal/a11y.js";import{finiteInteger}from"../../../internal/numbers.js";import{setCustomState}from"../../../internal/custom-states.js";import{contextualSizes}from"../../../internal/contextual-vocabulary.styles.js";import{findImplicitSubmitter,isNativeSubmitter,submitOnEnter}from"../../../internal/submit-on-enter.js";import{styles}from"./otp-input.styles.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{currentValidityValidator}from"../form-validator.js";import{declaredDefaultConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_otpInputIncomplete,LYRA_DEFAULT_otpInputLabel}from"../../../internal/default-strings.generated.js";const ACCEPTED={numeric:/[0-9]/,alpha:/[a-zA-Z]/,alphanumeric:/[a-zA-Z0-9]/},DEFAULT_LENGTH=6,MAX_LENGTH=32,MAX_FORMAT_SOURCE_LENGTH=4096,MAX_VALUE_SOURCE_LENGTH=4096;class LyraOtpInputBase extends LyraElement{static{this.styles=[LyraElement.styles,contextualSizes,styles]}}class LyraOtpInput extends FormAssociated(LyraOtpInputBase){constructor(){super(...arguments),this.label="",this.hint="",this.errorText="",this.appearance="outlined",this.autofocus=!1,this.autosubmit=!1,this.size="m",this.length=DEFAULT_LENGTH,this.format="",this.type="numeric",this.case="preserve",this.mask=!1,this.withMask=!1,this.readonly=!1,this.autocomplete="one-time-code",this.focused=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.touched=!1,this.labelId=nextId("otp-input-label"),this.hintId=nextId("otp-input-hint"),this.errorId=nextId("otp-input-error"),this.activeSegmentIndex=0,this.segmentValues=[],this.rawValue="",this.segmentEditPendingChange=!1,this.autosubmitToken=0,this.onInput=event=>{if(event.isComposing===!0){event.stopPropagation();return}const raw=event.target.value,next=this.sanitize(raw),previous=this.value,previousFilled=this.filledSegmentCount,layoutChanged=Array.from({length:this.renderedSegmentCount},(_,index)=>next[index]??"").some((value,index)=>value!==this.segmentValues[index]);if(this.control&&this.control.value!==next&&(this.control.value=next),next===this.value&&!layoutChanged){event.stopImmediatePropagation();return}this.touched=!0,this.value=next,relayNativeEvent(this,event),previous&&!next&&this.emit("lr-clear"),this.completeIfTransition(previousFilled)},this.onKeyDown=event=>{if(this.effectiveDisabled)return;if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1,delta=this.effectiveDirection==="rtl"?-physical:physical;this.setActiveSegment(this.activeSegmentIndex+delta);return}if(event.key==="Enter"){this.readonly||submitOnEnter(this,event,{beforeSubmit:()=>this.flushPendingChange()});return}if(this.readonly||event.isComposing)return;const selection=this.selectedSegmentRange;if(event.key==="Backspace"||event.key==="Delete"){event.preventDefault();const values2=this.normalizedSegmentValues();if(selection){for(const index of selection.indices)values2[index]="";this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),this.setActiveSegment(selection.first);return}const changed=!!values2[this.activeSegmentIndex];values2[this.activeSegmentIndex]="",changed&&this.commitSegmentEdit(values2,event.key==="Backspace"?"deleteContentBackward":"deleteContentForward"),event.key==="Backspace"&&this.setActiveSegment(this.activeSegmentIndex-1);return}if(event.ctrlKey||event.metaKey||event.altKey||event.key.length!==1)return;event.preventDefault();const accepted=this.sanitize(event.key).slice(0,1);if(!accepted)return;const values=this.normalizedSegmentValues(),targetIndex=selection?.first??this.activeSegmentIndex;if(selection)for(const index of selection.indices)values[index]="";values[targetIndex]=accepted,this.commitSegmentEdit(values,"insertText",accepted),this.setActiveSegment(targetIndex+1)},this.onPaste=event=>{if(this.effectiveDisabled||this.readonly)return;const pasted=this.sanitize(event.clipboardData?.getData("text")??"");if(event.preventDefault(),!pasted)return;const values=Array.from({length:this.renderedSegmentCount},(_,index)=>pasted[index]??"");this.commitSegmentEdit(values,"insertFromPaste",pasted),this.setActiveSegment(Math.min(pasted.length,this.renderedSegmentCount-1))},this.onChange=event=>{this.segmentEditPendingChange=!1,relayNativeEvent(this,event)},this.onFocus=event=>{this.focused=!0,relayNativeEvent(this,event)},this.onBlur=event=>{this.focused=!1,this.effectiveDisabled||(this.touched=!0),this.flushPendingChange(),relayNativeEvent(this,event)},this.onLabelSlotChange=event=>{this.hasLabelSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onHintSlotChange=event=>{this.hasHintSlot=event.target.assignedNodes({flatten:!0}).length>0},this.onErrorSlotChange=event=>{this.hasErrorSlot=event.target.assignedNodes({flatten:!0}).length>0}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,otpInputIncomplete:LYRA_DEFAULT_otpInputIncomplete,otpInputLabel:LYRA_DEFAULT_otpInputLabel}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","length","pattern")]}get input(){return this.control??null}get validationTarget(){return this.control??null}get value(){return super.value}set value(next){this.autosubmitToken+=1,this.rawValue=next??"";const normalized=this.sanitize(this.rawValue);this.packSegmentValues(normalized),super.value=normalized}get defaultValue(){return super.defaultValue}set defaultValue(next){this.autosubmitToken+=1,super.defaultValue=next}get formattedCells(){if(this.parsedFormatSource===this.format)return this.parsedFormatCells??null;if(this.parsedFormatSource=this.format,!this.format)return this.parsedFormatCells=null,null;const cells=[];let segments=0,literal="";const flushLiteral=()=>{literal&&(cells.push({kind:"separator",text:literal}),literal="")};for(const char of this.format.slice(0,MAX_FORMAT_SOURCE_LENGTH)){if(char!=="#"){literal+=char;continue}if(segments>=MAX_LENGTH)break;flushLiteral(),cells.push({kind:"segment"}),segments+=1}return flushLiteral(),this.parsedFormatCells=segments>0?cells:null,this.parsedFormatCells}get renderedSegmentCount(){const formatted=this.formattedCells;return formatted?formatted.filter(cell=>cell.kind==="segment").length:Math.min(MAX_LENGTH,Math.max(1,finiteInteger(this.length,DEFAULT_LENGTH)))}get effectiveLength(){return this.renderedSegmentCount}get cells(){return this.formattedCells??Array.from({length:this.renderedSegmentCount},()=>({kind:"segment"}))}sanitize(raw){const accepted=ACCEPTED[this.type]??ACCEPTED.numeric,limit=this.renderedSegmentCount;let out="";for(const char of(raw??"").slice(0,MAX_VALUE_SOURCE_LENGTH))if(accepted.test(char)&&(out+=char),out.length>=limit)break;return this.case==="upper"?out=out.toUpperCase():this.case==="lower"&&(out=out.toLowerCase()),out.slice(0,limit)}packSegmentValues(value){const count=this.renderedSegmentCount;this.segmentValues=Array.from({length:count},(_,index)=>value[index]??""),this.activeSegmentIndex=Math.min(value.length,count-1)}get filledSegmentCount(){return Array.isArray(this.segmentValues)?this.segmentValues.reduce((count,value)=>count+(value?1:0),0):this.value.length}normalizedSegmentValues(values=this.segmentValues){return Array.from({length:this.renderedSegmentCount},(_,index)=>values[index]??"")}setActiveSegment(index){const next=Math.min(this.renderedSegmentCount-1,Math.max(0,index));this.activeSegmentIndex=next;const caret=this.normalizedSegmentValues().slice(0,next).filter(Boolean).length;this.control?.setSelectionRange(caret,caret),this.updateComplete.then(()=>{this.renderRoot.querySelectorAll('[part~="segment"]')[next]?.scrollIntoView({block:"nearest",inline:"nearest"})})}submitOwningForm(){const form=this.getForm();if(!form)return;const submitter=findImplicitSubmitter(form);submitter?isNativeSubmitter(submitter)?form.requestSubmit(submitter):submitter.click():form.requestSubmit()}completeIfTransition(previousFilled){if(previousFilled>=this.renderedSegmentCount||this.filledSegmentCount!==this.renderedSegmentCount)return;const completionValue=this.value,token=this.autosubmitToken,completeEvent=this.emit("lr-complete",{value:completionValue},{cancelable:!0});this.autosubmit&&setTimeout(()=>{token!==this.autosubmitToken||completeEvent.defaultPrevented||!this.isConnected||!this.autosubmit||this.value!==completionValue||this.filledSegmentCount!==this.renderedSegmentCount||this.submitOwningForm()})}commitSegmentEdit(values,inputType,data=null){this.autosubmitToken+=1;const previousValue=this.value,previousFilled=this.filledSegmentCount;this.segmentValues=this.normalizedSegmentValues(values);const nextValue=this.segmentValues.join("");super.value=nextValue,this.control&&(this.control.value=nextValue),this.touched=!0,dispatchNativeInputEvent(this,{data,inputType}),this.segmentEditPendingChange=!0,previousValue&&!nextValue&&this.emit("lr-clear"),this.completeIfTransition(previousFilled),this.requestUpdate()}get selectedSegmentRange(){const start=this.control?.selectionStart,end=this.control?.selectionEnd;if(start==null||end===void 0||end===null||start===end)return null;const indices=this.normalizedSegmentValues().map((value,index)=>value?index:-1).filter(index=>index>=0).slice(start,end),first=indices[0];return first===void 0?null:{indices,first}}segmentIndexAtCompactOffset(offset){const values=this.normalizedSegmentValues();let occupied=0;for(let index=0;index<values.length;index+=1){if(occupied>=offset)return index;values[index]&&(occupied+=1)}return Math.max(0,values.length-1)}syncActiveSegmentFromSelection(){const control=this.control;if(!control||control.selectionStart===null)return;const selected=this.selectedSegmentRange;this.activeSegmentIndex=selected?.first??this.segmentIndexAtCompactOffset(control.selectionStart)}get selectionStart(){return this.control?.selectionStart??null}set selectionStart(value){this.control&&(this.control.selectionStart=value,this.syncActiveSegmentFromSelection())}get selectionEnd(){return this.control?.selectionEnd??null}set selectionEnd(value){this.control&&(this.control.selectionEnd=value,this.syncActiveSegmentFromSelection())}get selectionDirection(){return this.control?.selectionDirection??null}set selectionDirection(value){this.control&&(this.control.selectionDirection=value)}focus(options){this.effectiveDisabled||this.control?.focus(options)}blur(){this.control?.blur()}click(){this.effectiveDisabled||this.control?.click()}select(){this.control?.select()}setSelectionRange(start,end,direction){this.control&&(this.control.setSelectionRange(start,end,direction),this.syncActiveSegmentFromSelection())}setRangeText(replacement,start,end,selectMode){const control=this.control;if(!control)return;const selectionPrefixLength=(value,offset)=>{if(offset===null)return null;const boundedOffset=Math.min(MAX_VALUE_SOURCE_LENGTH,Math.max(0,offset));return this.sanitize(value.slice(0,boundedOffset)).length},currentRaw=control.value,currentSelectionStart=selectionPrefixLength(currentRaw,control.selectionStart),currentSelectionEnd=selectionPrefixLength(currentRaw,control.selectionEnd),currentSelectionDirection=control.selectionDirection,boundedCurrent=this.sanitize(currentRaw);currentRaw!==boundedCurrent&&(control.value=boundedCurrent,currentSelectionStart!==null&¤tSelectionEnd!==null&&control.setSelectionRange(currentSelectionStart,currentSelectionEnd,currentSelectionDirection??void 0));const boundedReplacement=this.sanitize(replacement);start===void 0||end===void 0?control.setRangeText(boundedReplacement):control.setRangeText(boundedReplacement,start,end,selectMode);const raw=control.value,selectionStart=selectionPrefixLength(raw,control.selectionStart),selectionEnd=selectionPrefixLength(raw,control.selectionEnd),selectionDirection=control.selectionDirection,normalized=this.sanitize(raw);this.value=normalized,control.value=normalized,selectionStart!==null&&selectionEnd!==null&&control.setSelectionRange(selectionStart,selectionEnd,selectionDirection??void 0),this.syncActiveSegmentFromSelection()}clear(){const hadValue=this.value.length>0;this.value="",this.control&&(this.control.value=""),this.focus(),hadValue&&this.emit("lr-clear")}formResetCallback(){this.autosubmitToken+=1,super.formResetCallback(),this.touched=!1,this.segmentEditPendingChange=!1}formStateRestoreCallback(state2,reason){this.autosubmitToken+=1,super.formStateRestoreCallback(state2,reason)}disconnectedCallback(){this.releaseExternalDescription(),super.disconnectedCallback(),this.autosubmitToken+=1}reportValidity(){return this.touched=!0,super.reportValidity()}firstUpdated(changed){super.firstUpdated(changed),this.autofocus&&this.scheduleAfterUpdate(()=>this.focus(),"otp-autofocus")}adoptedCallback(){super.adoptedCallback(),this.releaseExternalDescription(),this.hasUpdated&&this.syncExternalDescription()}updated(changed){super.updated(changed),this.syncExternalDescription()}syncExternalDescription(){if(!this.isConnected)return;const target=this.control??null;target&&(this.externalDescriptionLease?this.externalDescriptionLease.update(target):this.externalDescriptionLease=acquireResolvedAriaRelationship(this,target,"aria-describedby"))}releaseExternalDescription(){this.externalDescriptionLease?.release(),this.externalDescriptionLease=void 0}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncExternalDescription()}willUpdate(changed){if(super.willUpdate(changed),changed.has("type")||changed.has("case")||changed.has("length")||changed.has("format")){const next=this.sanitize(this.rawValue);next!==this.value?this.value=next:this.packSegmentValues(next)}(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("length")||changed.has("format"))&&this.updateValidity(),this.syncOtpStates()}syncOtpStates(){setCustomState(this.internals,"--blank",this.value.length===0),setCustomState(this.internals,"--filled",this.filledSegmentCount===this.renderedSegmentCount),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"readonly",this.readonly)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const total=this.renderedSegmentCount,filled=this.filledSegmentCount,complete=filled===total;if(this.required&&filled===0){this[SET_ANCHORED_VALIDITY]({valueMissing:!0},this.localize("fieldRequired"));return}if(filled>0&&!complete){this[SET_ANCHORED_VALIDITY]({tooShort:!0},this.localize("otpInputIncomplete",void 0,{total}));return}this[SET_ANCHORED_VALIDITY]({})}flushPendingChange(){this.segmentEditPendingChange&&(this.segmentEditPendingChange=!1,dispatchNativeEvent(this,"change"))}renderSegment(index,invalid){const char=this.segmentValues[index]??"",filled=char!=="",active=this.focused&&!this.effectiveDisabled&&index===this.activeSegmentIndex,masked=filled&&this.mask,placeholderMask=!filled&&this.withMask,parts=["segment"];return active&&parts.push("active"),masked&&parts.push("masked"),placeholderMask&&parts.push("placeholder-mask"),invalid&&parts.push("invalid"),html`<div part=${parts.join(" ")} aria-hidden="true">${masked?nothing:placeholderMask?nothing:char}</div>`}render(){const hasLabel=!!this.label||this.hasLabelSlot,hasHint=!!this.hint||this.hasHintSlot,hasError=!!this.errorText||this.hasErrorSlot,intrinsicInvalid=this.touched&&!this.validity.valid,ariaInvalid=hasError||intrinsicInvalid,describedBy=[hasError?this.errorId:"",hasHint?this.hintId:""].filter(Boolean).join(" "),labelledBy=hasLabel&&!this.getAttribute("aria-label")?this.labelId:nothing;let segmentIndex=-1;return html`
|
|
2
2
|
<div part="base form-control">
|
|
3
3
|
<label part="label form-control-label" id=${this.labelId} for="control" ?hidden=${!hasLabel}>
|
|
4
4
|
${this.label}<slot name="label" ?hidden=${!!this.label} @slotchange=${this.onLabelSlotChange}></slot>
|