@aceshooting/lyra-ui 11.2.0 → 12.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +388 -0
- package/README.md +11 -8
- package/custom-elements.json +1 -1
- package/dist/all.d.ts +1 -0
- package/dist/all.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +13 -1
- package/dist/components/data/funnel/funnel.class.d.ts +92 -0
- package/dist/components/data/funnel/funnel.class.js +25 -0
- package/dist/components/data/funnel/funnel.d.ts +1 -0
- package/dist/components/data/funnel/funnel.js +1 -0
- package/dist/components/data/funnel/funnel.styles.d.ts +1 -0
- package/dist/components/data/funnel/funnel.styles.js +127 -0
- package/dist/components/data/heatmap/heatmap.class.d.ts +195 -13
- package/dist/components/data/heatmap/heatmap.class.js +30 -22
- package/dist/components/data/heatmap/heatmap.styles.js +36 -0
- package/dist/components/data/index.d.ts +1 -0
- package/dist/components/data/index.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.d.ts +23 -0
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail-item.class.d.ts +16 -0
- package/dist/components/layout/app-rail/app-rail-item.class.js +4 -4
- package/dist/components/layout/filter-bar/filter-bar.class.d.ts +32 -3
- package/dist/components/layout/filter-bar/filter-bar.class.js +2 -1
- package/dist/components/layout/widget/widget.class.d.ts +16 -0
- package/dist/components/layout/widget/widget.class.js +2 -2
- package/dist/components/lr-funnel.d.ts +1 -0
- package/dist/components/lr-funnel.js +1 -0
- package/dist/components/media/flag/flag-peer-bulk-standard.d.ts +25 -0
- package/dist/components/media/flag/flag-peer-bulk-standard.js +1 -0
- package/dist/components/media/flag/flag.class.d.ts +8 -0
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/map/map.class.d.ts +196 -15
- package/dist/components/media/map/map.class.js +1 -1
- package/dist/components/overlays/chip/chip-group.class.d.ts +16 -0
- package/dist/components/overlays/chip/chip-group.class.js +10 -3
- package/dist/custom-elements-jsx.d.ts +12 -4
- package/dist/internal/autoloader-manifest.js +1 -1
- package/dist/internal/autoloader-tags.d.ts +1 -1
- package/dist/internal/autoloader-tags.js +1 -1
- package/dist/internal/lyra-element.d.ts +7 -1
- package/dist/internal/lyra-element.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/root-registration-allowlist.d.ts +1 -1
- package/dist/internal/root-registration-allowlist.js +1 -1
- package/dist/lyra.d.ts +4 -2
- package/dist/lyra.js +1 -1
- package/dist/ssr/all.d.ts +1 -0
- package/dist/ssr/all.js +1 -1
- package/dist/ssr.d.ts +4 -4
- package/dist/styles/tokens-root.css +488 -0
- package/dist/svelte.d.ts +13 -4
- package/dist/vue.d.ts +12 -4
- package/llms/components/lr-app-rail-item.md +8 -1
- package/llms/components/lr-app-rail.md +6 -0
- package/llms/components/lr-chip-group.md +7 -0
- package/llms/components/lr-chip.md +7 -0
- package/llms/components/lr-date-input.md +19 -1
- package/llms/components/lr-date-picker.md +19 -1
- package/llms/components/lr-filter-bar.md +50 -1
- package/llms/components/lr-flag.md +14 -0
- package/llms/components/lr-funnel.md +122 -0
- package/llms/components/lr-heatmap.md +51 -7
- package/llms/components/lr-map.md +65 -8
- package/llms/components/lr-widget.md +7 -1
- package/llms/index.md +3 -2
- package/llms/peers.md +1 -1
- package/llms/shared.md +110 -1
- package/llms-full.txt +468 -18
- package/llms.txt +1 -1
- package/package.json +25 -6
- package/vscode-css-data.json +42 -0
- package/vscode-html-data.json +96 -17
- package/web-types.json +32714 -317
|
@@ -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.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`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{place}from"../../../internal/positioner.js";import{nextId}from"../../../internal/a11y.js";import{closeIcon,calendarIcon,chevronIcon}from"../../../internal/icons.js";import{activateOverlay,composedContains,deepActiveElement}from"../../../internal/overlay-manager.js";import{setCustomState}from"../../../internal/custom-states.js";import{finiteCount,finiteNumber}from"../../../internal/numbers.js";import{isDateObject}from"../../../internal/dom-guards.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dateTimeFormat,parseISO,formatISO,localDate,utcDate,normalizeCalendarMonths,normalizeWeekdayFormat}from"./calendar-core.js";import{sizes}from"../../../internal/sizes.styles.js";import{styles}from"./date-input.styles.js";import"./date-picker.class.js";import"./date-picker.class.js";import{spellcheckFromAttributeConverter as spellcheckConverter}from"../../../internal/converters.js";import{isImplicitSubmission,submitOnEnter}from"../../../internal/submit-on-enter.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{LYRA_DEFAULT_chooseDate,LYRA_DEFAULT_clear,LYRA_DEFAULT_date,LYRA_DEFAULT_dateInputFutureDisabled,LYRA_DEFAULT_dateInputInvalid,LYRA_DEFAULT_dateInputMaxMessage,LYRA_DEFAULT_dateInputMinMessage,LYRA_DEFAULT_dateInputPastDisabled,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_openCalendar}from"../../../internal/default-strings.generated.js";function localeDateOrder(locale){try{const order=dateTimeFormat(locale,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2026,0,2)).filter(p=>p.type==="day"||p.type==="month"||p.type==="year").map(p=>p.type);return order.length===3?order:["month","day","year"]}catch{return["month","day","year"]}}const BIDI_FORMATTING_MARKS=/[\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;function normalizeLocalizedDateText(raw,locale){let normalized=raw.replace(BIDI_FORMATTING_MARKS,"");try{const formatter=getNumberFormat(locale||void 0,{useGrouping:!1});for(let digit=0;digit<=9;digit++){const localized=formatter.format(digit).replace(BIDI_FORMATTING_MARKS,"");localized&&localized!==String(digit)&&(normalized=normalized.split(localized).join(String(digit)))}}catch{}return normalized.trim()}const monthsConverter={fromAttribute:normalizeCalendarMonths,toAttribute:normalizeCalendarMonths},weekdayFormatConverter={fromAttribute:normalizeWeekdayFormat,toAttribute:normalizeWeekdayFormat};function normalizeDateInputAppearance(value){return value==="filled"||value==="filled-outlined"?value:"outlined"}const appearanceConverter={fromAttribute:normalizeDateInputAppearance,toAttribute:normalizeDateInputAppearance},placements=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]);function normalizeDateInputPlacement(value){return typeof value=="string"&&placements.has(value)?value:"bottom-start"}const placementConverter={fromAttribute:normalizeDateInputPlacement,toAttribute:normalizeDateInputPlacement};function normalizeDateInputPageBy(value){return value==="single"?"single":"months"}const pageByConverter={fromAttribute:normalizeDateInputPageBy,toAttribute:normalizeDateInputPageBy},VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}class LyraDateInputBase extends LyraElement{}class LyraDateInput extends FormAssociated(LyraDateInputBase){static{this.defaultStrings={...super.defaultStrings,chooseDate:LYRA_DEFAULT_chooseDate,clear:LYRA_DEFAULT_clear,date:LYRA_DEFAULT_date,dateInputFutureDisabled:LYRA_DEFAULT_dateInputFutureDisabled,dateInputInvalid:LYRA_DEFAULT_dateInputInvalid,dateInputMaxMessage:LYRA_DEFAULT_dateInputMaxMessage,dateInputMinMessage:LYRA_DEFAULT_dateInputMinMessage,dateInputPastDisabled:LYRA_DEFAULT_dateInputPastDisabled,fieldRequired:LYRA_DEFAULT_fieldRequired,openCalendar:LYRA_DEFAULT_openCalendar}}static{this.styles=[LyraElement.styles,sizes,styles]}static{this.properties={mode:{reflect:!0,noAccessor:!0},min:{reflect:!0,noAccessor:!0},max:{reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},disablePast:{type:Boolean,attribute:"disable-past",reflect:!0,noAccessor:!0},disableFuture:{type:Boolean,attribute:"disable-future",reflect:!0,noAccessor:!0}}}get open(){return this._open}set open(next){const old=this._open,liveDisabled=this.effectiveDisabled||typeof this.matches=="function"&&this.matches(":disabled");if(this._open=!!next&&!this.readonly&&!liveDisabled,this._open===old){next&&!this._open&&this.hasAttribute("open")&&this.removeAttribute("open");return}this.requestUpdate("open",old)}get appliedPreset(){return this._appliedPreset}constructor(){super(),this.appearance="outlined",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.size="m",this.pill=!1,this.label="",this.hint="",this.errorText="",this.placeholder="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.autocomplete="",this.inputMode="",this.enterKeyHint="",this.accessibleLabel=null,this.locale="",this.months=1,this.firstDayOfWeek="auto",this.weekdayFormat="short",this.presets=Object.freeze([]),this.withOutsideDays=!1,this.withWeekNumbers=!1,this.disabledDates="",this.disabledDaysOfWeek="",this.minRange=0,this.maxRange=0,this.pageBy="months",this.today="",this.distance=0,this.placement="bottom-start",this.assumeInteractionOn=["input"],this.validators=[],this.clearLabel="",this.openLabel="",this.dialogLabel="Choose date",this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.restorePopupFocusOnClose=!1,this.transitionToken=0,this.transitionWaiters=new Map,this.interactionListeners=new Map,this.inputId=nextId("date-input"),this.popupId=nextId("date-popup"),this.touched=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasLabelSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.validityRevision=0,this._mode="single",this._min="",this._max="",this._open=!1,this._readonly=!1,this._disablePast=!1,this._disableFuture=!1,this.typedBadInput=!1,this.now=()=>new Date,this.onVisibilityChange=()=>{this.ownerDocument.visibilityState==="visible"&&(this.updateValidity(),this.validityRevision++)},this.onDocPointer=e=>{e.composedPath().includes(this)||this.hide(!1)},this.onInputChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const raw=e.target.value;if(this.enterCommittedText!==null&&(raw===this.enterCommittedText||raw===this.displayText))return;this.enterCommittedText=null,this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)):this.inputRelayedSinceCommit=!1},this.onInput=event=>{event.stopPropagation(),!this.liveDisabled&&(this.inputRelayedSinceCommit=!0,relayNativeEvent(this,event))},this.onInputKey=e=>{if(e.altKey&&e.key==="ArrowDown"){e.preventDefault(),this.show();return}if(this.liveDisabled||this.readonly||!isImplicitSubmission(e))return;const input=this.inputElement;if(input&&input.value!==this.displayText){const raw=input.value;this.applyTypedText(raw)?(this.inputRelayedSinceCommit||dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.inputRelayedSinceCommit=!1,dispatchNativeEvent(this,"change")):this.inputRelayedSinceCommit=!1,this.enterCommittedText=raw}submitOnEnter(this,e)},this.onInputBlur=event=>{this.liveDisabled||(this.touched=!0),relayNativeEvent(this,event)},this.onInputFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onHintSlotChange=e=>{this.hasHintSlot=e.target.assignedElements({flatten:!0}).length>0},this.onErrorSlotChange=e=>{this.hasErrorSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{this.hasLabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.onStartSlotChange=e=>{this.hasStartSlot=e.target.assignedElements({flatten:!0}).length>0},this.onEndSlotChange=e=>{this.hasEndSlot=e.target.assignedElements({flatten:!0}).length>0},this.onPickerInput=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,this._appliedPreset=picker.appliedPreset,this.inputRelayedSinceCommit=!1,relayNativeEvent(this,e)},this.onPickerChange=e=>{if(e.stopPropagation(),this.liveDisabled)return;const picker=e.target;this.value=picker.value,this._appliedPreset=picker.appliedPreset,relayNativeEvent(this,e),this.hide(!0)},this.addEventListener("invalid",()=>{this.touched=!0})}get mode(){return this._mode}set mode(next){const old=this._mode;this._mode=next==="range"?"range":"single",this.internals.setFormValue(this.isIncompleteRangeValue(this.value)?"":this.value),this.updateValidity(),this.syncCustomStates(),this.requestUpdate("mode",old)}get min(){return this._min}set min(next){const old=this._min;this._min=next??"",this.updateValidity(),this.requestUpdate("min",old)}get max(){return this._max}set max(next){const old=this._max;this._max=next??"",this.updateValidity(),this.requestUpdate("max",old)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this._readonly&&this.hide(),this.updateValidity(),this.requestUpdate("readonly",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.hide(),this.syncCustomStates()}get disablePast(){return this._disablePast}set disablePast(next){const old=this._disablePast;this._disablePast=!!next,this.updateValidity(),this.requestUpdate("disablePast",old)}get disableFuture(){return this._disableFuture}set disableFuture(next){const old=this._disableFuture;this._disableFuture=!!next,this.updateValidity(),this.requestUpdate("disableFuture",old)}get input(){return this.inputElement}get selectionStart(){return this.inputElement?.selectionStart??null}set selectionStart(value){this.inputElement&&(this.inputElement.selectionStart=value??0)}get selectionEnd(){return this.inputElement?.selectionEnd??null}set selectionEnd(value){this.inputElement&&(this.inputElement.selectionEnd=value??0)}get selectionDirection(){return this.inputElement?.selectionDirection??null}set selectionDirection(value){this.inputElement&&(this.inputElement.selectionDirection=value??"none")}get value(){return super.value}set value(next){this.setTypedBadInput(!1);const normalized=this.normalizeCommittedValue(next??"");super.value=normalized,this.internals.setFormValue(this.isIncompleteRangeValue(normalized)?"":normalized),this.syncCustomStates()}get valueAsDate(){return this.mode==="single"?this.parseStrictISO(this.value):null}set valueAsDate(next){this.value=isDateObject(next)&&Number.isFinite(next.getTime())?formatISO(next):""}get valueAsRange(){if(this.mode!=="range")return{from:null,to:null};const[from="",to=""]=this.value.split("/");return{from:this.parseStrictISO(from),to:this.parseStrictISO(to)}}set valueAsRange(next){let from=isDateObject(next?.from)&&Number.isFinite(next.from.getTime())?next.from:null,to=isDateObject(next?.to)&&Number.isFinite(next.to.getTime())?next.to:null;from&&to&&to<from&&([from,to]=[to,from]),this.value=from?to?`${formatISO(from)}/${formatISO(to)}`:formatISO(from):""}get validationTarget(){return this.validationTargetOverride??this.inputElement}set validationTarget(next){const old=this.validationTarget;this.validationTargetOverride=next??void 0,this.requestUpdate("validationTarget",old)}[VALIDITY_ANCHOR](){return this.validationTarget}resetValidity(){this.setCustomValidity(""),this.updateValidity()}setTypedBadInput(next){const old=this.typedBadInput;this.typedBadInput=next,old!==next&&this.requestUpdate("typedBadInput",old)}parseStrictISO(value){return/^\d{4}-\d{2}-\d{2}$/.test(value)?parseISO(value):null}normalizeCommittedValue(value){if(value==="")return"";const parts=value.split("/");if(parts.length!==1&&parts.length!==2)return"";const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?"":parts.length===2&&dates[0]>dates[1]?`${parts[1]}/${parts[0]}`:value}isIncompleteRangeValue(value){return this.mode==="range"&&value!==""&&!value.includes("/")}valueDates(value){const parts=value.split("/"),expectedParts=this.mode==="range"&&parts.length===2?2:1;if(parts.length!==expectedParts)return null;const dates=parts.map(part=>this.parseStrictISO(part));return dates.some(date=>date===null)?null:dates}configuredDisabledDateKeys(){const values=Array.isArray(this.disabledDates)?this.disabledDates:String(this.disabledDates||"").split(/[\s,]+/);return new Set(values.map(value=>isDateObject(value)?value:parseISO(String(value))).filter(value=>isDateObject(value)&&Number.isFinite(value.getTime())).map(value=>formatISO(value)))}configuredDisabledWeekdays(){const names={sun:0,sunday:0,mon:1,monday:1,tue:2,tues:2,tuesday:2,wed:3,wednesday:3,thu:4,thur:4,thurs:4,thursday:4,fri:5,friday:5,sat:6,saturday:6};return new Set(String(this.disabledDaysOfWeek||"").toLowerCase().split(/[\s,]+/).filter(Boolean).map(value=>names[value]??(/^[0-6]$/.test(value)?Number(value):-1)).filter(value=>value>=0))}rangeLength(from,to){const fromUtc=utcDate(from.getFullYear(),from.getMonth(),from.getDate()).getTime(),toUtc=utcDate(to.getFullYear(),to.getMonth(),to.getDate()).getTime();return Math.round(Math.abs(toUtc-fromUtc)/864e5)+1}validatorResult(){for(const validator of Array.isArray(this.validators)?this.validators:[]){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("dateInputInvalid")}}result=typeof validator=="function"?validator(this.value,this):validator?.validate(this.value,this)}catch{return{flags:{customError:!0},message:this.localize("dateInputInvalid")}}if(!(result===void 0||result===!0)){if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("dateInputInvalid")};if(result&&typeof result=="object"&&Object.values(result).some(Boolean))return{flags:result,message:this.localize("dateInputInvalid")}}}return{}}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let underflowMessage="",overflowMessage="";const incompleteRange=this.isIncompleteRangeValue(this.value);if(this.required&&(this.value===""||incompleteRange)&&(flags.valueMissing=!0),this.typedBadInput&&(flags.badInput=!0),this.value!==""){const dates=this.valueDates(this.value);if(!dates)flags.badInput=!0;else{const min=this.parseStrictISO(this.min),max=this.parseStrictISO(this.max),now=this.parseStrictISO(this.today)??this.now(),today=localDate(now.getFullYear(),now.getMonth(),now.getDate());min!==null&&dates.some(date=>date<min)&&(flags.rangeUnderflow=!0,underflowMessage=this.localize("dateInputMinMessage",void 0,{min:this.min})),this.disablePast&&dates.some(date=>date<today)&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputPastDisabled")),max!==null&&dates.some(date=>date>max)&&(flags.rangeOverflow=!0,overflowMessage=this.localize("dateInputMaxMessage",void 0,{max:this.max})),this.disableFuture&&dates.some(date=>date>today)&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputFutureDisabled"));const disabledDates=this.configuredDisabledDateKeys(),disabledWeekdays=this.configuredDisabledWeekdays();let configuredDisabled=dates.some(date=>disabledDates.has(formatISO(date))||disabledWeekdays.has(date.getDay()));if(!configuredDisabled&&this.isDateDisabled)try{configuredDisabled=dates.some(date=>!!this.isDateDisabled?.(new Date(date.getTime())))}catch{configuredDisabled=!1}if(configuredDisabled&&(flags.customError=!0),this.mode==="range"&&dates.length===2){const length=this.rangeLength(dates[0],dates[1]),minimum=finiteCount(this.minRange,0),maximum=finiteCount(this.maxRange,0);minimum>0&&length<minimum&&(flags.rangeUnderflow=!0,underflowMessage||=this.localize("dateInputInvalid")),maximum>0&&length>maximum&&(flags.rangeOverflow=!0,overflowMessage||=this.localize("dateInputInvalid"))}}}const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags);let message="";configured.message?message=configured.message:flags.badInput||flags.customError?message=this.localize("dateInputInvalid"):flags.rangeUnderflow?message=underflowMessage:flags.rangeOverflow?message=overflowMessage:flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.updateValidity(),super.reportValidity()}bindVisibilityListener(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.visibilityListenerDocument===ownerDocument&&this.visibilityListener)return;this.unbindVisibilityListener();const listener=()=>{this.visibilityListener!==listener||this.visibilityListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onVisibilityChange()};this.visibilityListenerDocument=ownerDocument,this.visibilityListener=listener,ownerDocument.addEventListener("visibilitychange",listener)}unbindVisibilityListener(){this.visibilityListenerDocument&&this.visibilityListener&&this.visibilityListenerDocument.removeEventListener("visibilitychange",this.visibilityListener),this.visibilityListenerDocument=void 0,this.visibilityListener=void 0}get displayText(){const parts=this.value.split("/"),from=parseISO(parts[0]),to=parseISO(parts[1]??"");if(!from)return"";const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"}),fmt=d=>formatter.format(d);if(this.mode!=="range"||!to)return fmt(from);try{return formatter.formatRange(from,to)}catch{return`${fmt(from)} \u2013 ${fmt(to)}`}}willUpdate(changed){super.willUpdate(changed),this.hasUpdated||(this.hasHintSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="hint"),this.hasErrorSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="error"),this.hasLabelSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="label"),this.hasStartSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="start"),this.hasEndSlot=Array.from(this.children??[]).some(el=>el.getAttribute("slot")==="end")),changed.has("open")&&(this.open&&this.isConnected?this.bindDocumentPointer():this.unbindDocumentPointer())}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}show(){if(this.open||this.liveDisabled||this.readonly||this.emit("lr-show",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-hide");const settled=this.waitForTransition("lr-after-show");return this.open=!0,this.settleTransition("lr-after-show"),settled}hide(restoreFocus=!1){if(!this.open||this.emit("lr-hide",null,{cancelable:!0}).defaultPrevented)return Promise.resolve();this.resolveTransitionWaiters("lr-after-show");const settled=this.waitForTransition("lr-after-hide");return this.restorePopupFocusOnClose||=restoreFocus,this.open=!1,this.settleTransition("lr-after-hide"),settled}bindDocumentPointer(){if(!this.isConnected)return;const ownerDocument=this.ownerDocument;if(this.pointerListenerDocument===ownerDocument&&this.pointerListener)return;this.unbindDocumentPointer();const listener=event=>{this.pointerListener!==listener||this.pointerListenerDocument!==ownerDocument||!this.isConnected||this.ownerDocument!==ownerDocument||this.onDocPointer(event)};this.pointerListenerDocument=ownerDocument,this.pointerListener=listener,ownerDocument.addEventListener("pointerdown",listener)}unbindDocumentPointer(){this.pointerListenerDocument&&this.pointerListener&&this.pointerListenerDocument.removeEventListener("pointerdown",this.pointerListener),this.pointerListenerDocument=void 0,this.pointerListener=void 0}reconnectOpenPopup(){if(!this.isConnected||!this.open)return;this.bindDocumentPointer(),this.cleanupFn?.();const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}),this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)},modal:!1,trapFocus:!1}))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event),this.resolveTransitionWaiters(event)}}waitForTransition(event){return new Promise(resolve=>{const waiters=this.transitionWaiters.get(event)??new Set;waiters.add(resolve),this.transitionWaiters.set(event,waiters)})}resolveTransitionWaiters(event){const waiters=this.transitionWaiters.get(event);if(waiters){this.transitionWaiters.delete(event);for(const resolve of waiters)resolve()}}connectedCallback(){super.connectedCallback(),this.bindVisibilityListener(),this.syncInteractionListeners(),this.syncValidatorAttributeObserver(),this.syncCustomStates(),this.hasUpdated&&this.open&&queueMicrotask(()=>this.reconnectOpenPopup())}clear(){!this.value||this.liveDisabled||this.readonly||(this.touched=!0,this._appliedPreset=void 0,this.value="",this.emit("lr-clear"),this.inputRelayedSinceCommit=!1,dispatchNativeInputEvent(this,{inputType:"deleteContentBackward"}),dispatchNativeEvent(this,"change"))}syncInteractionListeners(){const requested=new Set((Array.isArray(this.assumeInteractionOn)?this.assumeInteractionOn:[]).filter(name=>typeof name=="string"&&name.length>0));for(const[name,listener]of this.interactionListeners)requested.has(name)||(this.removeEventListener(name,listener),this.interactionListeners.delete(name));for(const name of requested){if(this.interactionListeners.has(name))continue;const listener=()=>{this.touched=!0,this.syncCustomStates()};this.addEventListener(name,listener),this.interactionListeners.set(name,listener)}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;for(const validator of Array.isArray(this.validators)?this.validators:[]){if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;let observed;try{observed=validator.observedAttributes}catch{continue}if(Array.isArray(observed))for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}syncCustomStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open),setCustomState(this.internals,"range",this.mode==="range")}disconnectedCallback(){this.transitionToken++,this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver(),this.restorePopupFocusOnClose=!1,this.resolveTransitionWaiters("lr-after-show"),this.resolveTransitionWaiters("lr-after-hide");for(const[name,listener]of this.interactionListeners)this.removeEventListener(name,listener);this.interactionListeners.clear(),this.enterCommittedText=null,this.inputRelayedSinceCommit=!1,this.open=!1,super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cleanupFn?.(),this.cleanupFn=void 0,this.overlayHandle?.deactivate({restoreFocus:!1}),this.overlayHandle=void 0,this.unbindVisibilityListener(),this.unbindDocumentPointer(),this.disconnectValidatorAttributeObserver()}updated(changed){if(super.updated(changed),(changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("isDateDisabled")||changed.has("minRange")||changed.has("maxRange")||changed.has("today")||changed.has("validators"))&&this.updateValidity(),(changed.has("open")||this.open&&(changed.has("placement")||changed.has("distance")))&&(this.cleanupFn?.(),this.cleanupFn=void 0,this.open&&this.isConnected)){const anchor=this.renderRoot.querySelector('[part="input-wrapper"]'),popup=this.renderRoot.querySelector('[part="popup"]');anchor&&popup&&(this.cleanupFn=place(anchor,popup,{placement:normalizeDateInputPlacement(this.placement),offset:finiteNumber(this.distance,0)}))}if(changed.has("open")){if(this.open&&this.isConnected)this.renderRoot.querySelector('[part="popup"]')&&(this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide(!0)},modal:!1,trapFocus:!1}));else if(!this.open){const popup=this.renderRoot.querySelector('[part="popup"]'),focusWasInsidePopup=popup!==null&&composedContains(popup,deepActiveElement(this.ownerDocument));this.overlayHandle?.deactivate({restoreFocus:this.restorePopupFocusOnClose||focusWasInsidePopup}),this.overlayHandle=void 0,this.restorePopupFocusOnClose=!1}}changed.has("assumeInteractionOn")&&this.syncInteractionListeners(),changed.has("validators")&&this.syncValidatorAttributeObserver(),this.syncCustomStates(),(changed.has("touched")||changed.has("required")||changed.has("value")||changed.has("mode")||changed.has("min")||changed.has("max")||changed.has("readonly")||changed.has("disablePast")||changed.has("disableFuture")||changed.has("disabledDates")||changed.has("disabledDaysOfWeek")||changed.has("minRange")||changed.has("maxRange")||changed.has("validators")||changed.has("typedBadInput")||changed.has("validityRevision"))&&this.toggleAttribute("data-invalid",this.touched&&!this.internals.validity.valid)}applyTypedText(raw){this.enterCommittedText=null;const trimmed=raw.trim();if(!trimmed)return this.value!==""&&(this._appliedPreset=void 0),this.value="",!0;const parsed=this.mode==="range"?this.parseRangeText(trimmed):this.parseSingleText(trimmed);return parsed?(parsed!==this.value&&(this._appliedPreset=void 0),this.value=parsed,!0):(this.inputElement&&(this.inputElement.value=this.displayText),this.setTypedBadInput(!0),this.updateValidity(),!1)}parseOneDate(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),/^\d{4}-\d{2}-\d{2}$/.test(raw))return parseISO(raw);const ambiguous=/^(\d{1,4})[/.-](\d{1,4})[/.-](\d{1,4})$/.exec(raw);if(ambiguous){const[,g1,g2,g3]=ambiguous;if(g1.length===4)return parseISO(`${g1}-${g2.padStart(2,"0")}-${g3.padStart(2,"0")}`);const order=localeDateOrder(this.effectiveLocale),values=[Number(g1),Number(g2),Number(g3)],fields={};if(order.forEach((type,i)=>{fields[type]=values[i]}),fields.day!=null&&fields.month!=null&&fields.year!=null){const year=fields.year<100?2e3+fields.year:fields.year;return parseISO(`${String(year).padStart(4,"0")}-${String(fields.month).padStart(2,"0")}-${String(fields.day).padStart(2,"0")}`)}}const timestamp=Date.parse(raw);return Number.isNaN(timestamp)?null:new Date(timestamp)}parseSingleText(raw){const parsed=this.parseOneDate(raw);return parsed?formatISO(parsed):null}localizedRangeSeparator(){const formatter=dateTimeFormat(this.effectiveLocale,{year:"numeric",month:"numeric",day:"numeric"});try{const parts=formatter.formatRangeToParts(localDate(2026,0,2),localDate(2026,0,3)),firstEnd=parts.findIndex(part=>part.source==="endRange");let lastStart=-1;for(let index=0;index<firstEnd;index++)parts[index]?.source==="startRange"&&(lastStart=index);const separator=parts.slice(lastStart+1,firstEnd).map(part=>part.value).join("");return normalizeLocalizedDateText(separator,this.effectiveLocale)||"\u2013"}catch{return"\u2013"}}parseRangeText(raw){if(raw=normalizeLocalizedDateText(raw,this.effectiveLocale),raw===normalizeLocalizedDateText(this.displayText,this.effectiveLocale)&&this.value.includes("/"))return this.normalizeCommittedValue(this.value);if(/^\d{4}-\d{2}-\d{2}\/\d{4}-\d{2}-\d{2}$/.test(raw)){const[a,b]=raw.split("/"),from2=parseISO(a),to2=parseISO(b);return!from2||!to2?null:from2<=to2?raw:`${b}/${a}`}const separator=this.localizedRangeSeparator(),idx=raw.indexOf(separator);if(idx===-1)return null;const from=this.parseOneDate(raw.slice(0,idx).trim()),to=this.parseOneDate(raw.slice(idx+separator.length).trim());return!from||!to?null:from<=to?`${formatISO(from)}/${formatISO(to)}`:`${formatISO(to)}/${formatISO(from)}`}click(){this.liveDisabled||this.inputElement?.click()}focus(options){this.liveDisabled||this.inputElement?.focus(options)}blur(){this.inputElement?.blur()}select(){this.inputElement?.select()}setSelectionRange(start,end,direction){this.inputElement?.setSelectionRange(start,end,direction)}setRangeText(replacement,start,end,selectMode){const input=this.inputElement;input&&(start===void 0||end===void 0?input.setRangeText(replacement):input.setRangeText(replacement,start,end,selectMode),this.applyTypedText(input.value))}formStateRestoreCallback(state2,_mode){this.value=typeof state2=="string"?state2:""}formResetCallback(){super.formResetCallback(),this.touched=!1,this._appliedPreset=void 0}formDisabledCallback(disabled){Object.getPrototypeOf(LyraDateInput.prototype).formDisabledCallback.call(this,disabled),disabled&&this.hide(),this.syncCustomStates()}render(){const hasValue=this.value.length>0,hasHint=this.withHint||this.hasHintSlot||this.hint.length>0,hasError=this.hasErrorSlot||this.errorText.length>0,hasLabel=this.withLabel||this.hasLabelSlot||this.label.length>0,invalid=this.touched&&!this.internals.validity.valid,describedBy=[hasError?"date-input-error":"",hasHint?"date-input-hint":""].filter(Boolean).join(" "),dynamicDaySlots=[...new Set(Array.from(this.children??[]).map(child=>child.getAttribute("slot")??"").filter(name=>/^day-\d{4}-\d{2}-\d{2}$/.test(name)))];return html`
|
|
2
2
|
<div part="date-input">
|
|
3
3
|
<div part="base">
|
|
4
4
|
<div part="form-control">
|
|
@@ -49,6 +49,22 @@ export declare class LyraAppRailItem extends LyraElement {
|
|
|
49
49
|
* treatment -- the rail has no built-in routing, so the consumer sets
|
|
50
50
|
* this per item (e.g. by comparing `href` against the current location). */
|
|
51
51
|
current: boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Deprecated alias for `current`, read alongside it.
|
|
54
|
+
*
|
|
55
|
+
* `active` was this property's original public name. It was renamed to `current` with no
|
|
56
|
+
* changelog entry, no alias and no deprecation record, which broke every shipped consumer
|
|
57
|
+
* silently: a Lit `.active=${...}` binding on a custom element is untyped, so it did not error --
|
|
58
|
+
* it became a dead expando, leaving the rail with no current-item indicator and a permanent
|
|
59
|
+
* `aria-current="false"`. Nothing in a consumer's type check, test suite or build could see that.
|
|
60
|
+
*
|
|
61
|
+
* Set either name; the item is current when either is true. Prefer `current`.
|
|
62
|
+
*
|
|
63
|
+
* @deprecated Use `current`.
|
|
64
|
+
*/
|
|
65
|
+
active: boolean;
|
|
66
|
+
/** True when either the canonical `current` or its deprecated `active` alias is set. */
|
|
67
|
+
private get isCurrent();
|
|
52
68
|
/** Opt-in hover/focus flyout showing this item's label text while `icon-only` (set externally by
|
|
53
69
|
* the parent `<lr-app-rail>` as the viewport narrows) hides it from view -- an explicit,
|
|
54
70
|
* documented property instead of an unverified cross-browser `::part()` + `::after` + `attr()`
|
|
@@ -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{activeElementIn}from"../../../internal/active-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{applyComposedFocusRepair,captureComposedFocusRepair,isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{styles}from"./app-rail-item.styles.js";class LyraAppRailItem extends LyraElement{constructor(){super(...arguments),this.href="",this.target="",this.disabled=!1,this.current=!1,this.tooltip=!1,this.showTooltip=!1,this.onFocusShow=event=>{if(this.tooltip&&this.hasAttribute("icon-only")&&(this.showTooltip=!0),event.type!=="focus")return;const related=event.relatedTarget;related&&related.nodeType===1&&isComposedFocusAvailable(related)&&(this.focusReturnTarget=related)},this.onBlurHide=()=>{this.showTooltip=!1}}static{this.styles=[LyraElement.styles,styles]}static get observedAttributes(){return[...super.observedAttributes,"icon-only"]}connectedCallback(){super.connectedCallback(),this.armLabelObserver()}armLabelObserver(){this.labelObserver?.disconnect();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.labelObserver=new MutationObserverCtor(()=>{this.showTooltip&&this.requestUpdate()}),this.labelObserver.observe(this,{childList:!0,characterData:!0,subtree:!0}))}get labelText(){return Array.from(this.childNodes).filter(node=>node.nodeType===3?!0:node.nodeType!==1?!1:node.getAttribute("slot")!=="icon").map(n=>n.textContent??"").join("").trim()}get tooltipText(){return hostAriaLabel(this)??(this.labelText||"")}attributeChangedCallback(name,oldValue,newValue){super.attributeChangedCallback(name,oldValue,newValue),!(name!=="icon-only"||oldValue===newValue)&&(newValue===null&&(this.showTooltip=!1),this.requestUpdate())}willUpdate(changed){if(super.willUpdate(changed),changed.has("tooltip")&&!this.tooltip&&(this.showTooltip=!1),changed.has("href")||changed.has("disabled")){const previous=this.renderRoot?.querySelector('[part="base"]')??null,nextIsLink=!!safeLinkHref(this.href)&&!this.disabled,ownerReplaced=previous!==null&&previous.localName==="a"!==nextIsLink;this.semanticFocusRepair=ownerReplaced&&activeElementIn(this.shadowRoot)===previous?captureComposedFocusRepair(this,this.focusFallback()??previous)??void 0:void 0}}updated(changed){super.updated(changed);const focusRepair=this.semanticFocusRepair;this.semanticFocusRepair=void 0,focusRepair&&this.scheduleAfterUpdate(()=>{const replacement=this.renderRoot.querySelector('[part="base"]'),target=replacement&&isComposedFocusAvailable(replacement)?replacement:this.focusFallback();applyComposedFocusRepair(focusRepair,target)},"app-rail-item-owner-focus");const popup=this.renderRoot.querySelector('[part="tooltip"]');if(!popup){this.stopPositioning?.(),this.stopPositioning=void 0;return}if(changed.has("showTooltip")||!this.stopPositioning){this.stopPositioning?.();const anchor=this.renderRoot.querySelector('[part="base"]');this.stopPositioning=place(anchor,popup,{placement:rtlAwarePlacement("right",this)})}}disconnectedCallback(){super.disconnectedCallback(),this.semanticFocusRepair=void 0,this.focusReturnTarget=void 0,this.labelObserver?.disconnect(),this.labelObserver=void 0,this.stopPositioning?.(),this.stopPositioning=void 0,this.showTooltip=!1}focusFallback(){if(this.focusReturnTarget&&isComposedFocusAvailable(this.focusReturnTarget))return this.focusReturnTarget;const owner=this.closest("lr-app-rail")?.shadowRoot?.querySelector('[part~="base"], [part~="panel"]')??null;return owner&&isComposedFocusAvailable(owner)?owner:null}click(){this.disabled||this.renderRoot.querySelector('[part~="base"]')?.click()}render(){const label=hostAriaLabel(this),href=safeLinkHref(this.href),content=html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{activeElementIn}from"../../../internal/active-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{applyComposedFocusRepair,captureComposedFocusRepair,isComposedFocusAvailable}from"../../../internal/focus-navigation.js";import{LyraElement}from"../../../internal/lyra-element.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{safeLinkHref}from"../../../internal/safe-url.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{styles}from"./app-rail-item.styles.js";class LyraAppRailItem extends LyraElement{constructor(){super(...arguments),this.href="",this.target="",this.disabled=!1,this.current=!1,this.active=!1,this.tooltip=!1,this.showTooltip=!1,this.onFocusShow=event=>{if(this.tooltip&&this.hasAttribute("icon-only")&&(this.showTooltip=!0),event.type!=="focus")return;const related=event.relatedTarget;related&&related.nodeType===1&&isComposedFocusAvailable(related)&&(this.focusReturnTarget=related)},this.onBlurHide=()=>{this.showTooltip=!1}}static{this.styles=[LyraElement.styles,styles]}static get observedAttributes(){return[...super.observedAttributes,"icon-only"]}get isCurrent(){return this.current||this.active}connectedCallback(){super.connectedCallback(),this.armLabelObserver()}armLabelObserver(){this.labelObserver?.disconnect();const MutationObserverCtor=this.ownerDocument.defaultView?.MutationObserver;MutationObserverCtor&&(this.labelObserver=new MutationObserverCtor(()=>{this.showTooltip&&this.requestUpdate()}),this.labelObserver.observe(this,{childList:!0,characterData:!0,subtree:!0}))}get labelText(){return Array.from(this.childNodes).filter(node=>node.nodeType===3?!0:node.nodeType!==1?!1:node.getAttribute("slot")!=="icon").map(n=>n.textContent??"").join("").trim()}get tooltipText(){return hostAriaLabel(this)??(this.labelText||"")}attributeChangedCallback(name,oldValue,newValue){super.attributeChangedCallback(name,oldValue,newValue),!(name!=="icon-only"||oldValue===newValue)&&(newValue===null&&(this.showTooltip=!1),this.requestUpdate())}willUpdate(changed){if(super.willUpdate(changed),changed.has("tooltip")&&!this.tooltip&&(this.showTooltip=!1),changed.has("href")||changed.has("disabled")){const previous=this.renderRoot?.querySelector('[part="base"]')??null,nextIsLink=!!safeLinkHref(this.href)&&!this.disabled,ownerReplaced=previous!==null&&previous.localName==="a"!==nextIsLink;this.semanticFocusRepair=ownerReplaced&&activeElementIn(this.shadowRoot)===previous?captureComposedFocusRepair(this,this.focusFallback()??previous)??void 0:void 0}}updated(changed){super.updated(changed);const focusRepair=this.semanticFocusRepair;this.semanticFocusRepair=void 0,focusRepair&&this.scheduleAfterUpdate(()=>{const replacement=this.renderRoot.querySelector('[part="base"]'),target=replacement&&isComposedFocusAvailable(replacement)?replacement:this.focusFallback();applyComposedFocusRepair(focusRepair,target)},"app-rail-item-owner-focus");const popup=this.renderRoot.querySelector('[part="tooltip"]');if(!popup){this.stopPositioning?.(),this.stopPositioning=void 0;return}if(changed.has("showTooltip")||!this.stopPositioning){this.stopPositioning?.();const anchor=this.renderRoot.querySelector('[part="base"]');this.stopPositioning=place(anchor,popup,{placement:rtlAwarePlacement("right",this)})}}disconnectedCallback(){super.disconnectedCallback(),this.semanticFocusRepair=void 0,this.focusReturnTarget=void 0,this.labelObserver?.disconnect(),this.labelObserver=void 0,this.stopPositioning?.(),this.stopPositioning=void 0,this.showTooltip=!1}focusFallback(){if(this.focusReturnTarget&&isComposedFocusAvailable(this.focusReturnTarget))return this.focusReturnTarget;const owner=this.closest("lr-app-rail")?.shadowRoot?.querySelector('[part~="base"], [part~="panel"]')??null;return owner&&isComposedFocusAvailable(owner)?owner:null}click(){this.disabled||this.renderRoot.querySelector('[part~="base"]')?.click()}render(){const label=hostAriaLabel(this),href=safeLinkHref(this.href),content=html`
|
|
2
2
|
${renderInertPresentation(html`<slot name="icon"></slot>`,{part:"icon"})}
|
|
3
3
|
<span part="label"><slot></slot></span>
|
|
4
4
|
`,tooltip=this.showTooltip&&this.tooltip&&this.hasAttribute("icon-only")?html`<span part="tooltip" role="tooltip" aria-hidden="true">${this.tooltipText}</span>`:nothing;return href&&!this.disabled?html`
|
|
@@ -9,7 +9,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
9
9
|
rel=${this.target?"noopener noreferrer":nothing}
|
|
10
10
|
aria-label=${label??nothing}
|
|
11
11
|
aria-disabled="false"
|
|
12
|
-
aria-current=${this.
|
|
12
|
+
aria-current=${this.isCurrent?"page":"false"}
|
|
13
13
|
@mouseenter=${this.onFocusShow}
|
|
14
14
|
@mouseleave=${this.onBlurHide}
|
|
15
15
|
@focus=${this.onFocusShow}
|
|
@@ -23,11 +23,11 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
23
23
|
?disabled=${this.disabled}
|
|
24
24
|
aria-disabled=${this.disabled?"true":"false"}
|
|
25
25
|
aria-label=${label??nothing}
|
|
26
|
-
aria-current=${this.
|
|
26
|
+
aria-current=${this.isCurrent?"page":"false"}
|
|
27
27
|
@mouseenter=${this.onFocusShow}
|
|
28
28
|
@mouseleave=${this.onBlurHide}
|
|
29
29
|
@focus=${this.onFocusShow}
|
|
30
30
|
@blur=${this.onBlurHide}
|
|
31
31
|
>${content}</button>
|
|
32
32
|
${tooltip}
|
|
33
|
-
`}}__decorate([property()],LyraAppRailItem.prototype,"href",void 0),__decorate([property()],LyraAppRailItem.prototype,"target",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraAppRailItem.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraAppRailItem.prototype,"current",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraAppRailItem.prototype,"tooltip",void 0),__decorate([state()],LyraAppRailItem.prototype,"showTooltip",void 0);export{LyraAppRailItem};
|
|
33
|
+
`}}__decorate([property()],LyraAppRailItem.prototype,"href",void 0),__decorate([property()],LyraAppRailItem.prototype,"target",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraAppRailItem.prototype,"disabled",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraAppRailItem.prototype,"current",void 0),__decorate([property({type:Boolean,attribute:"active"})],LyraAppRailItem.prototype,"active",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraAppRailItem.prototype,"tooltip",void 0),__decorate([state()],LyraAppRailItem.prototype,"showTooltip",void 0);export{LyraAppRailItem};
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { LyraEventDetailSnapshot } from '../../../internal/lyra-element.js';
|
|
2
|
+
import type { LyraDateRangePreset } from '../../forms/date-picker/date-picker.class.js';
|
|
2
3
|
import { type TemplateResult, type PropertyValues } from 'lit';
|
|
3
4
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
4
5
|
import '../../forms/select/select.class.js';
|
|
@@ -129,6 +130,17 @@ export interface LyraFilterBarDateDefinition extends LyraFilterBarDateDefinition
|
|
|
129
130
|
}
|
|
130
131
|
export interface LyraFilterBarDateRangeDefinition extends LyraFilterBarDateDefinitionBase {
|
|
131
132
|
readonly type: 'date-range';
|
|
133
|
+
/** Quick-range options ("Last 7 days", "This month", "All time") forwarded verbatim to the
|
|
134
|
+
* composed `<lr-date-input>`'s own `presets`, exactly like `min`/`max` -- this is the dashboard
|
|
135
|
+
* filter shape that row was built for, and `type: 'custom'` would mean hand-rendering the same
|
|
136
|
+
* control plus a full adapter just to set one property, forfeiting the built-in date-range chip
|
|
137
|
+
* localization on the way.
|
|
138
|
+
*
|
|
139
|
+
* `'date-range'` only, deliberately not on the shared date base: a preset names two dates, so
|
|
140
|
+
* `<lr-date-picker>` ignores the list outside range mode, and declaring it on `'date'` would
|
|
141
|
+
* type-check a field that is guaranteed inert. Which preset a commit came from arrives on that
|
|
142
|
+
* edit's own `lr-input` as `appliedPreset`. */
|
|
143
|
+
readonly presets?: readonly LyraDateRangePreset[];
|
|
132
144
|
}
|
|
133
145
|
export interface LyraFilterBarCustomDefinition extends LyraFilterBarDefinitionBase {
|
|
134
146
|
readonly type: 'custom';
|
|
@@ -150,6 +162,18 @@ export interface LyraFilterBarInputDetail {
|
|
|
150
162
|
readonly value: LyraFilterBarValue;
|
|
151
163
|
/** The filter that changed, or `undefined` when every filter changed at once (a `reset()`). */
|
|
152
164
|
readonly filterId?: string;
|
|
165
|
+
/** For a `'date-range'` filter committed from its quick-range row: the `presets` entry that
|
|
166
|
+
* produced this value, resolved from the composed `<lr-date-input>`'s own `appliedPreset`.
|
|
167
|
+
* `undefined` for every other filter type, and for a range picked or typed by hand.
|
|
168
|
+
*
|
|
169
|
+
* A filter bar whose values round-trip through a query string has to persist WHICH preset is
|
|
170
|
+
* active rather than the pair it froze to -- "Last 7 days" must still mean the last 7 days after
|
|
171
|
+
* tomorrow's reload -- and that fact is not recoverable from `value`, which holds only the frozen
|
|
172
|
+
* ISO range. It rides the event rather than `value` because it is metadata about one edit, not a
|
|
173
|
+
* filter value: `value` stays the plain, JSON-serializable record it has always been. The entry
|
|
174
|
+
* is the bar's own frozen snapshot of the definition, so it compares identical to
|
|
175
|
+
* `filters[i].presets[j]`. */
|
|
176
|
+
readonly appliedPreset?: LyraDateRangePreset;
|
|
153
177
|
}
|
|
154
178
|
export interface LyraFilterBarValidityDetail {
|
|
155
179
|
readonly valid: boolean;
|
|
@@ -193,7 +217,10 @@ export interface LyraFilterBarEventMap {
|
|
|
193
217
|
* bubbling path. Date/date-range chip labels localize only
|
|
194
218
|
* round-trip-valid ISO `YYYY-MM-DD` segments, including literal four-digit years `0000`-`0099`.
|
|
195
219
|
* Impossible dates, malformed values, and a range with either invalid endpoint remain verbatim so
|
|
196
|
-
* display never invents a normalized day.
|
|
220
|
+
* display never invents a normalized day. A `'date-range'` filter may also declare `presets`,
|
|
221
|
+
* forwarded to its composed `<lr-date-input>` exactly like `min`/`max`; the entry that produced a
|
|
222
|
+
* commit rides that edit's own `lr-input` as `appliedPreset`, so a bar whose values round-trip
|
|
223
|
+
* through a query string can persist which range is active rather than the pair it froze to.
|
|
197
224
|
*
|
|
198
225
|
* Validation is scoped to each filter definition's own `required` flag: `invalidFilterIds`/
|
|
199
226
|
* `checkValidity()` are always live (plain getters over `filters`/`value`, not cached), and
|
|
@@ -215,8 +242,10 @@ export interface LyraFilterBarEventMap {
|
|
|
215
242
|
*
|
|
216
243
|
* @customElement lr-filter-bar
|
|
217
244
|
* @event lr-input - A filter's value changed (including a chip removal or `reset()`).
|
|
218
|
-
* `detail: { value, filterId }` -- `value` is always the complete object;
|
|
219
|
-
* one filter that changed, or `undefined` for a `reset()
|
|
245
|
+
* `detail: { value, filterId, appliedPreset }` -- `value` is always the complete object;
|
|
246
|
+
* `filterId` is the one filter that changed, or `undefined` for a `reset()`; `appliedPreset` is
|
|
247
|
+
* the `'date-range'` quick-range entry that produced this commit, and `undefined` everywhere
|
|
248
|
+
* else (another filter type, or a range picked/typed by hand).
|
|
220
249
|
* @event lr-validity-change - The computed `{ valid, invalidFilterIds }` changed.
|
|
221
250
|
* @event lr-reset - `reset()` ran (via the reset button or a direct call). `detail: { value }`.
|
|
222
251
|
* @csspart base - The root `role="group"` wrapper.
|
|
@@ -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{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{styles}from"./filter-bar.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/combobox.class.js";import"../../forms/combobox/option.class.js";import"../../forms/date-picker/date-input.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../overlays/chip/chip-group.class.js";import"../../forms/button/button.class.js";import"../../overlays/spinner/spinner.class.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({});function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}if(!isArray)return EMPTY_FILTERS;const snapshot=snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0);return Array.isArray(snapshot)?snapshot:EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", ");function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function cloneFilterValue(value){const clone={};let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value??{})}catch{return EMPTY_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&(clone[key]=fieldValue)}return Object.freeze(clone)}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.touchedFilters=new Set,this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.debounceTimers=new Map,this.pendingText=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(id,e)=>{this.setFilterValue(id,e.target.value)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation(),this.setCustomContextValue(def,generation,def.custom.adapter.valueFromEvent(e))}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){const old=this._filters;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(next).filter(definition=>{try{return!(!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||seen.has(definition.filterId)||(seen.add(definition.filterId),(definition.type==="select"||definition.type==="combobox")&&!Array.isArray(definition.options))||definition.type==="custom"&&!definition.custom?.adapter)}catch{return!1}}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this._value),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){const old=this._value;this._value=this.normalizeValue(next),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||(normalized[def.filterId]=fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){this.disabled||(this.cancelDebounce(),this.touchedFilters=new Set,this.value=this.resetValue,this.emit("lr-input",Object.freeze({value:this.value,filterId:void 0})),this.emit("lr-reset",Object.freeze({value:this.value})))}get resetValue(){const out={};for(const def of this._filters)def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)&&(out[def.filterId]=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue);return Object.freeze(out)}setFilterValue(id,value){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:next[id]=value,this.value=next,this.emit("lr-input",Object.freeze({value:this.value,filterId:id}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"",delay=def.debounce;if(typeof delay!="number"||!Number.isFinite(delay)||delay<=0){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.pendingText.set(def.filterId,next);const existing=this.debounceTimers.get(def.filterId);existing!==void 0&&clearTimeout(existing),this.debounceTimers.set(def.filterId,setTimeout(()=>this.flushDebounce(def.filterId),delay))}flushDebounce(id){const timer=this.debounceTimers.get(id);if(timer===void 0)return;clearTimeout(timer),this.debounceTimers.delete(id);const pending=this.pendingText.get(id);this.pendingText.delete(id),pending!==void 0&&this.setFilterValue(id,pending)}cancelDebounce(id){for(const[key,timer]of this.debounceTimers)id!==void 0&&key!==id||(clearTimeout(timer),this.debounceTimers.delete(key),this.pendingText.delete(key))}onTextFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(def.type==="select"||def.type==="combobox"){const labels=(Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[]).map(v=>def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}connectedCallback(){super.connectedCallback(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll("lr-input[data-filter-id]")){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.debounceTimers.has(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderOption(option){return html`<lr-option value=${option.value}
|
|
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{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{styles}from"./filter-bar.styles.js";import"../../forms/select/select.class.js";import"../../forms/combobox/combobox.class.js";import"../../forms/combobox/option.class.js";import"../../forms/date-picker/date-input.class.js";import"../../forms/input/input.class.js";import"../../overlays/chip/chip.class.js";import"../../overlays/chip/chip-group.class.js";import"../../forms/button/button.class.js";import"../../overlays/spinner/spinner.class.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({}),EMPTY_DATE_PRESETS=Object.freeze([]);function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}if(!isArray)return EMPTY_FILTERS;const snapshot=snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0);return Array.isArray(snapshot)?snapshot:EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", ");function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function cloneFilterValue(value){const clone={};let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value??{})}catch{return EMPTY_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&(clone[key]=fieldValue)}return Object.freeze(clone)}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.touchedFilters=new Set,this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.debounceTimers=new Map,this.pendingText=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(id,e)=>{const control=e.target;this.setFilterValue(id,control.value,control.appliedPreset)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation(),this.setCustomContextValue(def,generation,def.custom.adapter.valueFromEvent(e))}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){const old=this._filters;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(next).filter(definition=>{try{return!(!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||seen.has(definition.filterId)||(seen.add(definition.filterId),(definition.type==="select"||definition.type==="combobox")&&!Array.isArray(definition.options))||definition.type==="custom"&&!definition.custom?.adapter)}catch{return!1}}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this._value),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){const old=this._value;this._value=this.normalizeValue(next),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||(normalized[def.filterId]=fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){this.disabled||(this.cancelDebounce(),this.touchedFilters=new Set,this.value=this.resetValue,this.emit("lr-input",Object.freeze({value:this.value,filterId:void 0,appliedPreset:void 0})),this.emit("lr-reset",Object.freeze({value:this.value})))}get resetValue(){const out={};for(const def of this._filters)def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)&&(out[def.filterId]=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue);return Object.freeze(out)}setFilterValue(id,value,appliedPreset){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:next[id]=value,this.value=next,this.emit("lr-input",Object.freeze({value:this.value,filterId:id,appliedPreset}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"",delay=def.debounce;if(typeof delay!="number"||!Number.isFinite(delay)||delay<=0){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.pendingText.set(def.filterId,next);const existing=this.debounceTimers.get(def.filterId);existing!==void 0&&clearTimeout(existing),this.debounceTimers.set(def.filterId,setTimeout(()=>this.flushDebounce(def.filterId),delay))}flushDebounce(id){const timer=this.debounceTimers.get(id);if(timer===void 0)return;clearTimeout(timer),this.debounceTimers.delete(id);const pending=this.pendingText.get(id);this.pendingText.delete(id),pending!==void 0&&this.setFilterValue(id,pending)}cancelDebounce(id){for(const[key,timer]of this.debounceTimers)id!==void 0&&key!==id||(clearTimeout(timer),this.debounceTimers.delete(key),this.pendingText.delete(key))}onTextFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(def.type==="select"||def.type==="combobox"){const labels=(Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[]).map(v=>def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}connectedCallback(){super.connectedCallback(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll("lr-input[data-filter-id]")){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.debounceTimers.has(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderOption(option){return html`<lr-option value=${option.value}
|
|
2
2
|
>${option.icon===void 0||option.icon===null?nothing:html`<span slot="start" aria-hidden="true" inert>${option.icon}</span>`}${option.label}</lr-option
|
|
3
3
|
>`}renderControl(def){const value=this.valueFor(def),missing=!!def.required&&this.isEmpty(def,value),errorText=this.touchedFilters.has(def.filterId)&&missing?this.localize("fieldRequired"):"",onChange=e=>this.onControlChange(def.filterId,e),onFocusout=()=>this.markTouched(def.filterId);if(def.type==="custom"){const custom=def.custom,generation=this.schemaGeneration,signal=this.schemaSignal,onCustomValueChange=e=>this.onCustomControlChange(def,generation,e),context={filterId:def.filterId,label:def.label,definition:def,value,disabled:this.disabled,required:!!def.required,errorText,signal,generation,setValue:next=>this.setCustomContextValue(def,generation,next),onValueChange:onCustomValueChange,onInput:onCustomValueChange,onChange:onCustomValueChange,onFocusout:()=>{generation===this.schemaGeneration&&!signal.aborted&&this._filters.includes(def)&&onFocusout()}};return html`<div
|
|
4
4
|
part="filter-control"
|
|
@@ -43,6 +43,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
43
43
|
.mode=${def.type==="date-range"?"range":"single"}
|
|
44
44
|
.min=${def.min||""}
|
|
45
45
|
.max=${def.max||""}
|
|
46
|
+
.presets=${def.type==="date-range"?def.presets??EMPTY_DATE_PRESETS:EMPTY_DATE_PRESETS}
|
|
46
47
|
?required=${!!def.required}
|
|
47
48
|
.errorText=${errorText}
|
|
48
49
|
.value=${typeof value=="string"?value:""}
|
|
@@ -167,6 +167,22 @@ export declare class LyraWidget extends LyraElement<LyraWidgetEventMap> {
|
|
|
167
167
|
* `views` is empty). Settable directly by a consumer wanting to control the active view
|
|
168
168
|
* externally; also updated internally when a view toggle is clicked. */
|
|
169
169
|
activeViewId: string;
|
|
170
|
+
/**
|
|
171
|
+
* Deprecated alias for `activeViewId`, which seeds it.
|
|
172
|
+
*
|
|
173
|
+
* `activeView` was this property's original public name. It was renamed to `activeViewId` with
|
|
174
|
+
* no changelog entry, no alias and no deprecation record, which broke shipped consumers
|
|
175
|
+
* silently: a Lit `.activeView=${id}` binding on a custom element is untyped, so it did not
|
|
176
|
+
* error -- it became a dead expando, and the widget quietly fell back to its first view.
|
|
177
|
+
*
|
|
178
|
+
* This seeds `activeViewId` rather than being read alongside it, because unlike a boolean flag
|
|
179
|
+
* this property is one the component itself writes (a view-toggle click, and the fallback when
|
|
180
|
+
* `views` no longer contains the active id). Seeding on change keeps a single source of truth:
|
|
181
|
+
* a later interactive change is not undone by the stale alias on the next update.
|
|
182
|
+
*
|
|
183
|
+
* @deprecated Use `activeViewId`.
|
|
184
|
+
*/
|
|
185
|
+
activeView: string;
|
|
170
186
|
private hasActionsSlot;
|
|
171
187
|
private hasIconSlot;
|
|
172
188
|
private hasLabelSlot;
|
|
@@ -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{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{nextId}from"../../../internal/a11y.js";import{bindAccessibleTextObserver,composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.collapsed=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.compact=!1,this.effectiveViews=Object.freeze([]),this.activeViewId="",this.hasActionsSlot=!1,this.hasIconSlot=!1,this.hasLabelSlot=!1,this.hasSublabelSlot=!1,this.labelSlotObserverGeneration=0,this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onIconSlotChange=e=>{this.hasIconSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.onSublabelSlotChange=e=>{this.hasSublabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.setActiveView=viewId=>{viewId===this.activeViewId||this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented||(this.activeViewId=viewId,this.emit("lr-view-change",{viewId}))},this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,styles]}get views(){return this.effectiveViews}set views(value){const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){this.hasActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="actions"),this.hasIconSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="icon");const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.hasLabelSlot=labelChildren.length>0,this.labelSlotText=this.readLabelSlotText(labelChildren),this.hasSublabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="sublabel");const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("views")||changed.has("activeViewId")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;views.some(view=>view.viewId===this.activeViewId)||(this.activeViewId=views[0]?.viewId??"")}}updated(changed){super.updated(changed);const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>this.overlayHandle?.focusInitial())),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){super.disconnectedCallback(),this.overlayHandle?.suspend(),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.resetLabelSlotObserver()}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.overlayHandle?.deactivate(),this.overlayHandle=void 0}syncLabelSlot(assigned){if(this.hasLabelSlot=assigned.length>0,this.labelSlotText=this.readLabelSlotText(assigned),this.resetLabelSlotObserver(),assigned.length===0||!this.isConnected)return;const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.labelSlotObserverGeneration,observer=new MutationObserverCtor(()=>{this.labelSlotObserver!==observer||this.labelSlotObserverDocument!==ownerDocument||this.labelSlotObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.labelSlotText=this.readLabelSlotText(assigned))});this.labelSlotObserver=observer,this.labelSlotObserverDocument=ownerDocument,bindAccessibleTextObserver(observer,this,["alt","aria-labelledby","slot"]);for(const element of assigned)observer.observe(element,{attributes:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","inert","style"],childList:!0,characterData:!0,subtree:!0})}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}resetLabelSlotObserver(){this.labelSlotObserverGeneration+=1,this.labelSlotObserver?.disconnect(),this.labelSlotObserver=void 0,this.labelSlotObserverDocument=void 0}requestCollapse(next){this.emit("lr-collapse-request",{collapsed:next},{cancelable:!0}).defaultPrevented||(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}))}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=this.label.length>0,hasSublabel=this.sublabel.length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{nextId}from"../../../internal/a11y.js";import{bindAccessibleTextObserver,composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.collapsed=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.compact=!1,this.effectiveViews=Object.freeze([]),this.activeViewId="",this.activeView="",this.hasActionsSlot=!1,this.hasIconSlot=!1,this.hasLabelSlot=!1,this.hasSublabelSlot=!1,this.labelSlotObserverGeneration=0,this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onIconSlotChange=e=>{this.hasIconSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.onSublabelSlotChange=e=>{this.hasSublabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.setActiveView=viewId=>{viewId===this.activeViewId||this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented||(this.activeViewId=viewId,this.emit("lr-view-change",{viewId}))},this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,styles]}get views(){return this.effectiveViews}set views(value){const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){this.hasActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="actions"),this.hasIconSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="icon");const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.hasLabelSlot=labelChildren.length>0,this.labelSlotText=this.readLabelSlotText(labelChildren),this.hasSublabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="sublabel");const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("activeView")&&this.activeView!==""&&(this.activeViewId=this.activeView),changed.has("views")||changed.has("activeViewId")||changed.has("activeView")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;views.some(view=>view.viewId===this.activeViewId)||(this.activeViewId=views[0]?.viewId??"")}}updated(changed){super.updated(changed);const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>this.overlayHandle?.focusInitial())),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){super.disconnectedCallback(),this.overlayHandle?.suspend(),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.resetLabelSlotObserver()}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.overlayHandle?.deactivate(),this.overlayHandle=void 0}syncLabelSlot(assigned){if(this.hasLabelSlot=assigned.length>0,this.labelSlotText=this.readLabelSlotText(assigned),this.resetLabelSlotObserver(),assigned.length===0||!this.isConnected)return;const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.labelSlotObserverGeneration,observer=new MutationObserverCtor(()=>{this.labelSlotObserver!==observer||this.labelSlotObserverDocument!==ownerDocument||this.labelSlotObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.labelSlotText=this.readLabelSlotText(assigned))});this.labelSlotObserver=observer,this.labelSlotObserverDocument=ownerDocument,bindAccessibleTextObserver(observer,this,["alt","aria-labelledby","slot"]);for(const element of assigned)observer.observe(element,{attributes:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","inert","style"],childList:!0,characterData:!0,subtree:!0})}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}resetLabelSlotObserver(){this.labelSlotObserverGeneration+=1,this.labelSlotObserver?.disconnect(),this.labelSlotObserver=void 0,this.labelSlotObserverDocument=void 0}requestCollapse(next){this.emit("lr-collapse-request",{collapsed:next},{cancelable:!0}).defaultPrevented||(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}))}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=this.label.length>0,hasSublabel=this.sublabel.length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return html`
|
|
2
2
|
${this.fullscreen?html`<div
|
|
3
3
|
part="backdrop"
|
|
4
4
|
style=${backdropInset?styleMap({"--lr-widget-backdrop-inset":backdropInset}):nothing}
|
|
@@ -82,4 +82,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
82
82
|
</div>`)}
|
|
83
83
|
</div>
|
|
84
84
|
</div>
|
|
85
|
-
`}}__decorate([property()],LyraWidget.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraWidget.prototype,"accessibleLabel",void 0),__decorate([property()],LyraWidget.prototype,"sublabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsible",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsed",void 0),__decorate([property({attribute:"storage-key"})],LyraWidget.prototype,"storageKey",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"expandable",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"fullscreen",void 0),__decorate([property({attribute:"fullscreen-inset"})],LyraWidget.prototype,"fullscreenInset",void 0),__decorate([property({attribute:"backdrop-inset"})],LyraWidget.prototype,"backdropInset",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"compact",void 0),__decorate([property({attribute:!1})],LyraWidget.prototype,"views",null),__decorate([property({attribute:!1})],LyraWidget.prototype,"activeViewId",void 0),__decorate([state()],LyraWidget.prototype,"hasActionsSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasIconSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraWidget.prototype,"labelSlotText",void 0),__decorate([state()],LyraWidget.prototype,"hasSublabelSlot",void 0);export{LyraWidget};
|
|
85
|
+
`}}__decorate([property()],LyraWidget.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraWidget.prototype,"accessibleLabel",void 0),__decorate([property()],LyraWidget.prototype,"sublabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsible",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsed",void 0),__decorate([property({attribute:"storage-key"})],LyraWidget.prototype,"storageKey",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"expandable",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"fullscreen",void 0),__decorate([property({attribute:"fullscreen-inset"})],LyraWidget.prototype,"fullscreenInset",void 0),__decorate([property({attribute:"backdrop-inset"})],LyraWidget.prototype,"backdropInset",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"compact",void 0),__decorate([property({attribute:!1})],LyraWidget.prototype,"views",null),__decorate([property({attribute:!1})],LyraWidget.prototype,"activeViewId",void 0),__decorate([property({attribute:!1})],LyraWidget.prototype,"activeView",void 0),__decorate([state()],LyraWidget.prototype,"hasActionsSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasIconSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraWidget.prototype,"labelSlotText",void 0),__decorate([state()],LyraWidget.prototype,"hasSublabelSlot",void 0);export{LyraWidget};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './data/funnel/funnel.js';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export*from"./data/funnel/funnel.js";
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type LyraFlagUrlResolver } from './flag.js';
|
|
2
|
+
/**
|
|
3
|
+
* Register the bulk-resolution `@aceshooting/lyra-flags` resolver through that package's
|
|
4
|
+
* tier-committed `./standard` entry — the pairing of `flag-peer-bulk.js`'s one-shared-fetch
|
|
5
|
+
* batching with `./standard`'s one-tier module graph. Import this entry **instead of**
|
|
6
|
+
* `flag-peer.js` or `flag-peer-bulk.js`, never alongside either: each `setFlagUrlResolver()` call
|
|
7
|
+
* simply replaces the previous resolver, so importing two entries just makes whichever loaded last
|
|
8
|
+
* win.
|
|
9
|
+
*
|
|
10
|
+
* Use it when both conditions hold: the page renders most or all flags at once (a country table, a
|
|
11
|
+
* full locale picker), *and* every `<lr-flag>` stays on the default `fidelity="standard"`.
|
|
12
|
+
* `flag-peer-bulk.js` reaches the same batching through the peer package's root entry, which
|
|
13
|
+
* statically imports all three fidelity tiers' generated loader maps so its `flagUrl()` can honour
|
|
14
|
+
* a per-call variant — so a bundler emits the detailed and compact tiers' whole lazy-chunk graph
|
|
15
|
+
* even though bulk resolution only ever reads the standard-tier eager map. On a real production
|
|
16
|
+
* build with a 156-country flag column, that difference was +15.8MB of emitted assets (+65 detailed
|
|
17
|
+
* SVGs, +31 compact WebPs) that no route rendered.
|
|
18
|
+
*
|
|
19
|
+
* The tradeoff this entry makes in exchange: it is committed to one tier, so `fidelity="compact"`
|
|
20
|
+
* or `fidelity="detailed"` on an individual element resolves to that code's *standard* asset
|
|
21
|
+
* rather than reaching for a tier the registered resolver deliberately does not ship. That is a
|
|
22
|
+
* silent visual no-op, not an error — for per-instance fidelity, import `flag-peer-bulk.js` (bulk,
|
|
23
|
+
* all three tiers) or `flag-peer.js` (per-code lazy, all three tiers) instead.
|
|
24
|
+
*/
|
|
25
|
+
export declare function registerLyraFlagStandardBulkPeer(): Promise<LyraFlagUrlResolver | null>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{loadBulkFlagUrl,setFlagUrlResolver}from"./flag.js";const peerResolver=loadBulkFlagUrl(()=>import("@aceshooting/lyra-flags/standard"));setFlagUrlResolver(peerResolver);async function registerLyraFlagStandardBulkPeer(){return peerResolver}registerLyraFlagStandardBulkPeer();export{registerLyraFlagStandardBulkPeer};
|
|
@@ -62,6 +62,14 @@ export declare function setFlagUrlResolver(value: LyraFlagUrlResolver | Promise<
|
|
|
62
62
|
* Or import `flag-peer-bulk.js` instead of `flag-peer.js` (never both) to get this automatically,
|
|
63
63
|
* registering a resolver backed by one shared `flagUrls()` call — worthwhile only when the page
|
|
64
64
|
* renders most/all flags; a page with a handful pays an unneeded 249-entry fetch.
|
|
65
|
+
* When that page ALSO leaves every `<lr-flag>` on the default `fidelity="standard"`, import
|
|
66
|
+
* `flag-peer-bulk-standard.js` instead: it registers the same bulk resolver through the peer
|
|
67
|
+
* package's tier-committed `@aceshooting/lyra-flags/standard` entry, so the detailed and compact
|
|
68
|
+
* tiers' lazy-chunk graphs never become reachable (measured at +15.8MB of emitted assets on a real
|
|
69
|
+
* production build with a 156-country flag column). It is committed to one tier, so
|
|
70
|
+
* `fidelity="compact"/"detailed"` on an individual element resolves to that code's standard asset
|
|
71
|
+
* — a silent no-op, not an error; use `flag-peer-bulk.js` when per-instance fidelity must be
|
|
72
|
+
* honoured.
|
|
65
73
|
*
|
|
66
74
|
* **Sizing:** the host has no intrinsic `width` — it sizes from `font-size` (`block-size: 1em`,
|
|
67
75
|
* `inline-size` derived from `--lr-flag-aspect-ratio` via CSS `aspect-ratio`), so `<lr-flag>` scales
|