@aceshooting/lyra-ui 9.1.0 → 9.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +246 -0
- package/README.md +7 -0
- package/custom-elements.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.class.js +1 -1
- package/dist/components/agent-tools/agent-eval-dashboard/agent-eval-dashboard.styles.js +2 -2
- package/dist/components/agent-tools/agent-run/agent-run.class.js +1 -1
- package/dist/components/agent-tools/agent-trace/agent-trace.class.js +1 -1
- package/dist/components/agent-tools/browser-frame/browser-frame.class.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.class.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +2 -2
- package/dist/components/agent-tools/context-inspector/context-inspector.class.js +1 -1
- package/dist/components/agent-tools/eval-result/eval-result.class.js +1 -1
- package/dist/components/agent-tools/policy-summary/policy-summary.class.js +1 -1
- package/dist/components/agent-tools/schema-viewer/schema-viewer.styles.js +2 -2
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.js +2 -2
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/thinking-panel/thinking-panel.class.js +1 -1
- package/dist/components/agent-tools/tool-call-chip/tool-call-chip.class.js +2 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +2 -2
- package/dist/components/agent-tools/trace-tree/trace-tree.class.js +2 -2
- package/dist/components/charts/chart/bar-chart.class.js +1 -1
- package/dist/components/charts/chart/bubble-chart.class.js +1 -1
- package/dist/components/charts/chart/chart.class.js +1 -1
- package/dist/components/charts/chart/doughnut-chart.class.js +1 -1
- package/dist/components/charts/chart/histogram.class.js +1 -1
- package/dist/components/charts/chart/line-chart.class.js +1 -1
- package/dist/components/charts/chart/pie-chart.class.js +1 -1
- package/dist/components/charts/chart/polar-area-chart.class.js +1 -1
- package/dist/components/charts/chart/radar-chart.class.js +1 -1
- package/dist/components/charts/chart/scatter-chart.class.js +1 -1
- package/dist/components/conversation/chat-message/chat-message.class.js +2 -2
- package/dist/components/conversation/chat-message/chat-message.styles.js +6 -0
- package/dist/components/conversation/chat-viewport/chat-viewport.class.js +1 -1
- package/dist/components/conversation/generation-metrics/generation-metrics.class.js +2 -2
- package/dist/components/conversation/realtime-session/realtime-session.styles.js +1 -1
- package/dist/components/conversation/thread-list/thread-list.styles.js +9 -0
- package/dist/components/conversation/usage-badge/usage-badge.class.js +1 -1
- package/dist/components/data/file-tree/file-tree.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +1 -1
- package/dist/components/data/heatmap/heatmap.class.js +1 -1
- package/dist/components/data/pagination/pagination.class.js +1 -1
- package/dist/components/data/table/table.class.js +1 -1
- package/dist/components/forms/button/button.styles.js +1 -1
- package/dist/components/forms/checkbox-group/checkbox-group.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/emoji-picker/emoji-picker.class.js +1 -1
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/switch/switch.styles.js +3 -1
- package/dist/components/layout/card/card.styles.js +2 -2
- package/dist/components/layout/dashboard-grid/dashboard-grid.class.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.styles.js +29 -9
- package/dist/components/media/attachment-chip/attachment-chip.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.styles.js +2 -2
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.class.js +1 -1
- package/dist/components/media/lightbox/lightbox.styles.js +2 -0
- package/dist/components/overlays/callout/callout.styles.js +2 -2
- package/dist/components/overlays/kbd/kbd.class.js +1 -1
- package/dist/components/overlays/overlay/popover.class.js +2 -2
- package/dist/components/overlays/overlay/tooltip.class.js +2 -2
- package/dist/components/overlays/popup/popup.class.js +2 -2
- package/dist/components/overlays/spinner/spinner.styles.js +2 -2
- package/dist/components/retrieval/citation-badge/citation-badge.class.js +1 -1
- package/dist/components/retrieval/claim-evidence/claim-evidence.class.js +1 -1
- package/dist/components/retrieval/entity-dossier/entity-dossier.class.js +1 -1
- package/dist/components/retrieval/grounding-summary/grounding-summary.class.js +2 -2
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.styles.js +11 -0
- package/dist/components/retrieval/memory-panel/memory-panel.class.js +1 -1
- package/dist/components/retrieval/provenance-panel/provenance-panel.class.js +1 -1
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-picker/source-picker.class.js +1 -1
- package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
- package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
- package/dist/components/viewers/document-compare/document-compare.class.js +1 -1
- package/dist/components/viewers/ebook-viewer/ebook-viewer.class.js +1 -1
- package/dist/internal/dev-mode-attribute-warning.d.ts +7 -0
- package/dist/internal/dev-mode-attribute-warning.js +1 -0
- 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/llms/components/lr-attachment-trigger.md +2 -2
- package/llms/components/lr-heatmap.md +1 -1
- package/llms/index.md +1 -1
- package/llms/peers.md +1 -1
- package/llms/shared.md +13 -0
- package/llms-full.txt +16 -3
- package/package.json +3 -3
- package/vscode-html-data.json +1 -1
- package/web-types.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteNumber}from"../../../internal/numbers.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateOverlay,composedContains}from"../../../internal/overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeStepBaseMilliseconds,to24Hour}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.hasFooterSlot=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.digitBuffer="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.transitionToken=0,this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault(),this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer(),this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name),next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.setDraftSegment(name,null);return}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const focusedSegment=event.target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus){queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&(this.activeSegment=focusedSegment)});return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"}),this.emit("lr-input",{value:this.value}))},this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncRequiredDescription()}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any")this._step=next;else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}const parsedValue=parseTimeValue(this.value);this.secondsVisible=this.numericStep<60||parsedValue!==void 0&&parsedValue.precision!=="minute",this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){let normalized=normalizeTimeValue(next);normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"&&(normalized+=":00"),this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get pattern(){return localeTimePattern(this.effectiveLocale,this.hourFormat,this.includeSeconds)}get segmentOrder(){return this.pattern.filter(part=>part.type!=="literal").map(part=>part.type)}get liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}get usesTwelveHour(){return this.segmentOrder.includes("dayPeriod")}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft(),this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"},this.secondsVisible=this.numericStep<60||parsed.precision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){try{return getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;try{const formatter=getNumberFormat(this.effectiveLocale,{useGrouping:!1});for(let value=0;value<=9;value++)if(formatter.formatToParts(value).find(part=>part.type==="integer")?.value===key)return String(value)}catch{}}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=dayPeriodLabels(this.effectiveLocale);return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second:this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer)return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length);if(name==="dayPeriod"){const labels=dayPeriodLabels(this.effectiveLocale);return this.draft.dayPeriod?labels[this.draft.dayPeriod]:"--"}const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){if(name==="hour")if(value===null)this.draft.hour=null;else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else this.draft[name]=value===null?null:Number(value);if(!user){this.requestUpdate();return}this.publishDraftEdit()}}publishDraftEdit(){const before=super.value,next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete,super.value=next,this.syncComponentStates(),dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(forceChange||this.value!==before)&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}resetDigitBuffer(){this.digitBuffer="",this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder,current=Math.max(0,order.indexOf(from)),next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour",this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,this.syncComponentStates(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){return this._open===next?this.visibilityPromise:next&&this.liveDisabled?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event)}}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"}))}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment),modal:!1,trapFocus:!1}),this.lightDismissDocument=this.ownerDocument,this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.updateComplete.then(()=>{this.renderRoot.querySelector('[part~="column-item-selected"]')?.scrollIntoView({block:"center"})}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose}),this.overlayHandle=void 0,this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=void 0,this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateSlotState(event){const slot=event.currentTarget,present=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="label"?this.hasLabelSlot=present:slot.name==="hint"?this.hasHintSlot=present:slot.name==="error"?this.hasErrorSlot=present:slot.name==="start"?this.hasStartSlot=present:slot.name==="end"?this.hasEndSlot=present:slot.name==="footer"&&(this.hasFooterSlot=present)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const slots=Array.from(this.children??[]).map(element=>element.getAttribute("slot"));this.hasLabelSlot=slots.includes("label"),this.hasHintSlot=slots.includes("hint"),this.hasErrorSlot=slots.includes("error"),this.hasStartSlot=slots.includes("start"),this.hasEndSlot=slots.includes("end"),this.hasFooterSlot=slots.includes("footer")}this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focusedSegment=orderKey!==this.segmentOrderKey?this.shadowRoot?.activeElement?.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step"))&&this.updateValidity(),this.syncComponentStates(),this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid),this.syncRequiredDescription();const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}syncRequiredDescription(){const target=this.renderRoot.querySelector('[part~="input"]'),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{FormAssociated,isBarredFromValidation}from"../../../internal/form-associated.js";import{SET_ANCHORED_VALIDITY,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{acquireAriaDescription}from"../../../internal/aria-controls.js";import{sizes}from"../../../internal/sizes.styles.js";import{closeIcon,chevronIcon}from"../../../internal/icons.js";import{finiteNumber}from"../../../internal/numbers.js";import{place}from"../../../internal/positioner.js";import{rtlAwarePlacement}from"../../../internal/rtl.js";import{activateOverlay,composedContains}from"../../../internal/overlay-manager.js";import{dispatchNativeEvent,dispatchNativeInputEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{setCustomState}from"../../../internal/custom-states.js";import{submitOnEnter}from"../../../internal/submit-on-enter.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{dayPeriodLabels,hasTimeStepMismatch,isTimeInRange,localeTimePattern,normalizeTimeValue,parseTimeValue,timeStepBaseMilliseconds,to24Hour}from"./time-input-shared.js";import{styles}from"./time-input.styles.js";import{currentValidityValidator}from"../form-validator.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_popover,LYRA_DEFAULT_timeInputDayPeriod,LYRA_DEFAULT_timeInputEmptySegment,LYRA_DEFAULT_timeInputHour,LYRA_DEFAULT_timeInputInvalid,LYRA_DEFAULT_timeInputLabel,LYRA_DEFAULT_timeInputMaxMessage,LYRA_DEFAULT_timeInputMinMessage,LYRA_DEFAULT_timeInputMinute,LYRA_DEFAULT_timeInputNow,LYRA_DEFAULT_timeInputOpen,LYRA_DEFAULT_timeInputPopup,LYRA_DEFAULT_timeInputRangeMessage,LYRA_DEFAULT_timeInputSecond,LYRA_DEFAULT_timeInputStepMessage}from"../../../internal/default-strings.generated.js";class LyraTimeInputBase extends LyraElement{}const stepConverter={fromAttribute(value){if(value==="any")return"any";const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?parsed:60},toAttribute(value){return String(value)}},hourFormatConverter={fromAttribute(value){return value==="12"||value==="24"?value:"auto"},toAttribute(value){return value}},PLACEMENTS=new Set(["top","top-start","top-end","right","right-start","right-end","bottom","bottom-start","bottom-end","left","left-start","left-end"]),placementConverter={fromAttribute(value){return PLACEMENTS.has(value)?value:"bottom-start"},toAttribute(value){return value}},blankDraft=()=>({hour:null,minute:null,second:null,dayPeriod:null}),pad=value=>String(value).padStart(2,"0");function isElementNode(value){if(value===null||typeof value!="object")return!1;const candidate=value;return candidate.nodeType===1&&typeof candidate.getRootNode=="function"&&typeof candidate.contains=="function"}function containsElement(container,value){if(!container||!isElementNode(value))return!1;try{return container.contains(value)}catch{return!1}}class LyraTimeInput extends FormAssociated(LyraTimeInputBase){static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,fieldRequired:LYRA_DEFAULT_fieldRequired,popover:LYRA_DEFAULT_popover,timeInputDayPeriod:LYRA_DEFAULT_timeInputDayPeriod,timeInputEmptySegment:LYRA_DEFAULT_timeInputEmptySegment,timeInputHour:LYRA_DEFAULT_timeInputHour,timeInputInvalid:LYRA_DEFAULT_timeInputInvalid,timeInputLabel:LYRA_DEFAULT_timeInputLabel,timeInputMaxMessage:LYRA_DEFAULT_timeInputMaxMessage,timeInputMinMessage:LYRA_DEFAULT_timeInputMinMessage,timeInputMinute:LYRA_DEFAULT_timeInputMinute,timeInputNow:LYRA_DEFAULT_timeInputNow,timeInputOpen:LYRA_DEFAULT_timeInputOpen,timeInputPopup:LYRA_DEFAULT_timeInputPopup,timeInputRangeMessage:LYRA_DEFAULT_timeInputRangeMessage,timeInputSecond:LYRA_DEFAULT_timeInputSecond,timeInputStepMessage:LYRA_DEFAULT_timeInputStepMessage}}static get validators(){return[currentValidityValidator("required","disabled","readonly","value","min","max","step")]}static{this.styles=[LyraElement.styles,sizes,srOnly,styles]}static{this.properties={open:{type:Boolean,reflect:!0,noAccessor:!0},readonly:{type:Boolean,reflect:!0,noAccessor:!0},step:{converter:stepConverter,reflect:!0,noAccessor:!0}}}constructor(){super(),this.appearance="outlined",this.autocomplete="",this.distance=0,this.hint="",this.hourFormat="auto",this.label="",this.min="",this.max="",this.pill=!1,this.placement="bottom-start",this.size="m",this.withClear=!1,this.withHint=!1,this.withLabel=!1,this.withNow=!1,this.errorText="",this.activeSegment="hour",this.touched=!1,this.hasLabelSlot=!1,this.hasHintSlot=!1,this.hasErrorSlot=!1,this.hasStartSlot=!1,this.hasEndSlot=!1,this.hasFooterSlot=!1,this._open=!1,this._readonly=!1,this._step=60,this.draft=blankDraft(),this.partial=!1,this.secondsVisible=!1,this.digitBuffer="",this.restoringSegmentFocus=!1,this.restoreFocusOnClose=!0,this.transitionToken=0,this.visibilityPromise=Promise.resolve(),this.segmentOrderKey="",this.pickerGridKey="",this.pickerGridMilliseconds=[],this.inputId=nextId("time-input"),this.labelId=nextId("time-input-label"),this.hintId=nextId("time-input-hint"),this.errorId=nextId("time-input-error"),this.requiredDescriptionId=nextId("time-input-required"),this.popupId=nextId("time-input-popup"),this.now=()=>new Date,this.onSegmentKeyDown=event=>{const name=event.currentTarget.dataset.segment;if(this.liveDisabled)return;if(event.altKey&&event.key==="ArrowDown"){event.preventDefault(),this.show();return}const digit=this.inputDigit(event.key);if(digit!==void 0&&!event.ctrlKey&&!event.metaKey&&!event.altKey&&!this.readonly){event.preventDefault(),this.acceptDigit(name,digit);return}if(name==="dayPeriod"&&!this.readonly&&(event.key.toLowerCase()==="a"||event.key.toLowerCase()==="p")){event.preventDefault(),this.setDraftSegment(name,event.key.toLowerCase()==="a"?"am":"pm");return}if(event.key==="ArrowLeft"||event.key==="ArrowRight"){event.preventDefault();const physical=event.key==="ArrowRight"?1:-1;this.resetDigitBuffer(),this.moveSegment(name,this.effectiveDirection==="rtl"?-physical:physical);return}if((event.key==="ArrowUp"||event.key==="ArrowDown")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.stepSegment(name,event.key==="ArrowUp"?1:-1);return}if((event.key==="Home"||event.key==="End")&&!this.readonly){event.preventDefault();const bounds=this.segmentBounds(name),next=event.key==="Home"?bounds.min:bounds.max;this.setDraftSegment(name,name==="dayPeriod"?next===0?"am":"pm":next);return}if((event.key==="Backspace"||event.key==="Delete")&&!this.readonly){event.preventDefault(),this.resetDigitBuffer(),this.setDraftSegment(name,null);return}event.key==="Enter"&&(this.open?this.hide():this.readonly||submitOnEnter(this,event))},this.onSegmentPaste=event=>{if(this.liveDisabled||this.readonly)return;const pasted=normalizeTimeValue(event.clipboardData?.getData("text").trim()??"");pasted&&(event.preventDefault(),this.resetDigitBuffer(),this.commitUserValue(pasted,"insertFromPaste",!0))},this.onSegmentFocus=event=>{if(event.stopPropagation(),this.liveDisabled)return;const focusedSegment=event.target.dataset.segment??this.activeSegment;if(this.restoringSegmentFocus){queueMicrotask(()=>{this.isConnected&&this.segmentOrder.includes(focusedSegment)&&(this.activeSegment=focusedSegment)});return}else this.activeSegment=focusedSegment;const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||relayNativeEvent(this,event)},this.onSegmentBlur=event=>{if(event.stopPropagation(),this.pendingSegmentFocus){this.resetDigitBuffer();return}const related=event.relatedTarget;containsElement(this.renderRoot.querySelector('[part="input"]'),related)||(this.liveDisabled||(this.touched=!0),this.resetDigitBuffer(),relayNativeEvent(this,event))},this.onDocumentPointerDown=event=>{const target=event.composedPath()[0];isElementNode(target)&&composedContains(this,target)||this.requestVisibility(!1,!0,!1)},this.onExpand=()=>{this.liveDisabled||(this.open?this.hide():this.show())},this.onClear=()=>{this.liveDisabled||this.readonly||!this.draftHasAny&&this.value===""||(this.touched=!0,this.commitUserValue("","deleteContentBackward",!0),this.emit("lr-clear"),this.focus())},this.onNow=()=>{if(this.liveDisabled||this.readonly)return;const now=this.now();let value=`${pad(now.getHours())}:${pad(now.getMinutes())}`;this.includeSeconds&&(value+=`:${pad(now.getSeconds())}`),this.commitUserValue(value)},this.onPopupPointerDown=event=>{event.preventDefault()},this.onAutofillInput=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value),intentionalClear=input.value===""&&(event.isTrusted||event.inputType.startsWith("delete")||event.inputType==="insertReplacementText");if(input.value===""&&this.value!==""&&!intentionalClear){input.value=this.value;return}input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeInputEvent(this,{data:event.data,inputType:event.inputType||"insertReplacementText"}),this.emit("lr-input",{value:this.value}))},this.onAutofillChange=event=>{event.stopPropagation();const input=event.currentTarget,normalized=normalizeTimeValue(input.value);input.value!==""&&!normalized||this.readonly||this.liveDisabled||(this.value=normalized,dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))},this.onColumnKeyDown=event=>{if(this.liveDisabled||!["ArrowUp","ArrowDown","Home","End"].includes(event.key))return;const current=event.currentTarget,column=current.closest('[role="listbox"]'),options=Array.from(column?.querySelectorAll('[role="option"]')??[]).filter(option=>!option.disabled);if(options.length===0)return;event.preventDefault();const index=Math.max(0,options.indexOf(current)),nextIndex=event.key==="Home"?0:event.key==="End"?options.length-1:(index+(event.key==="ArrowDown"?1:-1)+options.length)%options.length;for(const option of options)option.tabIndex=option===options[nextIndex]?0:-1;options[nextIndex].focus(),options[nextIndex].scrollIntoView({block:"nearest"})},this.addEventListener("invalid",()=>{this.touched=!0})}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.syncRequiredDescription()}get open(){return this._open}set open(next){this.requestVisibility(!!next,this.isConnected&&this.hasUpdated,!0)}get readonly(){return this._readonly}set readonly(next){const old=this._readonly;this._readonly=!!next,this.toggleAttribute("readonly",this._readonly),this.updateValidity(),this.requestUpdate("readonly",old)}get step(){return this._step}set step(next){const old=this._step;if(next==="any")this._step=next;else{const numeric=finiteNumber(Number(next),60);this._step=numeric>0?numeric:60}const parsedValue=parseTimeValue(this.value);this.secondsVisible=this.numericStep<60||parsedValue!==void 0&&parsedValue.precision!=="minute",this.updateValidity(),this.requestUpdate("step",old)}get disabled(){return super.disabled}set disabled(next){super.disabled=next,next&&this.forceClose(!1),this.syncComponentStates()}get value(){return super.value}set value(next){let normalized=normalizeTimeValue(next);normalized&&this.numericStep<60&&parseTimeValue(normalized)?.precision==="minute"&&(normalized+=":00"),this.partial=!1,this.resetDigitBuffer(),this.syncDraft(normalized),super.value=normalized,this.syncComponentStates()}get valueAsNumber(){return parseTimeValue(this.value)?.milliseconds??Number.NaN}get valueAsDate(){const parsed=parseTimeValue(this.value);if(!parsed)return null;const result=this.now();return result.setHours(parsed.hour,parsed.minute,parsed.second,parsed.millisecond),result}get numericStep(){return this.step==="any"?60:finiteNumber(this.step,60)}get includeSeconds(){return this.numericStep<60||this.secondsVisible}get pattern(){return localeTimePattern(this.effectiveLocale,this.hourFormat,this.includeSeconds)}get segmentOrder(){return this.pattern.filter(part=>part.type!=="literal").map(part=>part.type)}get liveDisabled(){const matches=this.matches;return this.effectiveDisabled||typeof matches=="function"&&matches.call(this,":disabled")}activeSegmentFor(order=this.segmentOrder){return order.includes(this.activeSegment)?this.activeSegment:order[0]??"hour"}get usesTwelveHour(){return this.segmentOrder.includes("dayPeriod")}get draftComplete(){return this.draft.hour!==null&&this.draft.minute!==null&&(!this.includeSeconds||this.draft.second!==null)&&(!this.usesTwelveHour||this.draft.dayPeriod!==null)}get draftHasAny(){return Object.values(this.draft).some(value=>value!==null)}syncDraft(value){const parsed=parseTimeValue(value);if(!parsed){this.draft=blankDraft(),this.secondsVisible=this.numericStep<60;return}this.draft={hour:parsed.hour,minute:parsed.minute,second:parsed.second,dayPeriod:parsed.hour>=12?"pm":"am"},this.secondsVisible=this.numericStep<60||parsed.precision!=="minute"}canonicalDraftValue(){if(!this.draftComplete)return"";const value=`${pad(this.draft.hour)}:${pad(this.draft.minute)}`;return this.includeSeconds?`${value}:${pad(this.draft.second)}`:value}syncComponentStates(){setCustomState(this.internals,"blank",this.value===""),setCustomState(this.internals,"disabled",this.effectiveDisabled),setCustomState(this.internals,"open",this.open)}formattedNumber(value,minimumIntegerDigits){try{return getNumberFormat(this.effectiveLocale,{minimumIntegerDigits,useGrouping:!1}).format(value)}catch{return String(value).padStart(minimumIntegerDigits,"0")}}inputDigit(key){if(/^[0-9]$/.test(key))return key;try{const formatter=getNumberFormat(this.effectiveLocale,{useGrouping:!1});for(let value=0;value<=9;value++)if(formatter.formatToParts(value).find(part=>part.type==="integer")?.value===key)return String(value)}catch{}}displayTime(value){const parsed=parseTimeValue(value);if(!parsed)return value;const includeSeconds=parsed.precision!=="minute",labels=dayPeriodLabels(this.effectiveLocale);return localeTimePattern(this.effectiveLocale,this.hourFormat,includeSeconds).map(part=>{if(part.type==="literal")return part.value;if(part.type==="hour"){const hour=this.usesTwelveHour?parsed.hour%12||12:parsed.hour;return this.formattedNumber(hour,this.usesTwelveHour?1:2)}return part.type==="minute"?this.formattedNumber(parsed.minute,2):part.type==="second"?this.formattedNumber(parsed.second,2):parsed.hour>=12?labels.pm:labels.am}).join("")}segmentNumericValue(name){return name==="hour"?this.draft.hour===null?null:this.usesTwelveHour?this.draft.hour%12||12:this.draft.hour:name==="minute"?this.draft.minute:name==="second"?this.draft.second:this.draft.dayPeriod==="am"?0:this.draft.dayPeriod==="pm"?1:null}segmentText(name){if(this.digitSegment===name&&this.digitBuffer)return this.formattedNumber(Number(this.digitBuffer),this.digitBuffer.length);if(name==="dayPeriod"){const labels=dayPeriodLabels(this.effectiveLocale);return this.draft.dayPeriod?labels[this.draft.dayPeriod]:"--"}const value=this.segmentNumericValue(name);if(value===null)return"--";const minimumDigits=name==="hour"&&this.usesTwelveHour?1:2;return this.formattedNumber(value,minimumDigits)}segmentLabel(name){const keys={hour:"timeInputHour",minute:"timeInputMinute",second:"timeInputSecond",dayPeriod:"timeInputDayPeriod"};return this.localize(keys[name])}segmentBounds(name){return name==="hour"?this.usesTwelveHour?{min:1,max:12}:{min:0,max:23}:name==="dayPeriod"?{min:0,max:1}:{min:0,max:59}}setDraftSegment(name,value,user=!0){if(!(this.liveDisabled||user&&this.readonly)){if(name==="hour")if(value===null)this.draft.hour=null;else{const numeric=Number(value);this.draft.hour=this.usesTwelveHour?to24Hour(numeric,this.draft.dayPeriod??"am"):numeric}else if(name==="dayPeriod"){const period=value==="pm"?"pm":value==="am"?"am":null;if(period&&this.draft.hour!==null){const displayHour=this.draft.hour%12||12;this.draft.hour=to24Hour(displayHour,period)}this.draft.dayPeriod=period}else this.draft[name]=value===null?null:Number(value);if(!user){this.requestUpdate();return}this.publishDraftEdit()}}publishDraftEdit(){const before=super.value,next=this.canonicalDraftValue();this.partial=this.draftHasAny&&!this.draftComplete,super.value=next,this.syncComponentStates(),dispatchNativeInputEvent(this,{inputType:"insertReplacementText"}),this.emit("lr-input",{value:this.value}),next!==""&&next!==before&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value})),this.requestUpdate()}commitUserValue(value,inputType="insertReplacementText",forceChange=!1){const before=this.value;this.value=value,dispatchNativeInputEvent(this,{inputType}),this.emit("lr-input",{value:this.value}),(forceChange||this.value!==before)&&(dispatchNativeEvent(this,"change"),this.emit("lr-change",{value:this.value}))}resetDigitBuffer(){this.digitBuffer="",this.digitSegment=void 0}moveSegment(from,direction){const order=this.segmentOrder,current=Math.max(0,order.indexOf(from)),next=Math.min(order.length-1,Math.max(0,current+direction));this.activeSegment=order[next]??"hour",this.segmentElement(this.activeSegment)?.focus()}acceptDigit(name,digit){if(name==="dayPeriod")return;this.digitSegment!==name&&(this.digitSegment=name,this.digitBuffer="");const bounds=this.segmentBounds(name);let candidateText=`${this.digitBuffer}${digit}`.slice(-2),candidate=Number(candidateText);(candidate>bounds.max||candidateText.length===2&&candidate<bounds.min)&&(candidateText=digit,candidate=Number(digit)),this.digitBuffer=candidateText,candidate>=bounds.min&&candidate<=bounds.max?this.setDraftSegment(name,candidate):this.requestUpdate();const cannotAcceptAnother=candidate*10>bounds.max;(candidateText.length===2||cannotAcceptAnother)&&(this.resetDigitBuffer(),this.moveSegment(name,1))}stepSegment(name,delta){const bounds=this.segmentBounds(name),current=this.segmentNumericValue(name),next=current===null?bounds.min:(current-bounds.min+delta+(bounds.max-bounds.min+1))%(bounds.max-bounds.min+1)+bounds.min;name==="dayPeriod"?this.setDraftSegment(name,next===0?"am":"pm"):this.setDraftSegment(name,next)}segmentElement(name){return this.renderRoot?.querySelector(`[data-segment="${name}"]`)}focus(options){if(this.liveDisabled)return;const order=this.segmentOrder,activeSegment=this.activeSegmentFor(order);activeSegment!==this.activeSegment&&(this.activeSegment=activeSegment),this.segmentElement(activeSegment)?.focus(options)}blur(){const active=this.shadowRoot?.activeElement;active&&typeof active.blur=="function"&&active.blur()}click(){this.liveDisabled||this.focus()}setOpen(next){if(this._open===next)return;const old=this._open;this._open=next,this.syncComponentStates(),this.requestUpdate("open",old)}syncOpenAttribute(){this.toggleAttribute("open",this._open)}requestVisibility(next,announce,restoreFocus){return this._open===next?this.visibilityPromise:next&&this.liveDisabled?(this.syncOpenAttribute(),Promise.resolve()):announce&&this.emit(next?"lr-show":"lr-hide",null,{cancelable:!0}).defaultPrevented?(this.syncOpenAttribute(),Promise.resolve()):(this.restoreFocusOnClose=restoreFocus,this.setOpen(next),this.visibilityPromise=announce?this.settleTransition(next?"lr-after-show":"lr-after-hide"):Promise.resolve(),this.visibilityPromise)}show(){return this.requestVisibility(!0,!0,!0)}hide(){return this.requestVisibility(!1,!0,!0)}forceClose(restoreFocus){this._open&&(this.restoreFocusOnClose=restoreFocus,this.setOpen(!1))}async settleTransition(event){const token=++this.transitionToken;if(await this.updateComplete,this.transitionToken===token){if(this.isConnected){const view=this.ownerDocument.defaultView;if(view&&await new Promise(resolve=>view.requestAnimationFrame(()=>resolve())),this.transitionToken!==token)return;const animations=this.renderRoot.querySelector('[part="popup"]')?.getAnimations({subtree:!0})??[];if(await Promise.all(animations.map(animation=>animation.finished.catch(()=>{}))),this.transitionToken!==token)return}this.emit(event)}}positionPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0;const anchor=this.renderRoot.querySelector('[part~="time-input"]'),popup=this.renderRoot.querySelector('[part="popup"]');!anchor||!popup||(this.cleanupPositioner=place(anchor,popup,{placement:rtlAwarePlacement(this.placement,this),offset:finiteNumber(this.distance,0),sync:"width"}))}activatePopup(){this.isConnected&&(this.positionPopup(),this.overlayHandle=activateOverlay({host:this,panel:()=>this.renderRoot.querySelector('[part="popup"]'),onEscape:()=>{this.hide()},restoreFocusTo:this.segmentElement(this.activeSegment),modal:!1,trapFocus:!1}),this.lightDismissDocument=this.ownerDocument,this.lightDismissDocument.addEventListener("pointerdown",this.onDocumentPointerDown,!0),this.updateComplete.then(()=>{this.renderRoot.querySelector('[part~="column-item-selected"]')?.scrollIntoView({block:"center"})}))}teardownPopup(){this.cleanupPositioner?.(),this.cleanupPositioner=void 0,this.overlayHandle?.deactivate({restoreFocus:this.restoreFocusOnClose}),this.overlayHandle=void 0,this.lightDismissDocument?.removeEventListener("pointerdown",this.onDocumentPointerDown,!0),this.lightDismissDocument=void 0,this.restoreFocusOnClose=!0}onColumnSelect(name,value){this.readonly||this.liveDisabled||(this.resetDigitBuffer(),this.setDraftSegment(name,value),this.activeSegment=name,this.updateComplete.then(()=>this.segmentElement(name)?.focus()))}updateSlotState(event){const slot=event.currentTarget,present=slot.assignedNodes({flatten:!0}).some(node=>node.nodeType===Node.ELEMENT_NODE||(node.textContent??"").trim().length>0);slot.name==="label"?this.hasLabelSlot=present:slot.name==="hint"?this.hasHintSlot=present:slot.name==="error"?this.hasErrorSlot=present:slot.name==="start"?this.hasStartSlot=present:slot.name==="end"?this.hasEndSlot=present:slot.name==="footer"&&(this.hasFooterSlot=present)}updateValidity(){if(isBarredFromValidation(this,this.internals)){this[SET_ANCHORED_VALIDITY]({});return}const flags={};let message="";this.required&&this.value===""&&(flags.valueMissing=!0),this.partial&&(flags.badInput=!0);const parsed=parseTimeValue(this.value);if(this.value!==""&&!parsed&&(flags.badInput=!0),parsed&&!isTimeInRange(this.value,this.min,this.max)){const parsedMin=parseTimeValue(this.min),parsedMax=parseTimeValue(this.max);parsedMin&&parsedMax&&parsedMin.milliseconds>parsedMax.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputRangeMessage",void 0,{min:this.displayTime(this.min),max:this.displayTime(this.max)})):parsedMin&&parsed.milliseconds<parsedMin.milliseconds?(flags.rangeUnderflow=!0,message=this.localize("timeInputMinMessage",void 0,{min:this.displayTime(this.min)})):(flags.rangeOverflow=!0,message=this.localize("timeInputMaxMessage",void 0,{max:this.displayTime(this.max)}))}parsed&&hasTimeStepMismatch(this.value,this.step,this.min,this.defaultValue)&&(flags.stepMismatch=!0,message||=this.localize("timeInputStepMessage")),flags.badInput?message=this.localize("timeInputInvalid"):flags.valueMissing&&(message=this.localize("fieldRequired")),this[SET_ANCHORED_VALIDITY](flags,message)}checkValidity(){return this.updateValidity(),super.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),super.reportValidity()}[VALIDITY_ANCHOR](){return this.segmentElement(this.activeSegmentFor())}formResetCallback(){super.formResetCallback(),this.touched=!1,this.partial=!1,this.resetDigitBuffer()}formStateRestoreCallback(state2,reason="restore"){super.formStateRestoreCallback(state2,reason)}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){const slots=Array.from(this.children??[]).map(element=>element.getAttribute("slot"));this.hasLabelSlot=slots.includes("label"),this.hasHintSlot=slots.includes("hint"),this.hasErrorSlot=slots.includes("error"),this.hasStartSlot=slots.includes("start"),this.hasEndSlot=slots.includes("end"),this.hasFooterSlot=slots.includes("footer")}this.open&&this.effectiveDisabled&&this.forceClose(!1);const order=this.segmentOrder,orderKey=order.join("|"),focusedSegment=orderKey!==this.segmentOrderKey?this.shadowRoot?.activeElement?.getAttribute("data-segment"):null,nextActiveSegment=focusedSegment&&order.includes(focusedSegment)?focusedSegment:this.activeSegmentFor(order);focusedSegment&&(this.pendingSegmentFocus=order.includes(focusedSegment)?focusedSegment:nextActiveSegment),this.segmentOrderKey=orderKey}updated(changed){super.updated(changed),changed.has("open")?this.open?this.activatePopup():this.teardownPopup():this.open&&(changed.has("placement")||changed.has("distance"))&&this.positionPopup(),(changed.has("value")||changed.has("required")||changed.has("readonly")||changed.has("min")||changed.has("max")||changed.has("step"))&&this.updateValidity(),this.syncComponentStates(),this.toggleAttribute("data-invalid",this.touched&&!this.validity.valid),this.syncRequiredDescription();const pendingSegmentFocus=this.pendingSegmentFocus;if(this.pendingSegmentFocus=void 0,pendingSegmentFocus&&!this.effectiveDisabled){this.restoringSegmentFocus=!0;try{this.segmentElement(pendingSegmentFocus)?.focus()}finally{this.restoringSegmentFocus=!1}}}disconnectedCallback(){this.releaseRequiredDescription(),this.transitionToken++,this.forceClose(!1),this.teardownPopup(),this.syncOpenAttribute(),this.pendingSegmentFocus=void 0,super.disconnectedCallback()}syncRequiredDescription(){const target=this.renderRoot.querySelector('[part~="input"]'),description=this.renderRoot.querySelector(`#${this.requiredDescriptionId}`);if(!this.required||!target||!description){this.releaseRequiredDescription();return}if(this.requiredDescriptionTarget!==target){this.releaseRequiredDescription(),this.requiredDescriptionTarget=target,this.requiredDescriptionLease=acquireAriaDescription(target,[description]);return}this.requiredDescriptionLease?.update([description])}releaseRequiredDescription(){this.requiredDescriptionLease?.release(),this.requiredDescriptionLease=void 0,this.requiredDescriptionTarget=void 0}renderSegment(name,invalid){const value=this.segmentNumericValue(name),bounds=this.segmentBounds(name),empty=value===null;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="segment"
|
|
4
4
|
role="spinbutton"
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import{css}from"lit";const styles=css`
|
|
2
2
|
:host {
|
|
3
3
|
display: inline-block;
|
|
4
|
+
max-inline-size: 100%;
|
|
4
5
|
/* Component-local geometry knobs (defined on :host so each instance can
|
|
5
6
|
tune its own geometry) — a fully-rounded pill/thumb
|
|
6
7
|
needs a radius well past --lr-radius's small 0.375rem default, so
|
|
@@ -26,6 +27,7 @@ import{css}from"lit";const styles=css`
|
|
|
26
27
|
gap: var(--lr-switch-gap, var(--lr-space-s));
|
|
27
28
|
cursor: pointer;
|
|
28
29
|
-webkit-tap-highlight-color: transparent;
|
|
30
|
+
max-inline-size: 100%;
|
|
29
31
|
}
|
|
30
32
|
.switch-owner {
|
|
31
33
|
display: inline-flex;
|
|
@@ -214,6 +216,6 @@ import{css}from"lit";const styles=css`
|
|
|
214
216
|
[part="error"] {
|
|
215
217
|
min-inline-size: 0;
|
|
216
218
|
max-inline-size: 100%;
|
|
217
|
-
overflow-wrap:
|
|
219
|
+
overflow-wrap: break-word;
|
|
218
220
|
}
|
|
219
221
|
`;export{styles};
|
|
@@ -147,7 +147,7 @@ import{css}from"lit";const styles=css`
|
|
|
147
147
|
::slotted([slot="header"]) {
|
|
148
148
|
flex: 1 1 auto;
|
|
149
149
|
min-inline-size: 0;
|
|
150
|
-
overflow-wrap:
|
|
150
|
+
overflow-wrap: break-word;
|
|
151
151
|
}
|
|
152
152
|
[part="actions"] {
|
|
153
153
|
display: flex;
|
|
@@ -163,7 +163,7 @@ import{css}from"lit";const styles=css`
|
|
|
163
163
|
padding: var(--spacing, var(--padding, var(--lr-space-m)));
|
|
164
164
|
flex: 1 1 auto;
|
|
165
165
|
min-inline-size: 0;
|
|
166
|
-
overflow-wrap:
|
|
166
|
+
overflow-wrap: break-word;
|
|
167
167
|
}
|
|
168
168
|
[part="footer"] {
|
|
169
169
|
display: flex;
|
|
@@ -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{tag}from"../../../internal/prefix.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{Announcer,acquireAnnouncementSink}from"../../../internal/announcer.js";import{isRtl}from"../../../internal/rtl.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{isArrowKey,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{styles}from"./dashboard-grid.styles.js";import"./layout.js";import{clampDashboardCandidate,createDashboardSpatialIndex,findDashboardCollisions,normalizeLyraDashboardCollisionPolicy,projectDashboardLayout,resolveDashboardPlacement,snapshotDashboardLayout,sortDashboardSpatial}from"./layout-internal.js";import{createWidgetDocument}from"../../conversation/widget-renderer/resolve.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dashboardCellCollisionRejected,LYRA_DEFAULT_dashboardCellMoved,LYRA_DEFAULT_dashboardCellResized,LYRA_DEFAULT_dashboardGridLabel,LYRA_DEFAULT_flowItemAnnouncement,LYRA_DEFAULT_noData}from"../../../internal/default-strings.generated.js";const INTERACTIVE_DESCENDANT_SELECTOR='button, a[href], area[href], input, select, textarea, summary, label, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="switch"], [role="slider"], [role="spinbutton"], [role="textbox"], [role="combobox"], [role="option"], [role="menuitem"], [tabindex]:not([part="cell"])';class LyraDashboardGrid extends LyraElement{constructor(){super(...arguments),this.authoredLayout=Object.freeze([]),this.effectiveLayout=Object.freeze([]),this.columns=12,this.rowHeight=80,this.gap=8,this.collisionValue="reject",this.cellsDraggable=!1,this.cellsResizable=!1,this.locked=!1,this.accessibleLabel=null,this.announcer=new Announcer({onFlush:text=>{this.liveText=text,isAccessibilityVisible(this)&&this.announcementSink?.announce(text)}}),this.liveText="",this.activeCellIndex=0,this.activeCellId="",this.rehomeCellFocus=!1,this.defaultCellSyncQueued=!1,this.ownedDefaultCells=new WeakSet,this.warnedUnmatchedCells=new WeakSet,this.authoredSlotBaselines=new WeakMap,this.managedAuthoredCells=new Set,this.suppressedClickCellId="",this.onCellPointerMove=e=>{const drag=this.cellDrag;if(!(!drag||e.pointerId!==drag.pointerId)){if(!this.canDragCell(drag.cellId)){this.cancelCellDrag();return}drag.pendingClientX=e.clientX,drag.pendingClientY=e.clientY,drag.previewFrame===void 0&&(drag.previewFrame=drag.ownerWindow.requestAnimationFrame(()=>{drag.previewFrame=void 0,this.cellDrag===drag&&this.applyDragPreview(drag)}))}},this.onCellPointerUp=e=>{const drag=this.cellDrag;if(!drag||e.pointerId!==drag.pointerId)return;if(e.type!=="pointerup"||!this.canDragCell(drag.cellId)){this.cancelCellDrag();return}this.flushDragPreview(drag),this.cellDrag=void 0,this.releaseGesturePointerCapture(drag.wrapper,drag.pointerId),drag.wrapper.removeAttribute("data-dragging"),drag.ownerWindow.removeEventListener("pointermove",this.onCellPointerMove),drag.ownerWindow.removeEventListener("pointerup",this.onCellPointerUp),drag.ownerWindow.removeEventListener("pointercancel",this.onCellPointerUp),drag.ownerWindow.removeEventListener("lostpointercapture",this.onCellPointerUp);const x=drag.currentX??drag.startX,y=drag.currentY??drag.startY;(x!==drag.startX||y!==drag.startY)&&this.commitPlacement(drag.cellId,{x,y,w:drag.w,h:drag.h},"move"),drag.moved&&this.armClickSuppression(drag.cellId,drag.ownerWindow),this.resetCellInlineStyle(drag.cellId,drag.wrapper),this.requestUpdate()},this.onResizeHandlePointerMove=e=>{const resize=this.cellResize;if(!(!resize||e.pointerId!==resize.pointerId)){if(!this.canResizeCell(resize.cellId)){this.cancelCellResize();return}resize.pendingClientX=e.clientX,resize.pendingClientY=e.clientY,resize.previewFrame===void 0&&(resize.previewFrame=resize.ownerWindow.requestAnimationFrame(()=>{resize.previewFrame=void 0,this.cellResize===resize&&this.applyResizePreview(resize)}))}},this.onResizeHandlePointerUp=e=>{const resize=this.cellResize;if(!resize||e.pointerId!==resize.pointerId)return;if(e.type!=="pointerup"||!this.canResizeCell(resize.cellId)){this.cancelCellResize();return}this.flushResizePreview(resize),this.cellResize=void 0,this.releaseGesturePointerCapture(resize.captureTarget,resize.pointerId),resize.wrapper.removeAttribute("data-resizing"),resize.ownerWindow.removeEventListener("pointermove",this.onResizeHandlePointerMove),resize.ownerWindow.removeEventListener("pointerup",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("pointercancel",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("lostpointercapture",this.onResizeHandlePointerUp);const w=resize.currentW??resize.startW,h=resize.currentH??resize.startH;(w!==resize.startW||h!==resize.startH)&&this.commitPlacement(resize.cellId,{x:resize.x,y:resize.y,w,h},"resize"),resize.moved&&this.armClickSuppression(resize.cellId,resize.ownerWindow),this.resetCellInlineStyle(resize.cellId,resize.wrapper),this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,dashboardCellCollisionRejected:LYRA_DEFAULT_dashboardCellCollisionRejected,dashboardCellMoved:LYRA_DEFAULT_dashboardCellMoved,dashboardCellResized:LYRA_DEFAULT_dashboardCellResized,dashboardGridLabel:LYRA_DEFAULT_dashboardGridLabel,flowItemAnnouncement:LYRA_DEFAULT_flowItemAnnouncement,noData:LYRA_DEFAULT_noData}}static{this.immutableEventDetails=Object.freeze(["lr-collision","lr-layout-change"])}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this.effectiveLayout}set layout(value){const previous=this.effectiveLayout;this.authoredLayout=snapshotDashboardLayout(value),this.effectiveLayout=projectDashboardLayout(this.authoredLayout,this.safeColumns),this.announceAppliedPlacement(),this.requestUpdate("layout",previous)}get collision(){return this.collisionValue}set collision(value){const previous=this.collisionValue;this.collisionValue=normalizeLyraDashboardCollisionPolicy(value),this.requestUpdate("collision",previous)}get safeColumns(){return finiteInteger(this.columns,12,1,48)}get safeRowHeight(){return finiteRange(this.rowHeight,80,1)}get safeGap(){return finiteRange(this.gap,8,0)}get sortedLayout(){return sortDashboardSpatial(this.effectiveLayout)}connectedCallback(){super.connectedCallback(),this.bindOwnerRealmResources(),this.scheduleDefaultCellSync()}disconnectedCallback(){this.announcer.cancel(),this.announcementSink?.release(),this.announcementSink=void 0,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0,this.defaultCellSyncQueued=!1,this.restoreManagedAuthoredSlots(),this.clearSuppressedClick(),this.pendingPlacementAnnouncement=void 0,this.cancelCellDrag(),this.cancelCellResize(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0,this.announcementSink?.release(),this.announcementSink=void 0,this.clearSuppressedClick(),this.isConnected&&(this.bindOwnerRealmResources(),this.scheduleDefaultCellSync())}bindOwnerRealmResources(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcementSink??=acquireAnnouncementSink("polite",{document:ownerDocument,source:this}),this.childObserver&&this.childObserverDocument===ownerDocument)return;this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0;const MutationObserverCtor=ownerWindow?.MutationObserver;if(!MutationObserverCtor)return;const observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||!records.some(record=>record.type==="childList"?record.target===this:record.target.parentNode===this)||this.scheduleDefaultCellSync()});observer.observe(this,{childList:!0,attributes:!0,attributeFilter:["cell-id"],subtree:!0}),this.childObserver=observer,this.childObserverDocument=ownerDocument}scheduleDefaultCellSync(){!this.isConnected||this.defaultCellSyncQueued||(this.defaultCellSyncQueued=!0,queueMicrotask(()=>{this.defaultCellSyncQueued=!1,this.isConnected&&this.syncDefaultCells()}))}willUpdate(changed){if(super.willUpdate(changed),changed.has("columns")&&(this.effectiveLayout=projectDashboardLayout(this.authoredLayout,this.safeColumns)),changed.has("layout")||changed.has("columns")){this.rehomeCellFocus=activeElementIn(this.renderRoot)?.getAttribute("part")==="cell",this.ownerDocument&&this.isConnected&&(this.hasUpdated?this.syncDefaultCells():this.seedFirstRenderState(()=>this.syncDefaultCells()));const cells=this.sortedLayout,retainedIndex=cells.findIndex(cell=>cell.cellId===this.activeCellId),nextIndex=cells.length===0?0:retainedIndex>=0?retainedIndex:Math.min(this.activeCellIndex,cells.length-1);this.activeCellIndex=nextIndex,this.activeCellId=cells[nextIndex]?.cellId??""}this.cellDrag&&(changed.has("layout")||changed.has("columns")||changed.has("rowHeight")||changed.has("gap")||(changed.has("cellsDraggable")||changed.has("locked"))&&!this.canDragCell(this.cellDrag.cellId))&&this.cancelCellDrag(),this.cellResize&&(changed.has("layout")||changed.has("columns")||changed.has("rowHeight")||changed.has("gap")||(changed.has("cellsResizable")||changed.has("locked"))&&!this.canResizeCell(this.cellResize.cellId))&&this.cancelCellResize()}updated(changed){super.updated(changed),this.rehomeCellFocus&&(this.rehomeCellFocus=!1,this.renderRoot.querySelector('[part="cell"][tabindex="0"]')?.focus())}cellLabel(cell){return cell.label||cell.cellId}restoreAuthoredSlot(child){if(!this.authoredSlotBaselines.has(child))return;const baseline=this.authoredSlotBaselines.get(child);baseline===null?child.removeAttribute("slot"):baseline!==void 0&&child.setAttribute("slot",baseline),this.authoredSlotBaselines.delete(child),this.managedAuthoredCells.delete(child)}restoreManagedAuthoredSlots(){for(const child of this.managedAuthoredCells)this.restoreAuthoredSlot(child);this.managedAuthoredCells.clear()}syncDefaultCells(){if(!this.isConnected)return;const ids=new Set(this.effectiveLayout.map(cell=>cell.cellId)),authoredById=new Map,ownedById=new Map;for(const child of Array.from(this.children)){const cellId=child.getAttribute("cell-id");if(this.ownedDefaultCells.has(child)){if(!cellId){child.remove();continue}const matches=ownedById.get(cellId)??[];matches.push(child),ownedById.set(cellId,matches);continue}cellId&&ids.has(cellId)&&!authoredById.has(cellId)?(authoredById.set(cellId,child),this.warnedUnmatchedCells.delete(child),this.authoredSlotBaselines.has(child)||this.authoredSlotBaselines.set(child,child.getAttribute("slot")),this.managedAuthoredCells.add(child),child.setAttribute("slot",`cell-${cellId}`)):(this.restoreAuthoredSlot(child),cellId&&!ids.has(cellId)&&!this.warnedUnmatchedCells.has(child)&&(this.warnedUnmatchedCells.add(child),console.warn(`<lr-dashboard-grid> a child with cell-id="${cellId}" matches no entry in \`layout\`; it will not render.`)))}const selectedAuthored=new Set(authoredById.values());for(const managed of[...this.managedAuthoredCells])(!this.contains(managed)||!selectedAuthored.has(managed))&&this.restoreAuthoredSlot(managed);for(const cell of this.effectiveLayout){const owned=ownedById.get(cell.cellId)??[];if(authoredById.has(cell.cellId)){for(const defaultCell of owned)defaultCell.remove();continue}const existing=owned.shift();existing?(existing.setAttribute("slot",`cell-${cell.cellId}`),this.updateDefaultCell(existing,cell)):this.appendChild(this.createDefaultCell(cell));for(const duplicate of owned)duplicate.remove();ownedById.delete(cell.cellId)}for(const stale of ownedById.values())for(const defaultCell of stale)defaultCell.remove()}createDefaultCell(cell){const ownerDocument=this.ownerDocument,widget=ownerDocument.createElement(tag("widget"));widget.setAttribute("cell-id",cell.cellId),widget.setAttribute("data-dashboard-grid-default-cell",""),widget.setAttribute("slot",`cell-${cell.cellId}`),this.ownedDefaultCells.add(widget);const renderer=ownerDocument.createElement(tag("widget-renderer"));return widget.appendChild(renderer),this.updateDefaultCell(widget,cell),widget}updateDefaultCell(widget,cell){widget.label=this.cellLabel(cell);const renderer=widget.querySelector(tag("widget-renderer"));renderer&&(renderer.document=cell.widget==null?null:createWidgetDocument(cell.widget))}onCellFocus(cellId){const index=this.sortedLayout.findIndex(cell=>cell.cellId===cellId);index>=0&&(this.activeCellIndex!==index&&(this.activeCellIndex=index),this.activeCellId!==cellId&&(this.activeCellId=cellId))}cellElement(cellId){const ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=this.renderRoot.querySelector(`[part="cell"][data-cell-id="${ownerCss.escape(cellId)}"]`);if(candidate?.getAttribute("data-cell-id")===cellId)return candidate}catch{}return Array.from(this.renderRoot.querySelectorAll('[part="cell"][data-cell-id]')).find(candidate=>candidate.getAttribute("data-cell-id")===cellId)??null}focusCellAt(index){const cells=this.sortedLayout;if(index<0||index>=cells.length)return;this.activeCellIndex=index;const cell=cells[index];this.activeCellId=cell.cellId;const number=getNumberFormat(this.effectiveLocale);this.announcer.announce(this.localize("flowItemAnnouncement",void 0,{item:this.cellLabel(cell),index:number.format(index+1),total:number.format(cells.length)})),this.updateComplete.then(()=>{this.cellElement(cell.cellId)?.focus()})}onCellKeyDown(e,cell){const owner=e.currentTarget;if(e.composedPath()[0]!==owner)return;if((e.ctrlKey||e.metaKey)&&isArrowKey(e.key)){(e.shiftKey?this.keyboardResize(cell,e.key):this.keyboardMove(cell,e.key))&&e.preventDefault();return}const cells=this.sortedLayout,index=cells.findIndex(c=>c.cellId===cell.cellId);if(index<0)return;const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=index;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(cells.length-1,index+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,index-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=cells.length-1;else return;next!==index&&(e.preventDefault(),this.focusCellAt(next))}keyboardMove(cell,key){if(!this.cellsDraggable||this.locked||cell.locked)return!1;const rtlFlip=isRtl(this)?-1:1;let dx=0,dy=0;if(key==="ArrowRight")dx=rtlFlip;else if(key==="ArrowLeft")dx=-rtlFlip;else if(key==="ArrowDown")dy=1;else if(key==="ArrowUp")dy=-1;else return!1;return this.commitPlacement(cell.cellId,{x:cell.x+dx,y:cell.y+dy,w:cell.w,h:cell.h},"move")}keyboardResize(cell,key){if(!this.cellsResizable||this.locked||cell.locked)return!1;let dw=0,dh=0;if(key==="ArrowRight")dw=1;else if(key==="ArrowLeft")dw=-1;else if(key==="ArrowDown")dh=1;else if(key==="ArrowUp")dh=-1;else return!1;return this.commitPlacement(cell.cellId,{x:cell.x,y:cell.y,w:cell.w+dw,h:cell.h+dh},"resize")}announceAppliedPlacement(){const pending=this.pendingPlacementAnnouncement;if(!pending)return;this.pendingPlacementAnnouncement=void 0;const cell=this.effectiveLayout.find(candidate=>candidate.cellId===pending.cellId);if(!cell||!(pending.kind==="move"?cell.x===pending.x&&cell.y===pending.y:cell.w===pending.w&&cell.h===pending.h))return;const number=getNumberFormat(this.effectiveLocale);if(pending.kind==="move"){this.announcer.announce(this.localize("dashboardCellMoved",void 0,{label:this.cellLabel(cell),x:number.format(cell.x+1),y:number.format(cell.y+1)}));return}this.announcer.announce(this.localize("dashboardCellResized",void 0,{label:this.cellLabel(cell),w:number.format(cell.w),h:number.format(cell.h)}))}commitPlacement(cellId,requested,kind){const layout=this.effectiveLayout,cell=layout.find(candidate=>candidate.cellId===cellId);if(!cell)return!1;const result=resolveDashboardPlacement(layout,cellId,requested,this.safeColumns,this.collision);if(result.collidedCellIds.length>0&&this.emit("lr-collision",Object.freeze({cellId,collidedCellIds:result.collidedCellIds,policy:this.collision,accepted:result.accepted})),!result.accepted)return this.announcer.announce(this.localize("dashboardCellCollisionRejected",void 0,{label:this.cellLabel(cell)})),!0;const updated=result.layout.find(candidate=>candidate.cellId===cellId);return(kind==="move"?updated.x===cell.x&&updated.y===cell.y:updated.w===cell.w&&updated.h===cell.h)?!1:(this.pendingPlacementAnnouncement={cellId,kind,x:updated.x,y:updated.y,w:updated.w,h:updated.h},kind==="move"?this.emit("lr-cell-move",Object.freeze({cellId,position:Object.freeze({x:updated.x,y:updated.y}),previous:Object.freeze({x:cell.x,y:cell.y})})):this.emit("lr-cell-resize",Object.freeze({cellId,size:Object.freeze({w:updated.w,h:updated.h}),previous:Object.freeze({w:cell.w,h:cell.h})})),this.emit("lr-layout-change",Object.freeze({layout:result.layout})),!0)}cellStyle(cell){return{"grid-column":`${cell.x+1} / span ${cell.w}`,"grid-row":`${cell.y+1} / span ${cell.h}`}}measurePitch(){const baseEl=this.renderRoot.querySelector('[part="base"]');if(!baseEl)return null;const rect=baseEl.getBoundingClientRect(),columns=this.safeColumns,gap=this.safeGap,rawColPitch=(rect.width-gap*(columns-1))/columns;return{colPitch:rawColPitch>0?rawColPitch:1,rowPitch:this.safeRowHeight+gap}}resetCellInlineStyle(cellId,wrapper){wrapper.removeAttribute("data-collision");const cell=this.effectiveLayout.find(candidate=>candidate.cellId===cellId);if(cell){const style=this.cellStyle(cell);wrapper.style.gridColumn=style["grid-column"],wrapper.style.gridRow=style["grid-row"]}}canDragCell(cellId){const cell=this.layout.find(candidate=>candidate.cellId===cellId);return this.cellsDraggable&&!this.locked&&cell!==void 0&&!cell.locked}canResizeCell(cellId){const cell=this.layout.find(candidate=>candidate.cellId===cellId);return this.cellsResizable&&!this.locked&&cell!==void 0&&!cell.locked}releaseGesturePointerCapture(target,pointerId){try{target.releasePointerCapture?.(pointerId)}catch{}}cancelCellDrag(){const drag=this.cellDrag;drag&&(this.cellDrag=void 0,drag.previewFrame!==void 0&&drag.ownerWindow.cancelAnimationFrame(drag.previewFrame),this.releaseGesturePointerCapture(drag.wrapper,drag.pointerId),drag.wrapper.removeAttribute("data-dragging"),this.resetCellInlineStyle(drag.cellId,drag.wrapper),drag.ownerWindow.removeEventListener("pointermove",this.onCellPointerMove),drag.ownerWindow.removeEventListener("pointerup",this.onCellPointerUp),drag.ownerWindow.removeEventListener("pointercancel",this.onCellPointerUp),drag.ownerWindow.removeEventListener("lostpointercapture",this.onCellPointerUp))}cancelCellResize(){const resize=this.cellResize;resize&&(this.cellResize=void 0,resize.previewFrame!==void 0&&resize.ownerWindow.cancelAnimationFrame(resize.previewFrame),this.releaseGesturePointerCapture(resize.captureTarget,resize.pointerId),resize.wrapper.removeAttribute("data-resizing"),this.resetCellInlineStyle(resize.cellId,resize.wrapper),resize.ownerWindow.removeEventListener("pointermove",this.onResizeHandlePointerMove),resize.ownerWindow.removeEventListener("pointerup",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("pointercancel",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("lostpointercapture",this.onResizeHandlePointerUp))}hasInteractiveTarget(e,wrapper){const path=e.composedPath(),stop=path.indexOf(wrapper);for(const node of stop<0?path:path.slice(0,stop)){const element=node;if(typeof element.matches=="function"&&node!==wrapper&&element.matches(INTERACTIVE_DESCENDANT_SELECTOR))return!0}return!1}onCellPointerDown(e,cell){if(!this.cellsDraggable||this.locked||cell.locked||this.cellDrag||!e.isPrimary||e.button!==0)return;const wrapper=e.currentTarget;if(this.hasInteractiveTarget(e,wrapper))return;const ownerWindow=wrapper.ownerDocument.defaultView;if(!ownerWindow)return;const pitch=this.measurePitch();if(!pitch)return;const layout=this.effectiveLayout;e.stopPropagation(),this.cellDrag={pointerId:e.pointerId,cellId:cell.cellId,startClientX:e.clientX,startClientY:e.clientY,startX:cell.x,startY:cell.y,w:cell.w,h:cell.h,...pitch,wrapper,ownerWindow,rtlFlip:isRtl(this)?-1:1,layout,spatialIndex:createDashboardSpatialIndex(layout,this.safeColumns)},wrapper.setPointerCapture?.(e.pointerId),wrapper.setAttribute("data-dragging",""),ownerWindow.addEventListener("pointermove",this.onCellPointerMove),ownerWindow.addEventListener("pointerup",this.onCellPointerUp),ownerWindow.addEventListener("pointercancel",this.onCellPointerUp),ownerWindow.addEventListener("lostpointercapture",this.onCellPointerUp)}applyDragPreview(drag){if(drag.pendingClientX===void 0||drag.pendingClientY===void 0)return;const clientX=drag.pendingClientX,clientY=drag.pendingClientY;drag.pendingClientX=void 0,drag.pendingClientY=void 0;const dxUnits=Math.round((clientX-drag.startClientX)*drag.rtlFlip/drag.colPitch),dyUnits=Math.round((clientY-drag.startClientY)/drag.rowPitch),{x,y}=clampDashboardCandidate({},{x:drag.startX+dxUnits,y:drag.startY+dyUnits,w:drag.w,h:drag.h},drag.spatialIndex.columns);if(drag.wrapper.style.gridColumn=`${x+1} / span ${drag.w}`,drag.wrapper.style.gridRow=`${y+1} / span ${drag.h}`,this.collision!=="overlap"){const collides=findDashboardCollisions(drag.spatialIndex,{cellId:drag.cellId,x,y,w:drag.w,h:drag.h}).length>0;drag.wrapper.toggleAttribute("data-collision",collides)}else drag.wrapper.removeAttribute("data-collision");drag.currentX=x,drag.currentY=y,(x!==drag.startX||y!==drag.startY)&&(drag.moved=!0)}flushDragPreview(drag){drag.previewFrame!==void 0&&(drag.ownerWindow.cancelAnimationFrame(drag.previewFrame),drag.previewFrame=void 0),this.applyDragPreview(drag)}onResizeHandlePointerDown(e,cell){if(!this.cellsResizable||this.locked||cell.locked||this.cellResize||!e.isPrimary||e.button!==0)return;const wrapper=e.currentTarget.closest('[part="cell"]');if(!wrapper)return;const ownerWindow=wrapper.ownerDocument.defaultView;if(!ownerWindow)return;const pitch=this.measurePitch();if(!pitch)return;const layout=this.effectiveLayout;e.stopPropagation();const captureTarget=e.currentTarget;this.cellResize={pointerId:e.pointerId,cellId:cell.cellId,startClientX:e.clientX,startClientY:e.clientY,startW:cell.w,startH:cell.h,x:cell.x,y:cell.y,...pitch,wrapper,captureTarget,ownerWindow,rtlFlip:isRtl(this)?-1:1,layout,spatialIndex:createDashboardSpatialIndex(layout,this.safeColumns)},captureTarget.setPointerCapture?.(e.pointerId),wrapper.setAttribute("data-resizing",""),ownerWindow.addEventListener("pointermove",this.onResizeHandlePointerMove),ownerWindow.addEventListener("pointerup",this.onResizeHandlePointerUp),ownerWindow.addEventListener("pointercancel",this.onResizeHandlePointerUp),ownerWindow.addEventListener("lostpointercapture",this.onResizeHandlePointerUp)}applyResizePreview(resize){if(resize.pendingClientX===void 0||resize.pendingClientY===void 0)return;const clientX=resize.pendingClientX,clientY=resize.pendingClientY;resize.pendingClientX=void 0,resize.pendingClientY=void 0;const dwUnits=Math.round((clientX-resize.startClientX)*resize.rtlFlip/resize.colPitch),dhUnits=Math.round((clientY-resize.startClientY)/resize.rowPitch),{w,h}=clampDashboardCandidate(resize.spatialIndex.byId.get(resize.cellId)??{},{x:resize.x,y:resize.y,w:resize.startW+dwUnits,h:resize.startH+dhUnits},resize.spatialIndex.columns);if(resize.wrapper.style.gridColumn=`${resize.x+1} / span ${w}`,resize.wrapper.style.gridRow=`${resize.y+1} / span ${h}`,this.collision!=="overlap"){const collides=findDashboardCollisions(resize.spatialIndex,{cellId:resize.cellId,x:resize.x,y:resize.y,w,h}).length>0;resize.wrapper.toggleAttribute("data-collision",collides)}else resize.wrapper.removeAttribute("data-collision");resize.currentW=w,resize.currentH=h,(w!==resize.startW||h!==resize.startH)&&(resize.moved=!0)}flushResizePreview(resize){resize.previewFrame!==void 0&&(resize.ownerWindow.cancelAnimationFrame(resize.previewFrame),resize.previewFrame=void 0),this.applyResizePreview(resize)}clearSuppressedClick(){this.suppressedClickTimer!==void 0&&this.suppressedClickWindow&&this.suppressedClickWindow.clearTimeout(this.suppressedClickTimer),this.suppressedClickTimer=void 0,this.suppressedClickWindow=void 0,this.suppressedClickCellId=""}armClickSuppression(cellId,ownerWindow){this.clearSuppressedClick(),this.suppressedClickCellId=cellId,this.suppressedClickWindow=ownerWindow,this.suppressedClickTimer=ownerWindow.setTimeout(()=>{this.suppressedClickTimer=void 0,this.suppressedClickWindow=void 0,this.suppressedClickCellId=""},0)}onCellClick(e,cellId){this.suppressedClickCellId===cellId&&(this.clearSuppressedClick(),e.preventDefault(),e.stopImmediatePropagation())}renderCell(cell,active){const resizableHere=this.cellsResizable&&!this.locked&&!cell.locked;return html`<div
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,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{tag}from"../../../internal/prefix.js";import{isAccessibilityVisible,srOnly}from"../../../internal/a11y.js";import{Announcer,acquireAnnouncementSink}from"../../../internal/announcer.js";import{isRtl}from"../../../internal/rtl.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{isArrowKey,finiteInteger,finiteRange}from"../../../internal/numbers.js";import{styles}from"./dashboard-grid.styles.js";import"./layout.js";import{clampDashboardCandidate,createDashboardSpatialIndex,findDashboardCollisions,normalizeLyraDashboardCollisionPolicy,projectDashboardLayout,resolveDashboardPlacement,snapshotDashboardLayout,sortDashboardSpatial}from"./layout-internal.js";import{createWidgetDocument}from"../../conversation/widget-renderer/resolve.js";import{activeElementIn}from"../../../internal/active-element.js";import{LYRA_DEFAULT_dashboardCellCollisionRejected,LYRA_DEFAULT_dashboardCellMoved,LYRA_DEFAULT_dashboardCellResized,LYRA_DEFAULT_dashboardGridLabel,LYRA_DEFAULT_flowItemAnnouncement,LYRA_DEFAULT_noData}from"../../../internal/default-strings.generated.js";const INTERACTIVE_DESCENDANT_SELECTOR='button, a[href], area[href], input, select, textarea, summary, label, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [role="checkbox"], [role="radio"], [role="switch"], [role="slider"], [role="spinbutton"], [role="textbox"], [role="combobox"], [role="option"], [role="menuitem"], [tabindex]:not([part="cell"])';class LyraDashboardGrid extends LyraElement{constructor(){super(...arguments),this.authoredLayout=Object.freeze([]),this.effectiveLayout=Object.freeze([]),this.columns=12,this.rowHeight=80,this.gap=8,this.collisionValue="reject",this.cellsDraggable=!1,this.cellsResizable=!1,this.locked=!1,this.accessibleLabel=null,this.announcer=new Announcer({onFlush:text=>{this.liveText=text,isAccessibilityVisible(this)&&this.announcementSink?.announce(text)}}),this.liveText="",this.activeCellIndex=0,this.activeCellId="",this.rehomeCellFocus=!1,this.defaultCellSyncQueued=!1,this.ownedDefaultCells=new WeakSet,this.warnedUnmatchedCells=new WeakSet,this.authoredSlotBaselines=new WeakMap,this.managedAuthoredCells=new Set,this.suppressedClickCellId="",this.onCellPointerMove=e=>{const drag=this.cellDrag;if(!(!drag||e.pointerId!==drag.pointerId)){if(!this.canDragCell(drag.cellId)){this.cancelCellDrag();return}drag.pendingClientX=e.clientX,drag.pendingClientY=e.clientY,drag.previewFrame===void 0&&(drag.previewFrame=drag.ownerWindow.requestAnimationFrame(()=>{drag.previewFrame=void 0,this.cellDrag===drag&&this.applyDragPreview(drag)}))}},this.onCellPointerUp=e=>{const drag=this.cellDrag;if(!drag||e.pointerId!==drag.pointerId)return;if(e.type!=="pointerup"||!this.canDragCell(drag.cellId)){this.cancelCellDrag();return}this.flushDragPreview(drag),this.cellDrag=void 0,this.releaseGesturePointerCapture(drag.wrapper,drag.pointerId),drag.wrapper.removeAttribute("data-dragging"),drag.ownerWindow.removeEventListener("pointermove",this.onCellPointerMove),drag.ownerWindow.removeEventListener("pointerup",this.onCellPointerUp),drag.ownerWindow.removeEventListener("pointercancel",this.onCellPointerUp),drag.ownerWindow.removeEventListener("lostpointercapture",this.onCellPointerUp);const x=drag.currentX??drag.startX,y=drag.currentY??drag.startY;(x!==drag.startX||y!==drag.startY)&&this.commitPlacement(drag.cellId,{x,y,w:drag.w,h:drag.h},"move"),drag.moved&&this.armClickSuppression(drag.cellId,drag.ownerWindow),this.resetCellInlineStyle(drag.cellId,drag.wrapper),this.requestUpdate()},this.onResizeHandlePointerMove=e=>{const resize=this.cellResize;if(!(!resize||e.pointerId!==resize.pointerId)){if(!this.canResizeCell(resize.cellId)){this.cancelCellResize();return}resize.pendingClientX=e.clientX,resize.pendingClientY=e.clientY,resize.previewFrame===void 0&&(resize.previewFrame=resize.ownerWindow.requestAnimationFrame(()=>{resize.previewFrame=void 0,this.cellResize===resize&&this.applyResizePreview(resize)}))}},this.onResizeHandlePointerUp=e=>{const resize=this.cellResize;if(!resize||e.pointerId!==resize.pointerId)return;if(e.type!=="pointerup"||!this.canResizeCell(resize.cellId)){this.cancelCellResize();return}this.flushResizePreview(resize),this.cellResize=void 0,this.releaseGesturePointerCapture(resize.captureTarget,resize.pointerId),resize.wrapper.removeAttribute("data-resizing"),resize.ownerWindow.removeEventListener("pointermove",this.onResizeHandlePointerMove),resize.ownerWindow.removeEventListener("pointerup",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("pointercancel",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("lostpointercapture",this.onResizeHandlePointerUp);const w=resize.currentW??resize.startW,h=resize.currentH??resize.startH;(w!==resize.startW||h!==resize.startH)&&this.commitPlacement(resize.cellId,{x:resize.x,y:resize.y,w,h},"resize"),resize.moved&&this.armClickSuppression(resize.cellId,resize.ownerWindow),this.resetCellInlineStyle(resize.cellId,resize.wrapper),this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,dashboardCellCollisionRejected:LYRA_DEFAULT_dashboardCellCollisionRejected,dashboardCellMoved:LYRA_DEFAULT_dashboardCellMoved,dashboardCellResized:LYRA_DEFAULT_dashboardCellResized,dashboardGridLabel:LYRA_DEFAULT_dashboardGridLabel,flowItemAnnouncement:LYRA_DEFAULT_flowItemAnnouncement,noData:LYRA_DEFAULT_noData}}static{this.immutableEventDetails=Object.freeze(["lr-collision","lr-layout-change"])}static{this.styles=[LyraElement.styles,styles,srOnly]}get layout(){return this.effectiveLayout}set layout(value){const previous=this.effectiveLayout;this.authoredLayout=snapshotDashboardLayout(value),this.effectiveLayout=projectDashboardLayout(this.authoredLayout,this.safeColumns),this.announceAppliedPlacement(),this.requestUpdate("layout",previous)}get collision(){return this.collisionValue}set collision(value){const previous=this.collisionValue;this.collisionValue=normalizeLyraDashboardCollisionPolicy(value),this.requestUpdate("collision",previous)}get safeColumns(){return finiteInteger(this.columns,12,1,48)}get safeRowHeight(){return finiteRange(this.rowHeight,80,1)}get safeGap(){return finiteRange(this.gap,8,0)}get sortedLayout(){return sortDashboardSpatial(this.effectiveLayout)}connectedCallback(){super.connectedCallback(),this.bindOwnerRealmResources(),this.scheduleDefaultCellSync()}disconnectedCallback(){this.announcer.cancel(),this.announcementSink?.release(),this.announcementSink=void 0,this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0,this.defaultCellSyncQueued=!1,this.restoreManagedAuthoredSlots(),this.clearSuppressedClick(),this.pendingPlacementAnnouncement=void 0,this.cancelCellDrag(),this.cancelCellResize(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0,this.announcementSink?.release(),this.announcementSink=void 0,this.clearSuppressedClick(),this.isConnected&&(this.bindOwnerRealmResources(),this.scheduleDefaultCellSync())}bindOwnerRealmResources(){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(ownerWindow&&this.announcer.setTimerHost(ownerWindow),this.announcementSink??=acquireAnnouncementSink("polite",{document:ownerDocument,source:this}),this.childObserver&&this.childObserverDocument===ownerDocument)return;this.childObserver?.disconnect(),this.childObserver=void 0,this.childObserverDocument=void 0;const MutationObserverCtor=ownerWindow?.MutationObserver;if(!MutationObserverCtor)return;const observer=new MutationObserverCtor(records=>{this.childObserver!==observer||this.childObserverDocument!==ownerDocument||!records.some(record=>record.type==="childList"?record.target===this:record.target.parentNode===this)||this.scheduleDefaultCellSync()});observer.observe(this,{childList:!0,attributes:!0,attributeFilter:["cell-id"],subtree:!0}),this.childObserver=observer,this.childObserverDocument=ownerDocument}scheduleDefaultCellSync(){!this.isConnected||this.defaultCellSyncQueued||(this.defaultCellSyncQueued=!0,queueMicrotask(()=>{this.defaultCellSyncQueued=!1,this.isConnected&&this.syncDefaultCells()}))}willUpdate(changed){if(super.willUpdate(changed),changed.has("columns")&&(this.effectiveLayout=projectDashboardLayout(this.authoredLayout,this.safeColumns)),changed.has("layout")||changed.has("columns")){this.rehomeCellFocus=activeElementIn(this.renderRoot)?.getAttribute("part")==="cell",this.ownerDocument&&this.isConnected&&(this.hasUpdated?this.syncDefaultCells():this.seedFirstRenderState(()=>this.syncDefaultCells()));const cells=this.sortedLayout,retainedIndex=cells.findIndex(cell=>cell.cellId===this.activeCellId),nextIndex=cells.length===0?0:retainedIndex>=0?retainedIndex:Math.min(this.activeCellIndex,cells.length-1);this.activeCellIndex=nextIndex,this.activeCellId=cells[nextIndex]?.cellId??""}this.cellDrag&&(changed.has("layout")||changed.has("columns")||changed.has("rowHeight")||changed.has("gap")||(changed.has("cellsDraggable")||changed.has("locked"))&&!this.canDragCell(this.cellDrag.cellId))&&this.cancelCellDrag(),this.cellResize&&(changed.has("layout")||changed.has("columns")||changed.has("rowHeight")||changed.has("gap")||(changed.has("cellsResizable")||changed.has("locked"))&&!this.canResizeCell(this.cellResize.cellId))&&this.cancelCellResize()}updated(changed){super.updated(changed),this.rehomeCellFocus&&(this.rehomeCellFocus=!1,this.renderRoot.querySelector('[part="cell"][tabindex="0"]')?.focus())}cellLabel(cell){return cell.label||cell.cellId}restoreAuthoredSlot(child){if(!this.authoredSlotBaselines.has(child))return;const baseline=this.authoredSlotBaselines.get(child);baseline===null?child.removeAttribute("slot"):baseline!==void 0&&child.setAttribute("slot",baseline),this.authoredSlotBaselines.delete(child),this.managedAuthoredCells.delete(child)}restoreManagedAuthoredSlots(){for(const child of this.managedAuthoredCells)this.restoreAuthoredSlot(child);this.managedAuthoredCells.clear()}syncDefaultCells(){if(!this.isConnected)return;const ids=new Set(this.effectiveLayout.map(cell=>cell.cellId)),authoredById=new Map,ownedById=new Map;for(const child of Array.from(this.children)){if(this.ownedDefaultCells.has(child)){const ownedCellId=child.getAttribute("data-cell-id");if(!ownedCellId){child.remove();continue}const matches=ownedById.get(ownedCellId)??[];matches.push(child),ownedById.set(ownedCellId,matches);continue}const cellId=child.getAttribute("cell-id");cellId&&ids.has(cellId)&&!authoredById.has(cellId)?(authoredById.set(cellId,child),this.warnedUnmatchedCells.delete(child),this.authoredSlotBaselines.has(child)||this.authoredSlotBaselines.set(child,child.getAttribute("slot")),this.managedAuthoredCells.add(child),child.setAttribute("slot",`cell-${cellId}`)):(this.restoreAuthoredSlot(child),cellId&&!ids.has(cellId)&&!this.warnedUnmatchedCells.has(child)&&(this.warnedUnmatchedCells.add(child),console.warn(`<lr-dashboard-grid> a child with cell-id="${cellId}" matches no entry in \`layout\`; it will not render.`)))}const selectedAuthored=new Set(authoredById.values());for(const managed of[...this.managedAuthoredCells])(!this.contains(managed)||!selectedAuthored.has(managed))&&this.restoreAuthoredSlot(managed);for(const cell of this.effectiveLayout){const owned=ownedById.get(cell.cellId)??[];if(authoredById.has(cell.cellId)){for(const defaultCell of owned)defaultCell.remove();continue}const existing=owned.shift();existing?(existing.setAttribute("slot",`cell-${cell.cellId}`),this.updateDefaultCell(existing,cell)):this.appendChild(this.createDefaultCell(cell));for(const duplicate of owned)duplicate.remove();ownedById.delete(cell.cellId)}for(const stale of ownedById.values())for(const defaultCell of stale)defaultCell.remove()}createDefaultCell(cell){const ownerDocument=this.ownerDocument,widget=ownerDocument.createElement(tag("widget"));widget.setAttribute("data-cell-id",cell.cellId),widget.setAttribute("data-dashboard-grid-default-cell",""),widget.setAttribute("slot",`cell-${cell.cellId}`),this.ownedDefaultCells.add(widget);const renderer=ownerDocument.createElement(tag("widget-renderer"));return widget.appendChild(renderer),this.updateDefaultCell(widget,cell),widget}updateDefaultCell(widget,cell){widget.label=this.cellLabel(cell);const renderer=widget.querySelector(tag("widget-renderer"));renderer&&(renderer.document=cell.widget==null?null:createWidgetDocument(cell.widget))}onCellFocus(cellId){const index=this.sortedLayout.findIndex(cell=>cell.cellId===cellId);index>=0&&(this.activeCellIndex!==index&&(this.activeCellIndex=index),this.activeCellId!==cellId&&(this.activeCellId=cellId))}cellElement(cellId){const ownerCss=this.ownerDocument.defaultView?.CSS;if(typeof ownerCss?.escape=="function")try{const candidate=this.renderRoot.querySelector(`[part="cell"][data-cell-id="${ownerCss.escape(cellId)}"]`);if(candidate?.getAttribute("data-cell-id")===cellId)return candidate}catch{}return Array.from(this.renderRoot.querySelectorAll('[part="cell"][data-cell-id]')).find(candidate=>candidate.getAttribute("data-cell-id")===cellId)??null}focusCellAt(index){const cells=this.sortedLayout;if(index<0||index>=cells.length)return;this.activeCellIndex=index;const cell=cells[index];this.activeCellId=cell.cellId;const number=getNumberFormat(this.effectiveLocale);this.announcer.announce(this.localize("flowItemAnnouncement",void 0,{item:this.cellLabel(cell),index:number.format(index+1),total:number.format(cells.length)})),this.updateComplete.then(()=>{this.cellElement(cell.cellId)?.focus()})}onCellKeyDown(e,cell){const owner=e.currentTarget;if(e.composedPath()[0]!==owner)return;if((e.ctrlKey||e.metaKey)&&isArrowKey(e.key)){(e.shiftKey?this.keyboardResize(cell,e.key):this.keyboardMove(cell,e.key))&&e.preventDefault();return}const cells=this.sortedLayout,index=cells.findIndex(c=>c.cellId===cell.cellId);if(index<0)return;const rtl=isRtl(this),forwardKey=rtl?"ArrowLeft":"ArrowRight",backwardKey=rtl?"ArrowRight":"ArrowLeft";let next=index;if(e.key===forwardKey||e.key==="ArrowDown")next=Math.min(cells.length-1,index+1);else if(e.key===backwardKey||e.key==="ArrowUp")next=Math.max(0,index-1);else if(e.key==="Home")next=0;else if(e.key==="End")next=cells.length-1;else return;next!==index&&(e.preventDefault(),this.focusCellAt(next))}keyboardMove(cell,key){if(!this.cellsDraggable||this.locked||cell.locked)return!1;const rtlFlip=isRtl(this)?-1:1;let dx=0,dy=0;if(key==="ArrowRight")dx=rtlFlip;else if(key==="ArrowLeft")dx=-rtlFlip;else if(key==="ArrowDown")dy=1;else if(key==="ArrowUp")dy=-1;else return!1;return this.commitPlacement(cell.cellId,{x:cell.x+dx,y:cell.y+dy,w:cell.w,h:cell.h},"move")}keyboardResize(cell,key){if(!this.cellsResizable||this.locked||cell.locked)return!1;let dw=0,dh=0;if(key==="ArrowRight")dw=1;else if(key==="ArrowLeft")dw=-1;else if(key==="ArrowDown")dh=1;else if(key==="ArrowUp")dh=-1;else return!1;return this.commitPlacement(cell.cellId,{x:cell.x,y:cell.y,w:cell.w+dw,h:cell.h+dh},"resize")}announceAppliedPlacement(){const pending=this.pendingPlacementAnnouncement;if(!pending)return;this.pendingPlacementAnnouncement=void 0;const cell=this.effectiveLayout.find(candidate=>candidate.cellId===pending.cellId);if(!cell||!(pending.kind==="move"?cell.x===pending.x&&cell.y===pending.y:cell.w===pending.w&&cell.h===pending.h))return;const number=getNumberFormat(this.effectiveLocale);if(pending.kind==="move"){this.announcer.announce(this.localize("dashboardCellMoved",void 0,{label:this.cellLabel(cell),x:number.format(cell.x+1),y:number.format(cell.y+1)}));return}this.announcer.announce(this.localize("dashboardCellResized",void 0,{label:this.cellLabel(cell),w:number.format(cell.w),h:number.format(cell.h)}))}commitPlacement(cellId,requested,kind){const layout=this.effectiveLayout,cell=layout.find(candidate=>candidate.cellId===cellId);if(!cell)return!1;const result=resolveDashboardPlacement(layout,cellId,requested,this.safeColumns,this.collision);if(result.collidedCellIds.length>0&&this.emit("lr-collision",Object.freeze({cellId,collidedCellIds:result.collidedCellIds,policy:this.collision,accepted:result.accepted})),!result.accepted)return this.announcer.announce(this.localize("dashboardCellCollisionRejected",void 0,{label:this.cellLabel(cell)})),!0;const updated=result.layout.find(candidate=>candidate.cellId===cellId);return(kind==="move"?updated.x===cell.x&&updated.y===cell.y:updated.w===cell.w&&updated.h===cell.h)?!1:(this.pendingPlacementAnnouncement={cellId,kind,x:updated.x,y:updated.y,w:updated.w,h:updated.h},kind==="move"?this.emit("lr-cell-move",Object.freeze({cellId,position:Object.freeze({x:updated.x,y:updated.y}),previous:Object.freeze({x:cell.x,y:cell.y})})):this.emit("lr-cell-resize",Object.freeze({cellId,size:Object.freeze({w:updated.w,h:updated.h}),previous:Object.freeze({w:cell.w,h:cell.h})})),this.emit("lr-layout-change",Object.freeze({layout:result.layout})),!0)}cellStyle(cell){return{"grid-column":`${cell.x+1} / span ${cell.w}`,"grid-row":`${cell.y+1} / span ${cell.h}`}}measurePitch(){const baseEl=this.renderRoot.querySelector('[part="base"]');if(!baseEl)return null;const rect=baseEl.getBoundingClientRect(),columns=this.safeColumns,gap=this.safeGap,rawColPitch=(rect.width-gap*(columns-1))/columns;return{colPitch:rawColPitch>0?rawColPitch:1,rowPitch:this.safeRowHeight+gap}}resetCellInlineStyle(cellId,wrapper){wrapper.removeAttribute("data-collision");const cell=this.effectiveLayout.find(candidate=>candidate.cellId===cellId);if(cell){const style=this.cellStyle(cell);wrapper.style.gridColumn=style["grid-column"],wrapper.style.gridRow=style["grid-row"]}}canDragCell(cellId){const cell=this.layout.find(candidate=>candidate.cellId===cellId);return this.cellsDraggable&&!this.locked&&cell!==void 0&&!cell.locked}canResizeCell(cellId){const cell=this.layout.find(candidate=>candidate.cellId===cellId);return this.cellsResizable&&!this.locked&&cell!==void 0&&!cell.locked}releaseGesturePointerCapture(target,pointerId){try{target.releasePointerCapture?.(pointerId)}catch{}}cancelCellDrag(){const drag=this.cellDrag;drag&&(this.cellDrag=void 0,drag.previewFrame!==void 0&&drag.ownerWindow.cancelAnimationFrame(drag.previewFrame),this.releaseGesturePointerCapture(drag.wrapper,drag.pointerId),drag.wrapper.removeAttribute("data-dragging"),this.resetCellInlineStyle(drag.cellId,drag.wrapper),drag.ownerWindow.removeEventListener("pointermove",this.onCellPointerMove),drag.ownerWindow.removeEventListener("pointerup",this.onCellPointerUp),drag.ownerWindow.removeEventListener("pointercancel",this.onCellPointerUp),drag.ownerWindow.removeEventListener("lostpointercapture",this.onCellPointerUp))}cancelCellResize(){const resize=this.cellResize;resize&&(this.cellResize=void 0,resize.previewFrame!==void 0&&resize.ownerWindow.cancelAnimationFrame(resize.previewFrame),this.releaseGesturePointerCapture(resize.captureTarget,resize.pointerId),resize.wrapper.removeAttribute("data-resizing"),this.resetCellInlineStyle(resize.cellId,resize.wrapper),resize.ownerWindow.removeEventListener("pointermove",this.onResizeHandlePointerMove),resize.ownerWindow.removeEventListener("pointerup",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("pointercancel",this.onResizeHandlePointerUp),resize.ownerWindow.removeEventListener("lostpointercapture",this.onResizeHandlePointerUp))}hasInteractiveTarget(e,wrapper){const path=e.composedPath(),stop=path.indexOf(wrapper);for(const node of stop<0?path:path.slice(0,stop)){const element=node;if(typeof element.matches=="function"&&node!==wrapper&&element.matches(INTERACTIVE_DESCENDANT_SELECTOR))return!0}return!1}onCellPointerDown(e,cell){if(!this.cellsDraggable||this.locked||cell.locked||this.cellDrag||!e.isPrimary||e.button!==0)return;const wrapper=e.currentTarget;if(this.hasInteractiveTarget(e,wrapper))return;const ownerWindow=wrapper.ownerDocument.defaultView;if(!ownerWindow)return;const pitch=this.measurePitch();if(!pitch)return;const layout=this.effectiveLayout;e.stopPropagation(),this.cellDrag={pointerId:e.pointerId,cellId:cell.cellId,startClientX:e.clientX,startClientY:e.clientY,startX:cell.x,startY:cell.y,w:cell.w,h:cell.h,...pitch,wrapper,ownerWindow,rtlFlip:isRtl(this)?-1:1,layout,spatialIndex:createDashboardSpatialIndex(layout,this.safeColumns)},wrapper.setPointerCapture?.(e.pointerId),wrapper.setAttribute("data-dragging",""),ownerWindow.addEventListener("pointermove",this.onCellPointerMove),ownerWindow.addEventListener("pointerup",this.onCellPointerUp),ownerWindow.addEventListener("pointercancel",this.onCellPointerUp),ownerWindow.addEventListener("lostpointercapture",this.onCellPointerUp)}applyDragPreview(drag){if(drag.pendingClientX===void 0||drag.pendingClientY===void 0)return;const clientX=drag.pendingClientX,clientY=drag.pendingClientY;drag.pendingClientX=void 0,drag.pendingClientY=void 0;const dxUnits=Math.round((clientX-drag.startClientX)*drag.rtlFlip/drag.colPitch),dyUnits=Math.round((clientY-drag.startClientY)/drag.rowPitch),{x,y}=clampDashboardCandidate({},{x:drag.startX+dxUnits,y:drag.startY+dyUnits,w:drag.w,h:drag.h},drag.spatialIndex.columns);if(drag.wrapper.style.gridColumn=`${x+1} / span ${drag.w}`,drag.wrapper.style.gridRow=`${y+1} / span ${drag.h}`,this.collision!=="overlap"){const collides=findDashboardCollisions(drag.spatialIndex,{cellId:drag.cellId,x,y,w:drag.w,h:drag.h}).length>0;drag.wrapper.toggleAttribute("data-collision",collides)}else drag.wrapper.removeAttribute("data-collision");drag.currentX=x,drag.currentY=y,(x!==drag.startX||y!==drag.startY)&&(drag.moved=!0)}flushDragPreview(drag){drag.previewFrame!==void 0&&(drag.ownerWindow.cancelAnimationFrame(drag.previewFrame),drag.previewFrame=void 0),this.applyDragPreview(drag)}onResizeHandlePointerDown(e,cell){if(!this.cellsResizable||this.locked||cell.locked||this.cellResize||!e.isPrimary||e.button!==0)return;const wrapper=e.currentTarget.closest('[part="cell"]');if(!wrapper)return;const ownerWindow=wrapper.ownerDocument.defaultView;if(!ownerWindow)return;const pitch=this.measurePitch();if(!pitch)return;const layout=this.effectiveLayout;e.stopPropagation();const captureTarget=e.currentTarget;this.cellResize={pointerId:e.pointerId,cellId:cell.cellId,startClientX:e.clientX,startClientY:e.clientY,startW:cell.w,startH:cell.h,x:cell.x,y:cell.y,...pitch,wrapper,captureTarget,ownerWindow,rtlFlip:isRtl(this)?-1:1,layout,spatialIndex:createDashboardSpatialIndex(layout,this.safeColumns)},captureTarget.setPointerCapture?.(e.pointerId),wrapper.setAttribute("data-resizing",""),ownerWindow.addEventListener("pointermove",this.onResizeHandlePointerMove),ownerWindow.addEventListener("pointerup",this.onResizeHandlePointerUp),ownerWindow.addEventListener("pointercancel",this.onResizeHandlePointerUp),ownerWindow.addEventListener("lostpointercapture",this.onResizeHandlePointerUp)}applyResizePreview(resize){if(resize.pendingClientX===void 0||resize.pendingClientY===void 0)return;const clientX=resize.pendingClientX,clientY=resize.pendingClientY;resize.pendingClientX=void 0,resize.pendingClientY=void 0;const dwUnits=Math.round((clientX-resize.startClientX)*resize.rtlFlip/resize.colPitch),dhUnits=Math.round((clientY-resize.startClientY)/resize.rowPitch),{w,h}=clampDashboardCandidate(resize.spatialIndex.byId.get(resize.cellId)??{},{x:resize.x,y:resize.y,w:resize.startW+dwUnits,h:resize.startH+dhUnits},resize.spatialIndex.columns);if(resize.wrapper.style.gridColumn=`${resize.x+1} / span ${w}`,resize.wrapper.style.gridRow=`${resize.y+1} / span ${h}`,this.collision!=="overlap"){const collides=findDashboardCollisions(resize.spatialIndex,{cellId:resize.cellId,x:resize.x,y:resize.y,w,h}).length>0;resize.wrapper.toggleAttribute("data-collision",collides)}else resize.wrapper.removeAttribute("data-collision");resize.currentW=w,resize.currentH=h,(w!==resize.startW||h!==resize.startH)&&(resize.moved=!0)}flushResizePreview(resize){resize.previewFrame!==void 0&&(resize.ownerWindow.cancelAnimationFrame(resize.previewFrame),resize.previewFrame=void 0),this.applyResizePreview(resize)}clearSuppressedClick(){this.suppressedClickTimer!==void 0&&this.suppressedClickWindow&&this.suppressedClickWindow.clearTimeout(this.suppressedClickTimer),this.suppressedClickTimer=void 0,this.suppressedClickWindow=void 0,this.suppressedClickCellId=""}armClickSuppression(cellId,ownerWindow){this.clearSuppressedClick(),this.suppressedClickCellId=cellId,this.suppressedClickWindow=ownerWindow,this.suppressedClickTimer=ownerWindow.setTimeout(()=>{this.suppressedClickTimer=void 0,this.suppressedClickWindow=void 0,this.suppressedClickCellId=""},0)}onCellClick(e,cellId){this.suppressedClickCellId===cellId&&(this.clearSuppressedClick(),e.preventDefault(),e.stopImmediatePropagation())}renderCell(cell,active){const resizableHere=this.cellsResizable&&!this.locked&&!cell.locked;return html`<div
|
|
2
2
|
part="cell"
|
|
3
3
|
role="group"
|
|
4
4
|
tabindex=${active?"0":"-1"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{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_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}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,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}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_collapse,LYRA_DEFAULT_date,LYRA_DEFAULT_details,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select}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,collapse:LYRA_DEFAULT_collapse,date:LYRA_DEFAULT_date,details:LYRA_DEFAULT_details,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}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}
|
|
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"
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isRtl}from"../../../internal/rtl.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{CollapseBreakpointController,OrientationBreakpointController}from"../../../internal/orientation-breakpoint.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{resolveCssLength}from"../../../internal/css-length.js";import{styles}from"./multi-split.styles.js";import{LYRA_DEFAULT_resizeDivider}from"../../../internal/default-strings.generated.js";const KEYBOARD_STEP=2;function isPersistedPanelLayout(value){if(typeof value!="object"||value===null)return!1;const candidate=value;return candidate.version!==1||!Array.isArray(candidate.panels)?!1:candidate.panels.every(panel=>{if(typeof panel!="object"||panel===null)return!1;const record=panel;return typeof record.panelId=="string"&&record.panelId!==""&&record.panelId.trim()===record.panelId&&typeof record.size=="number"&&Number.isFinite(record.size)&&record.size>=0})}const NO_MIN_PX=0,NO_MAX_PX=1e6,OWNED_PANEL_STYLE_PROPERTIES=["flex","order","position","inset-block","inset-inline-start","inset-inline-end","inline-size"];class LyraMultiSplit extends LyraElement{constructor(){super(...arguments),this.sizes=[],this.defaultSizes=[],this.min=10,this.orientation="horizontal",this.orientationBreakpointBasis="container",this.narrowOrientation="vertical",this.panelConstraints=[],this.collapse="none",this.railWidth="3.5rem",this.railBreakpoint=640,this.floatBreakpoint=400,this.collapseBreakpointBasis="container",this.open=!1,this.panelCount=0,this.sizesReconciledForMembership=!1,this._collapseState="wide",this._forced=!1,this.overlayActive=!1,this.justOpened=!1,this.drags=new Map,this.ownedPanels=[],this.panelOwnership=new Map,this.panelOwnershipObserverGeneration=0,this.constraintIssueKey="",this.initializedSizes=!1,this.measuredInlineSize=Number.POSITIVE_INFINITY,this._effectiveOrientation="horizontal",this.collapseObserverGeneration=0,this.orientationBreakpoints=new OrientationBreakpointController(this,()=>this.updateEffectiveOrientation(this.measuredInlineSize,!0)),this.collapseBreakpoints=new CollapseBreakpointController(this,()=>this.updateCollapseState(this.measuredInlineSize,!0)),this.onSlotChange=()=>{this.updateBrowserDerivedState(()=>this.syncPanelMembership())},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()},this.onPointerDown=(e,index)=>{if(e.button!==0||this.isDividerDisabled(index))return;const divider=e.currentTarget,ownerWindow=divider.ownerDocument.defaultView;ownerWindow&&(this.drags.size>0&&this.dragOwnerWindow!==ownerWindow||(this.drags.set(e.pointerId,{index,startPos:this.effectiveOrientation==="vertical"?e.clientY:e.clientX,base:this.baseEl,appliedDelta:0,acceptedResize:!1}),divider.setPointerCapture(e.pointerId),this.drags.size===1&&(this.dragOwnerWindow=ownerWindow,ownerWindow.addEventListener("pointermove",this.onPointerMove),ownerWindow.addEventListener("pointerup",this.onPointerUp),ownerWindow.addEventListener("pointercancel",this.onPointerUp),ownerWindow.addEventListener("lostpointercapture",this.onPointerUp))))},this.onPointerMove=e=>{const drag=this.drags.get(e.pointerId);if(!drag)return;if(this.isDividerDisabled(drag.index)){this.endDragGestures();return}const total=this.effectiveOrientation==="vertical"?drag.base.clientHeight:drag.base.clientWidth;if(!Number.isFinite(total)||total<=0){this.endDragGestures();return}let cumulativeDelta=((this.effectiveOrientation==="vertical"?e.clientY:e.clientX)-drag.startPos)/total*100;this.effectiveOrientation==="horizontal"&&isRtl(this)&&(cumulativeDelta=-cumulativeDelta);const incremental=cumulativeDelta-drag.appliedDelta,priorValue=this.sizes[drag.index];if(priorValue===void 0)return;const paired=this.clampPair(this.sizes,drag.index,incremental,total),pairedA=paired[drag.index],pairedB=paired[drag.index+1];if(pairedA===void 0||pairedB===void 0)return;const next=[...this.sizes];next[drag.index]=pairedA,next[drag.index+1]=pairedB,this.requestResize(next,!1)&&(drag.appliedDelta+=pairedA-priorValue,drag.acceptedResize=!0)},this.onPointerUp=e=>{const drag=this.drags.get(e.pointerId);drag&&(this.drags.delete(e.pointerId),e.type==="pointerup"&&drag.acceptedResize&&this.persist(),this.drags.size===0&&this.removeDragListeners())},this.onDividerKeyDown=(e,index)=>{if(this.isDividerDisabled(index))return;const rtl=this.effectiveOrientation==="horizontal"&&isRtl(this),forwardKey=this.effectiveOrientation==="vertical"?"ArrowDown":rtl?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveOrientation==="vertical"?"ArrowUp":rtl?"ArrowRight":"ArrowLeft";e.key===forwardKey?this.applyDelta(index,KEYBOARD_STEP,!0)&&e.preventDefault():e.key===backwardKey&&this.applyDelta(index,-KEYBOARD_STEP,!0)&&e.preventDefault()}}static{this.defaultStrings={...super.defaultStrings,resizeDivider:LYRA_DEFAULT_resizeDivider}}static{this.ownedCollectionProperties=Object.freeze(["sizes","defaultSizes","panelConstraints"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-resize-request","lr-resize"])}static{this.properties={collapseState:{reflect:!0,attribute:"collapse-state",noAccessor:!0}}}connectedCallback(){super.connectedCallback();const hostWidth=this.getBoundingClientRect().width;hostWidth>0&&(this.measuredInlineSize=hostWidth),this.seedFirstRenderState(()=>this.syncPanelMembership(!1)),this.hasUpdated&&this.syncPanelMembership(!1),this.initializedSizes&&this.ensureSizes(),this.responsiveObservationEnabled&&this.armCollapseObserver(),this.hasUpdated&&this.overlayActive&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFloatingOverlay(),queueMicrotask(()=>this.overlayHandle?.focusInitial()))}disconnectedCallback(){super.disconnectedCallback(),this.endDragGestures(),this.resetCollapseObserver(),this.overlayHandle?.suspend(),this.releaseOwnedPanels()}adoptedCallback(){super.adoptedCallback(),this.endDragGestures(),this.resetCollapseObserver(),this.releaseOwnedPanels()}firstUpdated(changed){super.firstUpdated(changed),this.responsiveObservationEnabled&&this.armCollapseObserver()}willUpdate(changed){if(super.willUpdate(changed),!this.ownerDocument&&this.panelCount===0&&(this.panelCount=Math.max(this.sizes.length,this.defaultSizes.length,this.panelConstraints.length)),!this.initializedSizes)this.initializeSizes(),this.initializedSizes=!0;else if(changed.has("sizes")){const previous=changed.get("sizes");this.sizesReconciledForMembership?this.sizesReconciledForMembership=!1:this.validLiveSizes(this.sizes)||(Array.isArray(previous)&&this.validLiveSizes(previous)?this.sizes=[...previous]:(this.sizes=[],this.ensureSizes()))}else this.sizes.length===0&&this.ensureSizes();if((changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.orientationBreakpoints.configure(this.orientationBreakpoint,this.orientationBreakpointBasis),(changed.has("orientation")||changed.has("narrowOrientation")||changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.updateEffectiveOrientation(this.measuredInlineSize,this.hasUpdated&&this.orientationBreakpointBasis==="viewport"),changed.has("collapse")||changed.has("railBreakpoint")||changed.has("floatBreakpoint")||changed.has("collapseBreakpointBasis")){const previousEffective=changed.has("collapse")?this.effectiveCollapseStateFor(changed.get("collapse")??"none"):this.collapseState;changed.has("collapse")&&previousEffective!=="wide"&&this.endDragGestures(),this.collapseBreakpoints.configure(this.railBreakpoint,this.floatBreakpoint,this.collapseBreakpointBasis),this.collapsingIndex!==-1&&!this._forced&&(this._collapseState=this.collapseBreakpoints.classify(this.measuredInlineSize)),this.applyEffectiveCollapseTransition(previousEffective,this.collapseState,this.hasUpdated)}if(changed.has("open")||changed.has("collapseState")||changed.has("collapse")||changed.has("panelCount")){const next=this.collapseState==="floating"&&this.open;next!==this.overlayActive&&(this.overlayActive=next,next?(this.justOpened=!0,this.activateFloatingOverlay()):this.deactivateFloatingOverlay())}}get collapseState(){return this.effectiveCollapseStateFor(this.collapse)}set collapseState(next){if(next==="auto"){this._forced=!1,this.updateCollapseState(this.currentMeasuredWidth());return}this._forced=!0,this.setRequestedCollapseState(next)}get effectiveOrientation(){return this._effectiveOrientation}get responsiveObservationEnabled(){return this.collapse!=="none"||this.orientationBreakpoints.containerObservationEnabled}updateEffectiveOrientation(width,shouldEmit){const next=this.orientationBreakpoints.isBelow(width)?this.narrowOrientation:this.orientation;next!==this._effectiveOrientation&&(this.endDragGestures(),this._effectiveOrientation=next,this.requestUpdate(),shouldEmit&&this.emit("lr-multi-split-orientation-change",{orientation:next}))}currentMeasuredWidth(){return this.baseEl?.clientWidth??0}effectiveCollapseStateFor(collapse){return collapse!=="none"&&this.panelCount>=2?this._collapseState:"wide"}applyEffectiveCollapseTransition(previous,next,shouldEmit=!0){previous!==next&&(this.endDragGestures(),this.requestUpdate("collapseState",previous),shouldEmit&&this.emit("lr-multi-split-collapse-change",{state:next}),next!=="floating"&&this.open&&(this.open=!1))}setRequestedCollapseState(next,shouldEmit=!0){const previousEffective=this.collapseState;if(next===this._collapseState)return;this._collapseState=next;const nextEffective=this.collapseState;this.applyEffectiveCollapseTransition(previousEffective,nextEffective,shouldEmit),previousEffective===nextEffective&&next!==nextEffective&&this.requestUpdate("collapseState",next)}get storageFullKey(){return this.storageKey?`lr-multi-split:${this.storageKey}:panels`:void 0}panelIdsFor(panels){const ids=[],seen=new Set;for(const panel of panels){const panelId=panel.getAttribute("panel-id")??"";if(!panelId||panelId.trim()!==panelId||seen.has(panelId))return null;seen.add(panelId),ids.push(panelId)}return ids}reconcileIdentitySizes(previousIds,previousValues,nextIds){if(previousIds.length!==previousValues.length||nextIds.length===0)return null;const previousSizes=new Map;previousIds.forEach((panelId,index)=>{previousSizes.set(panelId,previousValues[index])});const retainedTotal=nextIds.reduce((total,panelId)=>total+(previousSizes.get(panelId)??0),0),missingCount=nextIds.filter(panelId=>!previousSizes.has(panelId)).length;if(!(retainedTotal>0)){const equal=100/nextIds.length;return nextIds.map(()=>equal)}const newShare=100/nextIds.length,retainedScale=(100-newShare*missingCount)/retainedTotal;return nextIds.map(panelId=>{const previous=previousSizes.get(panelId);return previous===void 0?newShare:previous*retainedScale})}reconcileSizesByPanelId(previousPanels,nextPanels){if(previousPanels.length!==this.sizes.length||nextPanels.length===0)return null;const previousIds=this.panelIdsFor(previousPanels),nextIds=this.panelIdsFor(nextPanels);return!previousIds||!nextIds?null:this.reconcileIdentitySizes(previousIds,this.sizes,nextIds)}validInitialSizes(value){return!Array.isArray(value)||value.length!==this.panelCount||!value.every(size=>Number.isFinite(size)&&size>=this.safeMin)?!1:Math.abs(value.reduce((sum,size)=>sum+size,0)-100)<.01}validLiveSizes(value){if(!Array.isArray(value)||value.length!==this.panelCount)return!1;const floor=this.normalizedDefaultMin();return value.every(size=>Number.isFinite(size)&&size>=floor)?Math.abs(value.reduce((sum,size)=>sum+size,0)-100)<.01:!1}resolveDefaultSizes(){if(this.defaultSizes.length===0)return null;if(!this.defaultSizes.some(entry=>typeof entry=="string")){const numbers=this.defaultSizes;return this.validInitialSizes(numbers)?[...numbers]:null}const containerSize=this.currentMeasuredWidth()||this.getBoundingClientRect().width;if(!(containerSize>0))return null;const resolvedPx=[];for(const entry of this.defaultSizes){if(typeof entry=="number"){if(!Number.isFinite(entry))return null;resolvedPx.push(entry/100*containerSize);continue}const px=resolveCssLength(entry,{host:this,percentBase:containerSize,viewportBasis:this.ownerDocument.defaultView??void 0});if(px==null||!(px>=0))return null;resolvedPx.push(px)}const sum=resolvedPx.reduce((total,size)=>total+size,0);if(!(sum>0))return null;const normalized=resolvedPx.map(size=>size/sum*100);return this.validInitialSizes(normalized)?normalized:null}initializeSizes(){if(this.loadPersisted()||this.validInitialSizes(this.sizes))return;const resolved=this.resolveDefaultSizes();if(resolved){this.sizes=resolved;return}this.sizes=[],this.ensureSizes()}loadPersisted(){const panelIds=this.panelIdsFor(this.ownedPanels);if(!panelIds)return!1;const parsed=readPersistedState(this.storageFullKey,isPersistedPanelLayout);if(!parsed||parsed.panels.length===0)return!1;const persistedIds=[],persistedSizes=[],seen=new Set;for(const panel of parsed.panels){if(seen.has(panel.panelId))return!1;seen.add(panel.panelId),persistedIds.push(panel.panelId),persistedSizes.push(panel.size)}if(Math.abs(persistedSizes.reduce((sum,size)=>sum+size,0)-100)>=.01)return!1;const normalized=this.reconcileIdentitySizes(persistedIds,persistedSizes,panelIds);return normalized&&this.validInitialSizes(normalized)?(this.sizes=normalized,!0):!1}persist(){const panelIds=this.panelIdsFor(this.ownedPanels);if(!panelIds||panelIds.length!==this.sizes.length)return;const layout={version:1,panels:panelIds.map((panelId,index)=>({panelId,size:this.sizes[index]}))};writePersistedState(this.storageFullKey,layout)}ensureSizes(){if(this.panelCount===this.sizes.length)return;if(this.panelCount<=0){this.sizes=[];return}if(this.sizes.length===0){const equal=100/this.panelCount;this.sizes=Array.from({length:this.panelCount},()=>equal);return}const diff=this.panelCount-this.sizes.length;if(diff>0){const newShare=100/this.panelCount,scale=(100-newShare*diff)/100;this.sizes=[...this.sizes.map(s=>s*scale),...Array.from({length:diff},()=>newShare)]}else{const kept=this.sizes.slice(0,this.panelCount),removedTotal=this.sizes.slice(this.panelCount).reduce((sum,s)=>sum+s,0),keptTotal=kept.reduce((sum,s)=>sum+s,0)||1;this.sizes=kept.map(s=>s+s/keptTotal*removedTotal)}}readPanelStyle(panel,property2){return{value:panel.style.getPropertyValue(property2),priority:panel.style.getPropertyPriority(property2)}}samePanelStyle(left,right){return left.value===right.value&&left.priority===right.priority}snapshotPanelOwnership(panel){const styles2=new Map;for(const property2 of OWNED_PANEL_STYLE_PROPERTIES)styles2.set(property2,this.readPanelStyle(panel,property2));return{styles:styles2,appliedStyles:new Map,hidden:panel.hidden,collapseState:panel.getAttribute("data-collapse-state")}}adoptPanelOwnership(panel,snapshot){for(const property2 of OWNED_PANEL_STYLE_PROPERTIES){const current=this.readPanelStyle(panel,property2),applied=snapshot.appliedStyles.get(property2);(applied&&!this.samePanelStyle(current,applied)||!applied&&!this.samePanelStyle(current,snapshot.styles.get(property2)))&&snapshot.styles.set(property2,current)}(snapshot.appliedHidden!==void 0&&panel.hidden!==snapshot.appliedHidden||snapshot.appliedHidden===void 0&&panel.hidden!==snapshot.hidden)&&(snapshot.hidden=panel.hidden);const collapseState=panel.getAttribute("data-collapse-state");(snapshot.appliedCollapseState!==void 0&&collapseState!==snapshot.appliedCollapseState||snapshot.appliedCollapseState===void 0&&collapseState!==snapshot.collapseState)&&(snapshot.collapseState=collapseState)}applyOwnedPanelStyle(panel,snapshot,property2,value){value.value===""?panel.style.removeProperty(property2):panel.style.setProperty(property2,value.value,value.priority),snapshot.appliedStyles.set(property2,this.readPanelStyle(panel,property2))}applyOwnedPanelStyleValue(panel,snapshot,property2,value){this.applyOwnedPanelStyle(panel,snapshot,property2,{value,priority:""})}applyOwnedPanelHidden(panel,snapshot,hidden){panel.hidden=hidden,snapshot.appliedHidden=panel.hidden}applyOwnedPanelCollapseState(panel,snapshot,state){state===null?panel.removeAttribute("data-collapse-state"):panel.setAttribute("data-collapse-state",state),snapshot.appliedCollapseState=panel.getAttribute("data-collapse-state")}restorePanelOwnership(panel,snapshot){this.adoptPanelOwnership(panel,snapshot);for(const property2 of OWNED_PANEL_STYLE_PROPERTIES){const value=snapshot.styles.get(property2);value.value===""?panel.style.removeProperty(property2):panel.style.setProperty(property2,value.value,value.priority)}panel.hidden=snapshot.hidden,snapshot.collapseState===null?panel.removeAttribute("data-collapse-state"):panel.setAttribute("data-collapse-state",snapshot.collapseState)}panelProjectionDiverged(panel,snapshot){for(const property2 of OWNED_PANEL_STYLE_PROPERTIES){const current=this.readPanelStyle(panel,property2),expected=snapshot.appliedStyles.get(property2)??snapshot.styles.get(property2);if(!this.samePanelStyle(current,expected))return!0}if(panel.hidden!==(snapshot.appliedHidden??snapshot.hidden))return!0;const expectedCollapseState=snapshot.appliedCollapseState!==void 0?snapshot.appliedCollapseState:snapshot.collapseState;return panel.getAttribute("data-collapse-state")!==expectedCollapseState}resetPanelOwnershipObserver(){this.panelOwnershipObserverGeneration+=1,this.panelOwnershipObserver?.disconnect(),this.panelOwnershipObserver=void 0,this.panelOwnershipObserverDocument=void 0}observeOwnedPanels(){this.resetPanelOwnershipObserver();const ownerDocument=this.ownerDocument,MutationObserverConstructor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverConstructor||!this.isConnected||this.ownedPanels.length===0)return;const generation=this.panelOwnershipObserverGeneration,observer=new MutationObserverConstructor(records=>{if(this.panelOwnershipObserver!==observer||this.panelOwnershipObserverDocument!==this.ownerDocument||this.panelOwnershipObserverGeneration!==generation||!this.isConnected)return;records.some(record=>{const panel=record.target,snapshot=this.panelOwnership.get(panel);return snapshot?this.panelProjectionDiverged(panel,snapshot):!1})&&this.requestUpdate()});this.panelOwnershipObserver=observer,this.panelOwnershipObserverDocument=ownerDocument;for(const panel of this.ownedPanels)observer.observe(panel,{attributes:!0,attributeFilter:["style","hidden","data-collapse-state"]})}samePanelSequence(next){return next.length===this.ownedPanels.length&&next.every((panel,index)=>panel===this.ownedPanels[index])}syncPanelMembership(reconcileSizes=!0){const next=[...this.children];if(this.samePanelSequence(next))return;const previousPanels=this.ownedPanels,identitySizes=reconcileSizes?this.reconcileSizesByPanelId(previousPanels,next):null,previousEffective=this.collapseState,nextSet=new Set(next);for(const panel of this.ownedPanels){if(nextSet.has(panel))continue;const snapshot=this.panelOwnership.get(panel);snapshot&&this.restorePanelOwnership(panel,snapshot),this.panelOwnership.delete(panel)}for(const panel of next)this.panelOwnership.has(panel)||this.panelOwnership.set(panel,this.snapshotPanelOwnership(panel));const countChanged=next.length!==this.panelCount;this.ownedPanels=next,this.panelCount=next.length,this.collapsingIndex!==-1&&!this._forced&&(this._collapseState=this.collapseBreakpoints.classify(this.currentMeasuredWidth())),this.applyEffectiveCollapseTransition(previousEffective,this.collapseState,this.hasUpdated),identitySizes?(this.sizesReconciledForMembership=!0,this.sizes=identitySizes):countChanged&&reconcileSizes&&(this.sizesReconciledForMembership=!0,this.ensureSizes()),this.observeOwnedPanels(),this.hasUpdated&&this.requestUpdate()}releaseOwnedPanels(){this.resetPanelOwnershipObserver();for(const panel of this.ownedPanels){const snapshot=this.panelOwnership.get(panel);snapshot&&this.restorePanelOwnership(panel,snapshot)}this.ownedPanels=[],this.panelOwnership.clear()}getContainerSize(){return this.baseEl?this.effectiveOrientation==="vertical"?this.baseEl.clientHeight:this.baseEl.clientWidth:0}get collapsingIndex(){return this.collapse==="none"||this.panelCount<2?-1:this.collapse==="start"?0:this.panelCount-1}get collapseActive(){return this.collapsingIndex!==-1&&this.collapseState!=="wide"}isDividerDisabled(index){if(!this.collapseActive)return!1;const adjacent=this.collapsingIndex===0?0:this.panelCount-2;return index===adjacent}updateCollapseState(width,shouldEmit=!0){this.collapse!=="none"&&(this._forced||this.setRequestedCollapseState(this.collapseBreakpoints.classify(width),shouldEmit))}armCollapseObserver(){const observedElement=this.baseEl;if(!this.isConnected||!observedElement)return;const ownerDocument=this.ownerDocument;if(this.collapseResizeObserver&&this.collapseObservedElement===observedElement&&this.collapseObserverOwnerDocument===ownerDocument)return;this.resetCollapseObserver();const ResizeObserverConstructor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverConstructor)return;const generation=this.collapseObserverGeneration,observer=new ResizeObserverConstructor(entries=>{if(this.collapseResizeObserver!==observer||this.collapseObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.baseEl!==observedElement)return;const box=entries[0]?.contentBoxSize?.[0],width=box?box.inlineSize:observedElement.getBoundingClientRect().width;this.measuredInlineSize=width,this.updateCollapseState(width),this.updateEffectiveOrientation(width,!0)});this.collapseResizeObserver=observer,this.collapseObservedElement=observedElement,this.collapseObserverOwnerDocument=ownerDocument,observer.observe(observedElement)}resetCollapseObserver(){this.collapseObserverGeneration+=1,this.collapseResizeObserver?.disconnect(),this.collapseResizeObserver=void 0,this.collapseObservedElement=void 0,this.collapseObserverOwnerDocument=void 0}syncCollapseObserver(){if(!this.responsiveObservationEnabled){this.resetCollapseObserver();return}this.armCollapseObserver()}get safeMin(){return finiteRange(this.min,10,0)}normalizedDefaultMin(){if(this.panelCount<=0)return 0;const requested=this.safeMin,available=Math.max(0,100-KEYBOARD_STEP);return Math.min(requested,available/this.panelCount)}resolveConstraintBounds(containerSize){const fallbackMin=this.normalizedDefaultMin(),fallback=Array.from({length:this.panelCount},()=>({min:fallbackMin,max:1/0}));if(this.panelCount<=0)return{bounds:[],usePanelConstraints:!0};const bounds=[];let minimumTotal=0,maximumTotal=0,hasUnboundedMaximum=!1,issueReason;for(let index=0;index<this.panelCount;index++){const constraint=this.panelConstraints[index];let min=this.safeMin,max=1/0,minSet=!1,maxSet=!1;constraint&&(constraint.minPx!=null&&Number.isFinite(constraint.minPx)&&constraint.minPx>=0&&containerSize>0&&(min=constraint.minPx/containerSize*100,minSet=!0),constraint.minPercent!=null&&Number.isFinite(constraint.minPercent)&&constraint.minPercent>=0&&(min=minSet?Math.max(min,constraint.minPercent):constraint.minPercent,minSet=!0),constraint.maxPx!=null&&Number.isFinite(constraint.maxPx)&&constraint.maxPx>=0&&containerSize>0&&(max=constraint.maxPx/containerSize*100,maxSet=!0),constraint.maxPercent!=null&&Number.isFinite(constraint.maxPercent)&&constraint.maxPercent>=0&&(max=maxSet?Math.min(max,constraint.maxPercent):constraint.maxPercent,maxSet=!0),(constraint.minPx!=null&&(!Number.isFinite(constraint.minPx)||constraint.minPx<0)||constraint.maxPx!=null&&(!Number.isFinite(constraint.maxPx)||constraint.maxPx<0)||constraint.minPercent!=null&&(!Number.isFinite(constraint.minPercent)||constraint.minPercent<0)||constraint.maxPercent!=null&&(!Number.isFinite(constraint.maxPercent)||constraint.maxPercent<0))&&(issueReason??="minimum-exceeds-maximum")),min>max&&(issueReason??="minimum-exceeds-maximum"),bounds.push({min,max}),minimumTotal+=min,Number.isFinite(max)?maximumTotal+=max:hasUnboundedMaximum=!0}return issueReason==null&&minimumTotal>100+1e-9&&(issueReason="minimum-total"),issueReason==null&&!hasUnboundedMaximum&&maximumTotal<100-1e-9&&(issueReason="maximum-total"),issueReason==null?{bounds,usePanelConstraints:!0}:{bounds:fallback,usePanelConstraints:!1,issue:{reason:issueReason,panelCount:this.panelCount,minimumTotal,maximumTotal:hasUnboundedMaximum?null:maximumTotal,containerSize}}}percentBounds(index,containerSize){return this.resolveConstraintBounds(containerSize).bounds[index]??{min:0,max:1/0}}hasClampConstraint(constraint){return!!constraint&&(constraint.minPx!=null||constraint.maxPx!=null||constraint.minPercent!=null||constraint.maxPercent!=null)}minSideExpr(constraint){const terms=[];return constraint?.minPx!=null&&Number.isFinite(constraint.minPx)&&constraint.minPx>=0&&terms.push(`${constraint.minPx}px`),constraint?.minPercent!=null&&Number.isFinite(constraint.minPercent)&&constraint.minPercent>=0&&terms.push(`${constraint.minPercent}%`),terms.length===0?`${NO_MIN_PX}px`:terms.length===1?terms[0]:`max(${this.safeMin}%, ${terms.join(", ")})`}maxSideExpr(constraint){const terms=[];return constraint?.maxPx!=null&&Number.isFinite(constraint.maxPx)&&constraint.maxPx>=0&&terms.push(`${constraint.maxPx}px`),constraint?.maxPercent!=null&&Number.isFinite(constraint.maxPercent)&&constraint.maxPercent>=0&&terms.push(`${constraint.maxPercent}%`),terms.length===0?`${NO_MAX_PX}px`:terms.length===1?terms[0]:`min(${terms.join(", ")})`}clampPair(sizes,i,delta,containerSize=0){const next=[...sizes],currentA=next[i],currentB=next[i+1];if(currentA===void 0||currentB===void 0)return next;const pairTotal=currentA+currentB,a=this.percentBounds(i,containerSize),b=this.percentBounds(i+1,containerSize),loRaw=Math.max(a.min,pairTotal-b.max),hiRaw=Math.min(a.max,pairTotal-b.min),lo=Math.min(loRaw,pairTotal),hi=Math.max(hiRaw,lo),clampedA=Math.min(Math.max(currentA+delta,lo),hi);return next[i]=clampedA,next[i+1]=pairTotal-clampedA,next}requestResize(next,commit){return next.length===this.sizes.length&&next.every((size,index)=>Math.abs(size-this.sizes[index])<=1e-9)||this.emit("lr-resize-request",{sizes:[...next]},{cancelable:!0}).defaultPrevented?!1:(this.sizes=next,this.emit("lr-resize",{sizes:[...this.sizes]}),commit&&this.persist(),!0)}applyDelta(index,delta,commit){const next=this.clampPair(this.sizes,index,delta,this.getContainerSize());return next.length!==this.sizes.length||next.some((size,currentIndex)=>Math.abs(size-this.sizes[currentIndex])>1e-9)?(this.requestResize(next,commit),!0):!1}get floatingPanelEl(){const index=this.collapsingIndex;return index===-1?null:this.ownedPanels[index]??null}activateFloatingOverlay(){this.overlayHandle=activateOverlay({host:this,panel:()=>this.floatingPanelEl,onEscape:()=>this.open=!1,onBackdrop:()=>this.open=!1,lockScroll:!0,suspendWhenUnrendered:!0})}deactivateFloatingOverlay(){this.overlayHandle?.deactivate(),this.overlayHandle=void 0}removeDragListeners(){const ownerWindow=this.dragOwnerWindow;this.dragOwnerWindow=void 0,ownerWindow?.removeEventListener("pointermove",this.onPointerMove),ownerWindow?.removeEventListener("pointerup",this.onPointerUp),ownerWindow?.removeEventListener("pointercancel",this.onPointerUp),ownerWindow?.removeEventListener("lostpointercapture",this.onPointerUp)}endDragGestures(){this.drags.clear(),this.removeDragListeners()}updated(changed){super.updated(changed),(changed.has("collapse")||changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.syncCollapseObserver(),this.orientationBreakpoints.active?this.setAttribute("data-effective-orientation",this._effectiveOrientation):this.removeAttribute("data-effective-orientation");const constraintResolution=this.resolveConstraintBounds(this.getContainerSize()),issue=constraintResolution.issue,issueKey=issue?`${issue.reason}:${issue.panelCount}:${issue.minimumTotal}:${issue.maximumTotal??"unbounded"}`:"";issueKey!==this.constraintIssueKey&&(this.constraintIssueKey=issueKey,issue&&this.emit("lr-multi-split-constraints-invalid",issue));const panels=this.ownedPanels;for(const panel of panels){const snapshot=this.panelOwnership.get(panel);snapshot&&this.adoptPanelOwnership(panel,snapshot)}const collapsingIndex=this.collapseActive?this.collapsingIndex:-1,redistributedShare=new Array(panels.length).fill(0);if(collapsingIndex===-1){let freedPercent=0;const growableIndexes=[];let growableTotal=0;for(let i=0;i<panels.length;i++){const percent=this.sizes[i]??0,constraint=constraintResolution.usePanelConstraints?this.panelConstraints[i]:void 0;if(this.hasClampConstraint(constraint)){const bounds=constraintResolution.bounds[i],clamped=bounds?Math.min(Math.max(percent,bounds.min),bounds.max):percent;clamped<percent&&(freedPercent+=percent-clamped)}else growableIndexes.push(i),growableTotal+=percent}if(freedPercent>0&&growableTotal>0)for(const i of growableIndexes)redistributedShare[i]=freedPercent*((this.sizes[i]??0)/growableTotal)}panels.forEach((panel,i)=>{const snapshot=this.panelOwnership.get(panel);if(!snapshot)return;const percent=this.sizes[i]??0,constraint=constraintResolution.usePanelConstraints?this.panelConstraints[i]:void 0;for(const property2 of["position","inset-block","inset-inline-start","inset-inline-end","inline-size"])this.applyOwnedPanelStyle(panel,snapshot,property2,snapshot.styles.get(property2));if(this.applyOwnedPanelHidden(panel,snapshot,snapshot.hidden),collapsingIndex===i&&this.collapseState==="rail")this.applyOwnedPanelStyleValue(panel,snapshot,"flex",`0 0 ${this.railWidth}`);else if(collapsingIndex===i&&this.collapseState==="floating"&&!this.open)this.applyOwnedPanelStyleValue(panel,snapshot,"flex","none"),this.applyOwnedPanelHidden(panel,snapshot,!0);else if(collapsingIndex===i&&this.collapseState==="floating")this.applyOwnedPanelStyleValue(panel,snapshot,"flex","none"),this.applyOwnedPanelStyleValue(panel,snapshot,"position","absolute"),this.applyOwnedPanelStyleValue(panel,snapshot,"inset-block","0"),this.applyOwnedPanelStyleValue(panel,snapshot,collapsingIndex===0?"inset-inline-start":"inset-inline-end","0"),this.applyOwnedPanelStyleValue(panel,snapshot,"inline-size",`${percent}%`);else if(collapsingIndex!==-1&&i!==collapsingIndex)this.applyOwnedPanelStyleValue(panel,snapshot,"flex",this.hasClampConstraint(constraint)?`0 1 clamp(${this.minSideExpr(constraint)}, ${percent}%, ${this.maxSideExpr(constraint)})`:`${percent} 1 0%`);else{const adjustedPercent=percent+(redistributedShare[i]??0);this.applyOwnedPanelStyleValue(panel,snapshot,"flex",this.hasClampConstraint(constraint)?`0 1 clamp(${this.minSideExpr(constraint)}, ${percent}%, ${this.maxSideExpr(constraint)})`:`0 1 ${adjustedPercent}%`)}this.applyOwnedPanelStyleValue(panel,snapshot,"order",String(i*2)),collapsingIndex===i?this.applyOwnedPanelCollapseState(panel,snapshot,this.collapseState):this.applyOwnedPanelCollapseState(panel,snapshot,null)}),collapsingIndex!==-1?this.setAttribute("data-collapse-state",this.collapseState):this.removeAttribute("data-collapse-state"),this.justOpened&&(this.justOpened=!1,this.overlayHandle?.focusInitial())}render(){const dividers=[],bounds=this.resolveConstraintBounds(this.getContainerSize()).bounds;for(let i=0;i<this.panelCount-1;i++){const pairTotal=(this.sizes[i]??0)+(this.sizes[i+1]??0),a=bounds[i],b=bounds[i+1],valueMin=Math.max(a.min,pairTotal-b.max),valueMax=Math.max(valueMin,Math.min(a.max,pairTotal-b.min)),disabled=this.isDividerDisabled(i);dividers.push(html`<div
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activateOverlay}from"../../../internal/overlay-manager.js";import{isRtl}from"../../../internal/rtl.js";import{finiteRange}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{CollapseBreakpointController,OrientationBreakpointController}from"../../../internal/orientation-breakpoint.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{resolveCssLength}from"../../../internal/css-length.js";import{styles}from"./multi-split.styles.js";import{LYRA_DEFAULT_resizeDivider}from"../../../internal/default-strings.generated.js";const KEYBOARD_STEP=2;function isPersistedPanelLayout(value){if(typeof value!="object"||value===null)return!1;const candidate=value;return candidate.version!==1||!Array.isArray(candidate.panels)?!1:candidate.panels.every(panel=>{if(typeof panel!="object"||panel===null)return!1;const record=panel;return typeof record.panelId=="string"&&record.panelId!==""&&record.panelId.trim()===record.panelId&&typeof record.size=="number"&&Number.isFinite(record.size)&&record.size>=0})}const NO_MIN_PX=0,NO_MAX_PX=1e6,OWNED_PANEL_STYLE_PROPERTIES=["flex","order","inline-size"];class LyraMultiSplit extends LyraElement{constructor(){super(...arguments),this.sizes=[],this.defaultSizes=[],this.min=10,this.orientation="horizontal",this.orientationBreakpointBasis="container",this.narrowOrientation="vertical",this.panelConstraints=[],this.collapse="none",this.railWidth="3.5rem",this.railBreakpoint=640,this.floatBreakpoint=400,this.collapseBreakpointBasis="container",this.open=!1,this.panelCount=0,this.sizesReconciledForMembership=!1,this._collapseState="wide",this._forced=!1,this.overlayActive=!1,this.justOpened=!1,this.drags=new Map,this.ownedPanels=[],this.panelOwnership=new Map,this.panelOwnershipObserverGeneration=0,this.constraintIssueKey="",this.initializedSizes=!1,this.measuredInlineSize=Number.POSITIVE_INFINITY,this._effectiveOrientation="horizontal",this.collapseObserverGeneration=0,this.orientationBreakpoints=new OrientationBreakpointController(this,()=>this.updateEffectiveOrientation(this.measuredInlineSize,!0)),this.collapseBreakpoints=new CollapseBreakpointController(this,()=>this.updateCollapseState(this.measuredInlineSize,!0)),this.onSlotChange=()=>{this.updateBrowserDerivedState(()=>this.syncPanelMembership())},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()},this.onPointerDown=(e,index)=>{if(e.button!==0||this.isDividerDisabled(index))return;const divider=e.currentTarget,ownerWindow=divider.ownerDocument.defaultView;ownerWindow&&(this.drags.size>0&&this.dragOwnerWindow!==ownerWindow||(this.drags.set(e.pointerId,{index,startPos:this.effectiveOrientation==="vertical"?e.clientY:e.clientX,base:this.baseEl,appliedDelta:0,acceptedResize:!1}),divider.setPointerCapture(e.pointerId),this.drags.size===1&&(this.dragOwnerWindow=ownerWindow,ownerWindow.addEventListener("pointermove",this.onPointerMove),ownerWindow.addEventListener("pointerup",this.onPointerUp),ownerWindow.addEventListener("pointercancel",this.onPointerUp),ownerWindow.addEventListener("lostpointercapture",this.onPointerUp))))},this.onPointerMove=e=>{const drag=this.drags.get(e.pointerId);if(!drag)return;if(this.isDividerDisabled(drag.index)){this.endDragGestures();return}const total=this.effectiveOrientation==="vertical"?drag.base.clientHeight:drag.base.clientWidth;if(!Number.isFinite(total)||total<=0){this.endDragGestures();return}let cumulativeDelta=((this.effectiveOrientation==="vertical"?e.clientY:e.clientX)-drag.startPos)/total*100;this.effectiveOrientation==="horizontal"&&isRtl(this)&&(cumulativeDelta=-cumulativeDelta);const incremental=cumulativeDelta-drag.appliedDelta,priorValue=this.sizes[drag.index];if(priorValue===void 0)return;const paired=this.clampPair(this.sizes,drag.index,incremental,total),pairedA=paired[drag.index],pairedB=paired[drag.index+1];if(pairedA===void 0||pairedB===void 0)return;const next=[...this.sizes];next[drag.index]=pairedA,next[drag.index+1]=pairedB,this.requestResize(next,!1)&&(drag.appliedDelta+=pairedA-priorValue,drag.acceptedResize=!0)},this.onPointerUp=e=>{const drag=this.drags.get(e.pointerId);drag&&(this.drags.delete(e.pointerId),e.type==="pointerup"&&drag.acceptedResize&&this.persist(),this.drags.size===0&&this.removeDragListeners())},this.onDividerKeyDown=(e,index)=>{if(this.isDividerDisabled(index))return;const rtl=this.effectiveOrientation==="horizontal"&&isRtl(this),forwardKey=this.effectiveOrientation==="vertical"?"ArrowDown":rtl?"ArrowLeft":"ArrowRight",backwardKey=this.effectiveOrientation==="vertical"?"ArrowUp":rtl?"ArrowRight":"ArrowLeft";e.key===forwardKey?this.applyDelta(index,KEYBOARD_STEP,!0)&&e.preventDefault():e.key===backwardKey&&this.applyDelta(index,-KEYBOARD_STEP,!0)&&e.preventDefault()}}static{this.defaultStrings={...super.defaultStrings,resizeDivider:LYRA_DEFAULT_resizeDivider}}static{this.ownedCollectionProperties=Object.freeze(["sizes","defaultSizes","panelConstraints"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-resize-request","lr-resize"])}static{this.properties={collapseState:{reflect:!0,attribute:"collapse-state",noAccessor:!0}}}connectedCallback(){super.connectedCallback();const hostWidth=this.getBoundingClientRect().width;hostWidth>0&&(this.measuredInlineSize=hostWidth),this.seedFirstRenderState(()=>this.syncPanelMembership(!1)),this.hasUpdated&&this.syncPanelMembership(!1),this.initializedSizes&&this.ensureSizes(),this.responsiveObservationEnabled&&this.armCollapseObserver(),this.hasUpdated&&this.overlayActive&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFloatingOverlay(),queueMicrotask(()=>this.overlayHandle?.focusInitial()))}disconnectedCallback(){super.disconnectedCallback(),this.endDragGestures(),this.resetCollapseObserver(),this.overlayHandle?.suspend(),this.releaseOwnedPanels()}adoptedCallback(){super.adoptedCallback(),this.endDragGestures(),this.resetCollapseObserver(),this.releaseOwnedPanels()}firstUpdated(changed){super.firstUpdated(changed),this.responsiveObservationEnabled&&this.armCollapseObserver()}willUpdate(changed){if(super.willUpdate(changed),!this.ownerDocument&&this.panelCount===0&&(this.panelCount=Math.max(this.sizes.length,this.defaultSizes.length,this.panelConstraints.length)),!this.initializedSizes)this.initializeSizes(),this.initializedSizes=!0;else if(changed.has("sizes")){const previous=changed.get("sizes");this.sizesReconciledForMembership?this.sizesReconciledForMembership=!1:this.validLiveSizes(this.sizes)||(Array.isArray(previous)&&this.validLiveSizes(previous)?this.sizes=[...previous]:(this.sizes=[],this.ensureSizes()))}else this.sizes.length===0&&this.ensureSizes();if((changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.orientationBreakpoints.configure(this.orientationBreakpoint,this.orientationBreakpointBasis),(changed.has("orientation")||changed.has("narrowOrientation")||changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.updateEffectiveOrientation(this.measuredInlineSize,this.hasUpdated&&this.orientationBreakpointBasis==="viewport"),changed.has("collapse")||changed.has("railBreakpoint")||changed.has("floatBreakpoint")||changed.has("collapseBreakpointBasis")){const previousEffective=changed.has("collapse")?this.effectiveCollapseStateFor(changed.get("collapse")??"none"):this.collapseState;changed.has("collapse")&&previousEffective!=="wide"&&this.endDragGestures(),this.collapseBreakpoints.configure(this.railBreakpoint,this.floatBreakpoint,this.collapseBreakpointBasis),this.collapsingIndex!==-1&&!this._forced&&(this._collapseState=this.collapseBreakpoints.classify(this.measuredInlineSize)),this.applyEffectiveCollapseTransition(previousEffective,this.collapseState,this.hasUpdated)}if(changed.has("open")||changed.has("collapseState")||changed.has("collapse")||changed.has("panelCount")){const next=this.collapseState==="floating"&&this.open;next!==this.overlayActive&&(this.overlayActive=next,next?(this.justOpened=!0,this.activateFloatingOverlay()):this.deactivateFloatingOverlay())}}get collapseState(){return this.effectiveCollapseStateFor(this.collapse)}set collapseState(next){if(next==="auto"){this._forced=!1,this.updateCollapseState(this.currentMeasuredWidth());return}this._forced=!0,this.setRequestedCollapseState(next)}get effectiveOrientation(){return this._effectiveOrientation}get responsiveObservationEnabled(){return this.collapse!=="none"||this.orientationBreakpoints.containerObservationEnabled}updateEffectiveOrientation(width,shouldEmit){const next=this.orientationBreakpoints.isBelow(width)?this.narrowOrientation:this.orientation;next!==this._effectiveOrientation&&(this.endDragGestures(),this._effectiveOrientation=next,this.requestUpdate(),shouldEmit&&this.emit("lr-multi-split-orientation-change",{orientation:next}))}currentMeasuredWidth(){return this.baseEl?.clientWidth??0}effectiveCollapseStateFor(collapse){return collapse!=="none"&&this.panelCount>=2?this._collapseState:"wide"}applyEffectiveCollapseTransition(previous,next,shouldEmit=!0){previous!==next&&(this.endDragGestures(),this.requestUpdate("collapseState",previous),shouldEmit&&this.emit("lr-multi-split-collapse-change",{state:next}),next!=="floating"&&this.open&&(this.open=!1))}setRequestedCollapseState(next,shouldEmit=!0){const previousEffective=this.collapseState;if(next===this._collapseState)return;this._collapseState=next;const nextEffective=this.collapseState;this.applyEffectiveCollapseTransition(previousEffective,nextEffective,shouldEmit),previousEffective===nextEffective&&next!==nextEffective&&this.requestUpdate("collapseState",next)}get storageFullKey(){return this.storageKey?`lr-multi-split:${this.storageKey}:panels`:void 0}panelIdsFor(panels){const ids=[],seen=new Set;for(const panel of panels){const panelId=panel.getAttribute("panel-id")??"";if(!panelId||panelId.trim()!==panelId||seen.has(panelId))return null;seen.add(panelId),ids.push(panelId)}return ids}reconcileIdentitySizes(previousIds,previousValues,nextIds){if(previousIds.length!==previousValues.length||nextIds.length===0)return null;const previousSizes=new Map;previousIds.forEach((panelId,index)=>{previousSizes.set(panelId,previousValues[index])});const retainedTotal=nextIds.reduce((total,panelId)=>total+(previousSizes.get(panelId)??0),0),missingCount=nextIds.filter(panelId=>!previousSizes.has(panelId)).length;if(!(retainedTotal>0)){const equal=100/nextIds.length;return nextIds.map(()=>equal)}const newShare=100/nextIds.length,retainedScale=(100-newShare*missingCount)/retainedTotal;return nextIds.map(panelId=>{const previous=previousSizes.get(panelId);return previous===void 0?newShare:previous*retainedScale})}reconcileSizesByPanelId(previousPanels,nextPanels){if(previousPanels.length!==this.sizes.length||nextPanels.length===0)return null;const previousIds=this.panelIdsFor(previousPanels),nextIds=this.panelIdsFor(nextPanels);return!previousIds||!nextIds?null:this.reconcileIdentitySizes(previousIds,this.sizes,nextIds)}validInitialSizes(value){return!Array.isArray(value)||value.length!==this.panelCount||!value.every(size=>Number.isFinite(size)&&size>=this.safeMin)?!1:Math.abs(value.reduce((sum,size)=>sum+size,0)-100)<.01}validLiveSizes(value){if(!Array.isArray(value)||value.length!==this.panelCount)return!1;const floor=this.normalizedDefaultMin();return value.every(size=>Number.isFinite(size)&&size>=floor)?Math.abs(value.reduce((sum,size)=>sum+size,0)-100)<.01:!1}resolveDefaultSizes(){if(this.defaultSizes.length===0)return null;if(!this.defaultSizes.some(entry=>typeof entry=="string")){const numbers=this.defaultSizes;return this.validInitialSizes(numbers)?[...numbers]:null}const containerSize=this.currentMeasuredWidth()||this.getBoundingClientRect().width;if(!(containerSize>0))return null;const resolvedPx=[];for(const entry of this.defaultSizes){if(typeof entry=="number"){if(!Number.isFinite(entry))return null;resolvedPx.push(entry/100*containerSize);continue}const px=resolveCssLength(entry,{host:this,percentBase:containerSize,viewportBasis:this.ownerDocument.defaultView??void 0});if(px==null||!(px>=0))return null;resolvedPx.push(px)}const sum=resolvedPx.reduce((total,size)=>total+size,0);if(!(sum>0))return null;const normalized=resolvedPx.map(size=>size/sum*100);return this.validInitialSizes(normalized)?normalized:null}initializeSizes(){if(this.loadPersisted()||this.validInitialSizes(this.sizes))return;const resolved=this.resolveDefaultSizes();if(resolved){this.sizes=resolved;return}this.sizes=[],this.ensureSizes()}loadPersisted(){const panelIds=this.panelIdsFor(this.ownedPanels);if(!panelIds)return!1;const parsed=readPersistedState(this.storageFullKey,isPersistedPanelLayout);if(!parsed||parsed.panels.length===0)return!1;const persistedIds=[],persistedSizes=[],seen=new Set;for(const panel of parsed.panels){if(seen.has(panel.panelId))return!1;seen.add(panel.panelId),persistedIds.push(panel.panelId),persistedSizes.push(panel.size)}if(Math.abs(persistedSizes.reduce((sum,size)=>sum+size,0)-100)>=.01)return!1;const normalized=this.reconcileIdentitySizes(persistedIds,persistedSizes,panelIds);return normalized&&this.validInitialSizes(normalized)?(this.sizes=normalized,!0):!1}persist(){const panelIds=this.panelIdsFor(this.ownedPanels);if(!panelIds||panelIds.length!==this.sizes.length)return;const layout={version:1,panels:panelIds.map((panelId,index)=>({panelId,size:this.sizes[index]}))};writePersistedState(this.storageFullKey,layout)}ensureSizes(){if(this.panelCount===this.sizes.length)return;if(this.panelCount<=0){this.sizes=[];return}if(this.sizes.length===0){const equal=100/this.panelCount;this.sizes=Array.from({length:this.panelCount},()=>equal);return}const diff=this.panelCount-this.sizes.length;if(diff>0){const newShare=100/this.panelCount,scale=(100-newShare*diff)/100;this.sizes=[...this.sizes.map(s=>s*scale),...Array.from({length:diff},()=>newShare)]}else{const kept=this.sizes.slice(0,this.panelCount),removedTotal=this.sizes.slice(this.panelCount).reduce((sum,s)=>sum+s,0),keptTotal=kept.reduce((sum,s)=>sum+s,0)||1;this.sizes=kept.map(s=>s+s/keptTotal*removedTotal)}}readPanelStyle(panel,property2){return{value:panel.style.getPropertyValue(property2),priority:panel.style.getPropertyPriority(property2)}}samePanelStyle(left,right){return left.value===right.value&&left.priority===right.priority}snapshotPanelOwnership(panel){const styles2=new Map;for(const property2 of OWNED_PANEL_STYLE_PROPERTIES)styles2.set(property2,this.readPanelStyle(panel,property2));return{styles:styles2,appliedStyles:new Map,hidden:panel.hidden,collapseState:panel.getAttribute("data-collapse-state")}}adoptPanelOwnership(panel,snapshot){for(const property2 of OWNED_PANEL_STYLE_PROPERTIES){const current=this.readPanelStyle(panel,property2),applied=snapshot.appliedStyles.get(property2);(applied&&!this.samePanelStyle(current,applied)||!applied&&!this.samePanelStyle(current,snapshot.styles.get(property2)))&&snapshot.styles.set(property2,current)}(snapshot.appliedHidden!==void 0&&panel.hidden!==snapshot.appliedHidden||snapshot.appliedHidden===void 0&&panel.hidden!==snapshot.hidden)&&(snapshot.hidden=panel.hidden);const collapseState=panel.getAttribute("data-collapse-state");(snapshot.appliedCollapseState!==void 0&&collapseState!==snapshot.appliedCollapseState||snapshot.appliedCollapseState===void 0&&collapseState!==snapshot.collapseState)&&(snapshot.collapseState=collapseState)}applyOwnedPanelStyle(panel,snapshot,property2,value){value.value===""?panel.style.removeProperty(property2):panel.style.setProperty(property2,value.value,value.priority),snapshot.appliedStyles.set(property2,this.readPanelStyle(panel,property2))}applyOwnedPanelStyleValue(panel,snapshot,property2,value){this.applyOwnedPanelStyle(panel,snapshot,property2,{value,priority:""})}applyOwnedPanelHidden(panel,snapshot,hidden){panel.hidden=hidden,snapshot.appliedHidden=panel.hidden}applyOwnedPanelCollapseState(panel,snapshot,state){state===null?panel.removeAttribute("data-collapse-state"):panel.setAttribute("data-collapse-state",state),snapshot.appliedCollapseState=panel.getAttribute("data-collapse-state")}restorePanelOwnership(panel,snapshot){this.adoptPanelOwnership(panel,snapshot);for(const property2 of OWNED_PANEL_STYLE_PROPERTIES){const value=snapshot.styles.get(property2);value.value===""?panel.style.removeProperty(property2):panel.style.setProperty(property2,value.value,value.priority)}panel.hidden=snapshot.hidden,snapshot.collapseState===null?panel.removeAttribute("data-collapse-state"):panel.setAttribute("data-collapse-state",snapshot.collapseState)}panelProjectionDiverged(panel,snapshot){for(const property2 of OWNED_PANEL_STYLE_PROPERTIES){const current=this.readPanelStyle(panel,property2),expected=snapshot.appliedStyles.get(property2)??snapshot.styles.get(property2);if(!this.samePanelStyle(current,expected))return!0}if(panel.hidden!==(snapshot.appliedHidden??snapshot.hidden))return!0;const expectedCollapseState=snapshot.appliedCollapseState!==void 0?snapshot.appliedCollapseState:snapshot.collapseState;return panel.getAttribute("data-collapse-state")!==expectedCollapseState}resetPanelOwnershipObserver(){this.panelOwnershipObserverGeneration+=1,this.panelOwnershipObserver?.disconnect(),this.panelOwnershipObserver=void 0,this.panelOwnershipObserverDocument=void 0}observeOwnedPanels(){this.resetPanelOwnershipObserver();const ownerDocument=this.ownerDocument,MutationObserverConstructor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverConstructor||!this.isConnected||this.ownedPanels.length===0)return;const generation=this.panelOwnershipObserverGeneration,observer=new MutationObserverConstructor(records=>{if(this.panelOwnershipObserver!==observer||this.panelOwnershipObserverDocument!==this.ownerDocument||this.panelOwnershipObserverGeneration!==generation||!this.isConnected)return;records.some(record=>{const panel=record.target,snapshot=this.panelOwnership.get(panel);return snapshot?this.panelProjectionDiverged(panel,snapshot):!1})&&this.requestUpdate()});this.panelOwnershipObserver=observer,this.panelOwnershipObserverDocument=ownerDocument;for(const panel of this.ownedPanels)observer.observe(panel,{attributes:!0,attributeFilter:["style","hidden","data-collapse-state"]})}samePanelSequence(next){return next.length===this.ownedPanels.length&&next.every((panel,index)=>panel===this.ownedPanels[index])}syncPanelMembership(reconcileSizes=!0){const next=[...this.children];if(this.samePanelSequence(next))return;const previousPanels=this.ownedPanels,identitySizes=reconcileSizes?this.reconcileSizesByPanelId(previousPanels,next):null,previousEffective=this.collapseState,nextSet=new Set(next);for(const panel of this.ownedPanels){if(nextSet.has(panel))continue;const snapshot=this.panelOwnership.get(panel);snapshot&&this.restorePanelOwnership(panel,snapshot),this.panelOwnership.delete(panel)}for(const panel of next)this.panelOwnership.has(panel)||this.panelOwnership.set(panel,this.snapshotPanelOwnership(panel));const countChanged=next.length!==this.panelCount;this.ownedPanels=next,this.panelCount=next.length,this.collapsingIndex!==-1&&!this._forced&&(this._collapseState=this.collapseBreakpoints.classify(this.currentMeasuredWidth())),this.applyEffectiveCollapseTransition(previousEffective,this.collapseState,this.hasUpdated),identitySizes?(this.sizesReconciledForMembership=!0,this.sizes=identitySizes):countChanged&&reconcileSizes&&(this.sizesReconciledForMembership=!0,this.ensureSizes()),this.observeOwnedPanels(),this.hasUpdated&&this.requestUpdate()}releaseOwnedPanels(){this.resetPanelOwnershipObserver();for(const panel of this.ownedPanels){const snapshot=this.panelOwnership.get(panel);snapshot&&this.restorePanelOwnership(panel,snapshot)}this.ownedPanels=[],this.panelOwnership.clear()}getContainerSize(){return this.baseEl?this.effectiveOrientation==="vertical"?this.baseEl.clientHeight:this.baseEl.clientWidth:0}get collapsingIndex(){return this.collapse==="none"||this.panelCount<2?-1:this.collapse==="start"?0:this.panelCount-1}get collapseActive(){return this.collapsingIndex!==-1&&this.collapseState!=="wide"}isDividerDisabled(index){if(!this.collapseActive)return!1;const adjacent=this.collapsingIndex===0?0:this.panelCount-2;return index===adjacent}updateCollapseState(width,shouldEmit=!0){this.collapse!=="none"&&(this._forced||this.setRequestedCollapseState(this.collapseBreakpoints.classify(width),shouldEmit))}armCollapseObserver(){const observedElement=this.baseEl;if(!this.isConnected||!observedElement)return;const ownerDocument=this.ownerDocument;if(this.collapseResizeObserver&&this.collapseObservedElement===observedElement&&this.collapseObserverOwnerDocument===ownerDocument)return;this.resetCollapseObserver();const ResizeObserverConstructor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverConstructor)return;const generation=this.collapseObserverGeneration,observer=new ResizeObserverConstructor(entries=>{if(this.collapseResizeObserver!==observer||this.collapseObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.baseEl!==observedElement)return;const box=entries[0]?.contentBoxSize?.[0],width=box?box.inlineSize:observedElement.getBoundingClientRect().width;this.measuredInlineSize=width,this.updateCollapseState(width),this.updateEffectiveOrientation(width,!0)});this.collapseResizeObserver=observer,this.collapseObservedElement=observedElement,this.collapseObserverOwnerDocument=ownerDocument,observer.observe(observedElement)}resetCollapseObserver(){this.collapseObserverGeneration+=1,this.collapseResizeObserver?.disconnect(),this.collapseResizeObserver=void 0,this.collapseObservedElement=void 0,this.collapseObserverOwnerDocument=void 0}syncCollapseObserver(){if(!this.responsiveObservationEnabled){this.resetCollapseObserver();return}this.armCollapseObserver()}get safeMin(){return finiteRange(this.min,10,0)}normalizedDefaultMin(){if(this.panelCount<=0)return 0;const requested=this.safeMin,available=Math.max(0,100-KEYBOARD_STEP);return Math.min(requested,available/this.panelCount)}resolveConstraintBounds(containerSize){const fallbackMin=this.normalizedDefaultMin(),fallback=Array.from({length:this.panelCount},()=>({min:fallbackMin,max:1/0}));if(this.panelCount<=0)return{bounds:[],usePanelConstraints:!0};const bounds=[];let minimumTotal=0,maximumTotal=0,hasUnboundedMaximum=!1,issueReason;for(let index=0;index<this.panelCount;index++){const constraint=this.panelConstraints[index];let min=this.safeMin,max=1/0,minSet=!1,maxSet=!1;constraint&&(constraint.minPx!=null&&Number.isFinite(constraint.minPx)&&constraint.minPx>=0&&containerSize>0&&(min=constraint.minPx/containerSize*100,minSet=!0),constraint.minPercent!=null&&Number.isFinite(constraint.minPercent)&&constraint.minPercent>=0&&(min=minSet?Math.max(min,constraint.minPercent):constraint.minPercent,minSet=!0),constraint.maxPx!=null&&Number.isFinite(constraint.maxPx)&&constraint.maxPx>=0&&containerSize>0&&(max=constraint.maxPx/containerSize*100,maxSet=!0),constraint.maxPercent!=null&&Number.isFinite(constraint.maxPercent)&&constraint.maxPercent>=0&&(max=maxSet?Math.min(max,constraint.maxPercent):constraint.maxPercent,maxSet=!0),(constraint.minPx!=null&&(!Number.isFinite(constraint.minPx)||constraint.minPx<0)||constraint.maxPx!=null&&(!Number.isFinite(constraint.maxPx)||constraint.maxPx<0)||constraint.minPercent!=null&&(!Number.isFinite(constraint.minPercent)||constraint.minPercent<0)||constraint.maxPercent!=null&&(!Number.isFinite(constraint.maxPercent)||constraint.maxPercent<0))&&(issueReason??="minimum-exceeds-maximum")),min>max&&(issueReason??="minimum-exceeds-maximum"),bounds.push({min,max}),minimumTotal+=min,Number.isFinite(max)?maximumTotal+=max:hasUnboundedMaximum=!0}return issueReason==null&&minimumTotal>100+1e-9&&(issueReason="minimum-total"),issueReason==null&&!hasUnboundedMaximum&&maximumTotal<100-1e-9&&(issueReason="maximum-total"),issueReason==null?{bounds,usePanelConstraints:!0}:{bounds:fallback,usePanelConstraints:!1,issue:{reason:issueReason,panelCount:this.panelCount,minimumTotal,maximumTotal:hasUnboundedMaximum?null:maximumTotal,containerSize}}}percentBounds(index,containerSize){return this.resolveConstraintBounds(containerSize).bounds[index]??{min:0,max:1/0}}hasClampConstraint(constraint){return!!constraint&&(constraint.minPx!=null||constraint.maxPx!=null||constraint.minPercent!=null||constraint.maxPercent!=null)}minSideExpr(constraint){const terms=[];return constraint?.minPx!=null&&Number.isFinite(constraint.minPx)&&constraint.minPx>=0&&terms.push(`${constraint.minPx}px`),constraint?.minPercent!=null&&Number.isFinite(constraint.minPercent)&&constraint.minPercent>=0&&terms.push(`${constraint.minPercent}%`),terms.length===0?`${NO_MIN_PX}px`:terms.length===1?terms[0]:`max(${this.safeMin}%, ${terms.join(", ")})`}maxSideExpr(constraint){const terms=[];return constraint?.maxPx!=null&&Number.isFinite(constraint.maxPx)&&constraint.maxPx>=0&&terms.push(`${constraint.maxPx}px`),constraint?.maxPercent!=null&&Number.isFinite(constraint.maxPercent)&&constraint.maxPercent>=0&&terms.push(`${constraint.maxPercent}%`),terms.length===0?`${NO_MAX_PX}px`:terms.length===1?terms[0]:`min(${terms.join(", ")})`}clampPair(sizes,i,delta,containerSize=0){const next=[...sizes],currentA=next[i],currentB=next[i+1];if(currentA===void 0||currentB===void 0)return next;const pairTotal=currentA+currentB,a=this.percentBounds(i,containerSize),b=this.percentBounds(i+1,containerSize),loRaw=Math.max(a.min,pairTotal-b.max),hiRaw=Math.min(a.max,pairTotal-b.min),lo=Math.min(loRaw,pairTotal),hi=Math.max(hiRaw,lo),clampedA=Math.min(Math.max(currentA+delta,lo),hi);return next[i]=clampedA,next[i+1]=pairTotal-clampedA,next}requestResize(next,commit){return next.length===this.sizes.length&&next.every((size,index)=>Math.abs(size-this.sizes[index])<=1e-9)||this.emit("lr-resize-request",{sizes:[...next]},{cancelable:!0}).defaultPrevented?!1:(this.sizes=next,this.emit("lr-resize",{sizes:[...this.sizes]}),commit&&this.persist(),!0)}applyDelta(index,delta,commit){const next=this.clampPair(this.sizes,index,delta,this.getContainerSize());return next.length!==this.sizes.length||next.some((size,currentIndex)=>Math.abs(size-this.sizes[currentIndex])>1e-9)?(this.requestResize(next,commit),!0):!1}get floatingPanelEl(){const index=this.collapsingIndex;return index===-1?null:this.ownedPanels[index]??null}activateFloatingOverlay(){this.overlayHandle=activateOverlay({host:this,panel:()=>this.floatingPanelEl,onEscape:()=>this.open=!1,onBackdrop:()=>this.open=!1,lockScroll:!0,suspendWhenUnrendered:!0})}deactivateFloatingOverlay(){this.overlayHandle?.deactivate(),this.overlayHandle=void 0}removeDragListeners(){const ownerWindow=this.dragOwnerWindow;this.dragOwnerWindow=void 0,ownerWindow?.removeEventListener("pointermove",this.onPointerMove),ownerWindow?.removeEventListener("pointerup",this.onPointerUp),ownerWindow?.removeEventListener("pointercancel",this.onPointerUp),ownerWindow?.removeEventListener("lostpointercapture",this.onPointerUp)}endDragGestures(){this.drags.clear(),this.removeDragListeners()}updated(changed){super.updated(changed),(changed.has("collapse")||changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&this.syncCollapseObserver(),this.orientationBreakpoints.active?this.setAttribute("data-effective-orientation",this._effectiveOrientation):this.removeAttribute("data-effective-orientation");const constraintResolution=this.resolveConstraintBounds(this.getContainerSize()),issue=constraintResolution.issue,issueKey=issue?`${issue.reason}:${issue.panelCount}:${issue.minimumTotal}:${issue.maximumTotal??"unbounded"}`:"";issueKey!==this.constraintIssueKey&&(this.constraintIssueKey=issueKey,issue&&this.emit("lr-multi-split-constraints-invalid",issue));const panels=this.ownedPanels;for(const panel of panels){const snapshot=this.panelOwnership.get(panel);snapshot&&this.adoptPanelOwnership(panel,snapshot)}const collapsingIndex=this.collapseActive?this.collapsingIndex:-1,redistributedShare=new Array(panels.length).fill(0);if(collapsingIndex===-1){let freedPercent=0;const growableIndexes=[];let growableTotal=0;for(let i=0;i<panels.length;i++){const percent=this.sizes[i]??0,constraint=constraintResolution.usePanelConstraints?this.panelConstraints[i]:void 0;if(this.hasClampConstraint(constraint)){const bounds=constraintResolution.bounds[i],clamped=bounds?Math.min(Math.max(percent,bounds.min),bounds.max):percent;clamped<percent&&(freedPercent+=percent-clamped)}else growableIndexes.push(i),growableTotal+=percent}if(freedPercent>0&&growableTotal>0)for(const i of growableIndexes)redistributedShare[i]=freedPercent*((this.sizes[i]??0)/growableTotal)}panels.forEach((panel,i)=>{const snapshot=this.panelOwnership.get(panel);if(!snapshot)return;const percent=this.sizes[i]??0,constraint=constraintResolution.usePanelConstraints?this.panelConstraints[i]:void 0;if(this.applyOwnedPanelStyle(panel,snapshot,"inline-size",snapshot.styles.get("inline-size")),this.applyOwnedPanelHidden(panel,snapshot,snapshot.hidden),collapsingIndex===i&&this.collapseState==="rail")this.applyOwnedPanelStyleValue(panel,snapshot,"flex",`0 0 ${this.railWidth}`);else if(collapsingIndex===i&&this.collapseState==="floating"&&!this.open)this.applyOwnedPanelStyleValue(panel,snapshot,"flex","none"),this.applyOwnedPanelHidden(panel,snapshot,!0);else if(collapsingIndex===i&&this.collapseState==="floating")this.applyOwnedPanelStyleValue(panel,snapshot,"flex","none"),this.applyOwnedPanelStyleValue(panel,snapshot,"inline-size",`${percent}%`);else if(collapsingIndex!==-1&&i!==collapsingIndex)this.applyOwnedPanelStyleValue(panel,snapshot,"flex",this.hasClampConstraint(constraint)?`0 1 clamp(${this.minSideExpr(constraint)}, ${percent}%, ${this.maxSideExpr(constraint)})`:`${percent} 1 0%`);else{const adjustedPercent=percent+(redistributedShare[i]??0);this.applyOwnedPanelStyleValue(panel,snapshot,"flex",this.hasClampConstraint(constraint)?`0 1 clamp(${this.minSideExpr(constraint)}, ${percent}%, ${this.maxSideExpr(constraint)})`:`0 1 ${adjustedPercent}%`)}this.applyOwnedPanelStyleValue(panel,snapshot,"order",String(i*2)),collapsingIndex===i?this.applyOwnedPanelCollapseState(panel,snapshot,this.collapseState):this.applyOwnedPanelCollapseState(panel,snapshot,null)}),collapsingIndex!==-1?this.setAttribute("data-collapse-state",this.collapseState):this.removeAttribute("data-collapse-state"),this.justOpened&&(this.justOpened=!1,this.overlayHandle?.focusInitial())}render(){const dividers=[],bounds=this.resolveConstraintBounds(this.getContainerSize()).bounds;for(let i=0;i<this.panelCount-1;i++){const pairTotal=(this.sizes[i]??0)+(this.sizes[i+1]??0),a=bounds[i],b=bounds[i+1],valueMin=Math.max(a.min,pairTotal-b.max),valueMax=Math.max(valueMin,Math.min(a.max,pairTotal-b.min)),disabled=this.isDividerDisabled(i);dividers.push(html`<div
|
|
2
2
|
part="divider"
|
|
3
3
|
role="separator"
|
|
4
4
|
aria-label=${this.dividerLabel?this.dividerLabel(i,this.panelCount):this.localize("resizeDivider",void 0,{a:getNumberFormat(this.effectiveLocale).format(i+1),b:getNumberFormat(this.effectiveLocale).format(i+2)})}
|