@aceshooting/lyra-ui 14.3.2 → 15.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +103 -0
- package/custom-elements.json +1 -1
- package/design-tokens.json +1 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/agent-tools/activity-feed/activity-feed.class.d.ts +4 -0
- package/dist/components/agent-tools/activity-feed/activity-feed.class.js +3 -3
- package/dist/components/agent-tools/approval-queue/approval-queue.class.js +3 -2
- package/dist/components/agent-tools/artifact-panel/artifact-panel.styles.js +1 -1
- package/dist/components/agent-tools/commit-card/commit-card.styles.js +1 -1
- package/dist/components/agent-tools/compare-panel/compare-panel.styles.js +1 -1
- package/dist/components/agent-tools/confirm-bar/confirm-bar.class.js +8 -3
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.d.ts +3 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.class.js +10 -1
- package/dist/components/agent-tools/eval-dataset/eval-dataset.styles.js +1 -1
- package/dist/components/agent-tools/span-waterfall/span-waterfall.class.js +1 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.d.ts +19 -1
- package/dist/components/agent-tools/subagent-panel/subagent-panel.class.js +4 -4
- package/dist/components/agent-tools/subagent-panel/subagent-panel.styles.js +1 -1
- package/dist/components/agent-tools/task-list/task-list.class.d.ts +5 -0
- package/dist/components/agent-tools/task-list/task-list.class.js +3 -3
- package/dist/components/agent-tools/terminal/terminal.class.d.ts +1 -1
- package/dist/components/agent-tools/terminal/terminal.styles.js +1 -1
- package/dist/components/agent-tools/test-results/test-results.class.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.d.ts +10 -7
- package/dist/components/agent-tools/tool-param-form/tool-param-form.class.js +15 -14
- package/dist/components/agent-tools/tool-param-form/tool-param-form.d.ts +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.js +1 -1
- package/dist/components/agent-tools/tool-param-form/tool-param-form.styles.js +1 -1
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.d.ts +5 -2
- package/dist/components/agent-tools/tool-result-dialog/tool-result-dialog.class.js +1 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.d.ts +3 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.class.js +9 -1
- package/dist/components/agent-tools/tool-select-dialog/tool-select-dialog.styles.js +1 -1
- package/dist/components/charts/chart/box-plot.class.d.ts +64 -4
- package/dist/components/charts/chart/box-plot.class.js +5 -5
- package/dist/components/charts/chart/chart-colors.d.ts +10 -0
- package/dist/components/charts/chart/chart-colors.js +1 -1
- package/dist/components/charts/chart/chart.class.d.ts +35 -10
- package/dist/components/charts/chart/chart.class.js +4 -4
- package/dist/components/charts/chart/lite-chart.class.d.ts +10 -2
- package/dist/components/charts/chart/lite-chart.styles.js +1 -1
- package/dist/components/conversation/markdown/markdown.class.d.ts +9 -1
- package/dist/components/conversation/markdown/markdown.class.js +1 -1
- package/dist/components/conversation/message-parts/message-parts.class.d.ts +18 -1
- package/dist/components/conversation/message-parts/message-parts.class.js +4 -4
- package/dist/components/conversation/model-select/model-select.class.d.ts +6 -2
- package/dist/components/conversation/model-select/model-select.class.js +3 -3
- package/dist/components/conversation/prompt-input/prompt-input.styles.js +1 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.d.ts +5 -1
- package/dist/components/conversation/selection-toolbar/selection-toolbar.class.js +1 -1
- package/dist/components/data/calendar/calendar.class.js +2 -2
- package/dist/components/data/context-meter/context-meter.styles.js +1 -1
- package/dist/components/data/data-grid/data-grid-types.d.ts +8 -2
- package/dist/components/data/data-grid/data-grid.class.d.ts +16 -3
- package/dist/components/data/data-grid/data-grid.class.js +3 -2
- package/dist/components/data/env-list/env-list.styles.js +1 -1
- package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +22 -2
- package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
- package/dist/components/data/flow-minimap/flow-minimap.class.d.ts +12 -4
- package/dist/components/data/flow-minimap/flow-minimap.class.js +2 -2
- package/dist/components/data/flow-minimap/flow-minimap.styles.js +1 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.d.ts +5 -1
- package/dist/components/data/graph-query-builder/graph-query-builder.class.js +1 -1
- package/dist/components/data/heatmap/heatmap.class.d.ts +12 -1
- package/dist/components/data/heatmap/heatmap.class.js +3 -3
- package/dist/components/data/heatmap/heatmap.styles.js +1 -1
- package/dist/components/forms/code-editor/code-editor.class.js +1 -1
- package/dist/components/forms/combobox/combobox.class.js +1 -1
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/date-picker/date-input.class.js +1 -1
- package/dist/components/forms/date-picker/date-picker.class.d.ts +12 -1
- package/dist/components/forms/date-picker/date-picker.class.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +27 -5
- package/dist/components/forms/icon-button/icon-button.class.js +7 -3
- package/dist/components/forms/input/input.styles.js +1 -1
- package/dist/components/forms/input/time-input.class.d.ts +13 -2
- package/dist/components/forms/input/time-input.class.js +1 -1
- package/dist/components/forms/otp-input/otp-input.class.d.ts +8 -1
- package/dist/components/forms/otp-input/otp-input.class.js +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.d.ts +1 -1
- package/dist/components/forms/rubric-form/rubric-form.class.js +1 -1
- package/dist/components/forms/select/select.class.d.ts +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/forms/slider/slider.class.d.ts +4 -1
- package/dist/components/forms/slider/slider.class.js +1 -1
- package/dist/components/forms/textarea/textarea.class.d.ts +9 -4
- package/dist/components/forms/textarea/textarea.class.js +1 -1
- package/dist/components/forms/time-range/time-range.class.js +1 -1
- package/dist/components/layout/app-rail/app-rail.class.d.ts +7 -2
- package/dist/components/layout/app-rail/app-rail.class.js +1 -1
- package/dist/components/layout/card/card.class.js +2 -2
- package/dist/components/layout/card/card.styles.js +1 -1
- package/dist/components/layout/control-group/control-group.class.js +1 -1
- package/dist/components/layout/dashboard-grid/dashboard-grid.styles.js +1 -1
- package/dist/components/layout/details/details.styles.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.d.ts +13 -3
- package/dist/components/layout/filter-bar/filter-bar.class.js +1 -1
- package/dist/components/layout/menu/dropdown-item.class.d.ts +2 -0
- package/dist/components/layout/menu/menu-item.class.d.ts +28 -1
- package/dist/components/layout/menu/menu-item.class.js +45 -35
- package/dist/components/layout/menu/menu-item.styles.js +1 -1
- package/dist/components/layout/menu/menu.class.js +1 -1
- package/dist/components/layout/multi-split/multi-split.class.d.ts +12 -2
- package/dist/components/layout/multi-split/multi-split.class.js +1 -1
- package/dist/components/layout/page/page.class.js +2 -1
- package/dist/components/layout/page/page.styles.js +1 -1
- package/dist/components/layout/responsive-panel/responsive-panel.class.d.ts +6 -4
- package/dist/components/layout/responsive-panel/responsive-panel.class.js +2 -2
- package/dist/components/layout/responsive-panel/responsive-panel.styles.js +1 -1
- package/dist/components/layout/stepper/stepper.class.js +2 -2
- package/dist/components/layout/virtual-list/virtual-list.class.js +2 -2
- package/dist/components/layout/widget/widget.class.d.ts +12 -2
- package/dist/components/layout/widget/widget.class.js +2 -2
- package/dist/components/media/attachment-trigger/attachment-trigger.class.d.ts +1 -1
- package/dist/components/media/attachment-trigger/attachment-trigger.class.js +3 -3
- package/dist/components/media/file-icon/file-icon.class.d.ts +3 -1
- package/dist/components/media/file-icon/file-icon.class.js +1 -1
- package/dist/components/media/file-input/file-input.class.d.ts +1 -1
- package/dist/components/media/file-input/file-input.class.js +1 -1
- package/dist/components/media/flag/flag.styles.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.class.d.ts +5 -5
- package/dist/components/media/image-comparer/image-comparer.class.js +1 -1
- package/dist/components/media/image-comparer/image-comparer.styles.js +1 -1
- package/dist/components/media/lightbox/lightbox.styles.js +1 -1
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/media/sequence-playback/sequence-playback.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.class.js +1 -1
- package/dist/components/media/video-playlist/video-playlist.styles.js +1 -1
- package/dist/components/overlays/alert/alert.class.d.ts +6 -0
- package/dist/components/overlays/alert/alert.styles.js +1 -1
- package/dist/components/overlays/empty/empty.class.js +2 -2
- package/dist/components/overlays/kbd/kbd.styles.js +1 -1
- package/dist/components/overlays/progress/progress-ring.class.d.ts +4 -1
- package/dist/components/overlays/progress/progress.styles.js +1 -1
- package/dist/components/overlays/toast/toast.styles.js +1 -1
- package/dist/components/retrieval/graph/graph-canvas.js +1 -1
- package/dist/components/retrieval/graph/graph.class.d.ts +10 -3
- package/dist/components/retrieval/graph/graph.class.js +1 -1
- package/dist/components/retrieval/graph/graph.styles.js +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +1 -1
- package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +6 -6
- package/dist/components/retrieval/knowledge-base-admin/knowledge-base-admin.class.js +2 -2
- package/dist/components/retrieval/mind-map/mind-map.styles.js +1 -1
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.d.ts +3 -3
- package/dist/components/retrieval/neighbor-list/neighbor-list.class.js +3 -3
- package/dist/components/retrieval/node-palette/node-palette.class.d.ts +7 -1
- package/dist/components/retrieval/node-palette/node-palette.class.js +23 -13
- package/dist/components/retrieval/node-palette/node-palette.styles.js +1 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.d.ts +4 -1
- package/dist/components/retrieval/rag-eval-dashboard/rag-eval-dashboard.class.js +1 -1
- package/dist/components/retrieval/retrieval-results/retrieval-results.class.js +1 -1
- package/dist/components/retrieval/retrieval-search/retrieval-search.class.js +4 -3
- package/dist/components/retrieval/retrieval-trace/retrieval-trace.class.js +1 -1
- package/dist/components/retrieval/source-list/source-list.class.d.ts +7 -1
- package/dist/components/retrieval/source-list/source-list.class.js +1 -1
- package/dist/components/utility/export-button/export-button.class.d.ts +14 -2
- package/dist/components/utility/export-button/export-button.class.js +3 -3
- package/dist/components/utility/export-button/export-button.styles.js +1 -1
- package/dist/components/utility/json-viewer/json-viewer.styles.js +1 -1
- package/dist/components/utility/known-date/known-date.class.js +1 -1
- package/dist/components/utility/mention-popover/mention-popover.class.d.ts +4 -2
- package/dist/components/utility/mention-popover/mention-popover.class.js +1 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.d.ts +9 -1
- package/dist/components/viewers/csv-viewer/csv-viewer.class.js +4 -4
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.d.ts +1 -1
- package/dist/components/viewers/dataset-viewer/dataset-viewer.class.js +4 -4
- package/dist/components/viewers/document-compare/document-compare.class.d.ts +5 -0
- package/dist/components/viewers/document-compare/document-compare.class.js +9 -4
- package/dist/components/viewers/document-compare/document-compare.styles.js +1 -1
- package/dist/components/viewers/document-preview/document-preview.class.d.ts +9 -1
- package/dist/components/viewers/document-preview/document-preview.class.js +2 -1
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.d.ts +5 -0
- package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +1 -1
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +5 -0
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.d.ts +1 -1
- package/dist/components/viewers/spreadsheet-viewer/spreadsheet-viewer.class.js +3 -3
- package/dist/components/viewers/xml-viewer/xml-viewer.styles.js +1 -1
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +5 -4
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-alert.md +11 -3
- package/llms/components/lr-box-plot.md +21 -4
- package/llms/components/lr-chart.md +13 -4
- package/llms/components/lr-code-block.md +5 -4
- package/llms/components/lr-data-grid.md +24 -10
- package/llms/components/lr-document-compare.md +5 -0
- package/llms/components/lr-dropdown-item.md +24 -0
- package/llms/components/lr-eval-dataset.md +5 -4
- package/llms/components/lr-export-button.md +10 -5
- package/llms/components/lr-filter-bar.md +4 -1
- package/llms/components/lr-flow-minimap.md +7 -1
- package/llms/components/lr-icon-button.md +6 -1
- package/llms/components/lr-lite-chart.md +2 -1
- package/llms/components/lr-markdown.md +2 -2
- package/llms/components/lr-menu-item.md +24 -0
- package/llms/components/lr-menu.md +24 -0
- package/llms/components/lr-message-parts.md +7 -0
- package/llms/components/lr-model-settings-panel.md +4 -1
- package/llms/components/lr-node-palette.md +5 -4
- package/llms/components/lr-pdf-viewer.md +7 -0
- package/llms/components/lr-responsive-panel.md +2 -2
- package/llms/components/lr-subagent-panel.md +17 -2
- package/llms/components/lr-thinking-panel.md +4 -0
- package/llms/components/lr-timeline-item.md +1 -1
- package/llms/components/lr-timeline.md +1 -1
- package/llms/components/lr-tool-select-dialog.md +4 -3
- package/llms/components/lr-virtual-list.md +11 -11
- package/llms-full.txt +205 -59
- package/package.json +3 -3
- package/vscode-css-data.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{OrientationBreakpointController}from"../../../internal/orientation-breakpoint.js";import{isRtl}from"../../../internal/rtl.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{styles}from"./stepper.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";const STEP_STATES=new Set(["pending","current","completed","error"]),MAX_STEPS=256;function snapshotSteps(value){try{if(!Array.isArray(value))return Object.freeze([])}catch{return Object.freeze([])}const normalized=[];let length=0;try{length=Math.min(value.length,MAX_STEPS)}catch{return Object.freeze(normalized)}for(let index=0;index<length;index+=1)try{const candidate=value[index];if(!candidate||typeof candidate!="object")continue;const record=candidate,stepId=record.stepId,label=record.label,state=record.state,disabled=record.disabled,title=record.title,icon=record.icon;if(typeof stepId!="string"||stepId.length===0||stepId!==stepId.trim()||typeof label!="string"||label.trim()===""||typeof state!="string"||!STEP_STATES.has(state)||disabled!==void 0&&typeof disabled!="boolean"||title!==void 0&&typeof title!="string")continue;normalized.push(Object.freeze({stepId,label,state,...disabled!==void 0?{disabled}:{},...title!==void 0?{title}:{},...icon!==void 0?{icon}:{}}))}catch{}return Object.freeze(normalized)}const GLYPH_VIEW_BOX="0 0 24 24",GLYPH_STROKE_WIDTH="1.75";function checkmarkGlyph(){return html`<svg
|
|
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{repeat}from"lit/directives/repeat.js";import{LyraElement}from"../../../internal/lyra-element.js";import{OrientationBreakpointController}from"../../../internal/orientation-breakpoint.js";import{isRtl}from"../../../internal/rtl.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{styles}from"./stepper.styles.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{activeElementIn}from"../../../internal/active-element.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";const STEP_STATES=new Set(["pending","current","completed","error"]),MAX_STEPS=256;function snapshotSteps(value){try{if(!Array.isArray(value))return Object.freeze([])}catch{return Object.freeze([])}const normalized=[];let length=0;try{length=Math.min(value.length,MAX_STEPS)}catch{return Object.freeze(normalized)}for(let index=0;index<length;index+=1)try{const candidate=value[index];if(!candidate||typeof candidate!="object")continue;const record=candidate,stepId=record.stepId,label=record.label,state=record.state,disabled=record.disabled,title=record.title,icon=record.icon;if(typeof stepId!="string"||stepId.length===0||stepId!==stepId.trim()||typeof label!="string"||label.trim()===""||typeof state!="string"||!STEP_STATES.has(state)||disabled!==void 0&&typeof disabled!="boolean"||title!==void 0&&typeof title!="string")continue;normalized.push(Object.freeze({stepId,label,state,...disabled!==void 0?{disabled}:{},...title!==void 0?{title}:{},...icon!==void 0?{icon}:{}}))}catch{}return Object.freeze(normalized)}const GLYPH_VIEW_BOX="0 0 24 24",GLYPH_STROKE_WIDTH="1.75";function checkmarkGlyph(){return html`<svg
|
|
2
2
|
part="step-check"
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -12,7 +12,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
12
12
|
focusable="false"
|
|
13
13
|
>
|
|
14
14
|
<polyline points="5 12.5 10 17.5 19 6.5"></polyline>
|
|
15
|
-
</svg>`}class LyraStepper extends LyraElement{constructor(){super(...arguments),this.effectiveSteps=Object.freeze([]),this.orientation="horizontal",this.orientationBreakpointBasis="container",this.narrowOrientation="vertical",this.wrapLabels=!1,this.accessibleLabel=null,this._effectiveOrientation="horizontal",this.resizeObserverGeneration=0,this.measuredInlineSize=Number.POSITIVE_INFINITY,this.orientationBreakpoints=new OrientationBreakpointController(this,()=>this.updateEffectiveOrientation(this.baseEl?.clientWidth??this.measuredInlineSize,!0)),this.scrollOverflow=observeScrollOverflow(this,()=>this.baseEl),this.onKeyDown=e=>{const navigable=this.steps.map((step,index)=>({step,index})).filter(({step})=>!step.disabled);if(navigable.length===0)return;const focused=activeElementIn(this.renderRoot),focusedIndex=Number(focused?.dataset.index),currentIndex=navigable.findIndex(item=>item.index===focusedIndex),vertical=this.effectiveOrientation==="vertical",rtl=!vertical&&isRtl(this),forwardKey=vertical?"ArrowDown":rtl?"ArrowLeft":"ArrowRight",backwardKey=vertical?"ArrowUp":rtl?"ArrowRight":"ArrowLeft";let targetIndex;switch(e.key){case forwardKey:targetIndex=Math.min(navigable.length-1,(currentIndex<0?-1:currentIndex)+1);break;case backwardKey:targetIndex=Math.max(0,(currentIndex<0?1:currentIndex)-1);break;case"Home":targetIndex=0;break;case"End":targetIndex=navigable.length-1;break;case"Enter":case" ":if(e.preventDefault(),currentIndex>=0){const target=navigable[currentIndex];this.selectStep(target.step,target.index)}return;default:return}e.preventDefault(),this.focusStep(navigable[targetIndex].index)}}static{this.styles=[LyraElement.styles,styles]}get steps(){return this.effectiveSteps}set steps(value){const previous=this.effectiveSteps;this.effectiveSteps=snapshotSteps(value),this.requestUpdate("steps",previous)}get effectiveOrientation(){return this._effectiveOrientation}connectedCallback(){super.connectedCallback();const hostWidth=this.getBoundingClientRect().width;hostWidth>0&&(this.measuredInlineSize=hostWidth),this.orientationBreakpoints.containerObservationEnabled&&this.armResizeObserver()}disconnectedCallback(){super.disconnectedCallback(),this.resetResizeObserver()}adoptedCallback(){super.adoptedCallback(),this.resetResizeObserver()}firstUpdated(changed){super.firstUpdated(changed),this.orientationBreakpoints.containerObservationEnabled&&this.armResizeObserver()}willUpdate(changed){if(super.willUpdate(changed),changed.has("steps")){const focusedStep=activeElementIn(this.renderRoot);focusedStep?.getAttribute("part")==="step"&&(this.pendingStepFocus={stepId:focusedStep.dataset.stepId??"",index:Number(focusedStep.dataset.index)})}(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.baseEl?.clientWidth??this.measuredInlineSize,this.hasUpdated&&this.orientationBreakpointBasis==="viewport")}updated(changed){
|
|
15
|
+
</svg>`}class LyraStepper extends LyraElement{constructor(){super(...arguments),this.effectiveSteps=Object.freeze([]),this.orientation="horizontal",this.orientationBreakpointBasis="container",this.narrowOrientation="vertical",this.wrapLabels=!1,this.accessibleLabel=null,this._effectiveOrientation="horizontal",this.resizeObserverGeneration=0,this.measuredInlineSize=Number.POSITIVE_INFINITY,this.orientationBreakpoints=new OrientationBreakpointController(this,()=>this.updateEffectiveOrientation(this.baseEl?.clientWidth??this.measuredInlineSize,!0)),this.scrollOverflow=observeScrollOverflow(this,()=>this.baseEl),this.onKeyDown=e=>{const navigable=this.steps.map((step,index)=>({step,index})).filter(({step})=>!step.disabled);if(navigable.length===0)return;const focused=activeElementIn(this.renderRoot),focusedIndex=Number(focused?.dataset.index),currentIndex=navigable.findIndex(item=>item.index===focusedIndex),vertical=this.effectiveOrientation==="vertical",rtl=!vertical&&isRtl(this),forwardKey=vertical?"ArrowDown":rtl?"ArrowLeft":"ArrowRight",backwardKey=vertical?"ArrowUp":rtl?"ArrowRight":"ArrowLeft";let targetIndex;switch(e.key){case forwardKey:targetIndex=Math.min(navigable.length-1,(currentIndex<0?-1:currentIndex)+1);break;case backwardKey:targetIndex=Math.max(0,(currentIndex<0?1:currentIndex)-1);break;case"Home":targetIndex=0;break;case"End":targetIndex=navigable.length-1;break;case"Enter":case" ":if(e.preventDefault(),currentIndex>=0){const target=navigable[currentIndex];this.selectStep(target.step,target.index)}return;default:return}e.preventDefault(),this.focusStep(navigable[targetIndex].index)}}static{this.styles=[LyraElement.styles,styles]}get steps(){return this.effectiveSteps}set steps(value){const previous=this.effectiveSteps;this.effectiveSteps=snapshotSteps(value),this.requestUpdate("steps",previous)}get effectiveOrientation(){return this._effectiveOrientation}connectedCallback(){super.connectedCallback();const hostWidth=this.getBoundingClientRect().width;hostWidth>0&&(this.measuredInlineSize=hostWidth),this.orientationBreakpoints.containerObservationEnabled&&this.armResizeObserver()}disconnectedCallback(){super.disconnectedCallback(),this.resetResizeObserver()}adoptedCallback(){super.adoptedCallback(),this.resetResizeObserver()}firstUpdated(changed){super.firstUpdated(changed),this.orientationBreakpoints.containerObservationEnabled&&this.armResizeObserver()}willUpdate(changed){if(super.willUpdate(changed),changed.has("steps")){const focusedStep=activeElementIn(this.renderRoot);focusedStep?.getAttribute("part")==="step"&&(this.pendingStepFocus={stepId:focusedStep.dataset.stepId??"",index:Number(focusedStep.dataset.index)})}(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.baseEl?.clientWidth??this.measuredInlineSize,this.hasUpdated&&this.orientationBreakpointBasis==="viewport")}updated(changed){super.updated(changed);const base=this.renderRoot.querySelector('[part~="base"]')??void 0;if(syncAriaDescribedByElements(this,base,this.getAttribute("aria-describedby")),this.scrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="step"]')),this.pendingStepFocus!==void 0){const focusedOccurrence=this.pendingStepFocus;this.pendingStepFocus=void 0;const enabledIdentityMatches=[...this.renderRoot.querySelectorAll('[part="step"]')].filter(step=>step.dataset.stepId===focusedOccurrence.stepId&&step.getAttribute("aria-disabled")!=="true");(enabledIdentityMatches.find(step=>Number(step.dataset.index)===focusedOccurrence.index)??(enabledIdentityMatches.length===1?enabledIdentityMatches[0]:void 0)??this.renderRoot.querySelector('[part="step"][tabindex="0"]'))?.focus()}(changed.has("orientationBreakpoint")||changed.has("orientationBreakpointBasis"))&&(this.orientationBreakpoints.containerObservationEnabled?this.armResizeObserver():this.resetResizeObserver())}updateEffectiveOrientation(width,emitOnChange){const next=this.orientationBreakpoints.isBelow(width)?this.narrowOrientation:this.orientation;this.orientationBreakpoints.active?this.setAttribute("data-effective-orientation",next):this.removeAttribute("data-effective-orientation"),next!==this._effectiveOrientation&&(this._effectiveOrientation=next,this.requestUpdate(),emitOnChange&&this.emit("lr-stepper-orientation-change",{orientation:next}))}armResizeObserver(){const observedElement=this.baseEl;if(!this.isConnected||!observedElement)return;const ownerDocument=this.ownerDocument;if(this.resizeObserver&&this.resizeObservedElement===observedElement&&this.resizeObserverOwnerDocument===ownerDocument)return;this.resetResizeObserver();const ResizeObserverConstructor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverConstructor)return;const generation=this.resizeObserverGeneration,observer=new ResizeObserverConstructor(entries=>{if(this.resizeObserver!==observer||this.resizeObserverGeneration!==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.updateEffectiveOrientation(width,!0)});this.resizeObserver=observer,this.resizeObservedElement=observedElement,this.resizeObserverOwnerDocument=ownerDocument,observer.observe(observedElement)}resetResizeObserver(){this.resizeObserverGeneration+=1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObservedElement=void 0,this.resizeObserverOwnerDocument=void 0}selectStep(step,index){step.disabled||this.emit("lr-step-select",{stepId:step.stepId,index})}focusStep(index){this.renderRoot.querySelector(`[part="step"][data-index="${index}"]`)?.focus()}render(){const currentIndex=this.steps.findIndex(step=>step.state==="current"),rovingIndex=currentIndex>=0&&!this.steps[currentIndex].disabled?currentIndex:this.steps.findIndex(step=>!step.disabled),numberFormat=getNumberFormat(this.effectiveLocale);return html`
|
|
16
16
|
<div
|
|
17
17
|
part="base"
|
|
18
18
|
role="list"
|
|
@@ -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{prefersReducedMotion}from"../../../internal/motion.js";import{finiteAdd,finiteCount,finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./virtual-list.styles.js";const DEFAULT_ROW_ESTIMATE_PX=48,DEFAULT_GROUP_ESTIMATE_PX=32,DEFAULT_OVERSCAN_ROWS=6,MAX_OVERSCAN_ROWS=100,MAX_VIRTUAL_LIST_GROUPS=1e4,EMPTY_VIRTUAL_LIST_GROUPS=Object.freeze([]);function normalizeOverscan(value){if(value===null)return DEFAULT_OVERSCAN_ROWS;const numeric=typeof value=="number"?value:Number(value);return Number.isFinite(numeric)?Math.min(MAX_OVERSCAN_ROWS,Math.max(0,Math.floor(numeric))):DEFAULT_OVERSCAN_ROWS}const overscanConverter={fromAttribute(value){return normalizeOverscan(value)}};function normalizeRowHeight(value){if(value==="auto")return"auto";const numeric=typeof value=="number"?value:Number(value);return Number.isFinite(numeric)&&numeric>0?numeric:"auto"}const rowHeightConverter={fromAttribute(value){return value===null?"auto":normalizeRowHeight(value)}};function isIndexedSource(source){return!Array.isArray(source)}function domKeyToken(key){if(typeof key=="number"){if(Number.isNaN(key))return"number:NaN";if(Object.is(key,-0))return"number:-0"}return`${typeof key}:${String(key)}`}class LyraVirtualList extends LyraElement{constructor(){super(...arguments),this.items=[],this.renderItem=()=>nothing,this.rowHeight="auto",this.itemRole="listitem",this.rowIndexOffset=0,this.overscan=DEFAULT_OVERSCAN_ROWS,this.activeItemId="",this.loading=!1,this.hasMore=!1,this.containerScrollTop=0,this.viewportHeight=0,this.renderUnmeasuredWindow=!0,this.offsets=[0],this.rowIdentities=[],this.fixedRowHeight=null,this.measuredHeights=new Map,this.measuredIndices=new Map,this.indexedMeasurementIndices=[],this.indexedMeasurementDeltaPrefix=[0],this.indexedMeasurementIndexDirty=!0,this.offsetsDirty=!0,this.itemsChangedPendingPrune=!1,this.renderStart=0,this.renderEnd=-1,this.visibleStart=0,this.visibleEnd=-1,this.lastEmittedStart=-1,this.lastEmittedEnd=-1,this.loadMoreArmed=!0,this.measurementGeneration=0,this.isFirstUpdate=!0,this.stickyHeight=0,this.observedRows=new Map,this.observedRowKeys=new WeakMap,this.observedRowIndices=new WeakMap,this.observedGroups=new Map,this.observedGroupIndices=new WeakMap,this.ownerRealmGeneration=0,this.inResizeDelivery=!1,this.deferredRowObservations=new Map,this.deferredGroupObservations=new Map,this.activeIndexForLength=-1,this.activeIndexForId="",this.activeIndexCache=-1,this.pendingScrollTop=null,this.normalizedGroups=EMPTY_VIRTUAL_LIST_GROUPS,this.normalizedGroupByIndex=new Map,this.measuredGroupHeights=new Map,this.groupHeightPrefix=[0],this.onUserScrollIntent=event=>{event instanceof KeyboardEvent&&!new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]).has(event.key)||(this.pendingScrollCorrection=void 0)},this.onScroll=e=>{if(this.pendingScrollTop=e.currentTarget.scrollTop,this.scrollRafId!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{if(!(this.scrollRafId!==handle||this.scrollRafOwner!==ownerWindow||this.scrollRafDocument!==ownerDocument||!this.isCurrentOwnerWork(ownerDocument,generation))&&(this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0,this.pendingScrollTop!==null)){const scrollTop=this.pendingScrollTop;this.pendingScrollTop=null;const moved=this.containerScrollTop!==scrollTop;this.containerScrollTop=scrollTop,moved&&this.emit("lr-virtual-scroll",{scrollTop,viewportHeight:this.viewportHeight})}});this.scrollRafId=handle,this.scrollRafOwner=ownerWindow,this.scrollRafDocument=ownerDocument},this.onRowsResized=entries=>{if(this.beginResizeDelivery(),this.fixedRowHeight!=null)return;const base=this.scrollContainer,oldScrollTop=base?.scrollTop??this.containerScrollTop;let scrollAdjustment=0,changed=!1;for(const entry of entries){const row=entry.target,key=this.observedRowKeys.get(row),index=this.observedRowIndices.get(row);if(key===void 0||index===void 0)continue;const height=entry.borderBoxSize?.[0]?.blockSize??entry.target.getBoundingClientRect().height,prev=this.measuredHeights.get(key);if(prev===void 0||Math.abs(prev-height)>.5){const oldBottom=this.rowBottomAt(index);this.measuredHeights.set(key,height),this.measuredIndices.set(key,index);const oldHeight=prev??DEFAULT_ROW_ESTIMATE_PX;oldBottom<=oldScrollTop&&(scrollAdjustment+=height-oldHeight),changed=!0}}if(changed){if(this.indexedMeasurementIndexDirty=!0,base&&scrollAdjustment!==0){const nextScrollTop=Math.max(0,oldScrollTop+scrollAdjustment);base.scrollTop=nextScrollTop,this.containerScrollTop=nextScrollTop,this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,this.requestUpdate()}},this.onGroupsResized=entries=>{this.beginResizeDelivery();const base=this.scrollContainer,oldScrollTop=base?.scrollTop??this.containerScrollTop;let scrollAdjustment=0,changed=!1;for(const entry of entries){const marker=entry.target,index=this.observedGroupIndices.get(marker);if(index===void 0||!this.normalizedGroupByIndex.has(index))continue;const height=entry.borderBoxSize?.[0]?.blockSize??entry.target.getBoundingClientRect().height;if(!Number.isFinite(height)||height<0)continue;const previous=this.measuredGroupHeights.get(index)??DEFAULT_GROUP_ESTIMATE_PX;if(Math.abs(previous-height)<=.5)continue;const oldRowTop=this.offsetAt(index);this.measuredGroupHeights.set(index,height),oldRowTop<=oldScrollTop&&(scrollAdjustment+=height-previous),changed=!0}if(changed){if(base&&scrollAdjustment!==0){const nextScrollTop=Math.max(0,oldScrollTop+scrollAdjustment);base.scrollTop=nextScrollTop,this.containerScrollTop=nextScrollTop,this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,this.requestUpdate()}},this.onStickyResized=entries=>{this.beginResizeDelivery();const entry=entries[0];if(!entry)return;const height=entry.borderBoxSize?.[0]?.blockSize??entry.contentRect.height;Math.abs(this.stickyHeight-height)>.5&&(this.stickyHeight=height)}}static{this.ownedCollectionProperties=Object.freeze(["items","source","groups"])}static{this.identityCollectionProperties=Object.freeze(["items","source"])}static{this.identityCollectionObjectProperties=Object.freeze(["source"])}static{this.styles=[LyraElement.styles,styles]}get scrollContainer(){return this.renderRoot?.querySelector('[part="base"]')??void 0}get renderedRows(){const root=this.renderRoot;return root?[...root.querySelectorAll('[part="row"]')]:[]}get safeRowIndexOffset(){return finiteCount(this.rowIndexOffset)}computedAriaRowIndex(index){return finiteInteger(finiteAdd(index+1,this.safeRowIndexOffset),1,1,Number.MAX_SAFE_INTEGER)}get activeIndex(){if(this.activeItemId==="")return-1;const source=this.effectiveSource,count=this.itemCount;if(this.activeIndexFor===source&&this.activeIndexForLength===count&&Object.is(this.activeIndexForId,this.activeItemId)&&this.activeIndexForKeyFn===this.keyFunction)return this.activeIndexCache;if(this.activeIndexFor=source,this.activeIndexForLength=count,this.activeIndexForId=this.activeItemId,this.activeIndexForKeyFn=this.keyFunction,this.activeIndexCache=-1,isIndexedSource(source)){if(!this.keyFunction&&source.indexOfKey){const candidate=source.indexOfKey(this.activeItemId);Number.isInteger(candidate)&&candidate>=0&&candidate<count&&(this.activeIndexCache=candidate)}return this.activeIndexCache}for(let index=0;index<count;index++){const item=this.itemAt(index);if(Object.is(this.keyOf(item,index),this.activeItemId)){this.activeIndexCache=index;break}}return this.activeIndexCache}connectedCallback(){super.connectedCallback(),this.ownerDocument.defaultView&&this.seedFirstRenderState(()=>{this.renderUnmeasuredWindow=!1,this.requestUpdate()}),this.resetOwnerRealmWork();const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView,generation=this.ownerRealmGeneration,ResizeObserverCtor=ownerWindow?.ResizeObserver;if(ResizeObserverCtor){const rowObserver=new ResizeObserverCtor(entries=>{this.rowResizeObserver!==rowObserver||!this.isCurrentOwnerWork(ownerDocument,generation)||this.onRowsResized(entries)}),groupObserver=new ResizeObserverCtor(entries=>{this.groupResizeObserver!==groupObserver||!this.isCurrentOwnerWork(ownerDocument,generation)||this.onGroupsResized(entries)}),stickyObserver=new ResizeObserverCtor(entries=>{this.stickyResizeObserver!==stickyObserver||!this.isCurrentOwnerWork(ownerDocument,generation)||this.onStickyResized(entries)});this.rowResizeObserver=rowObserver,this.groupResizeObserver=groupObserver,this.stickyResizeObserver=stickyObserver}this.hasUpdated&&(this.attachContainerListeners(),this.syncRowObservers(),this.syncGroupObservers(),this.syncStickyOverlay())}disconnectedCallback(){this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}isCurrentOwnerWork(ownerDocument,generation){return this.ownerRealmGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.rowResizeObserver?.disconnect(),this.rowResizeObserver=void 0,this.groupResizeObserver?.disconnect(),this.groupResizeObserver=void 0,this.observedRows.clear(),this.observedGroups.clear(),this.deferredRowObservations.clear(),this.deferredGroupObservations.clear(),this.inResizeDelivery=!1,this.rowObserveRafId!==void 0&&this.rowObserveRafOwner?.cancelAnimationFrame(this.rowObserveRafId),this.rowObserveRafId=void 0,this.rowObserveRafOwner=void 0,this.rowObserveRafDocument=void 0,this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0,this.stickyResizeObserver?.disconnect(),this.stickyResizeObserver=void 0,this.observedSticky=void 0,this.scrollRafId!==void 0&&this.scrollRafOwner?.cancelAnimationFrame(this.scrollRafId),this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0,this.pendingScrollTop=null,this.pendingScrollCorrection=void 0,this.detachContainerListeners(),this.scrollListenerTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.attachContainerListeners()}willUpdate(changed){super.willUpdate(changed),this.isFirstUpdate=!this.hasUpdated,(changed.has("items")||changed.has("source")||changed.has("keyFunction")||changed.has("rowHeight")||changed.has("groups")||changed.has("activeItemId"))&&(this.pendingScrollCorrection=void 0),(changed.has("items")||changed.has("source")||changed.has("rowHeight")||changed.has("keyFunction")||changed.has("groups"))&&(this.offsetsDirty=!0),(changed.has("items")||changed.has("source"))&&(this.itemsChangedPendingPrune=!0),isIndexedSource(this.effectiveSource)&&(changed.has("items")||changed.has("source")||changed.has("keyFunction"))&&(this.measuredHeights.clear(),this.measuredIndices.clear(),this.indexedMeasurementIndexDirty=!0),changed.has("groups")&&this.measuredGroupHeights.clear(),(changed.has("items")||changed.has("source")||changed.has("groups"))&&this.recomputeGroups(),changed.has("rowHeight")&&(this.fixedRowHeight=this.parseRowHeight(this.rowHeight),this.fixedRowHeight!=null&&(this.measuredHeights.clear(),this.measuredIndices.clear(),this.indexedMeasurementIndexDirty=!0)),this.offsetsDirty&&(this.recomputeOffsets(),this.offsetsDirty=!1),this.computeRange()}updated(changed){super.updated(changed),this.syncRowObservers(),this.syncGroupObservers(),this.syncStickyOverlay(),changed.has("activeItemId")&&!this.isFirstUpdate&&this.scrollActiveIntoView(),this.emitRangeChangeIfNeeded(),this.maybeFireLoadMore(),this.maybeCorrectPendingScroll()}parseRowHeight(value){const normalized=normalizeRowHeight(value);return normalized==="auto"?null:normalized}get effectiveSource(){return this.source??this.items}get itemCount(){const source=this.effectiveSource;return isIndexedSource(source)?finiteCount(source.count):source.length}itemAt(index){const source=this.effectiveSource;return isIndexedSource(source)?source.itemAt(index):source[index]}keyOf(item,index){const source=this.effectiveSource,key=this.keyFunction?this.keyFunction(item,index):isIndexedSource(source)?source.keyAt?.(index)??index:index;return typeof key=="string"||typeof key=="number"?key:index}rowIdentity(key,occurrence){const token=domKeyToken(key);return`${token.length}:${token}:${occurrence}`}identityAt(index,item=this.itemAt(index)){return isIndexedSource(this.effectiveSource)?this.rowIdentity(this.keyOf(item,index),index):this.rowIdentities[index]??this.rowIdentity(this.keyOf(item,index),index)}groupHeightAt(index){const group=this.normalizedGroupByIndex.get(index);return!group||group.label===""?0:this.measuredGroupHeights.get(index)??DEFAULT_GROUP_ESTIMATE_PX}rowHeightAt(index){return this.fixedRowHeight!=null?this.fixedRowHeight:this.measuredHeights.get(this.identityAt(index))??DEFAULT_ROW_ESTIMATE_PX}groupContributionThrough(index){let low=0,high=this.normalizedGroups.length;for(;low<high;){const middle=low+high>>1;this.normalizedGroups[middle].startIndex<=index?low=middle+1:high=middle}return this.groupHeightPrefix[low]??0}recomputeGroupHeightPrefix(){const prefix=new Array(this.normalizedGroups.length+1);prefix[0]=0;for(let index=0;index<this.normalizedGroups.length;index++){const group=this.normalizedGroups[index],height=group.label===""?0:this.measuredGroupHeights.get(group.startIndex)??DEFAULT_GROUP_ESTIMATE_PX;prefix[index+1]=finiteAdd(prefix[index],height)}this.groupHeightPrefix=prefix}indexedOffsetForIndex(index){const baseHeight=this.fixedRowHeight??DEFAULT_ROW_ESTIMATE_PX;let offset=index>Number.MAX_VALUE/baseHeight?Number.MAX_VALUE:index*baseHeight;if(this.fixedRowHeight==null){this.rebuildIndexedMeasurementIndex();let low=0,high=this.indexedMeasurementIndices.length;for(;low<high;){const middle=low+high>>1;this.indexedMeasurementIndices[middle]<index?low=middle+1:high=middle}offset=finiteAdd(offset,this.indexedMeasurementDeltaPrefix[low]??0)}return Math.max(0,finiteAdd(offset,this.groupContributionThrough(index)))}rebuildIndexedMeasurementIndex(){if(!this.indexedMeasurementIndexDirty)return;const retained=[];for(const[identity,index]of this.measuredIndices){const height=this.measuredHeights.get(identity);height!==void 0&&retained.push({index,delta:height-DEFAULT_ROW_ESTIMATE_PX})}retained.sort((a,b)=>a.index-b.index);const indices=new Array(retained.length),prefix=new Array(retained.length+1);prefix[0]=0;for(let position=0;position<retained.length;position++){const measurement=retained[position];indices[position]=measurement.index,prefix[position+1]=finiteAdd(prefix[position],measurement.delta)}this.indexedMeasurementIndices=indices,this.indexedMeasurementDeltaPrefix=prefix,this.indexedMeasurementIndexDirty=!1}pruneIndexedMeasurements(){if(!isIndexedSource(this.effectiveSource)||this.fixedRowHeight!=null||this.renderEnd<this.renderStart)return!1;const renderedCount=this.renderEnd-this.renderStart+1,retentionRows=Math.max(renderedCount,normalizeOverscan(this.overscan)*4),firstRetained=Math.max(0,this.renderStart-retentionRows),lastRetained=Math.min(this.itemCount-1,this.renderEnd+retentionRows);let removedDeltaBeforeWindow=0,pruned=!1;for(const[identity,measuredIndex]of this.measuredIndices)if(measuredIndex<firstRetained||measuredIndex>lastRetained){const height=this.measuredHeights.get(identity);height!==void 0&&measuredIndex<firstRetained&&(removedDeltaBeforeWindow=finiteAdd(removedDeltaBeforeWindow,height-DEFAULT_ROW_ESTIMATE_PX)),this.measuredIndices.delete(identity),this.measuredHeights.delete(identity),pruned=!0}if(pruned&&(this.indexedMeasurementIndexDirty=!0,removedDeltaBeforeWindow!==0)){const base=this.scrollContainer,oldScrollTop=base?.scrollTop??this.containerScrollTop,nextScrollTop=Math.max(0,oldScrollTop-removedDeltaBeforeWindow);base&&(base.scrollTop=nextScrollTop),this.containerScrollTop=nextScrollTop,this.pendingScrollTop=null}return pruned}offsetAt(index){return isIndexedSource(this.effectiveSource)?this.indexedOffsetForIndex(index):this.offsets[index]??0}recomputeOffsets(){const n=this.itemCount;if(this.recomputeGroupHeightPrefix(),isIndexedSource(this.effectiveSource)){this.offsets=[0],this.rowIdentities=[],this.itemsChangedPendingPrune=!1;return}const offsets=new Array(n+1);let cursor=0;const liveKeys=this.itemsChangedPendingPrune&&this.fixedRowHeight==null?new Set:null,occurrences=new Map,identities=new Array(n);for(let i=0;i<n;i++){cursor=finiteAdd(cursor,this.groupHeightAt(i)),offsets[i]=cursor;const key=this.keyOf(this.itemAt(i),i),token=domKeyToken(key),occurrence=occurrences.get(token)??0;occurrences.set(token,occurrence+1);const identity=this.rowIdentity(key,occurrence);identities[i]=identity;let h;this.fixedRowHeight!=null?h=this.fixedRowHeight:(liveKeys?.add(identity),h=this.measuredHeights.get(identity)??DEFAULT_ROW_ESTIMATE_PX),cursor=finiteAdd(cursor,h)}if(offsets[n]=cursor,this.offsets=offsets,this.rowIdentities=identities,this.itemsChangedPendingPrune=!1,liveKeys){for(const key of this.measuredHeights.keys())liveKeys.has(key)||(this.measuredHeights.delete(key),this.measuredIndices.delete(key),this.indexedMeasurementIndexDirty=!0);for(const key of this.measuredIndices.keys())liveKeys.has(key)||(this.measuredIndices.delete(key),this.indexedMeasurementIndexDirty=!0)}}groupTopAt(index){return Math.max(0,this.offsetAt(index)-this.groupHeightAt(index))}rowBottomAt(index){return finiteAdd(this.offsetAt(index),this.rowHeightAt(index))}entryTopAt(index){return this.groupTopAt(index)}findIndexAtOrAfter(offset){let lo=0,hi=this.itemCount-1;for(;lo<hi;){const mid=lo+Math.floor((hi-lo)/2);this.rowBottomAt(mid)<=offset?lo=mid+1:hi=mid}return lo}findIndexAtOrBefore(offset){let lo=0,hi=this.itemCount-1;for(;lo<hi;){const mid=lo+Math.ceil((hi-lo)/2);this.entryTopAt(mid)<offset?lo=mid:hi=mid-1}return lo}offsetForIndex(index){const clamped=Math.min(this.itemCount,Math.max(0,Math.trunc(index)||0));return this.offsetAt(clamped)}indexAtOffset(px){const n=this.itemCount;return n===0?-1:Number.isFinite(px)?Math.min(n-1,Math.max(0,this.findIndexAtOrAfter(px))):px>0?n-1:0}computeRange(){const n=this.itemCount;if(n===0){this.visibleStart=0,this.visibleEnd=-1,this.renderStart=0,this.renderEnd=-1;return}if(this.viewportHeight<=0){if(!this.renderUnmeasuredWindow){this.visibleStart=0,this.visibleEnd=-1,this.renderStart=0,this.renderEnd=-1;return}this.visibleStart=0,this.visibleEnd=0,this.renderStart=0,this.renderEnd=Math.min(n-1,normalizeOverscan(this.overscan));return}const viewTop=this.containerScrollTop,viewBottom=viewTop+this.viewportHeight;this.visibleStart=this.findIndexAtOrAfter(viewTop),this.visibleEnd=this.findIndexAtOrBefore(viewBottom);const overscan=normalizeOverscan(this.overscan);this.renderStart=Math.max(0,this.visibleStart-overscan),this.renderEnd=Math.min(n-1,this.visibleEnd+overscan),this.pruneIndexedMeasurements()&&this.computeRange()}attachContainerListeners(){const base=this.scrollContainer,ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!base||!this.isConnected||!ownerWindow)return;this.containerResizeObserver?.disconnect(),this.detachContainerListeners();const generation=this.ownerRealmGeneration,ResizeObserverCtor=ownerWindow.ResizeObserver;if(ResizeObserverCtor){const observer=new ResizeObserverCtor(entries=>{if(this.containerResizeObserver!==observer||this.scrollListenerTarget!==base||!this.isCurrentOwnerWork(ownerDocument,generation))return;this.beginResizeDelivery();const entry=entries[0];entry&&(this.viewportHeight=entry.borderBoxSize?.[0]?.blockSize??entry.contentRect.height)});this.containerResizeObserver=observer,observer.observe(base)}else this.containerResizeObserver=void 0;base.addEventListener("scroll",this.onScroll,{passive:!0}),base.addEventListener("wheel",this.onUserScrollIntent,{passive:!0}),base.addEventListener("pointerdown",this.onUserScrollIntent,{passive:!0}),base.addEventListener("touchstart",this.onUserScrollIntent,{passive:!0}),base.addEventListener("keydown",this.onUserScrollIntent),this.scrollListenerTarget=base,ownerWindow.queueMicrotask(()=>{if(this.scrollListenerTarget!==base||this.scrollContainer!==base||!this.isCurrentOwnerWork(ownerDocument,generation))return;const viewportHeight=base.clientHeight,scrollTop=base.scrollTop;this.viewportHeight!==viewportHeight&&(this.viewportHeight=viewportHeight),this.containerScrollTop!==scrollTop&&(this.containerScrollTop=scrollTop)})}detachContainerListeners(){const target=this.scrollListenerTarget;target&&(target.removeEventListener("scroll",this.onScroll),target.removeEventListener("wheel",this.onUserScrollIntent),target.removeEventListener("pointerdown",this.onUserScrollIntent),target.removeEventListener("touchstart",this.onUserScrollIntent),target.removeEventListener("keydown",this.onUserScrollIntent))}beginResizeDelivery(){if(this.inResizeDelivery=!0,this.rowObserveRafId!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected){this.inResizeDelivery=!1;return}const generation=this.ownerRealmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{if(this.rowObserveRafId!==handle||this.rowObserveRafOwner!==ownerWindow||this.rowObserveRafDocument!==ownerDocument||!this.isCurrentOwnerWork(ownerDocument,generation))return;this.rowObserveRafId=void 0,this.rowObserveRafOwner=void 0,this.rowObserveRafDocument=void 0,this.inResizeDelivery=!1;const ro=this.rowResizeObserver;for(const[identity,el]of this.deferredRowObservations)ro&&this.observedRows.get(identity)===el&&ro.observe(el);this.deferredRowObservations.clear();const groupObserver=this.groupResizeObserver;for(const[index,el]of this.deferredGroupObservations)groupObserver&&this.observedGroups.get(index)===el&&groupObserver.observe(el);this.deferredGroupObservations.clear()});this.rowObserveRafId=handle,this.rowObserveRafOwner=ownerWindow,this.rowObserveRafDocument=ownerDocument}syncRowObservers(){const ro=this.rowResizeObserver;if(!ro)return;if(this.fixedRowHeight!=null){for(const el of this.observedRows.values())ro.unobserve(el);this.observedRows.clear(),this.deferredRowObservations.clear();return}const current=new Map;this.renderRoot.querySelectorAll('[part="row"]').forEach(el=>{const index=Number(el.getAttribute("data-row-index"));if(!Number.isInteger(index)||index<0||index>=this.itemCount)return;const identity=this.identityAt(index);current.set(identity,el),this.observedRowKeys.set(el,identity),this.observedRowIndices.set(el,index)});for(const[identity,el]of this.observedRows)current.get(identity)!==el&&(ro.unobserve(el),this.observedRows.delete(identity),this.deferredRowObservations.delete(identity));for(const[identity,el]of current)this.observedRows.has(identity)||(this.observedRows.set(identity,el),this.inResizeDelivery?this.deferredRowObservations.set(identity,el):ro.observe(el))}syncGroupObservers(){const observer=this.groupResizeObserver;if(!observer)return;const current=new Map;this.renderRoot.querySelectorAll('[part="group"][data-group-index]').forEach(marker=>{const index=Number(marker.dataset.groupIndex);!Number.isInteger(index)||!this.normalizedGroupByIndex.has(index)||(current.set(index,marker),this.observedGroupIndices.set(marker,index))});for(const[index,marker]of this.observedGroups)current.get(index)!==marker&&(observer.unobserve(marker),this.observedGroups.delete(index),this.deferredGroupObservations.delete(index));for(const[index,marker]of current)this.observedGroups.has(index)||(this.observedGroups.set(index,marker),this.inResizeDelivery?this.deferredGroupObservations.set(index,marker):observer.observe(marker))}get stickyInset(){return this.renderStickyGroup?this.stickyHeight:0}scrollActiveIntoView(){const index=this.activeIndex;if(index<0)return;const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth";this.performScrollTo(index,"auto",behavior)&&this.beginPendingScrollCorrection(index,"auto",behavior,this.activeItemId)}scrollToIndex(index,options){const n=this.itemCount;if(n===0)return;const clamped=finiteInteger(index,0,0,n-1),align=options?.align??"auto",behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth";this.performScrollTo(clamped,align,behavior)?this.beginPendingScrollCorrection(clamped,align,behavior):this.pendingScrollCorrection=void 0}hasUnmeasuredGroupThrough(index){return this.normalizedGroups.some(group=>group.startIndex<=index&&group.label!==""&&!this.measuredGroupHeights.has(group.startIndex))}beginPendingScrollCorrection(index,align,behavior,activeItemId){if(this.fixedRowHeight!=null&&!this.hasUnmeasuredGroupThrough(index)){this.pendingScrollCorrection=void 0;return}this.pendingScrollCorrection={identity:this.identityAt(index),index,align,behavior,source:this.effectiveSource,keyFunction:this.keyFunction,activeItemId:activeItemId===""?void 0:activeItemId,lastMeasurementGeneration:this.measurementGeneration}}performScrollTo(index,align,behavior){const base=this.scrollContainer;if(!base)return!1;const inset=this.stickyInset,top=this.offsetAt(index),bottom=this.rowBottomAt(index),viewTop=base.scrollTop,viewBottom=viewTop+base.clientHeight;let target=null;return align==="start"?target=top-inset:align==="end"?target=bottom-base.clientHeight:top-inset<viewTop?target=top-inset:bottom>viewBottom&&(target=bottom-base.clientHeight),target===null?!1:(base.scrollTo({top:Math.max(0,target),behavior}),!0)}maybeCorrectPendingScroll(){const pending=this.pendingScrollCorrection;if(!pending||pending.lastMeasurementGeneration>=this.measurementGeneration)return;if(pending.source!==this.effectiveSource||pending.keyFunction!==this.keyFunction||pending.activeItemId!==void 0&&!Object.is(pending.activeItemId,this.activeItemId)){this.pendingScrollCorrection=void 0;return}const index=pending.activeItemId!==void 0?this.activeIndex:isIndexedSource(this.effectiveSource)?pending.index:this.rowIdentities.indexOf(pending.identity);if(index<0||index>=this.itemCount||this.identityAt(index)!==pending.identity){this.pendingScrollCorrection=void 0;return}this.performScrollTo(index,pending.align,pending.behavior),pending.index=index,pending.lastMeasurementGeneration=this.measurementGeneration,(this.fixedRowHeight!=null||this.measuredHeights.has(pending.identity))&&!this.hasUnmeasuredGroupThrough(index)&&(this.pendingScrollCorrection=void 0)}emitRangeChangeIfNeeded(){if(this.visibleEnd<this.visibleStart){this.lastEmittedStart=-1,this.lastEmittedEnd=-1;return}this.visibleStart===this.lastEmittedStart&&this.visibleEnd===this.lastEmittedEnd||(this.lastEmittedStart=this.visibleStart,this.lastEmittedEnd=this.visibleEnd,this.emit("lr-visible-range-change",{start:this.visibleStart,end:this.visibleEnd}))}maybeFireLoadMore(){const n=this.itemCount;if(!(n>0&&this.visibleEnd>=n-1)){this.loadMoreArmed=!0;return}!this.hasMore||this.loading||!this.loadMoreArmed||(this.loadMoreArmed=!1,this.emit("lr-load-more"))}renderRow(item,index,total,activeIndex){const key=this.keyOf(item,index),top=this.offsetAt(index),isActive=index===activeIndex,isRowMode=this.itemRole==="row";return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteAdd,finiteCount,finiteInteger}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{getOwnDataDescriptor,MISSING_OWN_DATA_DESCRIPTOR,UNSAFE_OWN_DATA_DESCRIPTOR}from"../../../internal/data-descriptors.js";import{styles}from"./virtual-list.styles.js";const DEFAULT_ROW_ESTIMATE_PX=48,DEFAULT_GROUP_ESTIMATE_PX=32,DEFAULT_OVERSCAN_ROWS=6,MAX_OVERSCAN_ROWS=100,MAX_VIRTUAL_LIST_GROUPS=1e4,EMPTY_VIRTUAL_LIST_GROUPS=Object.freeze([]);function normalizeOverscan(value){if(value===null)return DEFAULT_OVERSCAN_ROWS;const numeric=typeof value=="number"?value:Number(value);return Number.isFinite(numeric)?Math.min(MAX_OVERSCAN_ROWS,Math.max(0,Math.floor(numeric))):DEFAULT_OVERSCAN_ROWS}const overscanConverter={fromAttribute(value){return normalizeOverscan(value)}};function virtualListGroupsChanged(value,oldValue){if(value===oldValue)return!1;const next=value,previous=oldValue;if(next==null||previous==null)return next!==previous;if(next.length!==previous.length)return!0;for(let index=0;index<next.length;index+=1){const a=next[index],b=previous[index];if(a.key!==b.key||a.label!==b.label||a.startIndex!==b.startIndex)return!0}return!1}function normalizeRowHeight(value){if(value==="auto")return"auto";const numeric=typeof value=="number"?value:Number(value);return Number.isFinite(numeric)&&numeric>0?numeric:"auto"}const rowHeightConverter={fromAttribute(value){return value===null?"auto":normalizeRowHeight(value)}};function isIndexedSource(source){return!Array.isArray(source)}function domKeyToken(key){if(typeof key=="number"){if(Number.isNaN(key))return"number:NaN";if(Object.is(key,-0))return"number:-0"}return`${typeof key}:${String(key)}`}class LyraVirtualList extends LyraElement{constructor(){super(...arguments),this.items=[],this.renderItem=()=>nothing,this.rowHeight="auto",this.itemRole="listitem",this.rowIndexOffset=0,this.overscan=DEFAULT_OVERSCAN_ROWS,this.activeItemId="",this.loading=!1,this.hasMore=!1,this.containerScrollTop=0,this.viewportHeight=0,this.renderUnmeasuredWindow=!0,this.offsets=[0],this.rowIdentities=[],this.fixedRowHeight=null,this.measuredHeights=new Map,this.measuredIndices=new Map,this.indexedMeasurementIndices=[],this.indexedMeasurementDeltaPrefix=[0],this.indexedMeasurementIndexDirty=!0,this.offsetsDirty=!0,this.itemsChangedPendingPrune=!1,this.renderStart=0,this.renderEnd=-1,this.visibleStart=0,this.visibleEnd=-1,this.lastEmittedStart=-1,this.lastEmittedEnd=-1,this.loadMoreArmed=!0,this.measurementGeneration=0,this.isFirstUpdate=!0,this.stickyHeight=0,this.observedRows=new Map,this.observedRowKeys=new WeakMap,this.observedRowIndices=new WeakMap,this.observedGroups=new Map,this.observedGroupIndices=new WeakMap,this.ownerRealmGeneration=0,this.inResizeDelivery=!1,this.deferredRowObservations=new Map,this.deferredGroupObservations=new Map,this.activeIndexForLength=-1,this.activeIndexForId="",this.activeIndexCache=-1,this.pendingScrollTop=null,this.normalizedGroups=EMPTY_VIRTUAL_LIST_GROUPS,this.normalizedGroupByIndex=new Map,this.measuredGroupHeights=new Map,this.groupHeightPrefix=[0],this.onUserScrollIntent=event=>{event instanceof KeyboardEvent&&!new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]).has(event.key)||(this.pendingScrollCorrection=void 0)},this.onScroll=e=>{if(this.pendingScrollTop=e.currentTarget.scrollTop,this.scrollRafId!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{if(!(this.scrollRafId!==handle||this.scrollRafOwner!==ownerWindow||this.scrollRafDocument!==ownerDocument||!this.isCurrentOwnerWork(ownerDocument,generation))&&(this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0,this.pendingScrollTop!==null)){const scrollTop=this.pendingScrollTop;this.pendingScrollTop=null;const moved=this.containerScrollTop!==scrollTop;this.containerScrollTop=scrollTop,moved&&this.emit("lr-virtual-scroll",{scrollTop,viewportHeight:this.viewportHeight})}});this.scrollRafId=handle,this.scrollRafOwner=ownerWindow,this.scrollRafDocument=ownerDocument},this.onRowsResized=entries=>{if(this.beginResizeDelivery(),this.fixedRowHeight!=null)return;const base=this.scrollContainer,oldScrollTop=base?.scrollTop??this.containerScrollTop;let scrollAdjustment=0,changed=!1;for(const entry of entries){const row=entry.target,key=this.observedRowKeys.get(row),index=this.observedRowIndices.get(row);if(key===void 0||index===void 0)continue;const height=entry.borderBoxSize?.[0]?.blockSize??entry.target.getBoundingClientRect().height,prev=this.measuredHeights.get(key);if(prev===void 0||Math.abs(prev-height)>.5){const oldBottom=this.rowBottomAt(index);this.measuredHeights.set(key,height),this.measuredIndices.set(key,index);const oldHeight=prev??DEFAULT_ROW_ESTIMATE_PX;oldBottom<=oldScrollTop&&(scrollAdjustment+=height-oldHeight),changed=!0}}if(changed){if(this.indexedMeasurementIndexDirty=!0,base&&scrollAdjustment!==0){const nextScrollTop=Math.max(0,oldScrollTop+scrollAdjustment);base.scrollTop=nextScrollTop,this.containerScrollTop=nextScrollTop,this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,this.requestUpdate()}},this.onGroupsResized=entries=>{this.beginResizeDelivery();const base=this.scrollContainer,oldScrollTop=base?.scrollTop??this.containerScrollTop;let scrollAdjustment=0,changed=!1;for(const entry of entries){const marker=entry.target,index=this.observedGroupIndices.get(marker);if(index===void 0||!this.normalizedGroupByIndex.has(index))continue;const height=entry.borderBoxSize?.[0]?.blockSize??entry.target.getBoundingClientRect().height;if(!Number.isFinite(height)||height<0)continue;const previous=this.measuredGroupHeights.get(index)??DEFAULT_GROUP_ESTIMATE_PX;if(Math.abs(previous-height)<=.5)continue;const oldRowTop=this.offsetAt(index);this.measuredGroupHeights.set(index,height),oldRowTop<=oldScrollTop&&(scrollAdjustment+=height-previous),changed=!0}if(changed){if(base&&scrollAdjustment!==0){const nextScrollTop=Math.max(0,oldScrollTop+scrollAdjustment);base.scrollTop=nextScrollTop,this.containerScrollTop=nextScrollTop,this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,this.requestUpdate()}},this.onStickyResized=entries=>{this.beginResizeDelivery();const entry=entries[0];if(!entry)return;const height=entry.borderBoxSize?.[0]?.blockSize??entry.contentRect.height;Math.abs(this.stickyHeight-height)>.5&&(this.stickyHeight=height)}}static{this.ownedCollectionProperties=Object.freeze(["items","source","groups"])}static{this.identityCollectionProperties=Object.freeze(["items","source"])}static{this.identityCollectionObjectProperties=Object.freeze(["source"])}static{this.styles=[LyraElement.styles,styles]}get scrollContainer(){return this.renderRoot?.querySelector('[part="base"]')??void 0}get renderedRows(){const root=this.renderRoot;return root?[...root.querySelectorAll('[part="row"]')]:[]}get safeRowIndexOffset(){return finiteCount(this.rowIndexOffset)}computedAriaRowIndex(index){return finiteInteger(finiteAdd(index+1,this.safeRowIndexOffset),1,1,Number.MAX_SAFE_INTEGER)}get activeIndex(){if(this.activeItemId==="")return-1;const source=this.effectiveSource,count=this.itemCount;if(this.activeIndexFor===source&&this.activeIndexForLength===count&&Object.is(this.activeIndexForId,this.activeItemId)&&this.activeIndexForKeyFn===this.keyFunction)return this.activeIndexCache;if(this.activeIndexFor=source,this.activeIndexForLength=count,this.activeIndexForId=this.activeItemId,this.activeIndexForKeyFn=this.keyFunction,this.activeIndexCache=-1,isIndexedSource(source)){if(!this.keyFunction&&source.indexOfKey){const candidate=source.indexOfKey(this.activeItemId);Number.isInteger(candidate)&&candidate>=0&&candidate<count&&(this.activeIndexCache=candidate)}return this.activeIndexCache}for(let index=0;index<count;index++){const item=this.itemAt(index);if(Object.is(this.keyOf(item,index),this.activeItemId)){this.activeIndexCache=index;break}}return this.activeIndexCache}connectedCallback(){super.connectedCallback(),this.ownerDocument.defaultView&&this.seedFirstRenderState(()=>{this.renderUnmeasuredWindow=!1,this.requestUpdate()}),this.resetOwnerRealmWork();const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView,generation=this.ownerRealmGeneration,ResizeObserverCtor=ownerWindow?.ResizeObserver;if(ResizeObserverCtor){const rowObserver=new ResizeObserverCtor(entries=>{this.rowResizeObserver!==rowObserver||!this.isCurrentOwnerWork(ownerDocument,generation)||this.onRowsResized(entries)}),groupObserver=new ResizeObserverCtor(entries=>{this.groupResizeObserver!==groupObserver||!this.isCurrentOwnerWork(ownerDocument,generation)||this.onGroupsResized(entries)}),stickyObserver=new ResizeObserverCtor(entries=>{this.stickyResizeObserver!==stickyObserver||!this.isCurrentOwnerWork(ownerDocument,generation)||this.onStickyResized(entries)});this.rowResizeObserver=rowObserver,this.groupResizeObserver=groupObserver,this.stickyResizeObserver=stickyObserver}this.hasUpdated&&(this.attachContainerListeners(),this.syncRowObservers(),this.syncGroupObservers(),this.syncStickyOverlay())}disconnectedCallback(){this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}isCurrentOwnerWork(ownerDocument,generation){return this.ownerRealmGeneration===generation&&this.isConnected&&this.ownerDocument===ownerDocument}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.rowResizeObserver?.disconnect(),this.rowResizeObserver=void 0,this.groupResizeObserver?.disconnect(),this.groupResizeObserver=void 0,this.observedRows.clear(),this.observedGroups.clear(),this.deferredRowObservations.clear(),this.deferredGroupObservations.clear(),this.inResizeDelivery=!1,this.rowObserveRafId!==void 0&&this.rowObserveRafOwner?.cancelAnimationFrame(this.rowObserveRafId),this.rowObserveRafId=void 0,this.rowObserveRafOwner=void 0,this.rowObserveRafDocument=void 0,this.containerResizeObserver?.disconnect(),this.containerResizeObserver=void 0,this.stickyResizeObserver?.disconnect(),this.stickyResizeObserver=void 0,this.observedSticky=void 0,this.scrollRafId!==void 0&&this.scrollRafOwner?.cancelAnimationFrame(this.scrollRafId),this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0,this.pendingScrollTop=null,this.pendingScrollCorrection=void 0,this.detachContainerListeners(),this.scrollListenerTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.attachContainerListeners()}willUpdate(changed){super.willUpdate(changed),this.isFirstUpdate=!this.hasUpdated,(changed.has("items")||changed.has("source")||changed.has("keyFunction")||changed.has("rowHeight")||changed.has("groups")||changed.has("activeItemId"))&&(this.pendingScrollCorrection=void 0),(changed.has("items")||changed.has("source")||changed.has("rowHeight")||changed.has("keyFunction")||changed.has("groups"))&&(this.offsetsDirty=!0),(changed.has("items")||changed.has("source"))&&(this.itemsChangedPendingPrune=!0),isIndexedSource(this.effectiveSource)&&(changed.has("items")||changed.has("source")||changed.has("keyFunction"))&&(this.measuredHeights.clear(),this.measuredIndices.clear(),this.indexedMeasurementIndexDirty=!0),changed.has("groups")&&this.measuredGroupHeights.clear(),(changed.has("items")||changed.has("source")||changed.has("groups"))&&this.recomputeGroups(),changed.has("rowHeight")&&(this.fixedRowHeight=this.parseRowHeight(this.rowHeight),this.fixedRowHeight!=null&&(this.measuredHeights.clear(),this.measuredIndices.clear(),this.indexedMeasurementIndexDirty=!0)),this.offsetsDirty&&(this.recomputeOffsets(),this.offsetsDirty=!1),this.computeRange()}updated(changed){super.updated(changed),this.syncRowObservers(),this.syncGroupObservers(),this.syncStickyOverlay(),changed.has("activeItemId")&&!this.isFirstUpdate&&this.scrollActiveIntoView(),this.emitRangeChangeIfNeeded(),this.maybeFireLoadMore(),this.maybeCorrectPendingScroll()}parseRowHeight(value){const normalized=normalizeRowHeight(value);return normalized==="auto"?null:normalized}get effectiveSource(){return this.source??this.items}get itemCount(){const source=this.effectiveSource;return isIndexedSource(source)?finiteCount(source.count):source.length}itemAt(index){const source=this.effectiveSource;return isIndexedSource(source)?source.itemAt(index):source[index]}keyOf(item,index){const source=this.effectiveSource,key=this.keyFunction?this.keyFunction(item,index):isIndexedSource(source)?source.keyAt?.(index)??index:index;return typeof key=="string"||typeof key=="number"?key:index}rowIdentity(key,occurrence){const token=domKeyToken(key);return`${token.length}:${token}:${occurrence}`}identityAt(index,item=this.itemAt(index)){return isIndexedSource(this.effectiveSource)?this.rowIdentity(this.keyOf(item,index),index):this.rowIdentities[index]??this.rowIdentity(this.keyOf(item,index),index)}groupHeightAt(index){const group=this.normalizedGroupByIndex.get(index);return!group||group.label===""?0:this.measuredGroupHeights.get(index)??DEFAULT_GROUP_ESTIMATE_PX}rowHeightAt(index){return this.fixedRowHeight!=null?this.fixedRowHeight:this.measuredHeights.get(this.identityAt(index))??DEFAULT_ROW_ESTIMATE_PX}groupContributionThrough(index){let low=0,high=this.normalizedGroups.length;for(;low<high;){const middle=low+high>>1;this.normalizedGroups[middle].startIndex<=index?low=middle+1:high=middle}return this.groupHeightPrefix[low]??0}recomputeGroupHeightPrefix(){const prefix=new Array(this.normalizedGroups.length+1);prefix[0]=0;for(let index=0;index<this.normalizedGroups.length;index++){const group=this.normalizedGroups[index],height=group.label===""?0:this.measuredGroupHeights.get(group.startIndex)??DEFAULT_GROUP_ESTIMATE_PX;prefix[index+1]=finiteAdd(prefix[index],height)}this.groupHeightPrefix=prefix}indexedOffsetForIndex(index){const baseHeight=this.fixedRowHeight??DEFAULT_ROW_ESTIMATE_PX;let offset=index>Number.MAX_VALUE/baseHeight?Number.MAX_VALUE:index*baseHeight;if(this.fixedRowHeight==null){this.rebuildIndexedMeasurementIndex();let low=0,high=this.indexedMeasurementIndices.length;for(;low<high;){const middle=low+high>>1;this.indexedMeasurementIndices[middle]<index?low=middle+1:high=middle}offset=finiteAdd(offset,this.indexedMeasurementDeltaPrefix[low]??0)}return Math.max(0,finiteAdd(offset,this.groupContributionThrough(index)))}rebuildIndexedMeasurementIndex(){if(!this.indexedMeasurementIndexDirty)return;const retained=[];for(const[identity,index]of this.measuredIndices){const height=this.measuredHeights.get(identity);height!==void 0&&retained.push({index,delta:height-DEFAULT_ROW_ESTIMATE_PX})}retained.sort((a,b)=>a.index-b.index);const indices=new Array(retained.length),prefix=new Array(retained.length+1);prefix[0]=0;for(let position=0;position<retained.length;position++){const measurement=retained[position];indices[position]=measurement.index,prefix[position+1]=finiteAdd(prefix[position],measurement.delta)}this.indexedMeasurementIndices=indices,this.indexedMeasurementDeltaPrefix=prefix,this.indexedMeasurementIndexDirty=!1}pruneIndexedMeasurements(){if(!isIndexedSource(this.effectiveSource)||this.fixedRowHeight!=null||this.renderEnd<this.renderStart)return!1;const renderedCount=this.renderEnd-this.renderStart+1,retentionRows=Math.max(renderedCount,normalizeOverscan(this.overscan)*4),firstRetained=Math.max(0,this.renderStart-retentionRows),lastRetained=Math.min(this.itemCount-1,this.renderEnd+retentionRows);let removedDeltaBeforeWindow=0,pruned=!1;for(const[identity,measuredIndex]of this.measuredIndices)if(measuredIndex<firstRetained||measuredIndex>lastRetained){const height=this.measuredHeights.get(identity);height!==void 0&&measuredIndex<firstRetained&&(removedDeltaBeforeWindow=finiteAdd(removedDeltaBeforeWindow,height-DEFAULT_ROW_ESTIMATE_PX)),this.measuredIndices.delete(identity),this.measuredHeights.delete(identity),pruned=!0}if(pruned&&(this.indexedMeasurementIndexDirty=!0,removedDeltaBeforeWindow!==0)){const base=this.scrollContainer,oldScrollTop=base?.scrollTop??this.containerScrollTop,nextScrollTop=Math.max(0,oldScrollTop-removedDeltaBeforeWindow);base&&(base.scrollTop=nextScrollTop),this.containerScrollTop=nextScrollTop,this.pendingScrollTop=null}return pruned}offsetAt(index){return isIndexedSource(this.effectiveSource)?this.indexedOffsetForIndex(index):this.offsets[index]??0}recomputeOffsets(){const n=this.itemCount;if(this.recomputeGroupHeightPrefix(),isIndexedSource(this.effectiveSource)){this.offsets=[0],this.rowIdentities=[],this.itemsChangedPendingPrune=!1;return}const offsets=new Array(n+1);let cursor=0;const liveKeys=this.itemsChangedPendingPrune&&this.fixedRowHeight==null?new Set:null,occurrences=new Map,identities=new Array(n);for(let i=0;i<n;i++){cursor=finiteAdd(cursor,this.groupHeightAt(i)),offsets[i]=cursor;const key=this.keyOf(this.itemAt(i),i),token=domKeyToken(key),occurrence=occurrences.get(token)??0;occurrences.set(token,occurrence+1);const identity=this.rowIdentity(key,occurrence);identities[i]=identity;let h;this.fixedRowHeight!=null?h=this.fixedRowHeight:(liveKeys?.add(identity),h=this.measuredHeights.get(identity)??DEFAULT_ROW_ESTIMATE_PX),cursor=finiteAdd(cursor,h)}if(offsets[n]=cursor,this.offsets=offsets,this.rowIdentities=identities,this.itemsChangedPendingPrune=!1,liveKeys){for(const key of this.measuredHeights.keys())liveKeys.has(key)||(this.measuredHeights.delete(key),this.measuredIndices.delete(key),this.indexedMeasurementIndexDirty=!0);for(const key of this.measuredIndices.keys())liveKeys.has(key)||(this.measuredIndices.delete(key),this.indexedMeasurementIndexDirty=!0)}}groupTopAt(index){return Math.max(0,this.offsetAt(index)-this.groupHeightAt(index))}rowBottomAt(index){return finiteAdd(this.offsetAt(index),this.rowHeightAt(index))}entryTopAt(index){return this.groupTopAt(index)}findIndexAtOrAfter(offset){let lo=0,hi=this.itemCount-1;for(;lo<hi;){const mid=lo+Math.floor((hi-lo)/2);this.rowBottomAt(mid)<=offset?lo=mid+1:hi=mid}return lo}findIndexAtOrBefore(offset){let lo=0,hi=this.itemCount-1;for(;lo<hi;){const mid=lo+Math.ceil((hi-lo)/2);this.entryTopAt(mid)<offset?lo=mid:hi=mid-1}return lo}offsetForIndex(index){const clamped=Math.min(this.itemCount,Math.max(0,Math.trunc(index)||0));return this.offsetAt(clamped)}indexAtOffset(px){const n=this.itemCount;return n===0?-1:Number.isFinite(px)?Math.min(n-1,Math.max(0,this.findIndexAtOrAfter(px))):px>0?n-1:0}computeRange(){const n=this.itemCount;if(n===0){this.visibleStart=0,this.visibleEnd=-1,this.renderStart=0,this.renderEnd=-1;return}if(this.viewportHeight<=0){if(!this.renderUnmeasuredWindow){this.visibleStart=0,this.visibleEnd=-1,this.renderStart=0,this.renderEnd=-1;return}this.visibleStart=0,this.visibleEnd=0,this.renderStart=0,this.renderEnd=Math.min(n-1,normalizeOverscan(this.overscan));return}const viewTop=this.containerScrollTop,viewBottom=viewTop+this.viewportHeight;this.visibleStart=this.findIndexAtOrAfter(viewTop),this.visibleEnd=this.findIndexAtOrBefore(viewBottom);const overscan=normalizeOverscan(this.overscan);this.renderStart=Math.max(0,this.visibleStart-overscan),this.renderEnd=Math.min(n-1,this.visibleEnd+overscan),this.pruneIndexedMeasurements()&&this.computeRange()}attachContainerListeners(){const base=this.scrollContainer,ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!base||!this.isConnected||!ownerWindow)return;this.containerResizeObserver?.disconnect(),this.detachContainerListeners();const generation=this.ownerRealmGeneration,ResizeObserverCtor=ownerWindow.ResizeObserver;if(ResizeObserverCtor){const observer=new ResizeObserverCtor(entries=>{if(this.containerResizeObserver!==observer||this.scrollListenerTarget!==base||!this.isCurrentOwnerWork(ownerDocument,generation))return;this.beginResizeDelivery();const entry=entries[0];entry&&(this.viewportHeight=entry.borderBoxSize?.[0]?.blockSize??entry.contentRect.height)});this.containerResizeObserver=observer,observer.observe(base)}else this.containerResizeObserver=void 0;base.addEventListener("scroll",this.onScroll,{passive:!0}),base.addEventListener("wheel",this.onUserScrollIntent,{passive:!0}),base.addEventListener("pointerdown",this.onUserScrollIntent,{passive:!0}),base.addEventListener("touchstart",this.onUserScrollIntent,{passive:!0}),base.addEventListener("keydown",this.onUserScrollIntent),this.scrollListenerTarget=base,ownerWindow.queueMicrotask(()=>{if(this.scrollListenerTarget!==base||this.scrollContainer!==base||!this.isCurrentOwnerWork(ownerDocument,generation))return;const viewportHeight=base.clientHeight,scrollTop=base.scrollTop;this.viewportHeight!==viewportHeight&&(this.viewportHeight=viewportHeight),this.containerScrollTop!==scrollTop&&(this.containerScrollTop=scrollTop)})}detachContainerListeners(){const target=this.scrollListenerTarget;target&&(target.removeEventListener("scroll",this.onScroll),target.removeEventListener("wheel",this.onUserScrollIntent),target.removeEventListener("pointerdown",this.onUserScrollIntent),target.removeEventListener("touchstart",this.onUserScrollIntent),target.removeEventListener("keydown",this.onUserScrollIntent))}beginResizeDelivery(){if(this.inResizeDelivery=!0,this.rowObserveRafId!==void 0)return;const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected){this.inResizeDelivery=!1;return}const generation=this.ownerRealmGeneration,handle=ownerWindow.requestAnimationFrame(()=>{if(this.rowObserveRafId!==handle||this.rowObserveRafOwner!==ownerWindow||this.rowObserveRafDocument!==ownerDocument||!this.isCurrentOwnerWork(ownerDocument,generation))return;this.rowObserveRafId=void 0,this.rowObserveRafOwner=void 0,this.rowObserveRafDocument=void 0,this.inResizeDelivery=!1;const ro=this.rowResizeObserver;for(const[identity,el]of this.deferredRowObservations)ro&&this.observedRows.get(identity)===el&&ro.observe(el);this.deferredRowObservations.clear();const groupObserver=this.groupResizeObserver;for(const[index,el]of this.deferredGroupObservations)groupObserver&&this.observedGroups.get(index)===el&&groupObserver.observe(el);this.deferredGroupObservations.clear()});this.rowObserveRafId=handle,this.rowObserveRafOwner=ownerWindow,this.rowObserveRafDocument=ownerDocument}syncRowObservers(){const ro=this.rowResizeObserver;if(!ro)return;if(this.fixedRowHeight!=null){for(const el of this.observedRows.values())ro.unobserve(el);this.observedRows.clear(),this.deferredRowObservations.clear();return}const current=new Map;this.renderRoot.querySelectorAll('[part="row"]').forEach(el=>{const index=Number(el.getAttribute("data-row-index"));if(!Number.isInteger(index)||index<0||index>=this.itemCount)return;const identity=this.identityAt(index);current.set(identity,el),this.observedRowKeys.set(el,identity),this.observedRowIndices.set(el,index)});for(const[identity,el]of this.observedRows)current.get(identity)!==el&&(ro.unobserve(el),this.observedRows.delete(identity),this.deferredRowObservations.delete(identity));for(const[identity,el]of current)this.observedRows.has(identity)||(this.observedRows.set(identity,el),this.inResizeDelivery?this.deferredRowObservations.set(identity,el):ro.observe(el))}syncGroupObservers(){const observer=this.groupResizeObserver;if(!observer)return;const current=new Map;this.renderRoot.querySelectorAll('[part="group"][data-group-index]').forEach(marker=>{const index=Number(marker.dataset.groupIndex);!Number.isInteger(index)||!this.normalizedGroupByIndex.has(index)||(current.set(index,marker),this.observedGroupIndices.set(marker,index))});for(const[index,marker]of this.observedGroups)current.get(index)!==marker&&(observer.unobserve(marker),this.observedGroups.delete(index),this.deferredGroupObservations.delete(index));for(const[index,marker]of current)this.observedGroups.has(index)||(this.observedGroups.set(index,marker),this.inResizeDelivery?this.deferredGroupObservations.set(index,marker):observer.observe(marker))}get stickyInset(){return this.renderStickyGroup?this.stickyHeight:0}scrollActiveIntoView(){const index=this.activeIndex;if(index<0)return;const behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":"smooth";this.performScrollTo(index,"auto",behavior)&&this.beginPendingScrollCorrection(index,"auto",behavior,this.activeItemId)}scrollToIndex(index,options){const n=this.itemCount;if(n===0)return;const clamped=finiteInteger(index,0,0,n-1),align=options?.align??"auto",behavior=prefersReducedMotion(this.ownerDocument.defaultView)?"auto":options?.behavior??"smooth";this.performScrollTo(clamped,align,behavior)?this.beginPendingScrollCorrection(clamped,align,behavior):this.pendingScrollCorrection=void 0}hasUnmeasuredGroupThrough(index){return this.normalizedGroups.some(group=>group.startIndex<=index&&group.label!==""&&!this.measuredGroupHeights.has(group.startIndex))}beginPendingScrollCorrection(index,align,behavior,activeItemId){if(this.fixedRowHeight!=null&&!this.hasUnmeasuredGroupThrough(index)){this.pendingScrollCorrection=void 0;return}this.pendingScrollCorrection={identity:this.identityAt(index),index,align,behavior,source:this.effectiveSource,keyFunction:this.keyFunction,activeItemId:activeItemId===""?void 0:activeItemId,lastMeasurementGeneration:this.measurementGeneration}}performScrollTo(index,align,behavior){const base=this.scrollContainer;if(!base)return!1;const inset=this.stickyInset,top=this.offsetAt(index),bottom=this.rowBottomAt(index),viewTop=base.scrollTop,viewBottom=viewTop+base.clientHeight;let target=null;return align==="start"?target=top-inset:align==="end"?target=bottom-base.clientHeight:top-inset<viewTop?target=top-inset:bottom>viewBottom&&(target=bottom-base.clientHeight),target===null?!1:(base.scrollTo({top:Math.max(0,target),behavior}),!0)}maybeCorrectPendingScroll(){const pending=this.pendingScrollCorrection;if(!pending||pending.lastMeasurementGeneration>=this.measurementGeneration)return;if(pending.source!==this.effectiveSource||pending.keyFunction!==this.keyFunction||pending.activeItemId!==void 0&&!Object.is(pending.activeItemId,this.activeItemId)){this.pendingScrollCorrection=void 0;return}const index=pending.activeItemId!==void 0?this.activeIndex:isIndexedSource(this.effectiveSource)?pending.index:this.rowIdentities.indexOf(pending.identity);if(index<0||index>=this.itemCount||this.identityAt(index)!==pending.identity){this.pendingScrollCorrection=void 0;return}this.performScrollTo(index,pending.align,pending.behavior),pending.index=index,pending.lastMeasurementGeneration=this.measurementGeneration,(this.fixedRowHeight!=null||this.measuredHeights.has(pending.identity))&&!this.hasUnmeasuredGroupThrough(index)&&(this.pendingScrollCorrection=void 0)}emitRangeChangeIfNeeded(){if(this.visibleEnd<this.visibleStart){this.lastEmittedStart=-1,this.lastEmittedEnd=-1;return}this.visibleStart===this.lastEmittedStart&&this.visibleEnd===this.lastEmittedEnd||(this.lastEmittedStart=this.visibleStart,this.lastEmittedEnd=this.visibleEnd,this.emit("lr-visible-range-change",{start:this.visibleStart,end:this.visibleEnd}))}maybeFireLoadMore(){const n=this.itemCount;if(!(n>0&&this.visibleEnd>=n-1)){this.loadMoreArmed=!0;return}!this.hasMore||this.loading||!this.loadMoreArmed||(this.loadMoreArmed=!1,this.emit("lr-load-more"))}renderRow(item,index,total,activeIndex){const key=this.keyOf(item,index),top=this.offsetAt(index),isActive=index===activeIndex,isRowMode=this.itemRole==="row";return html`
|
|
2
2
|
<div
|
|
3
3
|
part="row"
|
|
4
4
|
role=${isRowMode?"row":"listitem"}
|
|
@@ -49,4 +49,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
49
49
|
${this.renderStickyLayer()}
|
|
50
50
|
</div>
|
|
51
51
|
</div>
|
|
52
|
-
`}}__decorate([property({attribute:!1})],LyraVirtualList.prototype,"items",void 0),__decorate([property({attribute:!1})],LyraVirtualList.prototype,"source",void 0),__decorate([property({attribute:!1})],LyraVirtualList.prototype,"renderItem",void 0),__decorate([property({attribute:!1})],LyraVirtualList.prototype,"keyFunction",void 0),__decorate([property({attribute:!1})],LyraVirtualList.prototype,"groups",void 0),__decorate([property({attribute:!1})],LyraVirtualList.prototype,"renderStickyGroup",void 0),__decorate([property({attribute:"row-height",converter:rowHeightConverter})],LyraVirtualList.prototype,"rowHeight",void 0),__decorate([property({attribute:"item-role"})],LyraVirtualList.prototype,"itemRole",void 0),__decorate([property({type:Number,attribute:"row-index-offset"})],LyraVirtualList.prototype,"rowIndexOffset",void 0),__decorate([property({converter:overscanConverter})],LyraVirtualList.prototype,"overscan",void 0),__decorate([property({attribute:"active-item-id"})],LyraVirtualList.prototype,"activeItemId",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraVirtualList.prototype,"loading",void 0),__decorate([property({type:Boolean,attribute:"has-more",reflect:!0})],LyraVirtualList.prototype,"hasMore",void 0),__decorate([state()],LyraVirtualList.prototype,"containerScrollTop",void 0),__decorate([state()],LyraVirtualList.prototype,"viewportHeight",void 0),__decorate([state()],LyraVirtualList.prototype,"stickyHeight",void 0);export{LyraVirtualList,MAX_OVERSCAN_ROWS};
|
|
52
|
+
`}}__decorate([property({attribute:!1})],LyraVirtualList.prototype,"items",void 0),__decorate([property({attribute:!1})],LyraVirtualList.prototype,"source",void 0),__decorate([property({attribute:!1})],LyraVirtualList.prototype,"renderItem",void 0),__decorate([property({attribute:!1})],LyraVirtualList.prototype,"keyFunction",void 0),__decorate([property({attribute:!1,hasChanged:virtualListGroupsChanged})],LyraVirtualList.prototype,"groups",void 0),__decorate([property({attribute:!1})],LyraVirtualList.prototype,"renderStickyGroup",void 0),__decorate([property({attribute:"row-height",converter:rowHeightConverter})],LyraVirtualList.prototype,"rowHeight",void 0),__decorate([property({attribute:"item-role"})],LyraVirtualList.prototype,"itemRole",void 0),__decorate([property({type:Number,attribute:"row-index-offset"})],LyraVirtualList.prototype,"rowIndexOffset",void 0),__decorate([property({converter:overscanConverter})],LyraVirtualList.prototype,"overscan",void 0),__decorate([property({attribute:"active-item-id"})],LyraVirtualList.prototype,"activeItemId",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraVirtualList.prototype,"loading",void 0),__decorate([property({type:Boolean,attribute:"has-more",reflect:!0})],LyraVirtualList.prototype,"hasMore",void 0),__decorate([state()],LyraVirtualList.prototype,"containerScrollTop",void 0),__decorate([state()],LyraVirtualList.prototype,"viewportHeight",void 0),__decorate([state()],LyraVirtualList.prototype,"stickyHeight",void 0);export{LyraVirtualList,MAX_OVERSCAN_ROWS};
|
|
@@ -104,7 +104,7 @@ ariaLabel?:string;}export interface LyraWidgetEventMap{'lr-collapse-request':Cus
|
|
|
104
104
|
* @status stable
|
|
105
105
|
* @since 4.0.0
|
|
106
106
|
*/
|
|
107
|
-
export declare class LyraWidget extends LyraElement<LyraWidgetEventMap>{static styles:import("lit").CSSResultGroup[];private actionsScrollOverflow;private viewTogglesScrollOverflow;
|
|
107
|
+
export declare class LyraWidget extends LyraElement<LyraWidgetEventMap>{static styles:import("lit").CSSResultGroup[];static properties:{collapsed:{type:BooleanConstructor;reflect:boolean;noAccessor:boolean;};};private actionsScrollOverflow;private viewTogglesScrollOverflow;
|
|
108
108
|
/** Header title. Removing the attribute omits the copy without changing null readback. */
|
|
109
109
|
label:string;
|
|
110
110
|
/** Overrides the fullscreen dialog's accessible name, taking precedence over both `label` and a
|
|
@@ -113,7 +113,17 @@ label:string;
|
|
|
113
113
|
* own host-override pattern. */
|
|
114
114
|
accessibleLabel:string|null;
|
|
115
115
|
/** Secondary header copy. Removed or empty attributes render no fallback text. */
|
|
116
|
-
sublabel:string;collapsible:boolean;
|
|
116
|
+
sublabel:string;collapsible:boolean;private _collapsed;
|
|
117
|
+
/** Explicitly assigned at least once (attribute, property, or `requestCollapse()`) -- lets
|
|
118
|
+
* `willUpdate()`'s `storage-key` restore skip an explicit `.collapsed=${…}`/`collapsed`
|
|
119
|
+
* binding on the very same mount instead of silently overwriting it, mirroring `lr-app-rail`'s
|
|
120
|
+
* `loadPersisted()` guard. `changed.has('collapsed')` alone can't do this: the class field
|
|
121
|
+
* default and an explicit binding both land in the same first-update batch, and Lit's
|
|
122
|
+
* `_changedProperties` only remembers the *first* recorded `oldValue`. */
|
|
123
|
+
private _collapsedExplicitlySet;
|
|
124
|
+
/** Whether the body is collapsed. Reflects to the `collapsed` attribute.
|
|
125
|
+
* @default false */
|
|
126
|
+
get collapsed():boolean;set collapsed(next:boolean);
|
|
117
127
|
/** Persists `collapsed` to `localStorage` across reloads when set. Namespaced as
|
|
118
128
|
* `lr-widget:${storageKey}` -- mirrors `lr-app-rail`'s/`lr-table`'s identical `storage-key`
|
|
119
129
|
* pattern. Unset (the default) touches storage not at all. */
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{nextId}from"../../../internal/a11y.js";import{bindAccessibleTextObserver,composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this.collapsed=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.compact=!1,this.effectiveViews=Object.freeze([]),this.activeViewId="",this.activeView="",this.hasActionsSlot=!1,this.hasIconSlot=!1,this.hasLabelSlot=!1,this.hasSublabelSlot=!1,this.labelSlotObserverGeneration=0,this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onIconSlotChange=e=>{this.hasIconSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.onSublabelSlotChange=e=>{this.hasSublabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.setActiveView=viewId=>{viewId===this.activeViewId||this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented||(this.activeViewId=viewId,this.emit("lr-view-change",{viewId}))},this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,styles]}get views(){return this.effectiveViews}set views(value){const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){this.hasActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="actions"),this.hasIconSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="icon");const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.hasLabelSlot=labelChildren.length>0,this.labelSlotText=this.readLabelSlotText(labelChildren),this.hasSublabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="sublabel");const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("activeView")&&this.activeView!==""&&(this.activeViewId=this.activeView),changed.has("views")||changed.has("activeViewId")||changed.has("activeView")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;views.some(view=>view.viewId===this.activeViewId)||(this.activeViewId=views[0]?.viewId??"")}}updated(changed){super.updated(changed);const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>this.overlayHandle?.focusInitial())),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){super.disconnectedCallback(),this.overlayHandle?.suspend(),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.resetLabelSlotObserver()}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.overlayHandle?.deactivate(),this.overlayHandle=void 0}syncLabelSlot(assigned){if(this.hasLabelSlot=assigned.length>0,this.labelSlotText=this.readLabelSlotText(assigned),this.resetLabelSlotObserver(),assigned.length===0||!this.isConnected)return;const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.labelSlotObserverGeneration,observer=new MutationObserverCtor(()=>{this.labelSlotObserver!==observer||this.labelSlotObserverDocument!==ownerDocument||this.labelSlotObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.labelSlotText=this.readLabelSlotText(assigned))});this.labelSlotObserver=observer,this.labelSlotObserverDocument=ownerDocument,bindAccessibleTextObserver(observer,this,["alt","aria-labelledby","slot"]);for(const element of assigned)observer.observe(element,{attributes:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","inert","style"],childList:!0,characterData:!0,subtree:!0})}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}resetLabelSlotObserver(){this.labelSlotObserverGeneration+=1,this.labelSlotObserver?.disconnect(),this.labelSlotObserver=void 0,this.labelSlotObserverDocument=void 0}requestCollapse(next){this.emit("lr-collapse-request",{collapsed:next},{cancelable:!0}).defaultPrevented||(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}))}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=(this.label??"").length>0,hasSublabel=(this.sublabel??"").length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return html`
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{renderInertPresentation}from"../../../internal/inert-presentation.js";import{activateOverlay,collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{nextId}from"../../../internal/a11y.js";import{bindAccessibleTextObserver,composedAccessibilityText}from"../../../internal/accessibility-visibility.js";import{observeScrollOverflow}from"../../../internal/scroll-overflow.js";import{chevronIcon,closeIcon,expandIcon}from"../../../internal/icons.js";import{styles}from"./widget.styles.js";import{sanitizeCssInset}from"../../../internal/safe-css.js";import{LYRA_DEFAULT_widgetCollapse,LYRA_DEFAULT_widgetExitFullscreen,LYRA_DEFAULT_widgetExpand,LYRA_DEFAULT_widgetExpandToFullscreen,LYRA_DEFAULT_widgetFullscreenPanel,LYRA_DEFAULT_widgetViewGroup}from"../../../internal/default-strings.generated.js";const MAX_WIDGET_VIEWS=256;function snapshotWidgetViews(value){if(!Array.isArray(value))return Object.freeze([]);const seen=new Set,normalized=[];for(const candidate of value.slice(0,MAX_WIDGET_VIEWS))try{if(!candidate||typeof candidate!="object")continue;const record=candidate,viewId=record.viewId;if(typeof viewId!="string"||viewId.length===0||viewId!==viewId.trim()||seen.has(viewId))continue;const label=record.label,ariaLabel=record.ariaLabel,icon=record.icon;if(label!==void 0&&typeof label!="string"||ariaLabel!==void 0&&typeof ariaLabel!="string")continue;seen.add(viewId),normalized.push(Object.freeze({viewId,...label!==void 0?{label}:{},...icon!==void 0?{icon}:{},...ariaLabel!==void 0?{ariaLabel}:{}}))}catch{}return Object.freeze(normalized)}class LyraWidget extends LyraElement{constructor(){super(...arguments),this.actionsScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="actions"]')),this.viewTogglesScrollOverflow=observeScrollOverflow(this,()=>this.renderRoot.querySelector('[part="view-toggles"]')),this.label="",this.accessibleLabel=null,this.sublabel="",this.collapsible=!1,this._collapsed=!1,this._collapsedExplicitlySet=!1,this.expandable=!1,this.fullscreen=!1,this.fullscreenInset="",this.backdropInset="",this.compact=!1,this.effectiveViews=Object.freeze([]),this.activeViewId="",this.activeView="",this.hasActionsSlot=!1,this.hasIconSlot=!1,this.hasLabelSlot=!1,this.hasSublabelSlot=!1,this.labelSlotObserverGeneration=0,this.ownerRealmGeneration=0,this.bodyId=nextId("widget-body"),this.persistReady=!1,this.onActionsSlotChange=e=>{this.hasActionsSlot=e.target.assignedElements({flatten:!0}).length>0},this.onIconSlotChange=e=>{this.hasIconSlot=e.target.assignedElements({flatten:!0}).length>0},this.onLabelSlotChange=e=>{const assigned=e.target.assignedElements({flatten:!0});this.syncLabelSlot(assigned)},this.onSublabelSlotChange=e=>{this.hasSublabelSlot=e.target.assignedElements({flatten:!0}).length>0},this.setActiveView=viewId=>{viewId===this.activeViewId||this.emit("lr-view-request",{viewId},{cancelable:!0}).defaultPrevented||(this.activeViewId=viewId,this.emit("lr-view-change",{viewId}))},this.toggleCollapsed=()=>{this.requestCollapse(!this.collapsed)},this.toggleFullscreen=e=>{const next=!this.fullscreen,trigger=e.currentTarget;this.requestFullscreenChange(next)&&next&&(this.explicitTrigger=trigger)},this.dismissFullscreen=()=>{this.fullscreen&&this.requestFullscreenChange(!1)},this.onBackdropClick=()=>{this.overlayHandle?.dismissBackdrop()}}static{this.defaultStrings={...super.defaultStrings,widgetCollapse:LYRA_DEFAULT_widgetCollapse,widgetExitFullscreen:LYRA_DEFAULT_widgetExitFullscreen,widgetExpand:LYRA_DEFAULT_widgetExpand,widgetExpandToFullscreen:LYRA_DEFAULT_widgetExpandToFullscreen,widgetFullscreenPanel:LYRA_DEFAULT_widgetFullscreenPanel,widgetViewGroup:LYRA_DEFAULT_widgetViewGroup}}static{this.styles=[LyraElement.styles,styles]}static{this.properties={collapsed:{type:Boolean,reflect:!0,noAccessor:!0}}}get collapsed(){return this._collapsed}set collapsed(next){this._collapsedExplicitlySet=!0;const old=this._collapsed;this._collapsed=!!next,this.toggleAttribute("collapsed",this._collapsed),this.requestUpdate("collapsed",old)}get views(){return this.effectiveViews}set views(value){const previous=this.effectiveViews;this.effectiveViews=snapshotWidgetViews(value),this.requestUpdate("views",previous)}get storageFullKey(){return this.storageKey?`lr-widget:${this.storageKey}`:void 0}willUpdate(changed){if(super.willUpdate(changed),!this.hasUpdated){this.hasActionsSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="actions"),this.hasIconSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="icon");const labelChildren=Array.from(this.children).filter(el=>el.getAttribute("slot")==="label");this.hasLabelSlot=labelChildren.length>0,this.labelSlotText=this.readLabelSlotText(labelChildren),this.hasSublabelSlot=Array.from(this.children).some(el=>el.getAttribute("slot")==="sublabel");const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.collapsed=="boolean"&&!this._collapsedExplicitlySet&&(this.collapsed=parsed.collapsed)}if(changed.has("fullscreen")&&(this.fullscreen?this.activateFullscreenOverlay():this.deactivateFullscreenOverlay()),changed.has("activeView")&&this.activeView!==""&&(this.activeViewId=this.activeView),changed.has("views")||changed.has("activeViewId")||changed.has("activeView")){const focused=this.renderRoot?.querySelector('[part="view-toggle"]:focus');this.focusedViewIdBeforeUpdate=focused?.dataset.viewId;const views=this.views;views.some(view=>view.viewId===this.activeViewId)||(this.activeViewId=views[0]?.viewId??"")}}updated(changed){super.updated(changed);const actionsSlot=this.renderRoot.querySelector('slot[name="actions"]');if(this.actionsScrollOverflow.observeExtra(actionsSlot?actionsSlot.assignedElements({flatten:!0}):[]),this.viewTogglesScrollOverflow.observeExtra(this.renderRoot.querySelectorAll('[part="view-toggle"]')),this.persistReady&&changed.has("collapsed")&&writePersistedState(this.storageFullKey,{collapsed:this.collapsed}),this.persistReady=!0,changed.has("fullscreen")&&this.fullscreen)this.overlayHandle?.focusInitial();else if(changed.has("collapsed")&&this.fullscreen){const panel=this.shadowRoot?.querySelector('[part="base"]'),active=deepActiveElement(this.ownerDocument);panel&&!collectFocusableElements(panel).includes(active)&&(active&&typeof active.blur=="function"&&active.blur(),this.overlayHandle?.focusInitial())}if(changed.has("views")||changed.has("activeViewId")){const focusedId=this.focusedViewIdBeforeUpdate;this.focusedViewIdBeforeUpdate=void 0,focusedId&&!this.views.some(view=>view.viewId===focusedId)&&Array.from(this.renderRoot.querySelectorAll('[part="view-toggle"]')).find(toggle=>toggle.dataset.viewId===this.activeViewId)?.focus()}}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.fullscreen&&(this.overlayHandle?.isActive()?this.overlayHandle.resume():this.activateFullscreenOverlay(),this.queueOwnerMicrotask(()=>this.overlayHandle?.focusInitial())),this.hasUpdated&&this.queueOwnerMicrotask(()=>{const slot=this.shadowRoot?.querySelector('slot[name="label"]');slot&&this.syncLabelSlot(slot.assignedElements({flatten:!0}))})}disconnectedCallback(){super.disconnectedCallback(),this.overlayHandle?.suspend(),this.resetOwnerRealmWork()}adoptedCallback(){super.adoptedCallback(),this.resetOwnerRealmWork()}resetOwnerRealmWork(){this.ownerRealmGeneration+=1,this.resetLabelSlotObserver()}queueOwnerMicrotask(callback){const ownerDocument=this.ownerDocument,ownerWindow=ownerDocument.defaultView;if(!ownerWindow||!this.isConnected)return;const generation=this.ownerRealmGeneration;ownerWindow.queueMicrotask(()=>{this.ownerRealmGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||callback()})}activateFullscreenOverlay(){this.overlayHandle=activateOverlay({host:this,panel:()=>this.shadowRoot?.querySelector('[part="base"]')??null,onEscape:this.dismissFullscreen,onBackdrop:this.dismissFullscreen,restoreFocusTo:this.explicitTrigger,lockScroll:!0,suspendWhenUnrendered:!0}),this.explicitTrigger=void 0}deactivateFullscreenOverlay(){this.overlayHandle?.deactivate(),this.overlayHandle=void 0}syncLabelSlot(assigned){if(this.hasLabelSlot=assigned.length>0,this.labelSlotText=this.readLabelSlotText(assigned),this.resetLabelSlotObserver(),assigned.length===0||!this.isConnected)return;const ownerDocument=this.ownerDocument,MutationObserverCtor=ownerDocument.defaultView?.MutationObserver;if(!MutationObserverCtor)return;const generation=this.labelSlotObserverGeneration,observer=new MutationObserverCtor(()=>{this.labelSlotObserver!==observer||this.labelSlotObserverDocument!==ownerDocument||this.labelSlotObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||(this.labelSlotText=this.readLabelSlotText(assigned))});this.labelSlotObserver=observer,this.labelSlotObserverDocument=ownerDocument,bindAccessibleTextObserver(observer,this,["alt","aria-labelledby","slot"]);for(const element of assigned)observer.observe(element,{attributes:!0,attributeFilter:["alt","aria-hidden","aria-label","aria-labelledby","class","hidden","inert","style"],childList:!0,characterData:!0,subtree:!0})}readLabelSlotText(assigned){return composedAccessibilityText(assigned).replace(/\s+/g," ").trim()||void 0}resetLabelSlotObserver(){this.labelSlotObserverGeneration+=1,this.labelSlotObserver?.disconnect(),this.labelSlotObserver=void 0,this.labelSlotObserverDocument=void 0}requestCollapse(next){this.emit("lr-collapse-request",{collapsed:next},{cancelable:!0}).defaultPrevented||(this.collapsed=next,this.emit("lr-collapse-change",{collapsed:next}))}requestFullscreenChange(next){return this.emit("lr-fullscreen-request",{fullscreen:next},{cancelable:!0}).defaultPrevented?!1:(this.fullscreen=next,this.emit("lr-fullscreen-change",{fullscreen:next}),!0)}render(){const hasLabel=(this.label??"").length>0,hasSublabel=(this.sublabel??"").length>0,views=this.views,fullscreenInset=sanitizeCssInset(this.fullscreenInset),backdropInset=sanitizeCssInset(this.backdropInset);return html`
|
|
2
2
|
${this.fullscreen?html`<div
|
|
3
3
|
part="backdrop"
|
|
4
4
|
style=${backdropInset?styleMap({"--lr-widget-backdrop-inset":backdropInset}):nothing}
|
|
@@ -82,4 +82,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
82
82
|
</div>`)}
|
|
83
83
|
</div>
|
|
84
84
|
</div>
|
|
85
|
-
`}}__decorate([property()],LyraWidget.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraWidget.prototype,"accessibleLabel",void 0),__decorate([property()],LyraWidget.prototype,"sublabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsible",void 0),__decorate([property({
|
|
85
|
+
`}}__decorate([property()],LyraWidget.prototype,"label",void 0),__decorate([property({attribute:"aria-label"})],LyraWidget.prototype,"accessibleLabel",void 0),__decorate([property()],LyraWidget.prototype,"sublabel",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"collapsible",void 0),__decorate([property({attribute:"storage-key"})],LyraWidget.prototype,"storageKey",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"expandable",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"fullscreen",void 0),__decorate([property({attribute:"fullscreen-inset"})],LyraWidget.prototype,"fullscreenInset",void 0),__decorate([property({attribute:"backdrop-inset"})],LyraWidget.prototype,"backdropInset",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraWidget.prototype,"compact",void 0),__decorate([property({attribute:!1})],LyraWidget.prototype,"views",null),__decorate([property({attribute:!1})],LyraWidget.prototype,"activeViewId",void 0),__decorate([property({attribute:!1})],LyraWidget.prototype,"activeView",void 0),__decorate([state()],LyraWidget.prototype,"hasActionsSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasIconSlot",void 0),__decorate([state()],LyraWidget.prototype,"hasLabelSlot",void 0),__decorate([state()],LyraWidget.prototype,"labelSlotText",void 0),__decorate([state()],LyraWidget.prototype,"hasSublabelSlot",void 0);export{LyraWidget};
|
|
@@ -77,4 +77,4 @@ accessibleLabel?:string;
|
|
|
77
77
|
* before this property existed. */
|
|
78
78
|
triggerTitle?:string;
|
|
79
79
|
/** Forwarded to the hidden file input's own `multiple` attribute. */
|
|
80
|
-
multiple:boolean;disabled:boolean;private inputEl?;private dropdownEl?;private pendingCapability;private pickerGeneration;private pendingPickerGeneration;private get effectiveCapabilities();private get hasFileCapability();protected willUpdate(changed:PropertyValues<this>):void;private effectiveAccept;private activateCapability;private onTriggerClick;private onMenuSelect;private onInputChange;disconnectedCallback():void;private onControlFocus;private onControlBlur;private stopInternalEvent;private primaryControl;focus(options?:FocusOptions):void;blur():void;click():void;private renderHiddenInput;private renderSingleTrigger;private renderMenu;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-attachment-trigger':LyraAttachmentTrigger;}}
|
|
80
|
+
multiple:boolean;disabled:boolean;private inputEl?;private dropdownEl?;private triggerEl?;private hasSyncedDescribedByElements;private pendingCapability;private pickerGeneration;private pendingPickerGeneration;private get effectiveCapabilities();private get hasFileCapability();protected willUpdate(changed:PropertyValues<this>):void;protected updated(changed:PropertyValues<this>):void;private effectiveAccept;private activateCapability;private onTriggerClick;private onMenuSelect;private onInputChange;disconnectedCallback():void;private onControlFocus;private onControlBlur;private stopInternalEvent;private primaryControl;focus(options?:FocusOptions):void;blur():void;click():void;private renderHiddenInput;private renderSingleTrigger;private renderMenu;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-attachment-trigger':LyraAttachmentTrigger;}}
|
|
@@ -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,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{chevronIcon}from"../../../internal/icons.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./attachment-trigger.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_attachmentAdd,LYRA_DEFAULT_attachmentMenuAudio,LYRA_DEFAULT_attachmentMenuCamera,LYRA_DEFAULT_attachmentMenuFiles,LYRA_DEFAULT_attachmentMenuImage,LYRA_DEFAULT_attachmentTriggerAudio,LYRA_DEFAULT_attachmentTriggerCamera,LYRA_DEFAULT_attachmentTriggerFiles,LYRA_DEFAULT_attachmentTriggerImage,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
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,svg}from"lit";import{property,query}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{chevronIcon}from"../../../internal/icons.js";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{styles}from"./attachment-trigger.styles.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{LYRA_DEFAULT_attachmentAdd,LYRA_DEFAULT_attachmentMenuAudio,LYRA_DEFAULT_attachmentMenuCamera,LYRA_DEFAULT_attachmentMenuFiles,LYRA_DEFAULT_attachmentMenuImage,LYRA_DEFAULT_attachmentTriggerAudio,LYRA_DEFAULT_attachmentTriggerCamera,LYRA_DEFAULT_attachmentTriggerFiles,LYRA_DEFAULT_attachmentTriggerImage,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_VIEW_BOX="0 0 24 24",ICON_STROKE_WIDTH="1.75";function icon(paths){return svg`
|
|
2
2
|
<svg
|
|
3
3
|
width="1em"
|
|
4
4
|
height="1em"
|
|
@@ -25,7 +25,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
25
25
|
<path d="M19 10v2a7 7 0 0 1-14 0v-2"></path>
|
|
26
26
|
<line x1="12" y1="19" x2="12" y2="23"></line>
|
|
27
27
|
<line x1="8" y1="23" x2="16" y2="23"></line>
|
|
28
|
-
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]),MAX_ATTACHMENT_CAPABILITIES=4,ATTACHMENT_CAPABILITY_SCAN_LIMIT=64;function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,ATTACHMENT_CAPABILITY_SCAN_LIMIT);for(let index=0;index<length&&normalized.length<MAX_ATTACHMENT_CAPABILITIES;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.multiple=!0,this.disabled=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const OwnerArray=this.ownerDocument.defaultView?.Array??Array,files=Object.freeze(OwnerArray.from(selected));this.emit("lr-files",{capability:this.pendingCapability,files})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
|
|
28
|
+
`)}const CAPABILITY_META={files:{icon:paperclipIcon,triggerKey:"attachmentTriggerFiles",menuKey:"attachmentMenuFiles"},image:{icon:imageIcon,triggerKey:"attachmentTriggerImage",menuKey:"attachmentMenuImage"},camera:{icon:cameraIcon,triggerKey:"attachmentTriggerCamera",menuKey:"attachmentMenuCamera"},audio:{icon:audioIcon,triggerKey:"attachmentTriggerAudio",menuKey:"attachmentMenuAudio"}},OWNED_CAPABILITY_SNAPSHOTS=new WeakSet;function ownCapabilitySnapshot(values){const snapshot=Object.freeze(values);return OWNED_CAPABILITY_SNAPSHOTS.add(snapshot),snapshot}const DEFAULT_CAPABILITIES=ownCapabilitySnapshot(["files"]),MAX_ATTACHMENT_CAPABILITIES=4,ATTACHMENT_CAPABILITY_SCAN_LIMIT=64;function normalizeCapabilities(value){try{if(!Array.isArray(value))return DEFAULT_CAPABILITIES;if(OWNED_CAPABILITY_SNAPSHOTS.has(value))return value;const normalized=[],length=Math.min(value.length,ATTACHMENT_CAPABILITY_SCAN_LIMIT);for(let index=0;index<length&&normalized.length<MAX_ATTACHMENT_CAPABILITIES;index++){const candidate=value[index];typeof candidate=="string"&&Object.prototype.hasOwnProperty.call(CAPABILITY_META,candidate)&&!normalized.includes(candidate)&&normalized.push(candidate)}return ownCapabilitySnapshot(normalized)}catch{return DEFAULT_CAPABILITIES}}function isCanonicalCapabilitySnapshot(source){try{return typeof source=="object"&&source!==null&&OWNED_CAPABILITY_SNAPSHOTS.has(source)}catch{return!1}}class LyraAttachmentTrigger extends LyraElement{constructor(){super(...arguments),this.capabilities=DEFAULT_CAPABILITIES,this.accept="",this.multiple=!0,this.disabled=!1,this.hasSyncedDescribedByElements=!1,this.pendingCapability="files",this.pickerGeneration=0,this.pendingPickerGeneration=-1,this.onTriggerClick=()=>{const capability=this.effectiveCapabilities[0];capability!==void 0&&this.activateCapability(capability)},this.onMenuSelect=e=>{e.stopPropagation();const capability=e.detail.item.value;Object.prototype.hasOwnProperty.call(CAPABILITY_META,capability)&&this.effectiveCapabilities.includes(capability)&&this.activateCapability(capability)},this.onInputChange=e=>{e.stopPropagation();const input=e.target,selected=input.files,generation=this.pendingPickerGeneration;if(this.pendingPickerGeneration=-1,this.isConnected&&generation===this.pickerGeneration&&!this.disabled&&selected&&selected.length>0){const OwnerArray=this.ownerDocument.defaultView?.Array??Array,files=Object.freeze(OwnerArray.from(selected));this.emit("lr-files",{capability:this.pendingCapability,files})}input.value=""},this.onControlFocus=event=>{relayNativeEvent(this,event)},this.onControlBlur=event=>{relayNativeEvent(this,event)},this.stopInternalEvent=event=>{event.stopPropagation()}}static{this.defaultStrings={...super.defaultStrings,attachmentAdd:LYRA_DEFAULT_attachmentAdd,attachmentMenuAudio:LYRA_DEFAULT_attachmentMenuAudio,attachmentMenuCamera:LYRA_DEFAULT_attachmentMenuCamera,attachmentMenuFiles:LYRA_DEFAULT_attachmentMenuFiles,attachmentMenuImage:LYRA_DEFAULT_attachmentMenuImage,attachmentTriggerAudio:LYRA_DEFAULT_attachmentTriggerAudio,attachmentTriggerCamera:LYRA_DEFAULT_attachmentTriggerCamera,attachmentTriggerFiles:LYRA_DEFAULT_attachmentTriggerFiles,attachmentTriggerImage:LYRA_DEFAULT_attachmentTriggerImage,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.ownedCollectionProperties=Object.freeze(["capabilities"])}static{this.styles=[LyraElement.styles,styles]}static{this.immutableEventDetails=Object.freeze(["lr-files"])}get effectiveCapabilities(){return normalizeCapabilities(this.capabilities)}get hasFileCapability(){return this.effectiveCapabilities.includes("files")||this.effectiveCapabilities.includes("image")}willUpdate(changed){if(super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.dropdownEl?.hide(),changed.has("capabilities")){const normalized=normalizeCapabilities(this.capabilities);isCanonicalCapabilitySnapshot(this.capabilities)||(this.capabilities=normalized)}}updated(changed){super.updated(changed);const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.triggerEl,hostDescribedBy))}effectiveAccept(capability){return capability==="image"?this.accept||"image/*":this.accept}activateCapability(capability){if(this.disabled)return;if(capability==="camera"){this.emit("lr-camera-request",null);return}if(capability==="audio"){this.emit("lr-audio-request",null);return}this.pendingCapability=capability,this.pendingPickerGeneration=++this.pickerGeneration;const input=this.inputEl;input&&(input.accept=this.effectiveAccept(capability),input.click())}disconnectedCallback(){this.pendingPickerGeneration=-1,this.pickerGeneration++,this.dropdownEl?.hide(),super.disconnectedCallback()}primaryControl(){return this.renderRoot.querySelector('[part="trigger"], [part="menu-trigger"]')??void 0}focus(options){this.primaryControl()?.focus(options)}blur(){this.primaryControl()?.blur()}click(){this.primaryControl()?.click()}renderHiddenInput(){return html`
|
|
29
29
|
<input
|
|
30
30
|
part="hidden-input"
|
|
31
31
|
type="file"
|
|
@@ -84,4 +84,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
84
84
|
${single?this.renderSingleTrigger(capabilities[0]):nothing}
|
|
85
85
|
${multi?this.renderMenu():nothing}
|
|
86
86
|
${this.hasFileCapability?this.renderHiddenInput():nothing}
|
|
87
|
-
`}}__decorate([property({attribute:!1})],LyraAttachmentTrigger.prototype,"capabilities",void 0),__decorate([property()],LyraAttachmentTrigger.prototype,"accept",void 0),__decorate([property({attribute:"accessible-label"})],LyraAttachmentTrigger.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"trigger-title"})],LyraAttachmentTrigger.prototype,"triggerTitle",void 0),__decorate([property({type:Boolean,reflect:!0,converter:trueDefaultBooleanConverter})],LyraAttachmentTrigger.prototype,"multiple",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraAttachmentTrigger.prototype,"disabled",void 0),__decorate([query('input[type="file"]')],LyraAttachmentTrigger.prototype,"inputEl",void 0),__decorate([query("lr-dropdown")],LyraAttachmentTrigger.prototype,"dropdownEl",void 0);export{LyraAttachmentTrigger};
|
|
87
|
+
`}}__decorate([property({attribute:!1})],LyraAttachmentTrigger.prototype,"capabilities",void 0),__decorate([property()],LyraAttachmentTrigger.prototype,"accept",void 0),__decorate([property({attribute:"accessible-label"})],LyraAttachmentTrigger.prototype,"accessibleLabel",void 0),__decorate([property({attribute:"trigger-title"})],LyraAttachmentTrigger.prototype,"triggerTitle",void 0),__decorate([property({type:Boolean,reflect:!0,converter:trueDefaultBooleanConverter})],LyraAttachmentTrigger.prototype,"multiple",void 0),__decorate([property({type:Boolean,reflect:!0})],LyraAttachmentTrigger.prototype,"disabled",void 0),__decorate([query('input[type="file"]')],LyraAttachmentTrigger.prototype,"inputEl",void 0),__decorate([query("lr-dropdown")],LyraAttachmentTrigger.prototype,"dropdownEl",void 0),__decorate([query('[part="trigger"], [part="menu-trigger"]')],LyraAttachmentTrigger.prototype,"triggerEl",void 0);export{LyraAttachmentTrigger};
|
|
@@ -28,7 +28,9 @@ bytes:number;
|
|
|
28
28
|
decorative:boolean;
|
|
29
29
|
/** Shows only the icon or the icon together with its label and optional description. */
|
|
30
30
|
private _mode;get mode():LyraFileIconMode;set mode(next:LyraFileIconMode);
|
|
31
|
-
/** Optional visible/accessibility label override. Explicit empty text is preserved
|
|
31
|
+
/** Optional visible/accessibility label override. Explicit empty text is preserved for the
|
|
32
|
+
* visible `mode="label"` text, but never leaves a non-decorative `role="img"` unnamed -- the
|
|
33
|
+
* computed accessible name falls back to the resolved file-type metadata label instead. */
|
|
32
34
|
label?:string;
|
|
33
35
|
/** Immutable metadata authority for this instance. */
|
|
34
36
|
registry:LyraFileTypeMetadataRegistry;private resolveMetadata;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-file-icon':LyraFileIcon;}}
|
|
@@ -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}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../attachment-chip/file-size.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{defaultFileTypeMetadataRegistry}from"./file-type-metadata.js";import{styles}from"./file-icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_fileTypeArchive,LYRA_DEFAULT_fileTypeAudio,LYRA_DEFAULT_fileTypeCode,LYRA_DEFAULT_fileTypeFile,LYRA_DEFAULT_fileTypeImage,LYRA_DEFAULT_fileTypePdf,LYRA_DEFAULT_fileTypePresentation,LYRA_DEFAULT_fileTypeSpreadsheet,LYRA_DEFAULT_fileTypeText,LYRA_DEFAULT_fileTypeVideo,LYRA_DEFAULT_fileTypeWithSize,LYRA_DEFAULT_fileTypeWord,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_LABELS={file:"fileTypeFile",pdf:"fileTypePdf",word:"fileTypeWord",spreadsheet:"fileTypeSpreadsheet",presentation:"fileTypePresentation",text:"fileTypeText",code:"fileTypeCode",archive:"fileTypeArchive",image:"fileTypeImage",audio:"fileTypeAudio",video:"fileTypeVideo"},FILE_ICON_MODE=literalSetConverter(["icon","label"],"icon");class LyraFileIcon extends LyraElement{constructor(){super(...arguments),this.mimeType="",this.name="",this.bytes=0,this.decorative=!1,this._mode="icon",this.registry=defaultFileTypeMetadataRegistry}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,fileTypeArchive:LYRA_DEFAULT_fileTypeArchive,fileTypeAudio:LYRA_DEFAULT_fileTypeAudio,fileTypeCode:LYRA_DEFAULT_fileTypeCode,fileTypeFile:LYRA_DEFAULT_fileTypeFile,fileTypeImage:LYRA_DEFAULT_fileTypeImage,fileTypePdf:LYRA_DEFAULT_fileTypePdf,fileTypePresentation:LYRA_DEFAULT_fileTypePresentation,fileTypeSpreadsheet:LYRA_DEFAULT_fileTypeSpreadsheet,fileTypeText:LYRA_DEFAULT_fileTypeText,fileTypeVideo:LYRA_DEFAULT_fileTypeVideo,fileTypeWithSize:LYRA_DEFAULT_fileTypeWithSize,fileTypeWord:LYRA_DEFAULT_fileTypeWord,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=FILE_ICON_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}resolveMetadata(){try{if(this.registry&&typeof this.registry.resolve=="function")return this.registry.resolve(this.mimeType,this.name)}catch{}return defaultFileTypeMetadataRegistry.resolve("","")}render(){const metadata=this.resolveMetadata(),metadataLabel=metadata.provenance==="consumer"?metadata.label:this.localize(ICON_LABELS[metadata.icon]),renderedLabel=this.label??metadataLabel,bytes=finiteRange(this.bytes,0,0),sizeText=bytes>0?formatFileSize(bytes,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),value=>getNumberFormat(this.effectiveLocale,{maximumFractionDigits:1}).format(value)):"",fallbackLabel=sizeText?this.localize("fileTypeWithSize",void 0,{label:
|
|
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}from"lit/decorators.js";import{hostAriaLabel}from"../../../internal/a11y.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{formatFileSize,FILE_SIZE_UNIT_KEYS}from"../attachment-chip/file-size.js";import{finiteRange}from"../../../internal/numbers.js";import{literalSetConverter}from"../../../internal/converters.js";import{defaultFileTypeMetadataRegistry}from"./file-type-metadata.js";import{styles}from"./file-icon.styles.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_fileTypeArchive,LYRA_DEFAULT_fileTypeAudio,LYRA_DEFAULT_fileTypeCode,LYRA_DEFAULT_fileTypeFile,LYRA_DEFAULT_fileTypeImage,LYRA_DEFAULT_fileTypePdf,LYRA_DEFAULT_fileTypePresentation,LYRA_DEFAULT_fileTypeSpreadsheet,LYRA_DEFAULT_fileTypeText,LYRA_DEFAULT_fileTypeVideo,LYRA_DEFAULT_fileTypeWithSize,LYRA_DEFAULT_fileTypeWord,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_search,LYRA_DEFAULT_select}from"../../../internal/default-strings.generated.js";const ICON_LABELS={file:"fileTypeFile",pdf:"fileTypePdf",word:"fileTypeWord",spreadsheet:"fileTypeSpreadsheet",presentation:"fileTypePresentation",text:"fileTypeText",code:"fileTypeCode",archive:"fileTypeArchive",image:"fileTypeImage",audio:"fileTypeAudio",video:"fileTypeVideo"},FILE_ICON_MODE=literalSetConverter(["icon","label"],"icon");class LyraFileIcon extends LyraElement{constructor(){super(...arguments),this.mimeType="",this.name="",this.bytes=0,this.decorative=!1,this._mode="icon",this.registry=defaultFileTypeMetadataRegistry}static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,fileTypeArchive:LYRA_DEFAULT_fileTypeArchive,fileTypeAudio:LYRA_DEFAULT_fileTypeAudio,fileTypeCode:LYRA_DEFAULT_fileTypeCode,fileTypeFile:LYRA_DEFAULT_fileTypeFile,fileTypeImage:LYRA_DEFAULT_fileTypeImage,fileTypePdf:LYRA_DEFAULT_fileTypePdf,fileTypePresentation:LYRA_DEFAULT_fileTypePresentation,fileTypeSpreadsheet:LYRA_DEFAULT_fileTypeSpreadsheet,fileTypeText:LYRA_DEFAULT_fileTypeText,fileTypeVideo:LYRA_DEFAULT_fileTypeVideo,fileTypeWithSize:LYRA_DEFAULT_fileTypeWithSize,fileTypeWord:LYRA_DEFAULT_fileTypeWord,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select}}static{this.styles=[LyraElement.styles,styles]}get mode(){return this._mode}set mode(next){const normalized=FILE_ICON_MODE.normalizeReflected(this,"mode",next),old=this._mode;old!==normalized&&(this._mode=normalized,this.requestUpdate("mode",old))}resolveMetadata(){try{if(this.registry&&typeof this.registry.resolve=="function")return this.registry.resolve(this.mimeType,this.name)}catch{}return defaultFileTypeMetadataRegistry.resolve("","")}render(){const metadata=this.resolveMetadata(),metadataLabel=metadata.provenance==="consumer"?metadata.label:this.localize(ICON_LABELS[metadata.icon]),renderedLabel=this.label??metadataLabel,bytes=finiteRange(this.bytes,0,0),sizeText=bytes>0?formatFileSize(bytes,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),value=>getNumberFormat(this.effectiveLocale,{maximumFractionDigits:1}).format(value)):"",accessibleNameBase=renderedLabel||metadataLabel,fallbackLabel=sizeText?this.localize("fileTypeWithSize",void 0,{label:accessibleNameBase,size:sizeText}):accessibleNameBase,accessibleLabel=hostAriaLabel(this)??fallbackLabel,descriptionId=this.mode==="label"&&metadata.provenance==="consumer"&&metadata.description?"metadata-description":void 0;return html`
|
|
2
2
|
<span
|
|
3
3
|
part="base"
|
|
4
4
|
role=${this.decorative?"presentation":"img"}
|
|
@@ -189,7 +189,7 @@ customError:string|null;private dragCounter;private dropToken;
|
|
|
189
189
|
* shadow root is not reliably announced (JAWS with Firefox ignores one outright), so
|
|
190
190
|
* `[part="status"]` is only an `aria-hidden` mirror and `[part="rejection"]` is plain visible
|
|
191
191
|
* text. */
|
|
192
|
-
private politeSink?;private assertiveSink?;
|
|
192
|
+
private politeSink?;private assertiveSink?;private hasSyncedDescribedByElements;
|
|
193
193
|
/** False until the first render has committed, so mounting never announces a resting state. */
|
|
194
194
|
private announcementsArmed;private _name;private _files;private _fileCount;private _disabled;private _required;private validationTargetOverride?;private validatorAttributeObserver?;private _fieldsetDisabled;private thumbnailUrls;constructor();get form():HTMLFormElement|null;set form(owner:FormOwnerValue);getForm():HTMLFormElement|null;get labels():NodeList;get validity():ValidityState;get validationMessage():string;get willValidate():boolean;
|
|
195
195
|
/** Submitted field name.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=this.effectiveMultiple?[...valid]:valid.slice(0,1);const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files:this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver()),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{LyraElement}from"../../../internal/lyra-element.js";import{installFormControlLabelSupport}from"../../../internal/form-control-labels.js";installFormControlLabelSupport();import{hostAriaLabel,srOnly}from"../../../internal/a11y.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{finiteRange}from"../../../internal/numbers.js";import{AnchoredValidityController,VALIDITY_ANCHOR}from"../../../internal/anchored-validity.js";import{setCustomState,syncValidityStates}from"../../../internal/custom-states.js";import{syncAriaDescribedByElements}from"../../../internal/aria-controls.js";import{attachInternalsSafely,getFormOwner,installCustomErrorProperty,isBarredFromValidation,setFormOwner}from"../../../internal/form-associated.js";import{installInvalidEventAlias}from"../../../internal/invalid-event-alias.js";import{dispatchNativeEvent,relayNativeEvent}from"../../../internal/native-event-relay.js";import{sizes}from"../../../internal/sizes.styles.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{closeIcon,fileIcon}from"../../../internal/icons.js";import{styles}from"./file-input.styles.js";import{matchesAccept}from"./accept.js";import{presenceTrueDefaultBooleanConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{FILE_SIZE_UNIT_KEYS,formatFileSize}from"../attachment-chip/file-size.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_dropzoneRejectedType,LYRA_DEFAULT_dropzoneReleaseToAdd,LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_fileInputAcceptedMany,LYRA_DEFAULT_fileInputAcceptedOne,LYRA_DEFAULT_fileInputDefaultLabel,LYRA_DEFAULT_fileInputFolderRejected,LYRA_DEFAULT_fileInputRejectedCount,LYRA_DEFAULT_fileInputRejectedLimit,LYRA_DEFAULT_fileInputRejectedMany,LYRA_DEFAULT_fileInputRejectedOne,LYRA_DEFAULT_fileInputRejectedRead,LYRA_DEFAULT_fileInputRejectedSize,LYRA_DEFAULT_fileInputRejectedType,LYRA_DEFAULT_fileSizeUnitB,LYRA_DEFAULT_fileSizeUnitGb,LYRA_DEFAULT_fileSizeUnitKb,LYRA_DEFAULT_fileSizeUnitMb,LYRA_DEFAULT_fileSizeUnitTb,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_removeWithContext,LYRA_DEFAULT_restore,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_valueInvalid}from"../../../internal/default-strings.generated.js";const VALIDITY_FLAG_KEYS=new Set(["badInput","customError","patternMismatch","rangeOverflow","rangeUnderflow","stepMismatch","tooLong","tooShort","typeMismatch","valueMissing"]);function isValidityFlagKey(value){return typeof value=="string"&&VALIDITY_FLAG_KEYS.has(value)}const DEFAULT_MAX_FILE_SIZE_BYTES=25*1024*1024,MAX_DROPPED_FOLDER_ENTRIES=1e4,MAX_MIME_TYPES=1e4,EMPTY_MIME_TYPES=Object.freeze([]);function snapshotMimeTypes(value){try{if(!Array.isArray(value))return EMPTY_MIME_TYPES;const count=Math.min(value.length,MAX_MIME_TYPES),values=[];for(let index=0;index<count;index++)try{const candidate=value[index];typeof candidate=="string"&&values.push(candidate)}catch{}return values.length?Object.freeze(values):EMPTY_MIME_TYPES}catch{return EMPTY_MIME_TYPES}}const INTERACTIVE_CONTENT_SELECTOR='a[href], area[href], button, input, select, textarea, summary, [contenteditable]:not([contenteditable="false"]), [role="button"], [role="link"], [tabindex]:not([tabindex="-1"])';function isElementTarget(value){const candidate=value;return candidate.nodeType===1&&typeof candidate.matches=="function"}function isFileValue(value){if(value===null||typeof value!="object")return!1;try{const candidate=value;return Object.prototype.toString.call(value)==="[object File]"&&typeof candidate.name=="string"&&typeof candidate.lastModified=="number"&&typeof candidate.size=="number"&&typeof candidate.type=="string"&&typeof candidate.slice=="function"}catch{return!1}}class LyraFileInput extends LyraElement{static{this.defaultStrings={...super.defaultStrings,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,dropzoneRejectedType:LYRA_DEFAULT_dropzoneRejectedType,dropzoneReleaseToAdd:LYRA_DEFAULT_dropzoneReleaseToAdd,fieldRequired:LYRA_DEFAULT_fieldRequired,fileInputAcceptedMany:LYRA_DEFAULT_fileInputAcceptedMany,fileInputAcceptedOne:LYRA_DEFAULT_fileInputAcceptedOne,fileInputDefaultLabel:LYRA_DEFAULT_fileInputDefaultLabel,fileInputFolderRejected:LYRA_DEFAULT_fileInputFolderRejected,fileInputRejectedCount:LYRA_DEFAULT_fileInputRejectedCount,fileInputRejectedLimit:LYRA_DEFAULT_fileInputRejectedLimit,fileInputRejectedMany:LYRA_DEFAULT_fileInputRejectedMany,fileInputRejectedOne:LYRA_DEFAULT_fileInputRejectedOne,fileInputRejectedRead:LYRA_DEFAULT_fileInputRejectedRead,fileInputRejectedSize:LYRA_DEFAULT_fileInputRejectedSize,fileInputRejectedType:LYRA_DEFAULT_fileInputRejectedType,fileSizeUnitB:LYRA_DEFAULT_fileSizeUnitB,fileSizeUnitGb:LYRA_DEFAULT_fileSizeUnitGb,fileSizeUnitKb:LYRA_DEFAULT_fileSizeUnitKb,fileSizeUnitMb:LYRA_DEFAULT_fileSizeUnitMb,fileSizeUnitTb:LYRA_DEFAULT_fileSizeUnitTb,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,removeWithContext:LYRA_DEFAULT_removeWithContext,restore:LYRA_DEFAULT_restore,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,valueInvalid:LYRA_DEFAULT_valueInvalid}}static{this.immutableEventDetails=Object.freeze(["lr-files"])}static{this.formAssociated=!0}static{this.styles=[LyraElement.styles,sizes,styles,srOnly]}static{this.properties={customError:{attribute:"custom-error",reflect:!0,noAccessor:!0},name:{reflect:!0,noAccessor:!0},files:{attribute:!1,noAccessor:!0},disabled:{type:Boolean,reflect:!0,noAccessor:!0},required:{type:Boolean,reflect:!0,noAccessor:!0}}}get allowedMimeTypes(){return this._allowedMimeTypes}set allowedMimeTypes(next){const old=this._allowedMimeTypes;this._allowedMimeTypes=snapshotMimeTypes(next),this.requestUpdate("allowedMimeTypes",old)}get forbiddenMimeTypes(){return this._forbiddenMimeTypes}set forbiddenMimeTypes(next){const old=this._forbiddenMimeTypes;this._forbiddenMimeTypes=snapshotMimeTypes(next),this.requestUpdate("forbiddenMimeTypes",old)}constructor(){super(),this.multiple=!1,this.compact=!1,this.accept="",this.capture="",this._allowedMimeTypes=EMPTY_MIME_TYPES,this._forbiddenMimeTypes=EMPTY_MIME_TYPES,this.maxFileSize=0,this.directory=!1,this.paste=!0,this.label="",this.hint="",this.errorText="",this.withLabel=!1,this.withHint=!1,this.withError=!1,this.size="m",this.validators=[],this.accessibleLabel="",this.dragState="default",this.resultStatus="",this.rejectedFiles=Object.freeze([]),this.touched=!1,this.validityRevision=0,this.slotPresence=new SlotPresenceController(this),this.dragCounter=0,this.dropToken=0,this.hasSyncedDescribedByElements=!1,this.announcementsArmed=!1,this._name=null,this._files=[],this._fileCount=0,this._disabled=!1,this._required=!1,this._fieldsetDisabled=!1,this.thumbnailUrls=new Map,this.onDragEnter=e=>{if(e.preventDefault(),this.liveDisabled)return;this.dragCounter++;const items=e.dataTransfer?[...e.dataTransfer.items].filter(i=>i.kind==="file"):[];this.dragState=items.length?this.previewState(items):"default",this.publishCustomStates()},this.onDragOver=e=>{e.preventDefault(),this.liveDisabled},this.onDragLeave=e=>{this.liveDisabled||(e.preventDefault(),this.dragCounter=Math.max(0,this.dragCounter-1),this.dragCounter===0&&(this.dragState="default",this.publishCustomStates()))},this.onDrop=e=>{if(e.preventDefault(),this.liveDisabled)return;this.resetDragSession();const token=++this.dropToken,files=[...e.dataTransfer?.files??[]],folders=[],items=e.dataTransfer?.items,itemCount=Math.min(items?.length??0,MAX_DROPPED_FOLDER_ENTRIES+1);for(let index=0;index<itemCount;index++){const entry=items?.[index]?.webkitGetAsEntry?.();entry?.isDirectory&&folders.push(entry)}if((items?.length??0)>MAX_DROPPED_FOLDER_ENTRIES&&this.effectiveMultiple){this.emitFiles([],[this.folderFailure(folders[0]?.name??"","limit")]);return}if(folders.length&&this.effectiveMultiple){const isCurrent=()=>token===this.dropToken&&this.isConnected&&!this.liveDisabled;this.readDroppedFolders(folders,isCurrent).then(result=>{if(!isCurrent()||result.status==="cancelled")return;if(result.status==="error"||result.status==="limit"){this.emitFiles([],[this.folderFailure(result.name,result.status==="limit"?"limit":"read")]);return}const allFiles=[...files,...result.files];allFiles.length&&this.emitFiles(allFiles)});return}const rejectedFolders=folders.map(folder=>this.folderFailure(folder.name,"directory"));(files.length||rejectedFolders.length)&&this.emitFiles(files,rejectedFolders)},this.onPaste=e=>{if(!this.paste||this.liveDisabled)return;const files=[...e.clipboardData?.files??[]];files.length&&(e.preventDefault(),this.emitFiles(files))},this.onInputChange=e=>{e.stopPropagation();const input=e.target,files=[...input.files??[]];input.value="",!this.liveDisabled&&files.length&&this.emitFiles(files)},this.onFocus=event=>{if(this.liveDisabled){event.stopPropagation();return}relayNativeEvent(this,event)},this.onBlur=event=>{this.liveDisabled||(this.touched=!0),this.publishCustomStates(),relayNativeEvent(this,event)},this.onKeyDown=e=>{this.liveDisabled||(e.key==="Enter"||e.key===" "||e.key==="Spacebar")&&(e.preventDefault(),this.openPicker())},this.onDropzoneClick=event=>{const path=event.composedPath();path.includes(this.baseEl)||path.some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.onVisibleLabelClick=event=>{const label=event.currentTarget,path=event.composedPath(),labelIndex=path.indexOf(label);(labelIndex<0?path:path.slice(0,labelIndex)).some(node=>isElementTarget(node)&&node.matches(INTERACTIVE_CONTENT_SELECTOR))||this.openPicker()},this.internals=attachInternalsSafely(this),this.validityController=new AnchoredValidityController(this,this.internals,()=>this[VALIDITY_ANCHOR]()),installCustomErrorProperty(this,()=>this.validityController.customValidityMessage),installInvalidEventAlias(this,init=>this.emit("lr-invalid",null,init)),this.internals.setFormValue(null)}get form(){return getFormOwner(this.internals)}set form(owner){setFormOwner(this,owner)}getForm(){return getFormOwner(this.internals)}get labels(){return this.internals.labels}get validity(){return this.internals.validity}get validationMessage(){return this.internals.validationMessage}get willValidate(){return this.internals.willValidate}get name(){return this._name}set name(next){const old=this._name;this._name=next==null||next===""?null:String(next),this._name==null?this.removeAttribute("name"):this.setAttribute("name",this._name),this.syncFormValue(),this.requestUpdate("name",old)}get files(){return[...this._files]}set files(next){const old=this._files,valid=Array.isArray(next)?next.filter(isFileValue):[];this._files=[...valid];const oldCount=this._fileCount;this._fileCount=this._files.length,this.syncThumbnailUrls(),this.syncFormValue(),this.updateValidity(),this.requestUpdate("files",old),oldCount!==this._fileCount&&this.requestUpdate("fileCount",oldCount)}get fileCount(){return this._fileCount}get dragging(){return this.dragState!=="default"}get effectiveMultiple(){return this.multiple||this.directory}get disabled(){return this._disabled}set disabled(next){const old=this._disabled;this._disabled=!!next,this.toggleAttribute("disabled",this._disabled),this._disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate("disabled",old)}get required(){return this._required}set required(next){const old=this._required;this._required=!!next,this.toggleAttribute("required",this._required),this.updateValidity(),this.requestUpdate("required",old)}get effectiveDisabled(){return this.disabled||this._fieldsetDisabled}get validationTarget(){return this.validationTargetOverride??this.baseEl}set validationTarget(next){this.validationTargetOverride=next??void 0,this.validityController.refreshAnchor()}[VALIDITY_ANCHOR](){return this.validationTarget??null}willUpdate(changed){super.willUpdate(changed),(changed.has("multiple")||changed.has("directory")||changed.has("files"))&&(!this.effectiveMultiple&&this._files.length>1?this.files=this._files.slice(0,1):this.syncFormValue())}connectedCallback(){super.connectedCallback(),this.syncThumbnailUrls(),this.updateValidity(),this.hasUpdated&&this.syncValidatorAttributeObserver(),this.politeSink??=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}),this.assertiveSink??=acquireAnnouncementSink("assertive",{document:this.ownerDocument,source:this})}disconnectedCallback(){this.dropToken++,this.disconnectValidatorAttributeObserver(),this.resetDragSession();for(const thumbnail of this.thumbnailUrls.values())thumbnail.revoke();this.thumbnailUrls.clear(),this.politeSink?.release(),this.politeSink=void 0,this.assertiveSink?.release(),this.assertiveSink=void 0,this.announcementsArmed=!1,super.disconnectedCallback()}updated(changed){super.updated(changed),changed.has("validators")&&(this.updateValidity(),this.syncValidatorAttributeObserver());const hostDescribedBy=this.getAttribute("aria-describedby");(hostDescribedBy||this.hasSyncedDescribedByElements)&&(this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,this.baseEl,hostDescribedBy)),this.announcementsArmed&&(changed.has("dragState")&&this.dragState!=="default"&&this.politeSink?.announce(this.dragStatusText()),changed.has("resultStatus")&&this.resultStatus&&this.politeSink?.announce(this.resultStatus),changed.has("rejectedFiles")&&this.rejectedFiles.length>0&&this.assertiveSink?.announce(this.rejectedFiles.map(rejected=>this.rejectionMessage(rejected)).join(" "))),this.announcementsArmed=!0}syncFormValue(){if(!this.name||this._files.length===0){const state2=this.effectiveMultiple?this.createRestorationFormData():this._files[0]??null;this.internals.setFormValue(null,state2);return}if(this.effectiveMultiple){const submitted=this.createFormData(),state2=this.createRestorationFormData();if(!submitted||!state2){this.internals.setFormValue(null);return}for(const file2 of this._files)submitted.append(this.name,file2);this.internals.setFormValue(submitted,state2);return}const file=this._files[0]??null;this.internals.setFormValue(file,file)}createFormData(){const FormDataCtor=this.ownerDocument?.defaultView?.FormData;return FormDataCtor?new FormDataCtor:null}createRestorationFormData(){const state2=this.createFormData();if(!state2)return null;for(const file of this._files)state2.append("file",file);return state2}get barredFromValidation(){return isBarredFromValidation(this,this.internals)}validatorResult(){let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}for(const validator of validators){let result;try{if(typeof validator=="object"&&validator!==null&&"checkValidity"in validator){const checked=validator.checkValidity(this);if(checked?.isValid===!0)continue;const flags={};for(const key of Array.isArray(checked?.invalidKeys)?checked.invalidKeys:[])isValidityFlagKey(key)&&(flags[key]=!0);Object.values(flags).some(Boolean)||(flags.customError=!0);let message=typeof checked?.message=="string"?checked.message:"";return!message&&typeof validator.message=="string"&&(message=validator.message),!message&&typeof validator.message=="function"&&(message=validator.message(this)),{flags,message:message||this.localize("valueInvalid")}}if(result=typeof validator=="function"?validator(this.files,this):validator?.validate(this.files,this),result===void 0||result===!0)continue;if(typeof result=="string")return{flags:{customError:!0},message:result};if(result===!1)return{flags:{customError:!0},message:this.localize("valueInvalid")};if(result&&typeof result=="object"){const flags={};for(const key of VALIDITY_FLAG_KEYS)Object.prototype.hasOwnProperty.call(result,key)&&result[key]&&(flags[key]=!0);if(Object.values(flags).some(Boolean))return{flags,message:this.localize("valueInvalid")}}}catch{return{flags:{customError:!0},message:this.localize("valueInvalid")}}}return{}}syncValidatorAttributeObserver(){this.disconnectValidatorAttributeObserver();const owner=this.ownerDocument.defaultView,MutationObserverCtor=owner?.MutationObserver;if(!this.isConnected||!owner||typeof MutationObserverCtor!="function")return;const attributes=new Set;let validators;try{validators=Array.isArray(this.validators)?Array.from(this.validators):[]}catch{return}for(const validator of validators)try{if(typeof validator!="object"||validator===null||!("checkValidity"in validator))continue;const observed=validator.observedAttributes;if(!Array.isArray(observed))continue;for(const name of observed)typeof name=="string"&&name.length>0&&attributes.add(name)}catch{continue}if(attributes.size===0)return;const binding={},observer=new MutationObserverCtor(()=>{this.validatorAttributeObserver!==binding||!this.isConnected||this.ownerDocument.defaultView!==owner||(this.updateValidity(),this.validityRevision++)});binding.observer=observer,binding.owner=owner;try{observer.observe(this,{attributes:!0,attributeFilter:[...attributes]}),this.validatorAttributeObserver=binding}catch{observer.disconnect()}}disconnectValidatorAttributeObserver(){const binding=this.validatorAttributeObserver;this.validatorAttributeObserver=void 0,binding?.observer.disconnect()}updateValidity(){if(this.barredFromValidation){this.validityController.setValidity({}),this.publishCustomStates();return}const flags={};let message="";this.required&&this._files.length===0&&(flags.valueMissing=!0,message=this.localize("fieldRequired"));const configured=this.validatorResult();configured.flags&&Object.assign(flags,configured.flags),configured.message&&(message=configured.message),this.validityController.setValidity(flags,message),this.publishCustomStates()}publishCustomStates(){syncValidityStates(this.internals,{required:this.required,hasInteracted:this.touched,barred:this.barredFromValidation}),setCustomState(this.internals,"blank",this._files.length===0),setCustomState(this.internals,"dragging",this.dragging),this.toggleAttribute("dragging",this.dragging)}checkValidity(){return this.updateValidity(),this.internals.checkValidity()}reportValidity(){return this.touched=!0,this.updateValidity(),this.publishCustomStates(),this.internals.reportValidity()}setCustomValidity(message){this.validityController.setCustomValidity(message??""),this.publishCustomStates(),this.requestUpdate()}resetValidity(){this.validityController.setCustomValidity(""),this.updateValidity(),this.requestUpdate()}formResetCallback(){this.touched=!1,this.files=[],this.rejectedFiles=[],this.resultStatus=""}formStateRestoreCallback(state2,reason){if(isFileValue(state2)){this.files=[state2];return}const restored=this.readFormDataFiles(state2);if(restored){this.files=restored;return}this.files=[]}readFormDataFiles(value){if(value===null||typeof value!="object")return;const FormDataCtor=this.ownerDocument.defaultView?.FormData??globalThis.FormData;try{FormDataCtor.prototype.has.call(value,"__lyra_form_state_brand_probe__");const iterator=value.values.call(value),files=[];let entries=0;for(;entries<=MAX_DROPPED_FOLDER_ENTRIES;){const next=iterator.next();if(next.done)return files;if(entries===MAX_DROPPED_FOLDER_ENTRIES)return;entries+=1,isFileValue(next.value)&&files.push(next.value)}return}catch{return}}formDisabledCallback(disabled){this._fieldsetDisabled=disabled,disabled&&(this.dropToken++,this.resetDragSession()),this.updateValidity(),this.requestUpdate()}syncThumbnailUrls(){const urlApi=this.ownerDocument.defaultView?.URL??globalThis.URL,canCreate=typeof urlApi.createObjectURL=="function",canRevoke=typeof urlApi.revokeObjectURL=="function";let changed=!1;for(const[file,thumbnail]of this.thumbnailUrls)(!this._files.includes(file)||thumbnail.owner!==urlApi)&&(thumbnail.revoke(),this.thumbnailUrls.delete(file),changed=!0);if(!this.isConnected){changed&&this.requestUpdate();return}if(canCreate)for(const file of this._files){if(!file.type.startsWith("image/")||this.thumbnailUrls.has(file))continue;const url=urlApi.createObjectURL(file);this.thumbnailUrls.set(file,{url,owner:urlApi,revoke:canRevoke?()=>urlApi.revokeObjectURL(url):()=>{}}),changed=!0}changed&&this.requestUpdate()}get effectiveMaxFileSize(){const maxFileSize=this.maxFileSize;return maxFileSize===0||maxFileSize===1/0?null:finiteRange(maxFileSize>0?maxFileSize:NaN,DEFAULT_MAX_FILE_SIZE_BYTES,1)}isAllowed(file,isPreview=!1){if(this.forbiddenMimeTypes.includes(file.type)||this.allowedMimeTypes.length>0&&!this.allowedMimeTypes.includes(file.type)||this.accept&&!matchesAccept(file,this.accept,isPreview))return"type";const maxFileSize=this.effectiveMaxFileSize;return maxFileSize!==null&&file.size>maxFileSize?"size":"ok"}classify(fileList,isPreview=!1){if(!this.effectiveMultiple&&fileList.length>1)return{files:[],rejected:fileList.map(file=>({file,reason:"count"}))};const files=[],rejected=[];for(const f of fileList){const reason=this.isAllowed(f,isPreview);reason==="ok"?files.push(f):rejected.push({file:f,reason})}return{files,rejected}}rejectionMessage(rejected){const filename=rejected.file.name;switch(rejected.reason){case"type":return this.localize("fileInputRejectedType",void 0,{filename});case"size":return this.localize("fileInputRejectedSize",void 0,{filename});case"count":return this.localize("fileInputRejectedCount",void 0,{filename});case"directory":return this.localize("fileInputFolderRejected",void 0,{filename});case"read":return this.localize("fileInputRejectedRead",void 0,{filename});case"limit":return this.localize("fileInputRejectedLimit",void 0,{filename})}}outcomeMessage(key,override,count){return override==null?this.localize(key,void 0,{count}):override.replace(/\{count\}/g,count)}emitFiles(fileList,additionalRejected=[]){const{files,rejected}=this.classify(fileList);rejected.push(...additionalRejected);const rejectedSnapshot=Object.freeze(rejected.map(item=>Object.freeze({...item}))),filesSnapshot=Object.freeze([...files]);this.rejectedFiles=rejectedSnapshot;const messages=[],numberFormat=getNumberFormat(this.effectiveLocale);files.length&&messages.push(this.outcomeMessage(files.length===1?"fileInputAcceptedOne":"fileInputAcceptedMany",this.acceptedMessage,numberFormat.format(files.length))),rejected.length&&messages.push(this.outcomeMessage(rejected.length===1?"fileInputRejectedOne":"fileInputRejectedMany",this.rejectedMessage,numberFormat.format(rejected.length))),this.resultStatus=messages.filter(message=>message.length>0).join(" "),(files.length||rejected.length)&&(this.touched=!0,this.updateValidity()),files.length&&(this.files=this.effectiveMultiple?[...this._files,...files]:files,dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change")),this.emit("lr-files",Object.freeze({files:filesSnapshot,rejected:rejectedSnapshot}))}get liveDisabled(){return this.effectiveDisabled||this.matches(":disabled")}openPicker(){this.liveDisabled||this.inputEl?.click()}focus(options){this.liveDisabled||this.baseEl?.focus(options)}blur(){this.baseEl?.blur()}click(){this.openPicker()}resetDragSession(){this.dragCounter=0,this.dragState="default",this.publishCustomStates()}previewState(fileList){const{rejected}=this.classify(fileList,!0);return rejected.length>0?"reject":"accept"}readDroppedFile(entry,isCurrent){return isCurrent()?new Promise(resolve=>{try{entry.file(file=>resolve(isCurrent()?{status:"complete",file}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}readDroppedDirectoryBatch(reader,isCurrent){return isCurrent()?new Promise(resolve=>{try{reader.readEntries(entries=>resolve(isCurrent()?{status:"complete",entries}:{status:"cancelled"}),()=>resolve(isCurrent()?{status:"error"}:{status:"cancelled"}))}catch{resolve(isCurrent()?{status:"error"}:{status:"cancelled"})}}):Promise.resolve({status:"cancelled"})}async readDroppedFolders(folders,isCurrent){const files=[],queue=[];let entryCount=0;const enqueue=entry=>entryCount>=MAX_DROPPED_FOLDER_ENTRIES?!1:(entryCount++,queue.push(entry),!0);for(const folder of folders){if(!isCurrent())return{status:"cancelled"};if(!enqueue(folder))return{status:"limit",name:folder.name}}for(let index=0;index<queue.length;index++){if(!isCurrent())return{status:"cancelled"};const entry=queue[index];if(entry.isFile){const result=await this.readDroppedFile(entry,isCurrent);if(result.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(result.status==="error")return{status:"error",name:entry.name};files.push(result.file);continue}if(!entry.isDirectory)continue;let reader;try{reader=entry.createReader()}catch{return{status:"error",name:entry.name}}for(;;){if(!isCurrent())return{status:"cancelled"};const batch=await this.readDroppedDirectoryBatch(reader,isCurrent);if(batch.status==="cancelled"||!isCurrent())return{status:"cancelled"};if(batch.status==="error")return{status:"error",name:entry.name};if(!batch.entries.length)break;for(const child of batch.entries){if(!isCurrent())return{status:"cancelled"};if(!enqueue(child))return{status:"limit",name:entry.name}}}}return{status:"complete",files}}folderFailure(name,reason){const FileCtor=this.ownerDocument.defaultView?.File??globalThis.File;return Object.freeze({file:new FileCtor([],name),reason})}statusText(){return this.dragState==="default"?this.resultStatus:this.dragStatusText()}dragStatusText(){return this.dragState==="accept"?this.localize("dropzoneReleaseToAdd"):this.dragState==="reject"?this.localize("dropzoneRejectedType"):""}get effectiveLabel(){return this.label||this.localize("fileInputDefaultLabel")}removeFile(index){this.liveDisabled||index<0||index>=this._files.length||(this.touched=!0,this.files=this._files.filter((_,candidate)=>candidate!==index),dispatchNativeEvent(this,"input"),dispatchNativeEvent(this,"change"))}fileSize(file){return formatFileSize(file.size,unit=>this.localize(FILE_SIZE_UNIT_KEYS[unit]),(value,fractionDigits)=>getNumberFormat(this.effectiveLocale,{minimumFractionDigits:fractionDigits,maximumFractionDigits:fractionDigits}).format(value))}renderFile(file,index){const thumbnail=this.thumbnailUrls.get(file)?.url;return html`<div part="file">
|
|
2
2
|
<span part="file-thumbnail" aria-hidden="true">
|
|
3
3
|
${thumbnail?html`<img part="file-image" src=${thumbnail} alt="" />`:html`<span part="file-icon">${fileIcon()}</span>`}
|
|
4
4
|
</span>
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";const styles=css`:host{aspect-ratio:var(--lr-flag-aspect-ratio,4 / 3);block-size:var(--lr-size-1em);vertical-align:middle;max-inline-size:100%;line-height:0;display:inline-block;position:relative}[part=image],[part=fallback-image]{border-radius:var(--lr-flag-radius,calc(var(--lr-radius) * .33));block-size:100%;inline-size:100%;box-shadow:0 0 0 var(--lr-
|
|
1
|
+
import{css}from"lit";const styles=css`:host{aspect-ratio:var(--lr-flag-aspect-ratio,4 / 3);block-size:var(--lr-size-1em);vertical-align:middle;max-inline-size:100%;line-height:0;display:inline-block;position:relative}[part=image],[part=fallback-image]{border-radius:var(--lr-flag-radius,calc(var(--lr-radius) * .33));block-size:100%;inline-size:100%;box-shadow:0 0 0 var(--lr-border-width-thin) var(--lr-color-border) inset;object-fit:var(--lr-flag-object-fit,cover);display:block}[part=image][hidden]{visibility:hidden;position:absolute;inset:0}[part=error]{color:var(--lr-color-danger);font-size:var(--lr-font-size-sm);line-height:var(--lr-line-height-normal);overflow-wrap:anywhere;max-inline-size:100%;display:inline-block}:host([data-error]){aspect-ratio:auto;block-size:auto;inline-size:auto;line-height:var(--lr-line-height-normal);vertical-align:baseline}:host([shape=circle]:not([data-error])){block-size:var(--lr-size-1em);inline-size:var(--lr-size-1em)}:host([shape=circle]) :is([part=image],[part=fallback-image]){border-radius:50%;block-size:100%;inline-size:100%}@media (forced-colors:active){[part=image],[part=fallback-image]{box-shadow:0 0 0 var(--lr-border-width-thin) CanvasText inset}[part=error]{color:mark;text-decoration:underline wavy}}`;export{styles};
|