@aceshooting/lyra-ui 10.0.1 → 11.1.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 +271 -0
- package/custom-elements.json +1 -1
- package/design-tokens.json +13 -0
- package/dist/cli/migrate-wa.mjs +164 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +27 -0
- package/dist/components/charts/chart/box-plot.class.js +14 -4
- package/dist/components/charts/chart/box-plot.styles.js +28 -0
- package/dist/components/charts/chart/chart.class.d.ts +27 -0
- package/dist/components/charts/chart/chart.class.js +15 -5
- package/dist/components/charts/chart/chart.styles.js +28 -0
- package/dist/components/charts/chart/lite-chart.class.d.ts +32 -0
- package/dist/components/charts/chart/lite-chart.class.js +17 -4
- package/dist/components/charts/chart/lite-chart.styles.js +29 -0
- package/dist/components/data/heatmap/heatmap.class.d.ts +35 -2
- package/dist/components/data/heatmap/heatmap.class.js +2 -2
- package/dist/components/data/table/table.class.d.ts +19 -0
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/forms/combobox/combobox.class.d.ts +71 -3
- package/dist/components/forms/combobox/combobox.class.js +4 -2
- package/dist/components/forms/combobox/combobox.styles.js +9 -0
- package/dist/components/forms/date-picker/date-input.class.d.ts +12 -1
- package/dist/components/forms/date-picker/date-input.class.js +4 -2
- package/dist/components/forms/date-picker/date-picker.class.d.ts +72 -0
- package/dist/components/forms/date-picker/date-picker.class.js +15 -3
- package/dist/components/forms/date-picker/date-picker.styles.js +46 -0
- package/dist/components/media/flag/flag.class.d.ts +3 -1
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/map/map.class.d.ts +39 -2
- package/dist/components/media/map/map.class.js +1 -1
- package/dist/components/overlays/dialog/dialog.class.d.ts +20 -0
- package/dist/components/overlays/overlay/popover.class.d.ts +19 -3
- package/dist/components/overlays/overlay/popover.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/custom-elements-jsx.d.ts +31 -16
- package/dist/internal/canvas.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/tokens.styles.js +1 -0
- package/dist/lyra.d.ts +1 -1
- package/dist/svelte.d.ts +31 -16
- package/dist/theme.css +32 -0
- package/dist/vue.d.ts +31 -16
- package/llms/components/lr-agent-eval-dashboard.md +1 -1
- package/llms/components/lr-agent-workspace.md +1 -1
- package/llms/components/lr-bar-chart.md +4 -3
- package/llms/components/lr-box-plot.md +15 -4
- package/llms/components/lr-bubble-chart.md +4 -3
- package/llms/components/lr-chart.md +13 -3
- package/llms/components/lr-chunk-inspector.md +1 -1
- package/llms/components/lr-combobox.md +42 -6
- package/llms/components/lr-date-input.md +40 -4
- package/llms/components/lr-date-picker.md +40 -4
- package/llms/components/lr-dialog.md +2 -1
- package/llms/components/lr-doughnut-chart.md +4 -3
- package/llms/components/lr-entity-dossier.md +1 -1
- package/llms/components/lr-eval-run.md +1 -1
- package/llms/components/lr-flag.md +10 -3
- package/llms/components/lr-grounding-summary.md +1 -1
- package/llms/components/lr-heatmap.md +20 -2
- package/llms/components/lr-histogram.md +4 -3
- package/llms/components/lr-line-chart.md +4 -3
- package/llms/components/lr-lite-chart.md +19 -3
- package/llms/components/lr-map.md +21 -4
- package/llms/components/lr-memory-panel.md +1 -1
- package/llms/components/lr-option.md +41 -5
- package/llms/components/lr-pie-chart.md +4 -3
- package/llms/components/lr-polar-area-chart.md +4 -3
- package/llms/components/lr-popover.md +20 -1
- package/llms/components/lr-provenance-panel.md +1 -1
- package/llms/components/lr-radar-chart.md +4 -3
- package/llms/components/lr-rag-answer.md +1 -1
- package/llms/components/lr-rag-eval-dashboard.md +1 -1
- package/llms/components/lr-retrieval-results.md +1 -1
- package/llms/components/lr-retrieval-trace.md +1 -1
- package/llms/components/lr-scatter-chart.md +4 -3
- package/llms/peers.md +8 -8
- package/llms/tokens.md +27 -1
- package/llms-full.txt +231 -28
- package/package.json +1 -1
- package/vscode-css-data.json +70 -0
- package/vscode-html-data.json +131 -20
- package/web-types.json +190 -23
|
@@ -2,7 +2,7 @@ import { type TemplateResult, type PropertyValues } from 'lit';
|
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
3
|
import { type WeekdayFormat } from './calendar-core.js';
|
|
4
4
|
import type { LyraAppearance, LyraSize } from '../../../internal/variants.js';
|
|
5
|
-
import { type DateRange, type LyraDatePickerDayContent, type LyraDatePickerDisabledDates, type LyraDatePickerFirstDayOfWeek, type LyraDatePickerPageBy } from './date-picker.class.js';
|
|
5
|
+
import { type DateRange, type LyraDatePickerDayContent, type LyraDatePickerDisabledDates, type LyraDatePickerFirstDayOfWeek, type LyraDatePickerPageBy, type LyraDateRangePreset } from './date-picker.class.js';
|
|
6
6
|
import './date-picker.class.js';
|
|
7
7
|
export type LyraDateInputSelectionDirection = 'forward' | 'backward' | 'none';
|
|
8
8
|
export type LyraDateInputPlacement = 'top' | 'top-start' | 'top-end' | 'right' | 'right-start' | 'right-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end';
|
|
@@ -100,6 +100,8 @@ declare const LyraDateInput_base: typeof LyraDateInputBase & (new (...args: any[
|
|
|
100
100
|
* @csspart expand-icon - The calendar icon.
|
|
101
101
|
* @csspart popup - The positioned calendar popup.
|
|
102
102
|
* @csspart date-picker - The nested date picker.
|
|
103
|
+
* @csspart presets - The nested picker's quick-range row, forwarded from `<lr-date-picker>`.
|
|
104
|
+
* @csspart preset-button - One quick-range button, forwarded from `<lr-date-picker>`.
|
|
103
105
|
* @csspart hint - The hint message.
|
|
104
106
|
* @csspart error - The validation message.
|
|
105
107
|
* @cssprop [--lr-date-input-padding-block=var(--lr-space-xs)] - Block padding of the input row, scaled by `size`.
|
|
@@ -239,6 +241,15 @@ export declare class LyraDateInput extends LyraDateInput_base {
|
|
|
239
241
|
months: 1 | 2;
|
|
240
242
|
firstDayOfWeek: LyraDateInputFirstDayOfWeek;
|
|
241
243
|
weekdayFormat: WeekdayFormat;
|
|
244
|
+
/**
|
|
245
|
+
* Quick-range options forwarded verbatim to the nested `<lr-date-picker>`; see that component's
|
|
246
|
+
* own `presets` doc for the semantics. Range mode only, and unset renders nothing.
|
|
247
|
+
*
|
|
248
|
+
* Forwarded rather than reimplemented: the picker lives in this component's shadow root, so a
|
|
249
|
+
* consumer has no route to it -- a CSS part cannot set a JS property -- and this compact
|
|
250
|
+
* text-field-plus-popover shape is the one a dashboard time filter actually uses.
|
|
251
|
+
*/
|
|
252
|
+
presets: readonly LyraDateRangePreset[];
|
|
242
253
|
withOutsideDays: boolean;
|
|
243
254
|
withWeekNumbers: boolean;
|
|
244
255
|
disabledDates: LyraDatePickerDisabledDates;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon,calendarIcon,chevronIcon}from"../../../internal/icons.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{isDateObject}from"../../../internal/dom-guards.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dateTimeFormat,parseISO,formatISO,localDate,utcDate,normalizeCalendarMonths,normalizeWeekdayFormat}from"./calendar-core.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./date-input.styles.js";import"./date-picker.class.js";import"./date-picker.class.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_chooseDate,LYRA_DEFAULT_clear,LYRA_DEFAULT_date,LYRA_DEFAULT_dateInputFutureDisabled,LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_dateInputPastDisabled,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_openCalendar}from"../../../internal/default-strings.generated.js";function localeDateOrder(locale){try{const order=dateTimeFormat(locale,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2)).filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}const BIDI_FORMATTING_MARKS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function normalizeLocalizedDateText(raw,locale){let normalized=raw.replace(BIDI_FORMATTING_MARKS,"");try{const formatter=getNumberFormat(locale||void 0,{useGrouping:!1});for(let digit=0;digit<=9;digit++){const localized=formatter.format(digit).replace(BIDI_FORMATTING_MARKS,"");localized&&localized!==String(digit)&&(normalized=normalized.split(localized).join(String(digit)))}}catch{}return normalized.trim()}const monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths},weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizeDateInputAppearance(value){return value==="filled"||value==="filled-outlined"?value:"outlined"}const appearanceConverter={fromAttribute:normalizeDateInputAppearance,toAttribute:normalizeDateInputAppearance},placements=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function normalizeDateInputPlacement(value){return typeof value=="string"&&placements.has(value)?value:"bottom-start"}const placementConverter={fromAttribute:normalizeDateInputPlacement,toAttribute:normalizeDateInputPlacement};function normalizeDateInputPageBy(value){return value==="single"?"single":"months"}const pageByConverter={fromAttribute:normalizeDateInputPageBy,toAttribute:normalizeDateInputPageBy},VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}class LyraDateInputBase extends LyraElement{}class LyraDateInput extends FormAssociated(LyraDateInputBase){static{this.defaultStrings={...super.defaultStrings,chooseDate:LYRA_DEFAULT_chooseDate,clear:LYRA_DEFAULT_clear,date:LYRA_DEFAULT_date,dateInputFutureDisabled:LYRA_DEFAULT_dateInputFutureDisabled,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,dateInputPastDisabled:LYRA_DEFAULT_dateInputPastDisabled,fieldRequired:LYRA_DEFAULT_fieldRequired,openCalendar:LYRA_DEFAULT_openCalendar}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={mode:{reflect:!0,noAccessor:!0},min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},disablePast:{type:Boolean,attribute:"disable-past",reflect:!0,noAccessor:!0},disableFuture:{type:Boolean,attribute:"disable-future",reflect:!0,noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!this.readonly&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}constructor(){super(),this.appearance="outlined",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.size="m",this.pill=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.accessibleLabel=null,this.locale="",this.months=1,this.firstDayOfWeek="auto",this.weekdayFormat="short",this.withOutsideDays=!1,this.withWeekNumbers=!1,this.disabledDates="",this.disabledDaysOfWeek="",this.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.distance=0,this.placement="bottom-start",this.assumeInteractionOn=["input"],this.validators=[],this.clearLabel="",this.openLabel="",this.dialogLabel="Choose date",this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.restorePopupFocusOnClose=!1,this.transitionToken=0,this.transitionWaiters=new Map,this.interactionListeners=new Map,this.inputId=nextId("date-input"),this.popupId=nextId("date-popup"),this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.validityRevision=0,this._mode="single",this._min="",this._max="",this._open=!1,this._readonly=!1,this._disablePast=!1,this._disableFuture=!1,this.typedBadInput=!1,this.now=()=>new Date,this.onVisibilityChange=()=>{this.ownerDocument.visibilityState==="visible"&&(this.updateValidity(),this.validityRevision++)},this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide(!1)},this.onInputChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const raw=e.target.value;if(this.enterCommittedText!==null&&(raw===this.enterCommittedText||raw===this.displayText))return;this.enterCommittedText=null,this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)):this.inputRelayedSinceCommit=!1},this.onInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.inputRelayedSinceCommit=!0,relayNativeEvent(this,event))},this.onInputKey=e=>{if(e.altKey&&e.key==="ArrowDown"){e.preventDefault(),this.show();return}if(this.liveDisabled||this.readonly||!isImplicitSubmission(e))return;const input=this.inputElement;if(input&&input.value!==this.displayText){const raw=input.value;this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,dispatchNativeEvent(this,"change")):this.inputRelayedSinceCommit=!1,this.enterCommittedText=raw}submitOnEnter(this,e)},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:!0}).length>0},this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:!0}).length>0},this.onPickerInput=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)},this.onPickerChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,relayNativeEvent(this,e),this.hide(!0)},this.addEventListener("invalid",()=>{this.touched=!0})}get mode(){return this._mode}set mode(next){const old=this._mode;this._mode=next==="range"?"range":"single",this.internals.setFormValue(this.isIncompleteRangeValue(this.value)?"":this.value),this.updateValidity(),this.syncCustomStates(),this.requestUpdate("mode",old)}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.hide(),this.updateValidity(),this.requestUpdate("readonly",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.hide(),this.syncCustomStates()}get disablePast(){return this._disablePast}set disablePast(next){const old=this._disablePast;this._disablePast=!!next,this.updateValidity(),this.requestUpdate("disablePast",old)}get disableFuture(){return this._disableFuture}set disableFuture(next){const old=this._disableFuture;this._disableFuture=!!next,this.updateValidity(),this.requestUpdate("disableFuture",old)}get input(){return this.inputElement}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){this.inputElement&&(this.inputElement.selectionStart=value??0)}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){this.inputElement&&(this.inputElement.selectionEnd=value??0)}get selectionDirection(){return this.inputElement?.selectionDirection??null}set selectionDirection(value){this.inputElement&&(this.inputElement.selectionDirection=value??"none")}get value(){return super.value}set value(next){this.setTypedBadInput(!1);const normalized=this.normalizeCommittedValue(next??"");super.value=normalized,this.internals.setFormValue(this.isIncompleteRangeValue(normalized)?"":normalized),this.syncCustomStates()}get valueAsDate(){return this.mode==="single"?this.parseStrictISO(this.value):null}set valueAsDate(next){this.value=isDateObject(next)&&Number.isFinite(next.getTime())?formatISO(next):""}get valueAsRange(){if(this.mode!=="range")return{from:null,to:null};const[from="",to=""]=this.value.split("/");return{from:this.parseStrictISO(from),to:this.parseStrictISO(to)}}set valueAsRange(next){let from=isDateObject(next?.from)&&Number.isFinite(next.from.getTime())?next.from:null,to=isDateObject(next?.to)&&Number.isFinite(next.to.getTime())?next.to:null;from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get validationTarget(){return this.validationTargetOverride??this.inputElement}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}setTypedBadInput(next){const old=this.typedBadInput;this.typedBadInput=next,old!==next&&this.requestUpdate("typedBadInput",old)}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}normalizeCommittedValue(value){if(value==="")return"";const parts=value.split("/");if(parts.length!==1&&parts.length!==2)return"";const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?"":parts.length===2&&dates[0]>dates[1]?`${parts[1]}/${parts[0]}`:value}isIncompleteRangeValue(value){return this.mode==="range"&&value!==""&&!value.includes("/")}valueDates(value){const parts=value.split("/"),expectedParts=this.mode==="range"&&parts.length===2?2:1;if(parts.length!==expectedParts)return null;const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?null:dates}configuredDisabledDateKeys(){const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return new Set(values.map(value=>isDateObject(value)?value:parseISO(String(value))).filter(value=>isDateObject(value)&&Number.isFinite(value.getTime())).map(value=>formatISO(value)))}configuredDisabledWeekdays(){const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6};return new Set(String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0))}rangeLength(from,to){const fromUtc=utcDate(from.getFullYear(),from.getMonth(),from.getDate()).getTime(),toUtc=utcDate(to.getFullYear(),to.getMonth(),to.getDate()).getTime();return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("dateInputInvalid")}}result=typeof validator=="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:!0},message:this.localize("dateInputInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("dateInputInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("dateInputInvalid")}}}return{}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let underflowMessage="",overflowMessage="";const incompleteRange=this.isIncompleteRangeValue(this.value);if(this.required&&(this.value===""||incompleteRange)&&(flags.valueMissing=!0),this.typedBadInput&&(flags.badInput=!0),this.value!==""){const dates=this.valueDates(this.value);if(!dates)flags.badInput=!0;else{const min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max),now=this.parseStrictISO(this.today)??this.now(),today=localDate(now.getFullYear(),now.getMonth(),now.getDate());min!==null&&dates.some(date=>date<min)&&(flags.rangeUnderflow=!0,underflowMessage=this.localize("dateInputMinMessage",void 0,{min:this.min})),this.disablePast&&dates.some(date=>date<today)&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputPastDisabled")),max!==null&&dates.some(date=>date>max)&&(flags.rangeOverflow=!0,overflowMessage=this.localize("dateInputMaxMessage",void 0,{max:this.max})),this.disableFuture&&dates.some(date=>date>today)&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputFutureDisabled"));const disabledDates=this.configuredDisabledDateKeys(),disabledWeekdays=this.configuredDisabledWeekdays();let configuredDisabled=dates.some(date=>disabledDates.has(formatISO(date))||disabledWeekdays.has(date.getDay()));if(!configuredDisabled&&this.isDateDisabled)try{configuredDisabled=dates.some(date=>!!this.isDateDisabled?.(new Date(date.getTime())))}catch{configuredDisabled=!1}if(configuredDisabled&&(flags.customError=!0),this.mode==="range"&&dates.length===2){const length=this.rangeLength(dates[0],dates[1]),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);minimum>0&&length<minimum&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputInvalid")),maximum>0&&length>maximum&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputInvalid"))}}}const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags);let message="";configured.message?message=configured.message:flags.badInput||flags.customError?message=this.localize("dateInputInvalid"):flags.rangeUnderflow?message=underflowMessage:flags.rangeOverflow?message=overflowMessage:flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.updateValidity(),super.reportValidity()}bindVisibilityListener(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.visibilityListenerDocument===ownerDocument&&this.visibilityListener)return;this.unbindVisibilityListener();const listener=()=>{this.visibilityListener!==listener||this.visibilityListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onVisibilityChange()};this.visibilityListenerDocument=ownerDocument,this.visibilityListener=listener,ownerDocument.addEventListener("visibilitychange",listener)}unbindVisibilityListener(){this.visibilityListenerDocument&&this.visibilityListener&&this.visibilityListenerDocument.removeEventListener("visibilitychange",this.visibilityListener),this.visibilityListenerDocument=void 0,this.visibilityListener=void 0}get displayText(){const parts=this.value.split("/"),from=parseISO(parts[0]),to=parseISO(parts[1]??"");if(!from)return"";const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"}),fmt=d=>formatter.format(d);if(this.mode!=="range"||!to)return fmt(from);try{return formatter.formatRange(from,to)}catch{return`${fmt(from)} \u2013 ${fmt(to)}`}}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasStartSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="end")),changed.has("open")&&(this.open&&this.isConnected?this.bindDocumentPointer():this.unbindDocumentPointer())}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}show(){if(this.open||this.liveDisabled||this.readonly||this.emit("lr-show",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,this.settleTransition("lr-after-show"),settled}hide(restoreFocus=!1){if(!this.open||this.emit("lr-hide",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.restorePopupFocusOnClose||=restoreFocus,this.open=!1,this.settleTransition("lr-after-hide"),settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.bindDocumentPointer(),this.cleanupFn?.();const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)},modal:!1,trapFocus:!1}))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}connectedCallback(){super.connectedCallback(),this.bindVisibilityListener(),this.syncInteractionListeners(),this.syncValidatorAttributeObserver(),this.syncCustomStates(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}clear(){!this.value||this.liveDisabled||this.readonly||(this.touched=!0,this.value="",this.emit("lr-clear"),this.inputRelayedSinceCommit=!1,dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),dispatchNativeEvent(this,"change"))}syncInteractionListeners(){const requested=new Set((Array.isArray(this.assumeInteractionOn)?this.assumeInteractionOn:[]).filter(name=>typeof name=="string"&&name.length>0));for(const[name,listener]of this.interactionListeners)requested.has(name)||(this.removeEventListener(name,listener),this.interactionListeners.delete(name));for(const name of requested){if(this.interactionListeners.has(name))continue;const listener=()=>{this.touched=!0,this.syncCustomStates()};this.addEventListener(name,listener),this.interactionListeners.set(name,listener)}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}syncCustomStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open),setCustomState(this.internals,"range",this.mode==="range")}disconnectedCallback(){this.transitionToken++,this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver(),this.restorePopupFocusOnClose=!1,this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide");for(const[name,listener]of this.interactionListeners)this.removeEventListener(name,listener);this.interactionListeners.clear(),this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.open=!1,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver()}updated(changed){if(super.updated(changed),(changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("isDateDisabled")||changed.has("minRange")||changed.has("maxRange")||changed.has("today")||changed.has("validators"))&&this.updateValidity(),(changed.has("open")||this.open&&(changed.has("placement")||changed.has("distance")))&&(this.cleanupFn?.(),this.cleanupFn=void 0,this.open&&this.isConnected)){const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');anchor&&popup&&(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}))}if(changed.has("open")){if(this.open&&this.isConnected)this.renderRoot.querySelector('[part="popup"]')&&(this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)},modal:!1,trapFocus:!1}));else if(!this.open){const popup=this.renderRoot.querySelector('[part="popup"]'),focusWasInsidePopup=popup!==null&&composedContains(popup,deepActiveElement(this.ownerDocument));this.overlayHandle?.deactivate({restoreFocus:this.restorePopupFocusOnClose||focusWasInsidePopup}),this.overlayHandle=void 0,this.restorePopupFocusOnClose=!1}}changed.has("assumeInteractionOn")&&this.syncInteractionListeners(),changed.has("validators")&&this.syncValidatorAttributeObserver(),this.syncCustomStates(),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("mode")||changed.has("min")||changed.has("max")||changed.has("readonly")||changed.has("disablePast")||changed.has("disableFuture")||changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("minRange")||changed.has("maxRange")||changed.has("validators")||changed.has("typedBadInput")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}applyTypedText(raw){this.enterCommittedText=null;const trimmed=raw.trim();if(!trimmed)return this.value="",!0;const parsed=this.mode==="range"?this.parseRangeText(trimmed):this.parseSingleText(trimmed);return parsed?(this.value=parsed,!0):(this.inputElement&&(this.inputElement.value=this.displayText),this.setTypedBadInput(!0),this.updateValidity(),!1)}parseOneDate(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),/^\d{4}-\d{2}-\d{2}$/.test(raw))return parseISO(raw);const ambiguous=/^(\d{1,4})[/.-](\d{1,4})[/.-](\d{1,4})$/.exec(raw);if(ambiguous){const[,g1,g2,g3]=ambiguous;if(g1.length===4)return parseISO(`${g1}-${g2.padStart(2,"0")}-${g3.padStart(2,"0")}`);const order=localeDateOrder(this.effectiveLocale),values=[Number(g1),Number(g2),Number(g3)],fields={};if(order.forEach((type,i)=>{fields[type]=values[i]}),fields.day!=null&&fields.month!=null&&fields.year!=null){const year=fields.year<100?2e3+fields.year:fields.year;return parseISO(`${String(year).padStart(4,"0")}-${String(fields.month).padStart(2,"0")}-${String(fields.day).padStart(2,"0")}`)}}const timestamp=Date.parse(raw);return Number.isNaN(timestamp)?null:new Date(timestamp)}parseSingleText(raw){const parsed=this.parseOneDate(raw);return parsed?formatISO(parsed):null}localizedRangeSeparator(){const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"});try{const parts=formatter.formatRangeToParts(localDate(2026,0,2),localDate(2026,0,3)),firstEnd=parts.findIndex(part=>part.source==="endRange");let lastStart=-1;for(let index=0;index<firstEnd;index++)parts[index]?.source==="startRange"&&(lastStart=index);const separator=parts.slice(lastStart+1,firstEnd).map(part=>part.value).join("");return normalizeLocalizedDateText(separator,this.effectiveLocale)||"\u2013"}catch{return"\u2013"}}parseRangeText(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),raw===normalizeLocalizedDateText(this.displayText,this.effectiveLocale)&&this.value.includes("/"))return this.normalizeCommittedValue(this.value);if(/^\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}$/.test(raw)){const[a,b]=raw.split("/"),from2=parseISO(a),to2=parseISO(b);return!from2||!to2?null:from2<=to2?raw:`${b}/${a}`}const separator=this.localizedRangeSeparator(),idx=raw.indexOf(separator);if(idx===-1)return null;const from=this.parseOneDate(raw.slice(0,idx).trim()),to=this.parseOneDate(raw.slice(idx+separator.length).trim());return!from||!to?null:from<=to?`${formatISO(from)}/${formatISO(to)}`:`${formatISO(to)}/${formatISO(from)}`}click(){this.liveDisabled||this.inputElement?.click()}focus(options){this.liveDisabled||this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.applyTypedText(input.value))}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formResetCallback(){super.formResetCallback(),this.touched=!1}formDisabledCallback(disabled){Object.getPrototypeOf(LyraDateInput.prototype).formDisabledCallback.call(this,disabled),disabled&&this.hide(),this.syncCustomStates()}render(){const hasValue=this.value.length>0,hasHint=this.withHint||this.hasHintSlot||this.hint.length>0,hasError=this.hasErrorSlot||this.errorText.length>0,hasLabel=this.withLabel||this.hasLabelSlot||this.label.length>0,invalid=this.touched&&!this.internals.validity.valid,describedBy=[hasError?"date-input-error":"",hasHint?"date-input-hint":""].filter(Boolean).join(" "),dynamicDaySlots=[...new Set(Array.from(this.children??[]).map(child=>child.getAttribute("slot")??"").filter(name=>/^day-\d{4}-\d{2}-\d{2}$/.test(name)))];return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon,calendarIcon,chevronIcon}from"../../../internal/icons.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{isDateObject}from"../../../internal/dom-guards.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dateTimeFormat,parseISO,formatISO,localDate,utcDate,normalizeCalendarMonths,normalizeWeekdayFormat}from"./calendar-core.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./date-input.styles.js";import"./date-picker.class.js";import"./date-picker.class.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_chooseDate,LYRA_DEFAULT_clear,LYRA_DEFAULT_date,LYRA_DEFAULT_dateInputFutureDisabled,LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_dateInputPastDisabled,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_openCalendar}from"../../../internal/default-strings.generated.js";function localeDateOrder(locale){try{const order=dateTimeFormat(locale,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2)).filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}const BIDI_FORMATTING_MARKS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function normalizeLocalizedDateText(raw,locale){let normalized=raw.replace(BIDI_FORMATTING_MARKS,"");try{const formatter=getNumberFormat(locale||void 0,{useGrouping:!1});for(let digit=0;digit<=9;digit++){const localized=formatter.format(digit).replace(BIDI_FORMATTING_MARKS,"");localized&&localized!==String(digit)&&(normalized=normalized.split(localized).join(String(digit)))}}catch{}return normalized.trim()}const monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths},weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizeDateInputAppearance(value){return value==="filled"||value==="filled-outlined"?value:"outlined"}const appearanceConverter={fromAttribute:normalizeDateInputAppearance,toAttribute:normalizeDateInputAppearance},placements=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function normalizeDateInputPlacement(value){return typeof value=="string"&&placements.has(value)?value:"bottom-start"}const placementConverter={fromAttribute:normalizeDateInputPlacement,toAttribute:normalizeDateInputPlacement};function normalizeDateInputPageBy(value){return value==="single"?"single":"months"}const pageByConverter={fromAttribute:normalizeDateInputPageBy,toAttribute:normalizeDateInputPageBy},VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}class LyraDateInputBase extends LyraElement{}class LyraDateInput extends FormAssociated(LyraDateInputBase){static{this.defaultStrings={...super.defaultStrings,chooseDate:LYRA_DEFAULT_chooseDate,clear:LYRA_DEFAULT_clear,date:LYRA_DEFAULT_date,dateInputFutureDisabled:LYRA_DEFAULT_dateInputFutureDisabled,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,dateInputPastDisabled:LYRA_DEFAULT_dateInputPastDisabled,fieldRequired:LYRA_DEFAULT_fieldRequired,openCalendar:LYRA_DEFAULT_openCalendar}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={mode:{reflect:!0,noAccessor:!0},min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},disablePast:{type:Boolean,attribute:"disable-past",reflect:!0,noAccessor:!0},disableFuture:{type:Boolean,attribute:"disable-future",reflect:!0,noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!this.readonly&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}constructor(){super(),this.appearance="outlined",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.size="m",this.pill=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.accessibleLabel=null,this.locale="",this.months=1,this.firstDayOfWeek="auto",this.weekdayFormat="short",this.presets=Object.freeze([]),this.withOutsideDays=!1,this.withWeekNumbers=!1,this.disabledDates="",this.disabledDaysOfWeek="",this.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.distance=0,this.placement="bottom-start",this.assumeInteractionOn=["input"],this.validators=[],this.clearLabel="",this.openLabel="",this.dialogLabel="Choose date",this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.restorePopupFocusOnClose=!1,this.transitionToken=0,this.transitionWaiters=new Map,this.interactionListeners=new Map,this.inputId=nextId("date-input"),this.popupId=nextId("date-popup"),this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.validityRevision=0,this._mode="single",this._min="",this._max="",this._open=!1,this._readonly=!1,this._disablePast=!1,this._disableFuture=!1,this.typedBadInput=!1,this.now=()=>new Date,this.onVisibilityChange=()=>{this.ownerDocument.visibilityState==="visible"&&(this.updateValidity(),this.validityRevision++)},this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide(!1)},this.onInputChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const raw=e.target.value;if(this.enterCommittedText!==null&&(raw===this.enterCommittedText||raw===this.displayText))return;this.enterCommittedText=null,this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)):this.inputRelayedSinceCommit=!1},this.onInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.inputRelayedSinceCommit=!0,relayNativeEvent(this,event))},this.onInputKey=e=>{if(e.altKey&&e.key==="ArrowDown"){e.preventDefault(),this.show();return}if(this.liveDisabled||this.readonly||!isImplicitSubmission(e))return;const input=this.inputElement;if(input&&input.value!==this.displayText){const raw=input.value;this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,dispatchNativeEvent(this,"change")):this.inputRelayedSinceCommit=!1,this.enterCommittedText=raw}submitOnEnter(this,e)},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:!0}).length>0},this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:!0}).length>0},this.onPickerInput=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)},this.onPickerChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,relayNativeEvent(this,e),this.hide(!0)},this.addEventListener("invalid",()=>{this.touched=!0})}get mode(){return this._mode}set mode(next){const old=this._mode;this._mode=next==="range"?"range":"single",this.internals.setFormValue(this.isIncompleteRangeValue(this.value)?"":this.value),this.updateValidity(),this.syncCustomStates(),this.requestUpdate("mode",old)}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.hide(),this.updateValidity(),this.requestUpdate("readonly",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.hide(),this.syncCustomStates()}get disablePast(){return this._disablePast}set disablePast(next){const old=this._disablePast;this._disablePast=!!next,this.updateValidity(),this.requestUpdate("disablePast",old)}get disableFuture(){return this._disableFuture}set disableFuture(next){const old=this._disableFuture;this._disableFuture=!!next,this.updateValidity(),this.requestUpdate("disableFuture",old)}get input(){return this.inputElement}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){this.inputElement&&(this.inputElement.selectionStart=value??0)}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){this.inputElement&&(this.inputElement.selectionEnd=value??0)}get selectionDirection(){return this.inputElement?.selectionDirection??null}set selectionDirection(value){this.inputElement&&(this.inputElement.selectionDirection=value??"none")}get value(){return super.value}set value(next){this.setTypedBadInput(!1);const normalized=this.normalizeCommittedValue(next??"");super.value=normalized,this.internals.setFormValue(this.isIncompleteRangeValue(normalized)?"":normalized),this.syncCustomStates()}get valueAsDate(){return this.mode==="single"?this.parseStrictISO(this.value):null}set valueAsDate(next){this.value=isDateObject(next)&&Number.isFinite(next.getTime())?formatISO(next):""}get valueAsRange(){if(this.mode!=="range")return{from:null,to:null};const[from="",to=""]=this.value.split("/");return{from:this.parseStrictISO(from),to:this.parseStrictISO(to)}}set valueAsRange(next){let from=isDateObject(next?.from)&&Number.isFinite(next.from.getTime())?next.from:null,to=isDateObject(next?.to)&&Number.isFinite(next.to.getTime())?next.to:null;from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get validationTarget(){return this.validationTargetOverride??this.inputElement}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}setTypedBadInput(next){const old=this.typedBadInput;this.typedBadInput=next,old!==next&&this.requestUpdate("typedBadInput",old)}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}normalizeCommittedValue(value){if(value==="")return"";const parts=value.split("/");if(parts.length!==1&&parts.length!==2)return"";const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?"":parts.length===2&&dates[0]>dates[1]?`${parts[1]}/${parts[0]}`:value}isIncompleteRangeValue(value){return this.mode==="range"&&value!==""&&!value.includes("/")}valueDates(value){const parts=value.split("/"),expectedParts=this.mode==="range"&&parts.length===2?2:1;if(parts.length!==expectedParts)return null;const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?null:dates}configuredDisabledDateKeys(){const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return new Set(values.map(value=>isDateObject(value)?value:parseISO(String(value))).filter(value=>isDateObject(value)&&Number.isFinite(value.getTime())).map(value=>formatISO(value)))}configuredDisabledWeekdays(){const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6};return new Set(String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0))}rangeLength(from,to){const fromUtc=utcDate(from.getFullYear(),from.getMonth(),from.getDate()).getTime(),toUtc=utcDate(to.getFullYear(),to.getMonth(),to.getDate()).getTime();return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("dateInputInvalid")}}result=typeof validator=="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:!0},message:this.localize("dateInputInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("dateInputInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("dateInputInvalid")}}}return{}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let underflowMessage="",overflowMessage="";const incompleteRange=this.isIncompleteRangeValue(this.value);if(this.required&&(this.value===""||incompleteRange)&&(flags.valueMissing=!0),this.typedBadInput&&(flags.badInput=!0),this.value!==""){const dates=this.valueDates(this.value);if(!dates)flags.badInput=!0;else{const min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max),now=this.parseStrictISO(this.today)??this.now(),today=localDate(now.getFullYear(),now.getMonth(),now.getDate());min!==null&&dates.some(date=>date<min)&&(flags.rangeUnderflow=!0,underflowMessage=this.localize("dateInputMinMessage",void 0,{min:this.min})),this.disablePast&&dates.some(date=>date<today)&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputPastDisabled")),max!==null&&dates.some(date=>date>max)&&(flags.rangeOverflow=!0,overflowMessage=this.localize("dateInputMaxMessage",void 0,{max:this.max})),this.disableFuture&&dates.some(date=>date>today)&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputFutureDisabled"));const disabledDates=this.configuredDisabledDateKeys(),disabledWeekdays=this.configuredDisabledWeekdays();let configuredDisabled=dates.some(date=>disabledDates.has(formatISO(date))||disabledWeekdays.has(date.getDay()));if(!configuredDisabled&&this.isDateDisabled)try{configuredDisabled=dates.some(date=>!!this.isDateDisabled?.(new Date(date.getTime())))}catch{configuredDisabled=!1}if(configuredDisabled&&(flags.customError=!0),this.mode==="range"&&dates.length===2){const length=this.rangeLength(dates[0],dates[1]),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);minimum>0&&length<minimum&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputInvalid")),maximum>0&&length>maximum&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputInvalid"))}}}const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags);let message="";configured.message?message=configured.message:flags.badInput||flags.customError?message=this.localize("dateInputInvalid"):flags.rangeUnderflow?message=underflowMessage:flags.rangeOverflow?message=overflowMessage:flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.updateValidity(),super.reportValidity()}bindVisibilityListener(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.visibilityListenerDocument===ownerDocument&&this.visibilityListener)return;this.unbindVisibilityListener();const listener=()=>{this.visibilityListener!==listener||this.visibilityListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onVisibilityChange()};this.visibilityListenerDocument=ownerDocument,this.visibilityListener=listener,ownerDocument.addEventListener("visibilitychange",listener)}unbindVisibilityListener(){this.visibilityListenerDocument&&this.visibilityListener&&this.visibilityListenerDocument.removeEventListener("visibilitychange",this.visibilityListener),this.visibilityListenerDocument=void 0,this.visibilityListener=void 0}get displayText(){const parts=this.value.split("/"),from=parseISO(parts[0]),to=parseISO(parts[1]??"");if(!from)return"";const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"}),fmt=d=>formatter.format(d);if(this.mode!=="range"||!to)return fmt(from);try{return formatter.formatRange(from,to)}catch{return`${fmt(from)} \u2013 ${fmt(to)}`}}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasStartSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="end")),changed.has("open")&&(this.open&&this.isConnected?this.bindDocumentPointer():this.unbindDocumentPointer())}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}show(){if(this.open||this.liveDisabled||this.readonly||this.emit("lr-show",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,this.settleTransition("lr-after-show"),settled}hide(restoreFocus=!1){if(!this.open||this.emit("lr-hide",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.restorePopupFocusOnClose||=restoreFocus,this.open=!1,this.settleTransition("lr-after-hide"),settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.bindDocumentPointer(),this.cleanupFn?.();const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)},modal:!1,trapFocus:!1}))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}connectedCallback(){super.connectedCallback(),this.bindVisibilityListener(),this.syncInteractionListeners(),this.syncValidatorAttributeObserver(),this.syncCustomStates(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}clear(){!this.value||this.liveDisabled||this.readonly||(this.touched=!0,this.value="",this.emit("lr-clear"),this.inputRelayedSinceCommit=!1,dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),dispatchNativeEvent(this,"change"))}syncInteractionListeners(){const requested=new Set((Array.isArray(this.assumeInteractionOn)?this.assumeInteractionOn:[]).filter(name=>typeof name=="string"&&name.length>0));for(const[name,listener]of this.interactionListeners)requested.has(name)||(this.removeEventListener(name,listener),this.interactionListeners.delete(name));for(const name of requested){if(this.interactionListeners.has(name))continue;const listener=()=>{this.touched=!0,this.syncCustomStates()};this.addEventListener(name,listener),this.interactionListeners.set(name,listener)}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}syncCustomStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open),setCustomState(this.internals,"range",this.mode==="range")}disconnectedCallback(){this.transitionToken++,this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver(),this.restorePopupFocusOnClose=!1,this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide");for(const[name,listener]of this.interactionListeners)this.removeEventListener(name,listener);this.interactionListeners.clear(),this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.open=!1,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver()}updated(changed){if(super.updated(changed),(changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("isDateDisabled")||changed.has("minRange")||changed.has("maxRange")||changed.has("today")||changed.has("validators"))&&this.updateValidity(),(changed.has("open")||this.open&&(changed.has("placement")||changed.has("distance")))&&(this.cleanupFn?.(),this.cleanupFn=void 0,this.open&&this.isConnected)){const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');anchor&&popup&&(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}))}if(changed.has("open")){if(this.open&&this.isConnected)this.renderRoot.querySelector('[part="popup"]')&&(this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)},modal:!1,trapFocus:!1}));else if(!this.open){const popup=this.renderRoot.querySelector('[part="popup"]'),focusWasInsidePopup=popup!==null&&composedContains(popup,deepActiveElement(this.ownerDocument));this.overlayHandle?.deactivate({restoreFocus:this.restorePopupFocusOnClose||focusWasInsidePopup}),this.overlayHandle=void 0,this.restorePopupFocusOnClose=!1}}changed.has("assumeInteractionOn")&&this.syncInteractionListeners(),changed.has("validators")&&this.syncValidatorAttributeObserver(),this.syncCustomStates(),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("mode")||changed.has("min")||changed.has("max")||changed.has("readonly")||changed.has("disablePast")||changed.has("disableFuture")||changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("minRange")||changed.has("maxRange")||changed.has("validators")||changed.has("typedBadInput")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}applyTypedText(raw){this.enterCommittedText=null;const trimmed=raw.trim();if(!trimmed)return this.value="",!0;const parsed=this.mode==="range"?this.parseRangeText(trimmed):this.parseSingleText(trimmed);return parsed?(this.value=parsed,!0):(this.inputElement&&(this.inputElement.value=this.displayText),this.setTypedBadInput(!0),this.updateValidity(),!1)}parseOneDate(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),/^\d{4}-\d{2}-\d{2}$/.test(raw))return parseISO(raw);const ambiguous=/^(\d{1,4})[/.-](\d{1,4})[/.-](\d{1,4})$/.exec(raw);if(ambiguous){const[,g1,g2,g3]=ambiguous;if(g1.length===4)return parseISO(`${g1}-${g2.padStart(2,"0")}-${g3.padStart(2,"0")}`);const order=localeDateOrder(this.effectiveLocale),values=[Number(g1),Number(g2),Number(g3)],fields={};if(order.forEach((type,i)=>{fields[type]=values[i]}),fields.day!=null&&fields.month!=null&&fields.year!=null){const year=fields.year<100?2e3+fields.year:fields.year;return parseISO(`${String(year).padStart(4,"0")}-${String(fields.month).padStart(2,"0")}-${String(fields.day).padStart(2,"0")}`)}}const timestamp=Date.parse(raw);return Number.isNaN(timestamp)?null:new Date(timestamp)}parseSingleText(raw){const parsed=this.parseOneDate(raw);return parsed?formatISO(parsed):null}localizedRangeSeparator(){const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"});try{const parts=formatter.formatRangeToParts(localDate(2026,0,2),localDate(2026,0,3)),firstEnd=parts.findIndex(part=>part.source==="endRange");let lastStart=-1;for(let index=0;index<firstEnd;index++)parts[index]?.source==="startRange"&&(lastStart=index);const separator=parts.slice(lastStart+1,firstEnd).map(part=>part.value).join("");return normalizeLocalizedDateText(separator,this.effectiveLocale)||"\u2013"}catch{return"\u2013"}}parseRangeText(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),raw===normalizeLocalizedDateText(this.displayText,this.effectiveLocale)&&this.value.includes("/"))return this.normalizeCommittedValue(this.value);if(/^\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}$/.test(raw)){const[a,b]=raw.split("/"),from2=parseISO(a),to2=parseISO(b);return!from2||!to2?null:from2<=to2?raw:`${b}/${a}`}const separator=this.localizedRangeSeparator(),idx=raw.indexOf(separator);if(idx===-1)return null;const from=this.parseOneDate(raw.slice(0,idx).trim()),to=this.parseOneDate(raw.slice(idx+separator.length).trim());return!from||!to?null:from<=to?`${formatISO(from)}/${formatISO(to)}`:`${formatISO(to)}/${formatISO(from)}`}click(){this.liveDisabled||this.inputElement?.click()}focus(options){this.liveDisabled||this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.applyTypedText(input.value))}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formResetCallback(){super.formResetCallback(),this.touched=!1}formDisabledCallback(disabled){Object.getPrototypeOf(LyraDateInput.prototype).formDisabledCallback.call(this,disabled),disabled&&this.hide(),this.syncCustomStates()}render(){const hasValue=this.value.length>0,hasHint=this.withHint||this.hasHintSlot||this.hint.length>0,hasError=this.hasErrorSlot||this.errorText.length>0,hasLabel=this.withLabel||this.hasLabelSlot||this.label.length>0,invalid=this.touched&&!this.internals.validity.valid,describedBy=[hasError?"date-input-error":"",hasHint?"date-input-hint":""].filter(Boolean).join(" "),dynamicDaySlots=[...new Set(Array.from(this.children??[]).map(child=>child.getAttribute("slot")??"").filter(name=>/^day-\d{4}-\d{2}-\d{2}$/.test(name)))];return html`
|
|
2
2
|
<div part="date-input">
|
|
3
3
|
<div part="base">
|
|
4
4
|
<div part="form-control">
|
|
@@ -114,6 +114,8 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
114
114
|
.withWeekNumbers=${this.withWeekNumbers}
|
|
115
115
|
.firstDayOfWeek=${this.firstDayOfWeek}
|
|
116
116
|
.weekdayFormat=${normalizeWeekdayFormat(this.weekdayFormat)}
|
|
117
|
+
.presets=${this.presets}
|
|
118
|
+
exportparts="presets, preset-button"
|
|
117
119
|
@input=${this.onPickerInput}
|
|
118
120
|
@change=${this.onPickerChange}
|
|
119
121
|
@lr-focus-day=${event=>event.stopPropagation()}
|
|
@@ -142,4 +144,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
142
144
|
</div>
|
|
143
145
|
</div>
|
|
144
146
|
</div>
|
|
145
|
-
`}}__decorate([property({converter:appearanceConverter,reflect:!0})],LyraDateInput.prototype,"appearance",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDateInput.prototype,"open",null),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraDateInput.prototype,"withClear",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraDateInput.prototype,"withHint",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraDateInput.prototype,"withLabel",void 0),__decorate([property({reflect:!0})],LyraDateInput.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDateInput.prototype,"pill",void 0),__decorate([property()],LyraDateInput.prototype,"label",void 0),__decorate([property()],LyraDateInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraDateInput.prototype,"errorText",void 0),__decorate([property()],LyraDateInput.prototype,"placeholder",void 0),__decorate([property({converter:spellcheckConverter})],LyraDateInput.prototype,"spellcheck",void 0),__decorate([property()],LyraDateInput.prototype,"autocapitalize",void 0),__decorate([property({attribute:"autocorrect"})],LyraDateInput.prototype,"autoCorrect",void 0),__decorate([property()],LyraDateInput.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraDateInput.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraDateInput.prototype,"enterKeyHint",void 0),__decorate([property({attribute:"aria-label"})],LyraDateInput.prototype,"accessibleLabel",void 0),__decorate([property()],LyraDateInput.prototype,"locale",void 0),__decorate([property({converter:monthsConverter,reflect:!0})],LyraDateInput.prototype,"months",void 0),__decorate([property({attribute:"first-day-of-week",reflect:!0})],LyraDateInput.prototype,"firstDayOfWeek",void 0),__decorate([property({attribute:"weekday-format",converter:weekdayFormatConverter,reflect:!0})],LyraDateInput.prototype,"weekdayFormat",void 0),__decorate([property({type:Boolean,attribute:"with-outside-days",reflect:!0})],LyraDateInput.prototype,"withOutsideDays",void 0),__decorate([property({type:Boolean,attribute:"with-week-numbers",reflect:!0})],LyraDateInput.prototype,"withWeekNumbers",void 0),__decorate([property({attribute:"disabled-dates"})],LyraDateInput.prototype,"disabledDates",void 0),__decorate([property({attribute:"disabled-days-of-week"})],LyraDateInput.prototype,"disabledDaysOfWeek",void 0),__decorate([property({attribute:!1})],LyraDateInput.prototype,"isDateDisabled",void 0),__decorate([property({attribute:!1})],LyraDateInput.prototype,"dayContent",void 0),__decorate([property({type:Number,attribute:"min-range",reflect:!0})],LyraDateInput.prototype,"minRange",void 0),__decorate([property({type:Number,attribute:"max-range",reflect:!0})],LyraDateInput.prototype,"maxRange",void 0),__decorate([property({converter:pageByConverter,attribute:"page-by",reflect:!0})],LyraDateInput.prototype,"pageBy",void 0),__decorate([property({reflect:!0})],LyraDateInput.prototype,"today",void 0),__decorate([property({type:Number,reflect:!0})],LyraDateInput.prototype,"distance",void 0),__decorate([property({converter:placementConverter,reflect:!0})],LyraDateInput.prototype,"placement",void 0),__decorate([property({attribute:!1})],LyraDateInput.prototype,"assumeInteractionOn",void 0),__decorate([property({attribute:!1})],LyraDateInput.prototype,"validators",void 0),__decorate([property({attribute:"clear-label"})],LyraDateInput.prototype,"clearLabel",void 0),__decorate([property({attribute:"open-label"})],LyraDateInput.prototype,"openLabel",void 0),__decorate([property({attribute:"dialog-label"})],LyraDateInput.prototype,"dialogLabel",void 0),__decorate([query('input[part="input"]')],LyraDateInput.prototype,"inputElement",void 0),__decorate([state()],LyraDateInput.prototype,"touched",void 0),__decorate([state()],LyraDateInput.prototype,"hasHintSlot",void 0),__decorate([state()],LyraDateInput.prototype,"hasErrorSlot",void 0),__decorate([state()],LyraDateInput.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraDateInput.prototype,"hasStartSlot",void 0),__decorate([state()],LyraDateInput.prototype,"hasEndSlot",void 0),__decorate([state()],LyraDateInput.prototype,"validityRevision",void 0);export{LyraDateInput};
|
|
147
|
+
`}}__decorate([property({converter:appearanceConverter,reflect:!0})],LyraDateInput.prototype,"appearance",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDateInput.prototype,"open",null),__decorate([property({type:Boolean,attribute:"with-clear"})],LyraDateInput.prototype,"withClear",void 0),__decorate([property({type:Boolean,attribute:"with-hint"})],LyraDateInput.prototype,"withHint",void 0),__decorate([property({type:Boolean,attribute:"with-label"})],LyraDateInput.prototype,"withLabel",void 0),__decorate([property({reflect:!0})],LyraDateInput.prototype,"size",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDateInput.prototype,"pill",void 0),__decorate([property()],LyraDateInput.prototype,"label",void 0),__decorate([property()],LyraDateInput.prototype,"hint",void 0),__decorate([property({attribute:"error-text"})],LyraDateInput.prototype,"errorText",void 0),__decorate([property()],LyraDateInput.prototype,"placeholder",void 0),__decorate([property({converter:spellcheckConverter})],LyraDateInput.prototype,"spellcheck",void 0),__decorate([property()],LyraDateInput.prototype,"autocapitalize",void 0),__decorate([property({attribute:"autocorrect"})],LyraDateInput.prototype,"autoCorrect",void 0),__decorate([property()],LyraDateInput.prototype,"autocomplete",void 0),__decorate([property({attribute:"inputmode"})],LyraDateInput.prototype,"inputMode",void 0),__decorate([property({attribute:"enterkeyhint"})],LyraDateInput.prototype,"enterKeyHint",void 0),__decorate([property({attribute:"aria-label"})],LyraDateInput.prototype,"accessibleLabel",void 0),__decorate([property()],LyraDateInput.prototype,"locale",void 0),__decorate([property({converter:monthsConverter,reflect:!0})],LyraDateInput.prototype,"months",void 0),__decorate([property({attribute:"first-day-of-week",reflect:!0})],LyraDateInput.prototype,"firstDayOfWeek",void 0),__decorate([property({attribute:"weekday-format",converter:weekdayFormatConverter,reflect:!0})],LyraDateInput.prototype,"weekdayFormat",void 0),__decorate([property({attribute:!1})],LyraDateInput.prototype,"presets",void 0),__decorate([property({type:Boolean,attribute:"with-outside-days",reflect:!0})],LyraDateInput.prototype,"withOutsideDays",void 0),__decorate([property({type:Boolean,attribute:"with-week-numbers",reflect:!0})],LyraDateInput.prototype,"withWeekNumbers",void 0),__decorate([property({attribute:"disabled-dates"})],LyraDateInput.prototype,"disabledDates",void 0),__decorate([property({attribute:"disabled-days-of-week"})],LyraDateInput.prototype,"disabledDaysOfWeek",void 0),__decorate([property({attribute:!1})],LyraDateInput.prototype,"isDateDisabled",void 0),__decorate([property({attribute:!1})],LyraDateInput.prototype,"dayContent",void 0),__decorate([property({type:Number,attribute:"min-range",reflect:!0})],LyraDateInput.prototype,"minRange",void 0),__decorate([property({type:Number,attribute:"max-range",reflect:!0})],LyraDateInput.prototype,"maxRange",void 0),__decorate([property({converter:pageByConverter,attribute:"page-by",reflect:!0})],LyraDateInput.prototype,"pageBy",void 0),__decorate([property({reflect:!0})],LyraDateInput.prototype,"today",void 0),__decorate([property({type:Number,reflect:!0})],LyraDateInput.prototype,"distance",void 0),__decorate([property({converter:placementConverter,reflect:!0})],LyraDateInput.prototype,"placement",void 0),__decorate([property({attribute:!1})],LyraDateInput.prototype,"assumeInteractionOn",void 0),__decorate([property({attribute:!1})],LyraDateInput.prototype,"validators",void 0),__decorate([property({attribute:"clear-label"})],LyraDateInput.prototype,"clearLabel",void 0),__decorate([property({attribute:"open-label"})],LyraDateInput.prototype,"openLabel",void 0),__decorate([property({attribute:"dialog-label"})],LyraDateInput.prototype,"dialogLabel",void 0),__decorate([query('input[part="input"]')],LyraDateInput.prototype,"inputElement",void 0),__decorate([state()],LyraDateInput.prototype,"touched",void 0),__decorate([state()],LyraDateInput.prototype,"hasHintSlot",void 0),__decorate([state()],LyraDateInput.prototype,"hasErrorSlot",void 0),__decorate([state()],LyraDateInput.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraDateInput.prototype,"hasStartSlot",void 0),__decorate([state()],LyraDateInput.prototype,"hasEndSlot",void 0),__decorate([state()],LyraDateInput.prototype,"validityRevision",void 0);export{LyraDateInput};
|
|
@@ -22,6 +22,25 @@ export interface LyraDatePickerEventMap {
|
|
|
22
22
|
date: Date;
|
|
23
23
|
}>;
|
|
24
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* One quick-range option for `presets`.
|
|
27
|
+
*
|
|
28
|
+
* Deliberately the same shape as `<lr-time-range>`'s `TimeRangePreset` (`label`/`start`/`end`,
|
|
29
|
+
* rendered as an `aria-pressed` button row) so the library has one preset vocabulary rather than
|
|
30
|
+
* two. The only difference is the unit: ISO `YYYY-MM-DD` dates instead of numbers, because this
|
|
31
|
+
* control's domain is dates.
|
|
32
|
+
*/
|
|
33
|
+
export interface LyraDateRangePreset {
|
|
34
|
+
readonly label: string;
|
|
35
|
+
/**
|
|
36
|
+
* Inclusive range start, ISO `YYYY-MM-DD`. Omit (or leave empty) for an OPEN start, which
|
|
37
|
+
* resolves to the picker's `min`. An open bound with no corresponding `min`/`max` cannot be
|
|
38
|
+
* resolved, so its button renders disabled rather than doing nothing when pressed.
|
|
39
|
+
*/
|
|
40
|
+
readonly start?: string;
|
|
41
|
+
/** Inclusive range end, ISO `YYYY-MM-DD`. Omit for an OPEN end, resolving to `max`. */
|
|
42
|
+
readonly end?: string;
|
|
43
|
+
}
|
|
25
44
|
/**
|
|
26
45
|
* `<lr-date-picker>` — an inline month-grid calendar for picking a single date
|
|
27
46
|
* or a date range. Mirrors the core `<wa-date-picker>` API under `lr-`.
|
|
@@ -79,6 +98,15 @@ export interface LyraDatePickerEventMap {
|
|
|
79
98
|
* @csspart day-label - The visible day label.
|
|
80
99
|
* @csspart day-weekend - A Saturday or Sunday.
|
|
81
100
|
* @csspart day-placeholder - A non-day grid placeholder.
|
|
101
|
+
* @csspart presets - The quick-range button row, rendered only in range mode with `presets` set.
|
|
102
|
+
* @csspart preset-button - One quick-range button; carries `data-active` while its range is the
|
|
103
|
+
* current value.
|
|
104
|
+
* @cssprop [--lr-date-picker-preset-hover-bg=var(--lr-color-brand-quiet)] - Hover background of a
|
|
105
|
+
* quick-range button.
|
|
106
|
+
* @cssprop --lr-date-picker-preset-active-bg - Pressed background of a quick-range button;
|
|
107
|
+
* defaults to a mix of the hover background with the shared active mix partner.
|
|
108
|
+
* @cssprop [--lr-date-picker-preset-selected-bg=var(--lr-color-brand)] - Background and border of
|
|
109
|
+
* the quick-range button whose range is currently selected.
|
|
82
110
|
* @csspart weeknumbers - The week-number column.
|
|
83
111
|
* @csspart weeknumber - One week number.
|
|
84
112
|
* @csspart footer - The footer region.
|
|
@@ -152,6 +180,42 @@ export declare class LyraDatePicker extends LyraElement<LyraDatePickerEventMap>
|
|
|
152
180
|
isDateDisabled?: (date: Date) => boolean;
|
|
153
181
|
/** Optional JavaScript renderer for individual calendar-day content. */
|
|
154
182
|
dayContent?: LyraDatePickerDayContent;
|
|
183
|
+
/**
|
|
184
|
+
* Quick-range options rendered as a `[part="presets"]` button row above the calendar, for the
|
|
185
|
+
* dashboard time-filter shape (Today / Last 7 days / Last 30 days / This month / All time).
|
|
186
|
+
*
|
|
187
|
+
* Range mode only — a preset names two dates, so it has no meaning for a single-date picker and
|
|
188
|
+
* is ignored there rather than rendering a row that cannot do anything. Unset renders nothing at
|
|
189
|
+
* all, so an existing picker is unchanged.
|
|
190
|
+
*
|
|
191
|
+
* Applying one commits the range exactly as a two-click selection would (clamped to `min`/`max`,
|
|
192
|
+
* then `input` followed by `change`), so a consumer's existing change handling needs no special
|
|
193
|
+
* case. The active preset carries `aria-pressed="true"` and `data-active`, mirroring
|
|
194
|
+
* `<lr-time-range>`'s already-shipped preset row.
|
|
195
|
+
*/
|
|
196
|
+
presets: readonly LyraDateRangePreset[];
|
|
197
|
+
private _appliedPreset?;
|
|
198
|
+
/**
|
|
199
|
+
* The preset whose button produced the current `value`, or `undefined` when the range was picked
|
|
200
|
+
* by hand. Read it inside your own `change`/`input` handler.
|
|
201
|
+
*
|
|
202
|
+
* Exists because a dashboard filter has to persist WHICH preset is active, not the pair it froze
|
|
203
|
+
* to: "Last 7 days" must still mean the last 7 days after tomorrow's reload. That fact is not
|
|
204
|
+
* recoverable from `value` -- re-deriving it by string-matching is the mapping table `presets`
|
|
205
|
+
* exists to delete, and it is ambiguous anyway (Today and This month coincide on the 1st of a
|
|
206
|
+
* month, and a hand-picked range can equal a preset's pair by construction).
|
|
207
|
+
*
|
|
208
|
+
* A property rather than an event detail: `input`/`change` are NATIVE events here, deliberately
|
|
209
|
+
* indistinguishable from a manual selection so existing handlers need no special case, and a
|
|
210
|
+
* native Event cannot carry a detail without changing its type.
|
|
211
|
+
*/
|
|
212
|
+
get appliedPreset(): LyraDateRangePreset | undefined;
|
|
213
|
+
/**
|
|
214
|
+
* Resolves a preset's bounds, treating an omitted/empty `start` or `end` as open and falling back
|
|
215
|
+
* to `min`/`max`. Returns null when an open bound has no corresponding limit -- there is simply no
|
|
216
|
+
* date to use, and `value`'s `YYYY-MM-DD/YYYY-MM-DD` form has no unbounded spelling.
|
|
217
|
+
*/
|
|
218
|
+
private resolvePresetRange;
|
|
155
219
|
minRange: number;
|
|
156
220
|
maxRange: number;
|
|
157
221
|
pageBy: LyraDatePickerPageBy;
|
|
@@ -266,6 +330,14 @@ export declare class LyraDatePicker extends LyraElement<LyraDatePickerEventMap>
|
|
|
266
330
|
private pickViewItem;
|
|
267
331
|
private navView;
|
|
268
332
|
private renderView;
|
|
333
|
+
/** The quick-range row. Range mode only -- see `presets`. */
|
|
334
|
+
private renderPresets;
|
|
335
|
+
/**
|
|
336
|
+
* Commits a preset through the same `commit()` path a two-click range selection uses, so the
|
|
337
|
+
* event pair, the ISO serialization and the min/max clamping are identical -- a consumer's
|
|
338
|
+
* change handler cannot tell the two apart, which is the point.
|
|
339
|
+
*/
|
|
340
|
+
private applyPreset;
|
|
269
341
|
render(): TemplateResult;
|
|
270
342
|
}
|
|
271
343
|
declare global {
|
|
@@ -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{chevronIcon}from"../../../internal/icons.js";import{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{isDateObject}from"../../../internal/dom-guards.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};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]}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.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.focusedDate="",this.view="days",this.previousLabel="Previous month",this.nextLabel="Next month",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.suppressViewSync=!1,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(!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]??"")}}get valueAsDate(){return this.effectiveMode==="single"?this.selection.from:null}set valueAsDate(next){if(!isDateObject(next)||!Number.isFinite(next.getTime())){this.value="";return}this.value=formatISO(next)}get valueAsRange(){return this.effectiveMode==="range"?this.selection:{from:null,to:null}}set valueAsRange(next){let from=isDateObject(next?.from)&&Number.isFinite(next.from.getTime())?next.from:null,to=isDateObject(next?.to)&&Number.isFinite(next.to.getTime())?next.to:null;from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get 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=this.renderRoot?.activeElement??null,activeViewStart=activeElement?.matches('[part~="view-item"]')?parseISO(activeElement.getAttribute("data-view-start")??""):null;if(changed.has("value")){const external=!this.suppressViewSync;if(this.suppressViewSync=!1,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.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(){if(this.disabledDatesCacheSource===this.disabledDates)return this.disabledDatesCache;this.disabledDatesCacheSource=this.disabledDates;const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return this.disabledDatesCache=new Set(values.map(value=>isDateObject(value)?value:parseISO(String(value))).filter(value=>isDateObject(value)&&Number.isFinite(value.getTime())).map(value=>formatISO(value))),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){if(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(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){if(!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;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),disabled&&(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}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.suppressViewSync=!0),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))if(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.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),parseISO(this.max));this.viewDate=localDate(clamped.getFullYear(),clamped.getMonth(),1),this.setFocusedDate(clamped),this.focusPending=!0}nav(delta){const page=this.pageBy==="single"?1:this.visibleMonths;this.viewDate=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:localDate(start.getFullYear(),start.getMonth()+span,0)}})}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(addMonths(last.start,span),1):backward?this.firstEnabledViewPeriod(addMonths(first.start,-span),-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++){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=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;if(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(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{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{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{isDateObject}from"../../../internal/dom-guards.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};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]}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},from=bound(preset.start,this.min),to=bound(preset.end,this.max);return!from||!to?null:from.getTime()<=to.getTime()?{from,to}:{from:to,to:from}}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.nextLabel="Next month",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.suppressViewSync=!1,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(!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]??"")}}get valueAsDate(){return this.effectiveMode==="single"?this.selection.from:null}set valueAsDate(next){if(!isDateObject(next)||!Number.isFinite(next.getTime())){this.value="";return}this.value=formatISO(next)}get valueAsRange(){return this.effectiveMode==="range"?this.selection:{from:null,to:null}}set valueAsRange(next){let from=isDateObject(next?.from)&&Number.isFinite(next.from.getTime())?next.from:null,to=isDateObject(next?.to)&&Number.isFinite(next.to.getTime())?next.to:null;from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get 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=this.renderRoot?.activeElement??null,activeViewStart=activeElement?.matches('[part~="view-item"]')?parseISO(activeElement.getAttribute("data-view-start")??""):null;if(changed.has("value")){const external=!this.suppressViewSync;if(this.suppressViewSync=!1,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.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(){if(this.disabledDatesCacheSource===this.disabledDates)return this.disabledDatesCache;this.disabledDatesCacheSource=this.disabledDates;const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return this.disabledDatesCache=new Set(values.map(value=>isDateObject(value)?value:parseISO(String(value))).filter(value=>isDateObject(value)&&Number.isFinite(value.getTime())).map(value=>formatISO(value))),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){if(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(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){if(!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;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),disabled&&(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}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.suppressViewSync=!0),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))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.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),parseISO(this.max));this.viewDate=localDate(clamped.getFullYear(),clamped.getMonth(),1),this.setFocusedDate(clamped),this.focusPending=!0}nav(delta){const page=this.pageBy==="single"?1:this.visibleMonths;this.viewDate=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:localDate(start.getFullYear(),start.getMonth()+span,0)}})}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(addMonths(last.start,span),1):backward?this.firstEnabledViewPeriod(addMonths(first.start,-span),-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++){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=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;if(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(outside&&!this.withOutsideDays)return html`<span
|
|
2
2
|
part="day-placeholder"
|
|
3
3
|
role="gridcell"
|
|
4
4
|
aria-hidden=${rowHasVisibleDay?"true":nothing}
|
|
@@ -140,9 +140,21 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
140
140
|
${row.map(item=>this.renderViewItem(item.start,item.end,item.label,today,selected,focused!=null&&isSameDay(item.start,focused)))}
|
|
141
141
|
</div>`)}
|
|
142
142
|
</div>
|
|
143
|
-
`}
|
|
143
|
+
`}renderPresets(){return this.effectiveMode!=="range"||this.presets.length===0?nothing:html`<div part="presets">
|
|
144
|
+
${this.presets.map(preset=>{const resolved=this.resolvePresetRange(preset),active=resolved!==null&&this.value===`${formatISO(resolved.from)}/${formatISO(resolved.to)}`;return html`<button
|
|
145
|
+
part="preset-button"
|
|
146
|
+
type="button"
|
|
147
|
+
?disabled=${this.disabled||this.readonly||resolved===null}
|
|
148
|
+
aria-pressed=${active?"true":"false"}
|
|
149
|
+
?data-active=${active}
|
|
150
|
+
@click=${()=>this.applyPreset(preset)}
|
|
151
|
+
>
|
|
152
|
+
${preset.label}
|
|
153
|
+
</button>`})}
|
|
154
|
+
</div>`}applyPreset(preset){if(this.disabled||this.readonly)return;const resolved=this.resolvePresetRange(preset);resolved&&(this._appliedPreset=preset,this.setFocusedDate(resolved.from),this.commit(resolved.from,resolved.to,!0))}render(){const selection=this.selection,min=parseISO(this.min),max=parseISO(this.max),today=this.resolvedToday(),fdow=this.fdow,labels=weekdayLabels(fdow,this.effectiveWeekdayFormat,this.effectiveLocale),dayLabelFmt=dateTimeFormat(this.effectiveLocale,{weekday:"long",year:"numeric",month:"long",day:"numeric"}),fallbackFocusDate=this.focusedDateValue||selection.from?null:this.firstEnabledDate(min,max,today),monthEls=[];if(this.effectiveView==="days")for(let i=0;i<this.visibleMonths;i++)monthEls.push(this.renderMonth(i,selection,min,max,today,fdow,labels,fallbackFocusDate,dayLabelFmt));return html`<div part="base date-picker">
|
|
144
155
|
<div class="content">
|
|
156
|
+
${this.renderPresets()}
|
|
145
157
|
${this.effectiveView==="days"?html`<div part="months">${monthEls}</div>`:this.renderView(today)}
|
|
146
158
|
<div part="footer"><slot name="footer"></slot></div>
|
|
147
159
|
</div>
|
|
148
|
-
</div>`}}__decorate([property({reflect:!0})],LyraDatePicker.prototype,"value",void 0),__decorate([property({converter:modeConverter,reflect:!0})],LyraDatePicker.prototype,"mode",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"min",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"max",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDatePicker.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDatePicker.prototype,"readonly",void 0),__decorate([property({converter:monthsConverter,reflect:!0})],LyraDatePicker.prototype,"months",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"locale",void 0),__decorate([property({attribute:"first-day-of-week",reflect:!0})],LyraDatePicker.prototype,"firstDayOfWeek",void 0),__decorate([property({attribute:"weekday-format",converter:weekdayFormatConverter,reflect:!0})],LyraDatePicker.prototype,"weekdayFormat",void 0),__decorate([property({type:Boolean,attribute:"disable-past",reflect:!0})],LyraDatePicker.prototype,"disablePast",void 0),__decorate([property({type:Boolean,attribute:"disable-future",reflect:!0})],LyraDatePicker.prototype,"disableFuture",void 0),__decorate([property({type:Boolean,attribute:"with-outside-days",reflect:!0})],LyraDatePicker.prototype,"withOutsideDays",void 0),__decorate([property({type:Boolean,attribute:"with-week-numbers",reflect:!0})],LyraDatePicker.prototype,"withWeekNumbers",void 0),__decorate([property({attribute:"disabled-dates"})],LyraDatePicker.prototype,"disabledDates",void 0),__decorate([property({attribute:"disabled-days-of-week"})],LyraDatePicker.prototype,"disabledDaysOfWeek",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"isDateDisabled",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"dayContent",void 0),__decorate([property({type:Number,attribute:"min-range",reflect:!0})],LyraDatePicker.prototype,"minRange",void 0),__decorate([property({type:Number,attribute:"max-range",reflect:!0})],LyraDatePicker.prototype,"maxRange",void 0),__decorate([property({attribute:"page-by",reflect:!0,converter:pageByConverter})],LyraDatePicker.prototype,"pageBy",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"today",void 0),__decorate([property({attribute:"focused-date",reflect:!0})],LyraDatePicker.prototype,"focusedDate",void 0),__decorate([property({reflect:!0,converter:viewConverter})],LyraDatePicker.prototype,"view",void 0),__decorate([property({attribute:"previous-label"})],LyraDatePicker.prototype,"previousLabel",void 0),__decorate([property({attribute:"next-label"})],LyraDatePicker.prototype,"nextLabel",void 0),__decorate([state()],LyraDatePicker.prototype,"viewDate",void 0),__decorate([state()],LyraDatePicker.prototype,"rangePreview",void 0);export{LyraDatePicker};
|
|
160
|
+
</div>`}}__decorate([property({reflect:!0})],LyraDatePicker.prototype,"value",void 0),__decorate([property({converter:modeConverter,reflect:!0})],LyraDatePicker.prototype,"mode",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"min",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"max",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDatePicker.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraDatePicker.prototype,"readonly",void 0),__decorate([property({converter:monthsConverter,reflect:!0})],LyraDatePicker.prototype,"months",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"size",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"locale",void 0),__decorate([property({attribute:"first-day-of-week",reflect:!0})],LyraDatePicker.prototype,"firstDayOfWeek",void 0),__decorate([property({attribute:"weekday-format",converter:weekdayFormatConverter,reflect:!0})],LyraDatePicker.prototype,"weekdayFormat",void 0),__decorate([property({type:Boolean,attribute:"disable-past",reflect:!0})],LyraDatePicker.prototype,"disablePast",void 0),__decorate([property({type:Boolean,attribute:"disable-future",reflect:!0})],LyraDatePicker.prototype,"disableFuture",void 0),__decorate([property({type:Boolean,attribute:"with-outside-days",reflect:!0})],LyraDatePicker.prototype,"withOutsideDays",void 0),__decorate([property({type:Boolean,attribute:"with-week-numbers",reflect:!0})],LyraDatePicker.prototype,"withWeekNumbers",void 0),__decorate([property({attribute:"disabled-dates"})],LyraDatePicker.prototype,"disabledDates",void 0),__decorate([property({attribute:"disabled-days-of-week"})],LyraDatePicker.prototype,"disabledDaysOfWeek",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"isDateDisabled",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"dayContent",void 0),__decorate([property({attribute:!1})],LyraDatePicker.prototype,"presets",void 0),__decorate([property({type:Number,attribute:"min-range",reflect:!0})],LyraDatePicker.prototype,"minRange",void 0),__decorate([property({type:Number,attribute:"max-range",reflect:!0})],LyraDatePicker.prototype,"maxRange",void 0),__decorate([property({attribute:"page-by",reflect:!0,converter:pageByConverter})],LyraDatePicker.prototype,"pageBy",void 0),__decorate([property({reflect:!0})],LyraDatePicker.prototype,"today",void 0),__decorate([property({attribute:"focused-date",reflect:!0})],LyraDatePicker.prototype,"focusedDate",void 0),__decorate([property({reflect:!0,converter:viewConverter})],LyraDatePicker.prototype,"view",void 0),__decorate([property({attribute:"previous-label"})],LyraDatePicker.prototype,"previousLabel",void 0),__decorate([property({attribute:"next-label"})],LyraDatePicker.prototype,"nextLabel",void 0),__decorate([state()],LyraDatePicker.prototype,"viewDate",void 0),__decorate([state()],LyraDatePicker.prototype,"rangePreview",void 0);export{LyraDatePicker};
|
|
@@ -324,6 +324,47 @@ import{css}from"lit";const styles=css`
|
|
|
324
324
|
var(--lr-opacity-disabled)
|
|
325
325
|
);
|
|
326
326
|
}
|
|
327
|
+
[part~="presets"] {
|
|
328
|
+
display: flex;
|
|
329
|
+
flex-wrap: wrap;
|
|
330
|
+
gap: var(--lr-space-2xs);
|
|
331
|
+
margin-block-end: var(--lr-space-xs);
|
|
332
|
+
}
|
|
333
|
+
[part~="preset-button"] {
|
|
334
|
+
font: inherit;
|
|
335
|
+
font-size: var(--lr-font-size-xs);
|
|
336
|
+
min-block-size: var(--lr-icon-button-size);
|
|
337
|
+
padding: var(--lr-size-0-15rem) var(--lr-size-0-5rem);
|
|
338
|
+
border: var(--lr-border-width-thin) solid var(--lr-color-border);
|
|
339
|
+
border-radius: var(--lr-radius);
|
|
340
|
+
background: var(--lr-color-surface);
|
|
341
|
+
color: var(--lr-color-text);
|
|
342
|
+
cursor: pointer;
|
|
343
|
+
white-space: normal;
|
|
344
|
+
overflow-wrap: break-word;
|
|
345
|
+
}
|
|
346
|
+
[part~="preset-button"]:hover:not(:disabled) {
|
|
347
|
+
background: var(--lr-date-picker-preset-hover-bg, var(--lr-color-brand-quiet));
|
|
348
|
+
}
|
|
349
|
+
[part~="preset-button"]:active:not(:disabled) {
|
|
350
|
+
background: var(
|
|
351
|
+
--lr-date-picker-preset-active-bg,
|
|
352
|
+
color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active))
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
[part~="preset-button"][data-active] {
|
|
356
|
+
background: var(--lr-date-picker-preset-selected-bg, var(--lr-color-brand));
|
|
357
|
+
border-color: var(--lr-date-picker-preset-selected-bg, var(--lr-color-brand));
|
|
358
|
+
color: var(--lr-color-brand-contrast, var(--lr-color-surface));
|
|
359
|
+
}
|
|
360
|
+
[part~="preset-button"]:focus-visible {
|
|
361
|
+
outline: var(--lr-focus-ring);
|
|
362
|
+
outline-offset: var(--lr-focus-ring-offset);
|
|
363
|
+
}
|
|
364
|
+
[part~="preset-button"]:disabled {
|
|
365
|
+
cursor: not-allowed;
|
|
366
|
+
opacity: var(--lr-opacity-disabled);
|
|
367
|
+
}
|
|
327
368
|
@media (forced-colors: active) {
|
|
328
369
|
.calendar-scroll[data-scroll-overflow] {
|
|
329
370
|
-webkit-mask-image: none;
|
|
@@ -363,5 +404,10 @@ import{css}from"lit";const styles=css`
|
|
|
363
404
|
color: GrayText;
|
|
364
405
|
forced-color-adjust: none;
|
|
365
406
|
}
|
|
407
|
+
[part~="preset-button"][data-active] {
|
|
408
|
+
forced-color-adjust: none;
|
|
409
|
+
background: Highlight;
|
|
410
|
+
color: HighlightText;
|
|
411
|
+
}
|
|
366
412
|
}
|
|
367
413
|
`;export{styles};
|
|
@@ -25,7 +25,9 @@ export declare function setFlagUrlResolver(value: LyraFlagUrlResolver | Promise<
|
|
|
25
25
|
* a representative country). While that peer package's `flagUrl()` resolves,
|
|
26
26
|
* the host carries `aria-busy="true"`; a decorative skeleton and ordinary, non-live localized
|
|
27
27
|
* loading text render in its place. A missing or failed peer resolver fails closed with a localized visible error and a
|
|
28
|
-
* shared light-DOM assertive announcement
|
|
28
|
+
* shared light-DOM assertive announcement, plus a one-time `console.warn` naming the code and the
|
|
29
|
+
* `flag-peer.js` import that registers a resolver -- the visible error alone cannot tell a
|
|
30
|
+
* developer that the fix is a missing import rather than missing flag data;
|
|
29
31
|
* an installed resolver returning no URL for an unknown code remains a valid
|
|
30
32
|
* empty result.
|
|
31
33
|
*
|
|
@@ -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{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadFlagUrl(importFlags){try{const resolver=resolverFromModule(await importFlags());if(resolver)return resolver;throw new TypeError("The flag peer does not expose a callable flagUrl capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
|
|
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{keyed}from"lit/directives/keyed.js";import{LyraElement}from"../../../internal/lyra-element.js";import{getDisplayNames}from"../../../internal/intl-cache.js";import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{safeMediaSrc}from"../../../internal/safe-url.js";import{styles}from"./flag.styles.js";import{ALPHA2_RE,alpha3ToAlpha2,languageToCountry}from"./language-map.js";import"../../overlays/skeleton/skeleton.class.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_flagLoadError,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const FLAG_LOAD_ERROR_KEY="flagLoadError",FLAG_FIDELITIES=new Set(["compact","standard","detailed"]),FLAG_SHAPES=new Set(["rect","circle"]);function normalizeFlagFidelity(value){return FLAG_FIDELITIES.has(value)?value:"standard"}function normalizeFlagShape(value){return FLAG_SHAPES.has(value)?value:"rect"}function resolverFromModule(module){try{if(typeof module=="object"&&module!==null||typeof module=="function"){const named=module.flagUrl;if(typeof named=="function")return named;const fallback=module.default??module;if(typeof fallback=="function")return fallback;if(typeof fallback=="object"&&fallback!==null){const defaultNamed=fallback.flagUrl;if(typeof defaultNamed=="function")return defaultNamed}}}catch{}return null}async function loadFlagUrl(importFlags){try{const resolver=resolverFromModule(await importFlags());if(resolver)return resolver;throw new TypeError("The flag peer does not expose a callable flagUrl capability.")}catch{return console.warn("<lr-flag> needs the optional peer dependency '@aceshooting/lyra-flags' to render flag images \u2014 install it with `pnpm add @aceshooting/lyra-flags`."),null}}function displayNameFor(code,locale){try{return getDisplayNames(locale,{type:"region"}).of(code.toUpperCase())??code.toUpperCase()}catch{return code.toUpperCase()}}let flagUrlResolver,flagResolverGeneration=0;const flagResolverSubscribers=new Set;let warnedMissingFlagResolver=!1;function warnMissingFlagResolver(code){warnedMissingFlagResolver||(warnedMissingFlagResolver=!0,console.warn(`<lr-flag> could not resolve the code "${code}" because no flag resolver is registered. Import the optional peer entry once at startup -- import '@aceshooting/lyra-ui/components/media/flag/flag-peer.js' -- and install '@aceshooting/lyra-flags', or pass an already-resolved URL through 'src' instead.`))}function setFlagUrlResolver(value){flagUrlResolver=value===null?Promise.resolve(null):Promise.resolve(value),warnedMissingFlagResolver=!1,flagResolverGeneration++;for(const subscriber of[...flagResolverSubscribers])subscriber(flagResolverGeneration)}function loadFlagUrlResolver(){return flagUrlResolver||(flagUrlResolver=Promise.resolve(null)),flagUrlResolver}class LyraFlag extends LyraElement{constructor(){super(...arguments),this._shape="rect",this._fidelity="standard",this.sourceState=Object.freeze({status:"idle",identity:"idle"}),this.resolverGeneration=flagResolverGeneration,this.sourceRestartPending=!0,this.activeSourceRequest=0,this.resolveToken=0,this.onResolverGeneration=generation=>{!this.isConnected||generation===this.resolverGeneration||(this.resolverGeneration=generation)}}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,flagLoadError:LYRA_DEFAULT_flagLoadError,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles,srOnly]}get shape(){return this._shape}set shape(value){const old=this._shape;this._shape=normalizeFlagShape(value),this.requestUpdate("shape",old)}get fidelity(){return this._fidelity}set fidelity(value){const old=this._fidelity;this._fidelity=normalizeFlagFidelity(value),this.requestUpdate("fidelity",old)}get effectiveFidelity(){return normalizeFlagFidelity(this.fidelity)}get loading(){return this.sourceState.status==="loading"}get code(){if(this.country)return ALPHA2_RE.test(this.country)?this.country.toLowerCase():alpha3ToAlpha2(this.country);if(this.language)return languageToCountry(this.language)}get unresolved(){return this.src||!this.country&&!this.language?!1:this.code===void 0}connectedCallback(){super.connectedCallback(),this.sourceRestartPending=!0,flagResolverSubscribers.add(this.onResolverGeneration),this.syncErrorAnnouncementSink(),this.resolverGeneration!==flagResolverGeneration&&(this.resolverGeneration=flagResolverGeneration),this.requestUpdate()}disconnectedCallback(){this.resolveToken++,this.sourceRestartPending=!0,flagResolverSubscribers.delete(this.onResolverGeneration),this.releaseErrorAnnouncementSink(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resolveToken++,this.sourceRestartPending=!0,this.releaseErrorAnnouncementSink(),this.syncErrorAnnouncementSink(),this.requestUpdate()}syncErrorAnnouncementSink(){this.isConnected&&this.errorAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseErrorAnnouncementSink(),this.errorAnnouncementSink=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this}))}releaseErrorAnnouncementSink(){this.errorAnnouncementSink?.release(),this.errorAnnouncementSink=void 0}announceLoadError(){this.errorAnnouncementSink?.announce(this.localize(FLAG_LOAD_ERROR_KEY))}setSourceState(state2,announceError=!1){this.sourceState=Object.freeze(state2),this.toggleAttribute("data-error",state2.status==="error"),this.toggleAttribute("data-unresolved",this.unresolved),this.setAttribute("aria-busy",String(state2.status==="loading")),announceError&&this.isConnected&&this.announceLoadError()}failSource(identity,announce=!0){this.setSourceState({status:"error",identity},announce)}onImageLoad(event,identity,url,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.sourceState.url!==url||this.setSourceState({status:"loaded",identity,url})}onImageError(event,identity,request){const image=event.currentTarget;!this.isConnected||request!==this.activeSourceRequest||!image||image!==this.renderRoot.querySelector('[part="image"]')||this.sourceState.status!=="loading"||this.sourceState.identity!==identity||this.failSource(identity)}willUpdate(changed){super.willUpdate(changed);const sourceChanged=changed.has("country")||changed.has("language")||changed.has("src")||changed.has("fidelity")||changed.has("resolverGeneration");if(typeof Node<"u"&&!this.isConnected){sourceChanged&&(this.resolveToken++,this.sourceRestartPending=!0);return}if(this.hasUpdated&&!sourceChanged&&!this.sourceRestartPending)return;const connectionBaseline=this.sourceRestartPending;this.sourceRestartPending=!1;const token=++this.resolveToken,request=++this.activeSourceRequest,URLCtor=this.ownerDocument?.defaultView?.URL??globalThis.URL,directValue=typeof this.src=="string"?this.src.trim():"";if(directValue){const identity2=`direct:${directValue}`,url=safeMediaSrc(directValue,URLCtor);if(!url){this.failSource(identity2,!connectionBaseline);return}this.setSourceState({status:"loading",identity:identity2,url});return}const code=this.code;if(!code){this.setSourceState({status:"idle",identity:"idle"});return}const fidelity=this.effectiveFidelity,identity=`peer:${code}:${fidelity}:${this.resolverGeneration}`;this.setSourceState({status:"loading",identity}),loadFlagUrlResolver().then(async resolve=>{if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(typeof resolve!="function"){warnMissingFlagResolver(code),this.failSource(identity);return}const candidate=await resolve(code,fidelity==="standard"?void 0:{variant:fidelity});if(token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected)return;if(candidate===void 0){this.setSourceState({status:"idle",identity});return}const url=safeMediaSrc(candidate,URLCtor);if(!url){this.failSource(identity);return}this.setSourceState({status:"loading",identity,url})}).catch(err=>{token!==this.resolveToken||request!==this.activeSourceRequest||!this.isConnected||(console.warn(`<lr-flag> failed to resolve a flag URL for "${code}":`,err),this.failSource(identity))})}updated(changed){super.updated(changed),this.setAttribute("aria-busy",String(this.sourceState.status==="loading")),this.toggleAttribute("data-unresolved",this.unresolved)}render(){const state2=this.sourceState,request=this.activeSourceRequest;if(this.unresolved)return html`<slot name="fallback"
|
|
2
2
|
>${this.fallback?html`<img part="fallback-image" src=${this.fallback} alt=${this.label??""} />`:nothing}</slot
|
|
3
3
|
>`;if(state2.status==="error")return html`<span part="error">${this.localize(FLAG_LOAD_ERROR_KEY)}</span>`;const url=state2.status==="loading"||state2.status==="loaded"?state2.url:void 0;if(!url&&state2.status!=="loading")return html``;const code=this.code,alt=hostAriaLabel(this)??this.label??(code?displayNameFor(code,this.effectiveLocale):"");return html`
|
|
4
4
|
${state2.status==="loading"?html`
|