@aceshooting/lyra-ui 11.0.0 → 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 +83 -0
- package/custom-elements.json +1 -1
- 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/table/table.class.d.ts +19 -0
- package/dist/components/data/table/table.class.js +3 -3
- 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 +30 -4
- package/dist/components/forms/date-picker/date-picker.class.js +4 -4
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/custom-elements-jsx.d.ts +4 -2
- 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/svelte.d.ts +4 -2
- package/dist/theme.css +32 -0
- package/dist/vue.d.ts +4 -2
- package/llms/components/lr-agent-eval-dashboard.md +1 -1
- package/llms/components/lr-agent-workspace.md +1 -1
- package/llms/components/lr-box-plot.md +2 -2
- package/llms/components/lr-chart.md +1 -1
- package/llms/components/lr-chunk-inspector.md +1 -1
- package/llms/components/lr-combobox.md +3 -3
- package/llms/components/lr-date-input.md +22 -6
- package/llms/components/lr-date-picker.md +21 -5
- package/llms/components/lr-entity-dossier.md +1 -1
- package/llms/components/lr-eval-run.md +1 -1
- package/llms/components/lr-grounding-summary.md +1 -1
- package/llms/components/lr-heatmap.md +2 -2
- package/llms/components/lr-lite-chart.md +19 -3
- package/llms/components/lr-map.md +2 -2
- package/llms/components/lr-memory-panel.md +1 -1
- package/llms/components/lr-option.md +3 -3
- package/llms/components/lr-popover.md +1 -1
- package/llms/components/lr-provenance-panel.md +1 -1
- 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/peers.md +8 -8
- package/llms/tokens.md +12 -0
- package/llms-full.txt +48 -16
- package/package.json +1 -1
- package/vscode-css-data.json +14 -0
- package/vscode-html-data.json +16 -2
- package/web-types.json +29 -3
|
@@ -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};
|
|
@@ -32,10 +32,14 @@ export interface LyraDatePickerEventMap {
|
|
|
32
32
|
*/
|
|
33
33
|
export interface LyraDateRangePreset {
|
|
34
34
|
readonly label: string;
|
|
35
|
-
/**
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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;
|
|
39
43
|
}
|
|
40
44
|
/**
|
|
41
45
|
* `<lr-date-picker>` — an inline month-grid calendar for picking a single date
|
|
@@ -190,6 +194,28 @@ export declare class LyraDatePicker extends LyraElement<LyraDatePickerEventMap>
|
|
|
190
194
|
* `<lr-time-range>`'s already-shipped preset row.
|
|
191
195
|
*/
|
|
192
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;
|
|
193
219
|
minRange: number;
|
|
194
220
|
maxRange: number;
|
|
195
221
|
pageBy: LyraDatePickerPageBy;
|
|
@@ -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.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.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}
|
|
@@ -141,17 +141,17 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
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 active=this.value===`${
|
|
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
145
|
part="preset-button"
|
|
146
146
|
type="button"
|
|
147
|
-
?disabled=${this.disabled||this.readonly}
|
|
147
|
+
?disabled=${this.disabled||this.readonly||resolved===null}
|
|
148
148
|
aria-pressed=${active?"true":"false"}
|
|
149
149
|
?data-active=${active}
|
|
150
150
|
@click=${()=>this.applyPreset(preset)}
|
|
151
151
|
>
|
|
152
152
|
${preset.label}
|
|
153
153
|
</button>`})}
|
|
154
|
-
</div>`}applyPreset(preset){if(this.disabled||this.readonly)return;const
|
|
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">
|
|
155
155
|
<div class="content">
|
|
156
156
|
${this.renderPresets()}
|
|
157
157
|
${this.effectiveView==="days"?html`<div part="months">${monthEls}</div>`:this.renderView(today)}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{ref}from"lit/directives/ref.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{invalidateLyraLocaleCache}from"../../../internal/localization-runtime.js";import{finiteCount,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{isAbortError,isResourceLimitError,LyraUserFacingError,readResponseArrayBuffer,resolveOwnerFetchTarget}from"../../../internal/resource-loader.js";import{srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{sanitizeCssLength,sanitizePercentRect}from"../../../internal/safe-css.js";import{DocumentAnchorTarget,prioritizedHighlightCandidates}from"../../../internal/anchor-target.js";import{boundedSelectionRects,boundedSelectionText,normalizeQuoteText,scopeFromItems,buildQuoteAnchor,createTextQuoteIndex,rangeFromTextQuoteMatch,rangesFromTextQuoteMatches,TEXT_QUOTE_LIMITS}from"../../../internal/text-quote.js";import{ViewerAnnouncementController}from"../viewer-announcements.js";import{boundedViewerSearchQuery}from"../viewer-search-limits.js";import{viewerSemanticLabel,viewerSemanticRole}from"../viewer-semantic-owner.js";import{loadPdfJs}from"./pdf-loader.js";import{styles}from"./pdf-viewer.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LYRA_DEFAULT_anchorJumped,LYRA_DEFAULT_anchorJumpedToPage,LYRA_DEFAULT_anchorNotFound,LYRA_DEFAULT_documentPreviewEmpty,LYRA_DEFAULT_documentPreviewFailedToLoad,LYRA_DEFAULT_documentPreviewResourceTooLarge,LYRA_DEFAULT_documentPreviewTypeDocument,LYRA_DEFAULT_documentPreviewUrlNotAllowed,LYRA_DEFAULT_loadingDocument,LYRA_DEFAULT_pdfViewerCurrentZoom,LYRA_DEFAULT_pdfViewerLabel,LYRA_DEFAULT_pdfViewerMissingLibrary,LYRA_DEFAULT_pdfViewerNextPage,LYRA_DEFAULT_pdfViewerPageOf,LYRA_DEFAULT_pdfViewerPreviousPage,LYRA_DEFAULT_pdfViewerZoomIn,LYRA_DEFAULT_pdfViewerZoomOut}from"../../../internal/default-strings.generated.js";const MIN_ZOOM=.25,MAX_ZOOM=4,ZOOM_STEP=.25,PAGE_TEXT_CACHE_LIMIT=64,PAGE_SEARCH_INDEX_CACHE_LIMIT=8,DEFAULT_THUMBNAIL_WIDTH=96,MAX_THUMBNAIL_WIDTH=2048,MAX_PAGE_COUNT=1e5,MAX_SEARCH_MATCHES=1e4,MAX_PAINTED_SEARCH_MATCHES=200,MAX_PAINTED_SEARCH_MARKS=200,MAX_PAINTED_HIGHLIGHTS=100,MAX_HIGHLIGHT_RESOLUTION_ATTEMPTS=1e3,MAX_HIGHLIGHT_RECTS=1e3,MAX_SEARCH_PAGES=1e3,MAX_OUTLINE_ITEMS=1e4,MAX_OUTLINE_DEPTH=100,MAX_PDF_TEXT_CHUNKS=TEXT_QUOTE_LIMITS.maxNodes;function isReadablePdfTextStream(value){return(typeof value=="object"||typeof value=="function")&&value!==null&&"getReader"in value&&typeof value.getReader=="function"}function appendPdfTextItems(items,accumulator){if(Array.isArray(items))for(let index=0;index<items.length;index++){if(accumulator.inspectedItems>=TEXT_QUOTE_LIMITS.maxNodes){accumulator.truncated=!0;return}accumulator.inspectedItems++;const item=items[index],value=item&&typeof item=="object"&&"str"in item&&typeof item.str=="string"?item.str:"",separator=item&&typeof item=="object"&&"hasEOL"in item&&item.hasEOL===!0?`
|
|
2
|
-
`:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length;if(remaining<=0){accumulator.truncated=!0;return}const retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[]
|
|
2
|
+
`:" ",remaining=TEXT_QUOTE_LIMITS.maxNodeCodeUnits-accumulator.length;if(remaining<=0){accumulator.truncated=!0;return}const retained=value.slice(0,remaining);if(accumulator.chunks.push(retained),accumulator.length+=retained.length,retained.length!==value.length){accumulator.truncated=!0;return}if(accumulator.length>=TEXT_QUOTE_LIMITS.maxNodeCodeUnits){accumulator.truncated=!0;return}accumulator.chunks.push(separator),accumulator.length++}}function boundedPdfTextLayerChunk(value,budget){if(!value||typeof value!="object"||!("items"in value)||!Array.isArray(value.items))return{value,exhausted:!1};const source=value,items=[];let inspected=0;for(;inspected<source.items.length&&budget.remainingItems>0&&budget.remainingCodeUnits>0;){const item=source.items[inspected++];if(!item||typeof item!="object"){items.push(item),budget.remainingItems--;continue}const text="str"in item&&typeof item.str=="string"?item.str:void 0;if(text!==void 0&&text.length>budget.remainingCodeUnits){const retained=text.slice(0,budget.remainingCodeUnits);if(retained){const record=item;items.push({str:retained,dir:record.dir,width:record.width,height:record.height,transform:record.transform,fontName:record.fontName,hasEOL:record.hasEOL}),budget.remainingItems--}budget.remainingCodeUnits=0;break}items.push(item),budget.remainingItems--,text!==void 0&&(budget.remainingCodeUnits-=text.length)}const styles2=Object.create(null);if(source.styles&&typeof source.styles=="object"){const sourceStyles=source.styles;for(const[fontName,style]of Object.entries(sourceStyles))style!==void 0&&(styles2[fontName]=style)}return{value:{items,styles:styles2,lang:source.lang},exhausted:inspected<source.items.length||budget.remainingItems<=0||budget.remainingCodeUnits<=0}}function singleChunkPdfTextStream(value){return new ReadableStream({start(controller){value!==void 0&&controller.enqueue(value),controller.close()}})}function boundedPdfTextLayerSource(source){const budget={remainingItems:TEXT_QUOTE_LIMITS.maxNodes,remainingCodeUnits:TEXT_QUOTE_LIMITS.maxNodeCodeUnits};if(typeof ReadableStream>"u")return;if(!isReadablePdfTextStream(source)){const bounded=boundedPdfTextLayerChunk(source,budget),hasBoundedItems=bounded.value&&typeof bounded.value=="object"&&"items"in bounded.value&&Array.isArray(bounded.value.items);return singleChunkPdfTextStream(hasBoundedItems?bounded.value:void 0)}const reader=source.getReader();let chunks=0,closed=!1;return new ReadableStream({async pull(controller){if(!closed)try{const result=await reader.read();if(result.done){closed=!0,controller.close();return}chunks++;const bounded=boundedPdfTextLayerChunk(result.value,budget);controller.enqueue(bounded.value),(bounded.exhausted||chunks>=MAX_PDF_TEXT_CHUNKS)&&(closed=!0,reader.cancel().catch(()=>{}),controller.close())}catch(error){closed=!0,controller.error(error)}},cancel(reason){return closed=!0,reader.cancel(reason).then(()=>{},()=>{})}})}function clampZoom(value){return finiteRange(value,1,MIN_ZOOM,MAX_ZOOM)}function containsAcrossShadowBoundaries(ancestor,node){let current=node;for(;current;){if(current===ancestor)return!0;current=current.nodeType===11&&"host"in current?current.host:current.parentNode}return!1}function nextPdfPaintNode(node,root){if(node.firstChild)return node.firstChild;let cursor=node;for(;cursor&&cursor!==root;){if(cursor.nextSibling)return cursor.nextSibling;cursor=cursor.parentNode}return null}function wrapPdfSearchRange(range,part,budget){const doc=range.startContainer.ownerDocument;if(!doc||budget.marks<=0)return[];const textNodeType=doc.defaultView?.Node.TEXT_NODE??3;if(range.startContainer===range.endContainer&&range.startContainer.nodeType===textNodeType){const textNode=range.startContainer;if(budget.traversalNodes<=0||budget.codeUnits<=0)return[];const inspectedLength=textNode.data.length;if(inspectedLength>budget.codeUnits)return budget.codeUnits=0,[];budget.traversalNodes--,budget.codeUnits-=inspectedLength;let target=textNode;if(range.endOffset<target.data.length&&target.splitText(range.endOffset),range.startOffset>0&&(target=target.splitText(range.startOffset)),!target.data)return[];const mark=doc.createElement("mark");return mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),budget.marks--,[mark]}const ancestor=range.commonAncestorContainer,covered=[];let node=ancestor;for(;node&&budget.traversalNodes>0&&budget.codeUnits>0;){if(budget.traversalNodes--,node.nodeType===textNodeType){const textNode=node;if(textNode.data.length>budget.codeUnits){budget.codeUnits=0;break}budget.codeUnits-=textNode.data.length;try{if(textNode.data.length>0&&range.intersectsNode(textNode)){if(covered.length>=budget.marks)return[];covered.push(textNode)}}catch{return[]}}node=nextPdfPaintNode(node,ancestor)}if(node)return[];const marks=[];for(const textNode of covered){const start=textNode===range.startContainer?range.startOffset:0,end=textNode===range.endContainer?range.endOffset:textNode.data.length;let target=textNode;if(end<target.data.length&&target.splitText(end),start>0&&(target=target.splitText(start)),!target.data)continue;const mark=doc.createElement("mark");mark.setAttribute("part",part),target.parentNode?.insertBefore(mark,target),mark.appendChild(target),marks.push(mark)}return budget.marks-=marks.length,marks}function unwrapPdfSearchMark(mark){const parent=mark.parentNode;if(!parent)return;const textNodeType=mark.ownerDocument.defaultView?.Node.TEXT_NODE??3,before=mark.previousSibling,after=mark.nextSibling,first=mark.firstChild;for(;mark.firstChild;)parent.insertBefore(mark.firstChild,mark);if(parent.removeChild(mark),before?.nodeType===textNodeType&&first?.nodeType===textNodeType){before.appendData(first.data),first.parentNode?.removeChild(first),after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after));return}first?.nodeType===textNodeType&&after?.nodeType===textNodeType?(first.appendData(after.data),after.parentNode?.removeChild(after)):!first&&before?.nodeType===textNodeType&&after?.nodeType===textNodeType&&(before.appendData(after.data),after.parentNode?.removeChild(after))}class LyraPdfViewerBase extends LyraElement{}class LyraPdfViewer extends DocumentAnchorTarget(LyraPdfViewerBase){constructor(){super(...arguments),this.src="",this.name="",this.page=1,this.zoom=1,this.maxHeight="",this.workerSrc="",this.anchorKinds=["page","text-quote","region"],this.loadState={kind:"idle"},this.pageViewerIdentity=0,this.pageViewerSnapshotValue=Object.freeze({identity:0,status:"idle",page:1,pageCount:0}),this.scrollDrivenPage=!1,this.loadLibrary=loadPdfJs,this.generation=0,this.pageCanvases=new Map,this.pageRenderTasks=new Map,this.pageRenderVersions=new Map,this.pageRenderGeneration=0,this.pageCanvasRefs=new Map,this.textLayerContainers=new Map,this.textLayerContainerRefs=new Map,this.textLayers=new Map,this.textLayerReadyPromises=new Map,this.pageTextCache=new Map,this.pageTextTruncated=new Set,this.pageSearchIndexes=new Map,this.mountedPageTextIndexes=new Map,this.pdfTextScopeBuilds=0,this.thumbnailRenderTasks=new Map,this.thumbnailRenderVersions=new Map,this.thumbnailRenderGeneration=0,this.pageHighlightItems=new Map,this.pageHighlightLayerElements=new Map,this.highlightLayerRefs=new Map,this.pendingPageMountWaitCancels=new Set,this.pdfPageSourceCount=-1,this.pdfPageSource=this.createPageSource(0),this.searchMatches=[],this.searchMatchCountExact=!0,this.searchActiveIndex=-1,this.searchQuery="",this.searchGeneration=0,this.pendingSearchResetEvent=!1,this.anchorOperationGeneration=0,this.announcements=new ViewerAnnouncementController(this),this.onHighlightLayerActivate=event=>{event.stopPropagation(),this.emit("lr-highlight-activate",event.detail)},this.renderPageItem=pageNumber=>{const number=pageNumber,highlightTransform=this.effectiveDirection==="rtl"?"50%":"-50%";return html`<div part="page" @click=${e=>this.onPageClick(number,e)}>
|
|
3
3
|
<canvas part="page-canvas" ${ref(this.pageCanvasRef(number))}></canvas>
|
|
4
4
|
<div part="page-error" hidden></div>
|
|
5
5
|
<lr-highlight-layer
|
|
@@ -723,7 +723,7 @@ export type LyraDatasetViewerReactProps = LyraReactElementProps<LyraDatasetViewe
|
|
|
723
723
|
'active-highlight-id'?: LyraDatasetViewer['activeHighlightId'];
|
|
724
724
|
'max-height'?: LyraDatasetViewer['maxHeight'];
|
|
725
725
|
}>;
|
|
726
|
-
export type LyraDateInputReactProps = LyraReactElementProps<LyraDateInput, 'accessibleLabel' | 'appearance' | 'assumeInteractionOn' | 'autocapitalize' | 'autocomplete' | 'autoCorrect' | 'clearLabel' | 'customError' | 'dayContent' | 'defaultValue' | 'dialogLabel' | 'disabled' | 'disabledDates' | 'disabledDaysOfWeek' | 'disableFuture' | 'disablePast' | 'distance' | 'enterKeyHint' | 'errorText' | 'firstDayOfWeek' | 'form' | 'hint' | 'inputMode' | 'isDateDisabled' | 'label' | 'locale' | 'max' | 'maxRange' | 'min' | 'minRange' | 'mode' | 'months' | 'name' | 'open' | 'openLabel' | 'pageBy' | 'pill' | 'placeholder' | 'placement' | 'readonly' | 'required' | 'selectionDirection' | 'selectionEnd' | 'selectionStart' | 'size' | 'spellcheck' | 'strings' | 'today' | 'validationTarget' | 'validators' | 'value' | 'valueAsDate' | 'valueAsRange' | 'weekdayFormat' | 'withClear' | 'withHint' | 'withLabel' | 'withOutsideDays' | 'withWeekNumbers', {
|
|
726
|
+
export type LyraDateInputReactProps = LyraReactElementProps<LyraDateInput, 'accessibleLabel' | 'appearance' | 'assumeInteractionOn' | 'autocapitalize' | 'autocomplete' | 'autoCorrect' | 'clearLabel' | 'customError' | 'dayContent' | 'defaultValue' | 'dialogLabel' | 'disabled' | 'disabledDates' | 'disabledDaysOfWeek' | 'disableFuture' | 'disablePast' | 'distance' | 'enterKeyHint' | 'errorText' | 'firstDayOfWeek' | 'form' | 'hint' | 'inputMode' | 'isDateDisabled' | 'label' | 'locale' | 'max' | 'maxRange' | 'min' | 'minRange' | 'mode' | 'months' | 'name' | 'open' | 'openLabel' | 'pageBy' | 'pill' | 'placeholder' | 'placement' | 'presets' | 'readonly' | 'required' | 'selectionDirection' | 'selectionEnd' | 'selectionStart' | 'size' | 'spellcheck' | 'strings' | 'today' | 'validationTarget' | 'validators' | 'value' | 'valueAsDate' | 'valueAsRange' | 'weekdayFormat' | 'withClear' | 'withHint' | 'withLabel' | 'withOutsideDays' | 'withWeekNumbers', {
|
|
727
727
|
form: HTMLFormElement | string | null;
|
|
728
728
|
}, LyraDateInputEventMap, 'blur' | 'change' | 'focus' | 'input' | 'lr-after-hide' | 'lr-after-show' | 'lr-clear' | 'lr-hide' | 'lr-invalid' | 'lr-show', '--hide-duration' | '--lr-date-input-action-active-bg' | '--lr-date-input-action-active-color' | '--lr-date-input-action-active-radius' | '--lr-date-input-action-hover-bg' | '--lr-date-input-action-hover-color' | '--lr-date-input-action-hover-radius' | '--lr-date-input-control-height' | '--lr-date-input-control-min-height' | '--lr-date-input-focus-border-color' | '--lr-date-input-font-size' | '--lr-date-input-gap' | '--lr-date-input-padding-block' | '--lr-date-input-padding-inline' | '--lr-date-input-placeholder-color' | '--lr-date-input-radius' | '--lr-form-control-required-color' | '--lr-form-control-required-content' | '--lr-form-control-required-offset' | '--show-duration', {
|
|
729
729
|
'aria-label'?: LyraDateInput['accessibleLabel'];
|
|
@@ -1166,15 +1166,17 @@ export type LyraLineChartReactProps = LyraReactElementProps<LyraLineChart, 'anno
|
|
|
1166
1166
|
'y-label'?: LyraLineChart['yLabel'];
|
|
1167
1167
|
'y2-label'?: LyraLineChart['y2Label'];
|
|
1168
1168
|
}>;
|
|
1169
|
-
export type LyraLiteChartReactProps = LyraReactElementProps<LyraLiteChart, 'accessibleLabel' | 'barGapRatio' | 'barWidth' | 'barX' | 'beginAtZero' | 'datasets' | 'description' | 'formatter' | 'height' | 'label' | 'labels' | 'layout' | 'legend' | 'legendPosition' | 'legendText' | 'locale' | 'maxLabels' | 'minBarHeight' | 'pointText' | 'roundedBars' | 'scale' | 'selectedIndices' | 'skipZero' | 'stacked' | 'strings' | 'tableCellFormatter' | 'tableTotals' | 'tickFormat' | 'type' | 'valueAxisGutter' | 'withoutValueAxis' | 'xLabel' | 'yLabel', {}, LyraLiteChartEventMap, 'lr-datum-activate' | 'lr-point-click', '--lr-chart-color-1' | '--lr-chart-color-2' | '--lr-chart-color-3' | '--lr-chart-color-4' | '--lr-chart-color-5' | '--lr-chart-color-6' | '--lr-chart-color-7' | '--lr-chart-color-8' | '--lr-chart-grid-color' | '--lr-chart-height' | '--lr-chart-legend-color' | '--lr-chart-legend-side-max' | '--lr-chart-pattern-step' | '--lr-chart-tick-color' | '--lr-lite-chart-selected-outline-color' | '--lr-lite-chart-selected-outline-width', {
|
|
1169
|
+
export type LyraLiteChartReactProps = LyraReactElementProps<LyraLiteChart, 'accessibleLabel' | 'barGapRatio' | 'barWidth' | 'barX' | 'beginAtZero' | 'datasets' | 'dataTableToggle' | 'description' | 'formatter' | 'height' | 'label' | 'labels' | 'layout' | 'legend' | 'legendPosition' | 'legendText' | 'locale' | 'maxLabels' | 'minBarHeight' | 'pointText' | 'roundedBars' | 'scale' | 'selectedIndices' | 'showDataTable' | 'skipZero' | 'stacked' | 'strings' | 'tableCellFormatter' | 'tableTotals' | 'tickFormat' | 'type' | 'valueAxisGutter' | 'withoutValueAxis' | 'xLabel' | 'yLabel', {}, LyraLiteChartEventMap, 'lr-datum-activate' | 'lr-point-click', '--lr-chart-color-1' | '--lr-chart-color-2' | '--lr-chart-color-3' | '--lr-chart-color-4' | '--lr-chart-color-5' | '--lr-chart-color-6' | '--lr-chart-color-7' | '--lr-chart-color-8' | '--lr-chart-grid-color' | '--lr-chart-height' | '--lr-chart-legend-color' | '--lr-chart-legend-side-max' | '--lr-chart-pattern-step' | '--lr-chart-tick-color' | '--lr-lite-chart-data-table-toggle-active-bg' | '--lr-lite-chart-data-table-toggle-hover-bg' | '--lr-lite-chart-selected-outline-color' | '--lr-lite-chart-selected-outline-width', {
|
|
1170
1170
|
'accessible-label'?: LyraLiteChart['accessibleLabel'];
|
|
1171
1171
|
'bar-gap-ratio'?: LyraLiteChart['barGapRatio'];
|
|
1172
1172
|
'bar-width'?: LyraLiteChart['barWidth'];
|
|
1173
1173
|
'begin-at-zero'?: LyraLiteChart['beginAtZero'];
|
|
1174
|
+
'data-table-toggle'?: LyraLiteChart['dataTableToggle'];
|
|
1174
1175
|
'legend-position'?: LyraLiteChart['legendPosition'];
|
|
1175
1176
|
'max-labels'?: LyraLiteChart['maxLabels'];
|
|
1176
1177
|
'min-bar-height'?: LyraLiteChart['minBarHeight'];
|
|
1177
1178
|
'rounded-bars'?: LyraLiteChart['roundedBars'];
|
|
1179
|
+
'show-data-table'?: LyraLiteChart['showDataTable'];
|
|
1178
1180
|
'skip-zero'?: LyraLiteChart['skipZero'];
|
|
1179
1181
|
'table-totals'?: LyraLiteChart['tableTotals'];
|
|
1180
1182
|
'value-axis-gutter'?: LyraLiteChart['valueAxisGutter'];
|
package/dist/internal/canvas.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const scratchContexts=new WeakMap;function positiveFinite(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:1}function resolveBoundedCanvasAllocation(input){const cssWidth=positiveFinite(input.cssWidth),cssHeight=positiveFinite(input.cssHeight),desiredScale=positiveFinite(input.desiredScale),maxDimension=Math.max(1,Math.floor(positiveFinite(input.maxDimension))),maxPixels=Math.max(1,positiveFinite(input.maxPixels)),areaScale=Math.sqrt(maxPixels)/Math.sqrt(cssWidth)/Math.sqrt(cssHeight),scale=Math.max(Number.MIN_VALUE,Math.min(desiredScale,maxDimension/cssWidth,maxDimension/cssHeight,areaScale)),pixelWidth=Math.max(1,Math.min(maxDimension,Math.floor(cssWidth*scale))),pixelHeight=Math.max(1,Math.min(maxDimension,Math.floor(cssHeight*scale)));return Object.freeze({cssWidth,cssHeight,pixelWidth,pixelHeight,scale,scaleX:pixelWidth/cssWidth,scaleY:pixelHeight/cssHeight})}function getScratchCtx(ownerDocument=typeof document>"u"?null:document){return ownerDocument?(scratchContexts.has(ownerDocument)||scratchContexts.set(ownerDocument,ownerDocument.createElement("canvas").getContext("2d")),scratchContexts.get(ownerDocument)??null):null}export{getScratchCtx,resolveBoundedCanvasAllocation};
|
|
1
|
+
const scratchContexts=new WeakMap;function positiveFinite(value){return typeof value=="number"&&Number.isFinite(value)&&value>0?value:1}function resolveBoundedCanvasAllocation(input){const cssWidth=positiveFinite(input.cssWidth),cssHeight=positiveFinite(input.cssHeight),desiredScale=positiveFinite(input.desiredScale),maxDimension=Math.max(1,Math.floor(positiveFinite(input.maxDimension))),maxPixels=Math.max(1,positiveFinite(input.maxPixels)),areaScale=Math.sqrt(maxPixels)/Math.sqrt(cssWidth)/Math.sqrt(cssHeight),scale=Math.max(Number.MIN_VALUE,Math.min(desiredScale,maxDimension/cssWidth,maxDimension/cssHeight,areaScale)),pixelWidth=Math.max(1,Math.min(maxDimension,Math.floor(cssWidth*scale))),pixelHeight=Math.max(1,Math.min(maxDimension,Math.floor(cssHeight*scale)));return Object.freeze({cssWidth,cssHeight,pixelWidth,pixelHeight,scale,scaleX:pixelWidth/cssWidth,scaleY:pixelHeight/cssHeight})}function getScratchCtx(ownerDocument=typeof document>"u"?null:document){return ownerDocument?(scratchContexts.has(ownerDocument)||scratchContexts.set(ownerDocument,ownerDocument.createElement("canvas").getContext("2d",{willReadFrequently:!0})),scratchContexts.get(ownerDocument)??null):null}export{getScratchCtx,resolveBoundedCanvasAllocation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="11.
|
|
1
|
+
const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="11.1.0";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
|
package/dist/svelte.d.ts
CHANGED
|
@@ -724,7 +724,7 @@ export type LyraDatasetViewerSvelteProps = LyraSvelteElementProps<LyraDatasetVie
|
|
|
724
724
|
'active-highlight-id'?: LyraDatasetViewer['activeHighlightId'];
|
|
725
725
|
'max-height'?: LyraDatasetViewer['maxHeight'];
|
|
726
726
|
}>;
|
|
727
|
-
export type LyraDateInputSvelteProps = LyraSvelteElementProps<LyraDateInput, 'accessibleLabel' | 'appearance' | 'assumeInteractionOn' | 'autocapitalize' | 'autocomplete' | 'autoCorrect' | 'clearLabel' | 'customError' | 'dayContent' | 'defaultValue' | 'dialogLabel' | 'disabled' | 'disabledDates' | 'disabledDaysOfWeek' | 'disableFuture' | 'disablePast' | 'distance' | 'enterKeyHint' | 'errorText' | 'firstDayOfWeek' | 'form' | 'hint' | 'inputMode' | 'isDateDisabled' | 'label' | 'locale' | 'max' | 'maxRange' | 'min' | 'minRange' | 'mode' | 'months' | 'name' | 'open' | 'openLabel' | 'pageBy' | 'pill' | 'placeholder' | 'placement' | 'readonly' | 'required' | 'selectionDirection' | 'selectionEnd' | 'selectionStart' | 'size' | 'spellcheck' | 'strings' | 'today' | 'validationTarget' | 'validators' | 'value' | 'valueAsDate' | 'valueAsRange' | 'weekdayFormat' | 'withClear' | 'withHint' | 'withLabel' | 'withOutsideDays' | 'withWeekNumbers', {
|
|
727
|
+
export type LyraDateInputSvelteProps = LyraSvelteElementProps<LyraDateInput, 'accessibleLabel' | 'appearance' | 'assumeInteractionOn' | 'autocapitalize' | 'autocomplete' | 'autoCorrect' | 'clearLabel' | 'customError' | 'dayContent' | 'defaultValue' | 'dialogLabel' | 'disabled' | 'disabledDates' | 'disabledDaysOfWeek' | 'disableFuture' | 'disablePast' | 'distance' | 'enterKeyHint' | 'errorText' | 'firstDayOfWeek' | 'form' | 'hint' | 'inputMode' | 'isDateDisabled' | 'label' | 'locale' | 'max' | 'maxRange' | 'min' | 'minRange' | 'mode' | 'months' | 'name' | 'open' | 'openLabel' | 'pageBy' | 'pill' | 'placeholder' | 'placement' | 'presets' | 'readonly' | 'required' | 'selectionDirection' | 'selectionEnd' | 'selectionStart' | 'size' | 'spellcheck' | 'strings' | 'today' | 'validationTarget' | 'validators' | 'value' | 'valueAsDate' | 'valueAsRange' | 'weekdayFormat' | 'withClear' | 'withHint' | 'withLabel' | 'withOutsideDays' | 'withWeekNumbers', {
|
|
728
728
|
form: HTMLFormElement | string | null;
|
|
729
729
|
}, LyraDateInputEventMap, 'blur' | 'change' | 'focus' | 'input' | 'lr-after-hide' | 'lr-after-show' | 'lr-clear' | 'lr-hide' | 'lr-invalid' | 'lr-show', '--hide-duration' | '--lr-date-input-action-active-bg' | '--lr-date-input-action-active-color' | '--lr-date-input-action-active-radius' | '--lr-date-input-action-hover-bg' | '--lr-date-input-action-hover-color' | '--lr-date-input-action-hover-radius' | '--lr-date-input-control-height' | '--lr-date-input-control-min-height' | '--lr-date-input-focus-border-color' | '--lr-date-input-font-size' | '--lr-date-input-gap' | '--lr-date-input-padding-block' | '--lr-date-input-padding-inline' | '--lr-date-input-placeholder-color' | '--lr-date-input-radius' | '--lr-form-control-required-color' | '--lr-form-control-required-content' | '--lr-form-control-required-offset' | '--show-duration', {
|
|
730
730
|
'aria-label'?: LyraDateInput['accessibleLabel'];
|
|
@@ -1167,15 +1167,17 @@ export type LyraLineChartSvelteProps = LyraSvelteElementProps<LyraLineChart, 'an
|
|
|
1167
1167
|
'y-label'?: LyraLineChart['yLabel'];
|
|
1168
1168
|
'y2-label'?: LyraLineChart['y2Label'];
|
|
1169
1169
|
}>;
|
|
1170
|
-
export type LyraLiteChartSvelteProps = LyraSvelteElementProps<LyraLiteChart, 'accessibleLabel' | 'barGapRatio' | 'barWidth' | 'barX' | 'beginAtZero' | 'datasets' | 'description' | 'formatter' | 'height' | 'label' | 'labels' | 'layout' | 'legend' | 'legendPosition' | 'legendText' | 'locale' | 'maxLabels' | 'minBarHeight' | 'pointText' | 'roundedBars' | 'scale' | 'selectedIndices' | 'skipZero' | 'stacked' | 'strings' | 'tableCellFormatter' | 'tableTotals' | 'tickFormat' | 'type' | 'valueAxisGutter' | 'withoutValueAxis' | 'xLabel' | 'yLabel', {}, LyraLiteChartEventMap, 'lr-datum-activate' | 'lr-point-click', '--lr-chart-color-1' | '--lr-chart-color-2' | '--lr-chart-color-3' | '--lr-chart-color-4' | '--lr-chart-color-5' | '--lr-chart-color-6' | '--lr-chart-color-7' | '--lr-chart-color-8' | '--lr-chart-grid-color' | '--lr-chart-height' | '--lr-chart-legend-color' | '--lr-chart-legend-side-max' | '--lr-chart-pattern-step' | '--lr-chart-tick-color' | '--lr-lite-chart-selected-outline-color' | '--lr-lite-chart-selected-outline-width', {
|
|
1170
|
+
export type LyraLiteChartSvelteProps = LyraSvelteElementProps<LyraLiteChart, 'accessibleLabel' | 'barGapRatio' | 'barWidth' | 'barX' | 'beginAtZero' | 'datasets' | 'dataTableToggle' | 'description' | 'formatter' | 'height' | 'label' | 'labels' | 'layout' | 'legend' | 'legendPosition' | 'legendText' | 'locale' | 'maxLabels' | 'minBarHeight' | 'pointText' | 'roundedBars' | 'scale' | 'selectedIndices' | 'showDataTable' | 'skipZero' | 'stacked' | 'strings' | 'tableCellFormatter' | 'tableTotals' | 'tickFormat' | 'type' | 'valueAxisGutter' | 'withoutValueAxis' | 'xLabel' | 'yLabel', {}, LyraLiteChartEventMap, 'lr-datum-activate' | 'lr-point-click', '--lr-chart-color-1' | '--lr-chart-color-2' | '--lr-chart-color-3' | '--lr-chart-color-4' | '--lr-chart-color-5' | '--lr-chart-color-6' | '--lr-chart-color-7' | '--lr-chart-color-8' | '--lr-chart-grid-color' | '--lr-chart-height' | '--lr-chart-legend-color' | '--lr-chart-legend-side-max' | '--lr-chart-pattern-step' | '--lr-chart-tick-color' | '--lr-lite-chart-data-table-toggle-active-bg' | '--lr-lite-chart-data-table-toggle-hover-bg' | '--lr-lite-chart-selected-outline-color' | '--lr-lite-chart-selected-outline-width', {
|
|
1171
1171
|
'accessible-label'?: LyraLiteChart['accessibleLabel'];
|
|
1172
1172
|
'bar-gap-ratio'?: LyraLiteChart['barGapRatio'];
|
|
1173
1173
|
'bar-width'?: LyraLiteChart['barWidth'];
|
|
1174
1174
|
'begin-at-zero'?: LyraLiteChart['beginAtZero'];
|
|
1175
|
+
'data-table-toggle'?: LyraLiteChart['dataTableToggle'];
|
|
1175
1176
|
'legend-position'?: LyraLiteChart['legendPosition'];
|
|
1176
1177
|
'max-labels'?: LyraLiteChart['maxLabels'];
|
|
1177
1178
|
'min-bar-height'?: LyraLiteChart['minBarHeight'];
|
|
1178
1179
|
'rounded-bars'?: LyraLiteChart['roundedBars'];
|
|
1180
|
+
'show-data-table'?: LyraLiteChart['showDataTable'];
|
|
1179
1181
|
'skip-zero'?: LyraLiteChart['skipZero'];
|
|
1180
1182
|
'table-totals'?: LyraLiteChart['tableTotals'];
|
|
1181
1183
|
'value-axis-gutter'?: LyraLiteChart['valueAxisGutter'];
|
package/dist/theme.css
CHANGED
|
@@ -468,4 +468,36 @@
|
|
|
468
468
|
--lr-theme-terminal-bg-bright-white: #696969;
|
|
469
469
|
/* terminal ramp: end */
|
|
470
470
|
}
|
|
471
|
+
|
|
472
|
+
/* Consumer-scope focus ring.
|
|
473
|
+
|
|
474
|
+
These four are LAYER-2 (--lr-*) names, which this file otherwise does not declare: every
|
|
475
|
+
component re-derives them from the --lr-theme-* inputs on its own :host, so a document-scope
|
|
476
|
+
declaration is normally both redundant and shadowed. They are the deliberate exception,
|
|
477
|
+
because --lr-focus-ring exists specifically to serve a CONSUMER-authored idiom -- the Web
|
|
478
|
+
Awesome `outline: var(--wa-focus-ring)` that migrating projects already have -- and that rule
|
|
479
|
+
is written against the consumer's own element, where a :host-only token resolves to nothing.
|
|
480
|
+
An empty var() makes the whole `outline` declaration invalid at computed-value time, and since
|
|
481
|
+
`outline` does not inherit, the ring did not degrade: it disappeared, with no console warning
|
|
482
|
+
and no test signal. That is a WCAG 2.4.7 failure, and it is the exact silent-failure class the
|
|
483
|
+
composite was introduced to prevent.
|
|
484
|
+
|
|
485
|
+
Declared on the mode selectors rather than :root alone, because .lr-dark /
|
|
486
|
+
[data-lr-theme='dark'] may sit on any ancestor: resolving the colour once at :root would
|
|
487
|
+
freeze the light value for a subtree that later switches to dark. Each mode host re-derives
|
|
488
|
+
from its own --lr-theme-color-focus.
|
|
489
|
+
|
|
490
|
+
Components are unaffected -- their own :host declarations still win over these inherited
|
|
491
|
+
values, which production-theme.test.ts asserts. */
|
|
492
|
+
:root,
|
|
493
|
+
.lr-light,
|
|
494
|
+
[data-lr-theme='light'],
|
|
495
|
+
.lr-dark,
|
|
496
|
+
[data-lr-theme='dark'] {
|
|
497
|
+
--lr-focus-ring-width: var(--lr-theme-focus-ring-width, 2px);
|
|
498
|
+
--lr-focus-ring-color: var(--lr-theme-color-focus, Highlight);
|
|
499
|
+
--lr-focus-ring-offset: var(--lr-theme-focus-ring-offset, 2px);
|
|
500
|
+
--lr-focus-ring: var(--lr-focus-ring-width) solid var(--lr-focus-ring-color);
|
|
501
|
+
}
|
|
502
|
+
|
|
471
503
|
}
|