@aceshooting/lyra-ui 18.0.0 → 18.2.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 +274 -0
- package/custom-elements.json +1 -1
- package/design-tokens.json +1 -1
- package/dist/cli/migration-contract.json +1 -1
- package/dist/components/conversation/message-actions/message-actions.class.d.ts +2 -1
- package/dist/components/forms/combobox/combobox.styles.js +1 -1
- package/dist/components/forms/icon-button/icon-button.class.d.ts +18 -9
- package/dist/components/forms/select/select.class.d.ts +34 -5
- package/dist/components/forms/select/select.class.js +4 -4
- package/dist/components/forms/select/select.styles.js +1 -1
- package/dist/components/layout/filter-bar/filter-bar.class.d.ts +80 -8
- package/dist/components/layout/filter-bar/filter-bar.class.js +11 -3
- package/dist/components/layout/filter-bar/filter-bar.styles.js +1 -1
- package/dist/components/layout/virtual-list/virtual-list.class.d.ts +47 -16
- package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
- package/dist/components/media/map/map.class.d.ts +161 -5
- package/dist/components/media/map/map.class.js +50 -21
- package/dist/components/media/map/map.styles.js +1 -1
- package/dist/components/utility/copy-button/copy-button.class.d.ts +4 -3
- package/dist/custom-elements-jsx.d.ts +1 -1
- package/dist/events.d.ts +7 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/tokens.styles.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/dist/styles/tokens-root.css +1 -1
- package/dist/svelte.d.ts +1 -1
- package/dist/testing/lyra-tag-event-map.js +1 -1
- package/dist/vue.d.ts +1 -1
- package/llms/components/lr-combobox.md +8 -4
- package/llms/components/lr-filter-bar.md +37 -4
- package/llms/components/lr-icon-button.md +15 -7
- package/llms/components/lr-map.md +87 -10
- package/llms/components/lr-option.md +8 -4
- package/llms/components/lr-select.md +30 -5
- package/llms/shared.md +46 -0
- package/llms/tokens.md +8 -3
- package/llms-full.txt +227 -29
- package/package.json +1 -1
- package/vscode-css-data.json +1 -1
- package/vscode-html-data.json +1 -1
- package/web-types.json +1 -1
|
@@ -96,9 +96,11 @@ readonly onFocusout:()=>void;}
|
|
|
96
96
|
* inside the filter bar's `filter-control` part and is re-rendered with the current value. */
|
|
97
97
|
export interface LyraFilterBarCustomControl{readonly render:(context:LyraFilterBarCustomControlContext)=>TemplateResult;readonly adapter:LyraFilterBarCustomControlAdapter;}
|
|
98
98
|
/** Whether a filter's `label` renders as the composed control's own visible label -- `'visible'`,
|
|
99
|
-
* the default and the behaviour every definition had before this option existed --
|
|
100
|
-
*
|
|
101
|
-
|
|
99
|
+
* the default and the behaviour every definition had before this option existed -- is routed to
|
|
100
|
+
* that control's accessible name instead (`'hidden'`), for a compact toolbar row, or is
|
|
101
|
+
* `'auto'`: rendered as the visible label while the bar's own allocation is wide enough for it,
|
|
102
|
+
* and visually clipped (never removed, so the name is unchanged) once it is not. */
|
|
103
|
+
export type LyraFilterBarLabelVisibility='visible'|'hidden'|'auto';
|
|
102
104
|
/** Which currently-active filters `render()`'s chip row shows -- see `LyraFilterBar.activeFiltersDisplay`. */
|
|
103
105
|
export type LyraFilterBarActiveFiltersDisplay='all'|'changed'|'hidden';interface LyraFilterBarDefinitionBase{
|
|
104
106
|
/** Stable, unique business identity and the key used in `LyraFilterBarValue`. */
|
|
@@ -125,7 +127,17 @@ readonly icon?:unknown;
|
|
|
125
127
|
* default) or is routed to its accessible name instead (`'hidden'`) -- which also supplies the
|
|
126
128
|
* label as the control's `placeholder` when the definition declares none, so the field still
|
|
127
129
|
* reads as itself with no stacked label above it. The label never simply disappears: routing it
|
|
128
|
-
* is the point, and a filter whose label were dropped would leave the control unnamed.
|
|
130
|
+
* is the point, and a filter whose label were dropped would leave the control unnamed.
|
|
131
|
+
*
|
|
132
|
+
* `'auto'` is the width-dependent middle: the label renders exactly as `'visible'` does --
|
|
133
|
+
* same stacked label element, same accessible name computed from it, no `aria-label` and no
|
|
134
|
+
* placeholder fallback -- and is *visually clipped* by this component's own stylesheet once the
|
|
135
|
+
* bar's own allocation drops below `30rem` (a container query on the host, so it reads the bar's
|
|
136
|
+
* allocated width and not the viewport's). Clipped, never removed: the name comes from the same
|
|
137
|
+
* node at every width, which is exactly what visually hiding `::part(filter-control-label)` from
|
|
138
|
+
* a consumer stylesheet could not achieve. The threshold is fixed rather than themeable -- a
|
|
139
|
+
* container query's prelude cannot read a custom property, so a `--lr-*` hook for it would parse
|
|
140
|
+
* and silently never apply. */
|
|
129
141
|
readonly labelVisibility?:LyraFilterBarLabelVisibility;}
|
|
130
142
|
/** The composed fields whose control also ships a built-in clear action. `'checkbox-menu'` is
|
|
131
143
|
* deliberately absent: its composed `<lr-dropdown>` has no clear affordance of its own, and the
|
|
@@ -453,6 +465,10 @@ export type LyraFilterBarInputEvent<Defs extends readonly LyraFilterBarFilterDef
|
|
|
453
465
|
* is visually hidden (never removed) under `labelVisibility: 'hidden'` -- except in the one case
|
|
454
466
|
* where the trigger's selection summary already IS the label (hidden routing, no declared
|
|
455
467
|
* `placeholder`, nothing selected), where it is omitted rather than naming the button twice.
|
|
468
|
+
* Under `labelVisibility: 'auto'` this component clips the same element itself once the bar's own
|
|
469
|
+
* allocation drops below `30rem`, and leaves it untouched above that -- so a consumer rule
|
|
470
|
+
* targeting this part sees a visible element at a wide allocation and a hairline, still-named one
|
|
471
|
+
* at a narrow one.
|
|
456
472
|
* @csspart filter-control-label-group - A `'checkbox-menu'` trigger's composed `<lr-button>`'s own
|
|
457
473
|
* label wrapper: the flex row laying out `filter-control-label` and `filter-control-input`
|
|
458
474
|
* beside each other and, with `with-caret`, growing to fill the stretched trigger so its content
|
|
@@ -528,7 +544,12 @@ loading:boolean;
|
|
|
528
544
|
* than `'changed'`/`'hidden'` (including a foreign attribute value) behaves like `'all'`,
|
|
529
545
|
* matching `labelVisibility`'s own foreign-value handling. Removing a chip always clears that
|
|
530
546
|
* filter, exactly as it always has -- this property only changes which already-active filters
|
|
531
|
-
* get a chip in the row, never what removing one does.
|
|
547
|
+
* get a chip in the row, never what removing one does.
|
|
548
|
+
*
|
|
549
|
+
* `'changed'` additionally gates the reset button on `hasChangedFilters` rather than
|
|
550
|
+
* `hasActiveFilters`, so an untouched defaults-only bar -- which renders no chip in this mode --
|
|
551
|
+
* no longer offers an enabled reset that would change nothing. `hasActiveFilters` itself is
|
|
552
|
+
* unaffected by this property in every mode, and so is reset enablement under `'all'`/`'hidden'`. */
|
|
532
553
|
activeFiltersDisplay:LyraFilterBarActiveFiltersDisplay;
|
|
533
554
|
/** Filters that have been visited (focusout'd) at least once -- gates only the *visual*
|
|
534
555
|
* inline-error presentation on each composed control, matching every other form control in
|
|
@@ -568,9 +589,44 @@ get filters():Defs;set filters(next:Defs|null|undefined);
|
|
|
568
589
|
* the manifest type is pinned here rather than left to the inferred alias name.
|
|
569
590
|
* @type {LyraFilterBarValue} */
|
|
570
591
|
get value():LyraFilterBarValueFor<Defs>;set value(next:LyraFilterBarValueFor<Defs> |null|undefined);private renewSchemaContext;private get schemaSignal();private isEmpty;private valueFor;private normalizeValue;
|
|
571
|
-
/** Whether any filter currently has a value
|
|
572
|
-
*
|
|
592
|
+
/** Whether any filter currently has a value -- including one sitting at its own declared
|
|
593
|
+
* `defaultValue`, which is a value the filter holds like any other. Also what gates whether the
|
|
594
|
+
* `active-filters` chip row renders at all, and the reset button's own disabled state in every
|
|
595
|
+
* `activeFiltersDisplay` mode except `'changed'`, where `hasChangedFilters` gates it instead.
|
|
596
|
+
* This getter itself is unaffected by `activeFiltersDisplay`. */
|
|
573
597
|
get hasActiveFilters():boolean;
|
|
598
|
+
/** Whether one filter's current value differs from its own declared `defaultValue`, using
|
|
599
|
+
* `filterValueEqualsDefault` -- the exact equality `activeFiltersDisplay: 'changed'` already
|
|
600
|
+
* filters its chip row on, not a second comparison.
|
|
601
|
+
*
|
|
602
|
+
* The `defaultIsSet` guard is what keeps a *pristine* filter out of the changed set: a filter
|
|
603
|
+
* declaring no meaningful default has nothing to still equal, so "changed" can only mean "holds
|
|
604
|
+
* a value". Reading that case through the raw equality instead would report a pristine bar as
|
|
605
|
+
* changed whenever a filter's cleared reading is a non-`undefined` sentinel -- a `'chip'`
|
|
606
|
+
* definition's own `clearValue` (`''` by default), or a `'custom'` adapter's. */
|
|
607
|
+
private filterIsChanged;
|
|
608
|
+
/** Whether any filter's value differs from its own declared `defaultValue`. Always live, never
|
|
609
|
+
* cached, exactly like `invalidFilterIds`.
|
|
610
|
+
*
|
|
611
|
+
* This is the counterpart to `hasActiveFilters`, not a synonym: a bar whose every filter sits
|
|
612
|
+
* at a non-empty declared default reads `hasActiveFilters === true` (those defaults are real
|
|
613
|
+
* values, and each one still renders its own chip under `activeFiltersDisplay: 'all'`) and
|
|
614
|
+
* `hasChangedFilters === false` -- a bar whose defaults narrow the view on load does not claim
|
|
615
|
+
* the user narrowed it. A filter with no declared `defaultValue` counts as changed the moment it
|
|
616
|
+
* holds any value at all, since there is nothing for it to still equal; conversely, clearing a
|
|
617
|
+
* filter that *does* declare one counts as changed too, because `reset()` would restore it.
|
|
618
|
+
*
|
|
619
|
+
* It differs from the `'changed'` chip row in exactly that last case: the row only ever
|
|
620
|
+
* considers filters that currently hold a value, so a cleared-but-defaulted filter shows no
|
|
621
|
+
* chip while still reading as changed here. */
|
|
622
|
+
get hasChangedFilters():boolean;
|
|
623
|
+
/** What the reset button's own enablement keys on: whether pressing it would change anything.
|
|
624
|
+
* Under `activeFiltersDisplay: 'changed'` -- the mode whose whole premise is that a value
|
|
625
|
+
* sitting at its own declared default is not something the user applied -- that is
|
|
626
|
+
* `hasChangedFilters`, so an untouched defaults-only bar offers no reset to press (and shows no
|
|
627
|
+
* chip to remove either, which is the state the enabled button used to contradict). Every other
|
|
628
|
+
* mode keeps `hasActiveFilters`, byte for byte what this component has always gated on. */
|
|
629
|
+
private get hasResettableFilters();
|
|
574
630
|
/** Filter ids currently failing their own `required` check -- a filter is invalid only when
|
|
575
631
|
* `required` is set and its value is unset (see `isSet`). Always live, never cached. */
|
|
576
632
|
get invalidFilterIds():readonly string[];
|
|
@@ -654,8 +710,24 @@ private renderOption;
|
|
|
654
710
|
* `labelVisibility`. Hiding the label routes it to the control's own `aria-label` (which every
|
|
655
711
|
* composed control here honours over its computed internal name) and, when the definition
|
|
656
712
|
* declares no `placeholder` of its own, also uses it as the placeholder -- so the field still
|
|
657
|
-
* reads as itself once the stacked label is gone.
|
|
713
|
+
* reads as itself once the stacked label is gone.
|
|
714
|
+
*
|
|
715
|
+
* `'auto'` deliberately resolves to the SAME triple as `'visible'`, not to the hidden branch.
|
|
716
|
+
* Under `'auto'` the visible label element still exists at every width -- the narrow state only
|
|
717
|
+
* clips it visually (see `labelAutoAttribute()`) -- so routing the name onto the control as well
|
|
718
|
+
* would name a wide-allocation field twice, and a *narrow* one twice over too, since the clipped
|
|
719
|
+
* label is still in the accessibility tree. Anything other than `'hidden'` (including a foreign
|
|
720
|
+
* value) therefore keeps the visible routing, matching `activeFiltersDisplay`'s own
|
|
721
|
+
* foreign-value handling. */
|
|
658
722
|
private labelRouting;
|
|
723
|
+
/** Marks a filter's rendered control as label-auto for `filter-bar.styles.ts`'s container query,
|
|
724
|
+
* which is what actually clips the label below the threshold. An attribute rather than a class
|
|
725
|
+
* because the same hook has to be readable from a rule reaching into the composed control's own
|
|
726
|
+
* shadow root -- `[data-label-auto]::part(form-control-label)` -- where a class on the host
|
|
727
|
+
* would work equally well but an attribute matches this component's existing `data-filter-id`
|
|
728
|
+
* marker. Absent for every other `labelVisibility`, so an unset filter renders byte-identical
|
|
729
|
+
* markup to before this option existed. */
|
|
730
|
+
private labelAutoAttribute;
|
|
659
731
|
/** A `'checkbox-menu'` row was activated. The composed `<lr-dropdown-item>` fires this
|
|
660
732
|
* cancelable event with its *proposed* next `checked` state and commits that state itself
|
|
661
733
|
* unless the event is prevented -- so this handler always prevents it and derives the next
|
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activeElementIn}from"../../../internal/active-element.js";import{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./filter-bar.styles.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({}),EMPTY_DATE_PRESETS=Object.freeze([]);function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}return isArray?snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0):EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","tags: filter-control-tags","tag: filter-control-tag","tag-label: filter-control-tag-label","tag__remove-button: filter-control-tag-remove-button","tag__remove-button__base: filter-control-tag-remove-button-base","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),CHECKBOX_MENU_EXPORT_PARTS=["base: filter-control-listbox"].join(", "),CHECKBOX_MENU_TRIGGER_EXPORT_PARTS=["base: filter-control-field","start: filter-control-start","label: filter-control-label-group","caret: filter-control-expand-icon"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", "),SAFE_FILTER_ID_PART=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fieldPartNames(filterId){return SAFE_FILTER_ID_PART.test(filterId)?`field field-${filterId}`:"field"}function isChoiceDefinition(definition){return definition.type==="select"||definition.type==="combobox"||definition.type==="checkbox-menu"}function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function filterValueEqualsDefault(value,defaultValue){const valueIsArray=Array.isArray(value),defaultIsArray=Array.isArray(defaultValue);return valueIsArray||defaultIsArray?!valueIsArray||!defaultIsArray?!1:value.length===defaultValue.length&&value.every((entry,index)=>entry===defaultValue[index]):Object.is(value,defaultValue)}function defineFilterValueEntry(record,key,value){Object.defineProperty(record,key,{value,enumerable:!0,configurable:!0,writable:!0})}function cloneFilterValueRecord(value){const clone={},descriptors=Object.getOwnPropertyDescriptors(value);let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&defineFilterValueEntry(clone,key,fieldValue)}return clone}function cloneFilterValue(value){return Object.freeze(cloneFilterValueRecord(value))}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.activeFiltersDisplay="all",this.touchedFilters=new Set,this.slotPresence=new SlotPresenceController(this),this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.rawValue=EMPTY_VALUE,this.debounceControllers=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(def,e)=>{const control=e.target;if(def.type==="combobox"&&this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,control.value,def.debounce);return}this.setFilterValue(def.filterId,control.value,control.appliedPreset)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation();const next=def.custom.adapter.valueFromEvent(e);if(this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,next,def.debounce,pending=>this.setCustomContextValue(def,generation,pending));return}this.setCustomContextValue(def,generation,next)}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,srOnly,styles]}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){const old=this._filters,widened=next;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(widened).filter(definition=>{try{return!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||typeof definition.label!="string"||definition.label.trim().length===0||seen.has(definition.filterId)||isChoiceDefinition(definition)&&!Array.isArray(definition.options)||definition.type==="custom"&&(!definition.custom?.adapter||typeof definition.custom.render!="function")?!1:(seen.add(definition.filterId),!0)}catch{return!1}}).map(definition=>{if(!isChoiceDefinition(definition))return definition;const options=definition.options.filter(option=>{try{return option!==null&&typeof option=="object"&&typeof Object.getOwnPropertyDescriptor(option,"value")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(option,"label")?.value=="string"}catch{return!1}});return Object.freeze({...definition,options:Object.freeze(options)})}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this.rawValue),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){const old=this._value,widened=next;try{this.rawValue=cloneFilterValue(widened??EMPTY_VALUE)}catch{this.rawValue=EMPTY_VALUE}this._value=this.normalizeValue(widened),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type==="chip")return typeof def.isEmpty=="function"?def.isEmpty(value):!isBuiltInSet(value);if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||defineFilterValueEntry(normalized,def.filterId,fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){if(this.disabled)return;this.cancelDebounce(),this.touchedFilters=new Set;const self=this;self.value=self.resetValue,self.emit("lr-input",Object.freeze({value:self.value,filterId:void 0,appliedPreset:void 0})),self.emit("lr-reset",Object.freeze({value:self.value}))}get resetValue(){const out={};for(const def of this._filters)if(def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)){const value=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue;defineFilterValueEntry(out,def.filterId,value)}return Object.freeze(out)}setFilterValue(id,value,appliedPreset){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:defineFilterValueEntry(next,id,value);const self=this;self.value=next,self.emit("lr-input",Object.freeze({value:self.value,filterId:id,appliedPreset}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}isDebounced(delay){return typeof delay=="number"&&Number.isFinite(delay)&&delay>0}scheduleDebounce(id,value,delay,commit=pending=>this.setFilterValue(id,pending)){let controller=this.debounceControllers.get(id);if(!controller){const created=new DebounceController(delay,pending=>{this.debounceControllers.get(id)===created&&this.debounceControllers.delete(id),pending!==void 0&&commit(pending)});controller=created,this.debounceControllers.set(id,created)}controller.delayMs=delay,controller.push(value)}hasPendingDebounce(id){return this.debounceControllers.get(id)?.pending??!1}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"";if(!this.isDebounced(def.debounce)){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.scheduleDebounce(def.filterId,next,def.debounce)}flushDebounce(id){this.debounceControllers.get(id)?.flush()}cancelDebounce(id){for(const[key,controller]of this.debounceControllers)id!==void 0&&key!==id||(controller.dispose(),this.debounceControllers.delete(key))}onFieldFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue??"":def.type==="checkbox-menu"||def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value,this.effectiveLocale);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(def.type==="chip"){const formatted=typeof def.formatValue=="function"?def.formatValue(value,this.effectiveLocale):void 0;return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(isChoiceDefinition(def)){const labels=(Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[]).map(v=>def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this.activeFiltersDisplay==="hidden"?[]:this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).filter(def=>this.activeFiltersDisplay!=="changed"||!filterValueEqualsDefault(this.valueFor(def),def.defaultValue)).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.closeCheckboxMenus(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}closeCheckboxMenus(){for(const menu of this.renderRoot?.querySelectorAll("lr-dropdown[data-filter-id]")??[])menu.open&&(menu.open=!1)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.closeCheckboxMenus(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll("lr-input[data-filter-id]")){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.hasPendingDebounce(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderStartAdornment(icon,slotName="start"){return icon==null?nothing:html`<span slot=${slotName} aria-hidden="true" inert>${icon}</span>`}renderOption(option){return html`<lr-option
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{activeElementIn}from"../../../internal/active-element.js";import{collectFocusableElements,deepActiveElement}from"../../../internal/overlay-manager.js";import{getDateTimeFormat,getListFormat}from"../../../internal/intl-cache.js";import{SlotPresenceController}from"../../../internal/slot-presence-controller.js";import{DebounceController}from"../../../internal/debounce-controller.js";import{srOnly}from"../../../internal/a11y.js";import{styles}from"./filter-bar.styles.js";import{LYRA_DEFAULT_fieldRequired,LYRA_DEFAULT_filterBarActiveFilters,LYRA_DEFAULT_filterBarReset}from"../../../internal/default-strings.generated.js";const MAX_FILTER_COLLECTION_ENTRIES=1e4,MAX_FILTER_COLLECTION_NODES=5e4,MAX_FILTER_COLLECTION_DEPTH=16,OMIT_FILTER_VALUE=Symbol("omit-filter-value"),EMPTY_FILTERS=Object.freeze([]),EMPTY_VALUE=Object.freeze({}),EMPTY_DATE_PRESETS=Object.freeze([]);function isPlainFilterRecord(value){try{const prototype=Object.getPrototypeOf(value);return prototype===null||Object.getPrototypeOf(prototype)===null}catch{return!1}}function snapshotFilterEntry(value,budget,depth){if(value===null||typeof value!="object"&&typeof value!="function"||typeof value=="function")return value;if(depth>MAX_FILTER_COLLECTION_DEPTH||budget.remaining<=0)return OMIT_FILTER_VALUE;const existing=budget.seen.get(value);if(existing!==void 0)return existing;let isArray=!1;try{isArray=Array.isArray(value)}catch{return OMIT_FILTER_VALUE}if(isArray){const output2=[];budget.seen.set(value,output2);let length=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(length=Math.min(descriptor.value,MAX_FILTER_COLLECTION_ENTRIES))}catch{return Object.freeze(output2)}for(let index=0;index<length&&budget.remaining>0;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;budget.remaining-=1;const entry=snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&output2.push(entry)}return Object.freeze(output2)}if(!isPlainFilterRecord(value))return value;const output={};budget.seen.set(value,output);let descriptors;try{descriptors=Object.getOwnPropertyDescriptors(value)}catch{return OMIT_FILTER_VALUE}let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES||budget.remaining<=0)break;const descriptor=descriptors[key];if(!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1,budget.remaining-=1;const entry=key==="icon"?descriptor.value:snapshotFilterEntry(descriptor.value,budget,depth+1);entry!==OMIT_FILTER_VALUE&&Object.defineProperty(output,key,{value:entry,enumerable:!0,configurable:!1,writable:!1})}return Object.freeze(output)}function snapshotFilterDefinitions(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return EMPTY_FILTERS}return isArray?snapshotFilterEntry(value,{remaining:MAX_FILTER_COLLECTION_NODES,seen:new WeakMap},0):EMPTY_FILTERS}function snapshotFilterFieldValue(value){let isArray=!1;try{isArray=Array.isArray(value)}catch{return}if(!isArray)return typeof value=="string"||typeof value=="boolean"||value===void 0?value:void 0;const output=[];let sourceLength=0;try{const descriptor=Object.getOwnPropertyDescriptor(value,"length");descriptor&&"value"in descriptor&&typeof descriptor.value=="number"&&Number.isSafeInteger(descriptor.value)&&descriptor.value>=0&&(sourceLength=descriptor.value)}catch{return Object.freeze(output)}const length=Math.min(sourceLength,MAX_FILTER_COLLECTION_ENTRIES);for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}descriptor&&"value"in descriptor&&typeof descriptor.value=="string"&&output.push(descriptor.value)}return Object.freeze(output)}const SELECT_EXPORT_PARTS=["form-control-label: filter-control-label","trigger: filter-control-field","display-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),COMBOBOX_EXPORT_PARTS=["form-control-label: filter-control-label","combobox: filter-control-field","combobox-input: filter-control-input","start: filter-control-start","end: filter-control-end","listbox: filter-control-listbox","option: filter-control-option","tags: filter-control-tags","tag: filter-control-tag","tag-label: filter-control-tag-label","tag__remove-button: filter-control-tag-remove-button","tag__remove-button__base: filter-control-tag-remove-button-base","clear-button: filter-control-clear-button","expand-icon: filter-control-expand-icon","error: filter-control-error","hint: filter-control-hint"].join(", "),INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","error: filter-control-error","hint: filter-control-hint"].join(", "),CHECKBOX_MENU_EXPORT_PARTS=["base: filter-control-listbox"].join(", "),CHECKBOX_MENU_TRIGGER_EXPORT_PARTS=["base: filter-control-field","start: filter-control-start","label: filter-control-label-group","caret: filter-control-expand-icon"].join(", "),DATE_INPUT_EXPORT_PARTS=["form-control-label: filter-control-label","input-wrapper: filter-control-field","input: filter-control-input","start: filter-control-start","end: filter-control-end","clear-button: filter-control-clear-button","expand-button: filter-control-expand-button","expand-icon: filter-control-expand-icon","popup: filter-control-popup","error: filter-control-error","hint: filter-control-hint"].join(", "),SAFE_FILTER_ID_PART=/^[a-zA-Z][a-zA-Z0-9_-]*$/;function fieldPartNames(filterId){return SAFE_FILTER_ID_PART.test(filterId)?`field field-${filterId}`:"field"}function isChoiceDefinition(definition){return definition.type==="select"||definition.type==="combobox"||definition.type==="checkbox-menu"}function isBuiltInSet(value){return value==null?!1:typeof value=="boolean"?value:Array.isArray(value)?value.length>0:value!==""}function filterValueEqualsDefault(value,defaultValue){const valueIsArray=Array.isArray(value),defaultIsArray=Array.isArray(defaultValue);return valueIsArray||defaultIsArray?!valueIsArray||!defaultIsArray?!1:value.length===defaultValue.length&&value.every((entry,index)=>entry===defaultValue[index]):Object.is(value,defaultValue)}function defineFilterValueEntry(record,key,value){Object.defineProperty(record,key,{value,enumerable:!0,configurable:!0,writable:!0})}function cloneFilterValueRecord(value){const clone={},descriptors=Object.getOwnPropertyDescriptors(value);let retained=0;for(const key of Reflect.ownKeys(descriptors)){if(retained>=MAX_FILTER_COLLECTION_ENTRIES)break;const descriptor=descriptors[key];if(typeof key!="string"||!descriptor?.enumerable||!("value"in descriptor))continue;retained+=1;const fieldValue=snapshotFilterFieldValue(descriptor.value);fieldValue!==void 0&&defineFilterValueEntry(clone,key,fieldValue)}return clone}function cloneFilterValue(value){return Object.freeze(cloneFilterValueRecord(value))}class LyraFilterBar extends LyraElement{constructor(){super(...arguments),this.label="",this.disabled=!1,this.loading=!1,this.activeFiltersDisplay="all",this.touchedFilters=new Set,this.slotPresence=new SlotPresenceController(this),this._filters=EMPTY_FILTERS,this._value=EMPTY_VALUE,this.rawValue=EMPTY_VALUE,this.debounceControllers=new Map,this.chipFocusGeneration=0,this.schemaGeneration=0,this.onControlChange=(def,e)=>{const control=e.target;if(def.type==="combobox"&&this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,control.value,def.debounce);return}this.setFilterValue(def.filterId,control.value,control.appliedPreset)},this.stopControlAlias=event=>{event.stopPropagation()},this.onCustomControlChange=(def,generation,e)=>{e.stopPropagation();const next=def.custom.adapter.valueFromEvent(e);if(this.isDebounced(def.debounce)){this.scheduleDebounce(def.filterId,next,def.debounce,pending=>this.setCustomContextValue(def,generation,pending));return}this.setCustomContextValue(def,generation,next)}}static{this.defaultStrings={...super.defaultStrings,fieldRequired:LYRA_DEFAULT_fieldRequired,filterBarActiveFilters:LYRA_DEFAULT_filterBarActiveFilters,filterBarReset:LYRA_DEFAULT_filterBarReset}}static{this.styles=[LyraElement.styles,srOnly,styles]}static{this.immutableEventDetails=Object.freeze(["lr-validity-change"])}static{this.properties={filters:{attribute:!1,noAccessor:!0},value:{attribute:!1,noAccessor:!0}}}get filters(){return this._filters}set filters(next){const old=this._filters,widened=next;this.cancelDebounce(),this.renewSchemaContext();const seen=new Set;this._filters=Object.freeze(snapshotFilterDefinitions(widened).filter(definition=>{try{return!definition||typeof definition.filterId!="string"||definition.filterId.length===0||definition.filterId!==definition.filterId.trim()||typeof definition.label!="string"||definition.label.trim().length===0||seen.has(definition.filterId)||isChoiceDefinition(definition)&&!Array.isArray(definition.options)||definition.type==="custom"&&(!definition.custom?.adapter||typeof definition.custom.render!="function")?!1:(seen.add(definition.filterId),!0)}catch{return!1}}).map(definition=>{if(!isChoiceDefinition(definition))return definition;const options=definition.options.filter(option=>{try{return option!==null&&typeof option=="object"&&typeof Object.getOwnPropertyDescriptor(option,"value")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(option,"label")?.value=="string"}catch{return!1}});return Object.freeze({...definition,options:Object.freeze(options)})}));const ids=new Set(this._filters.map(definition=>definition.filterId));this.touchedFilters=new Set([...this.touchedFilters].filter(id=>ids.has(id)));const oldValue=this._value;this._value=this.normalizeValue(this.rawValue),this.requestUpdate("filters",old),this._value!==oldValue&&this.requestUpdate("value",oldValue)}get value(){return cloneFilterValue(this._value)}set value(next){const old=this._value,widened=next;try{this.rawValue=cloneFilterValue(widened??EMPTY_VALUE)}catch{this.rawValue=EMPTY_VALUE}this._value=this.normalizeValue(widened),this.requestUpdate("value",old)}renewSchemaContext(){this.schemaAbortController?.abort();const AbortControllerCtor=this.ownerDocument.defaultView?.AbortController??AbortController;this.schemaAbortController=new AbortControllerCtor,this.schemaGeneration+=1}get schemaSignal(){return this.schemaAbortController||this.renewSchemaContext(),this.schemaAbortController.signal}isEmpty(def,value){if(def.type==="chip")return typeof def.isEmpty=="function"?def.isEmpty(value):!isBuiltInSet(value);if(def.type!=="custom")return!isBuiltInSet(value);const{adapter}=def.custom;if(adapter.isEmpty)return adapter.isEmpty(value);const clear=adapter.clearValue;return Array.isArray(value)&&Array.isArray(clear)?value.length===clear.length&&value.every((entry,index)=>entry===clear[index]):Object.is(value,clear)}valueFor(def){return Object.prototype.hasOwnProperty.call(this._value,def.filterId)?this._value[def.filterId]:def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue:void 0}normalizeValue(value){const normalized={};for(const def of this._filters){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value??{},def.filterId)}catch{continue}if(!descriptor||!("value"in descriptor))continue;const fieldValue=snapshotFilterFieldValue(descriptor.value);this.isEmpty(def,fieldValue)||defineFilterValueEntry(normalized,def.filterId,fieldValue)}return Object.freeze(normalized)}get hasActiveFilters(){return this._filters.some(def=>!this.isEmpty(def,this.valueFor(def)))}filterIsChanged(def){const value=this.valueFor(def),defaultValue=def.defaultValue;return defaultValue!==void 0&&!this.isEmpty(def,defaultValue)?!filterValueEqualsDefault(value,defaultValue):!this.isEmpty(def,value)}get hasChangedFilters(){return this._filters.some(def=>this.filterIsChanged(def))}get hasResettableFilters(){return this.activeFiltersDisplay==="changed"?this.hasChangedFilters:this.hasActiveFilters}get invalidFilterIds(){return Object.freeze(this._filters.filter(def=>def.required&&this.isEmpty(def,this.valueFor(def))).map(def=>def.filterId))}checkValidity(){return this.invalidFilterIds.length===0}reportValidity(){const invalid=this.invalidFilterIds;return invalid.length&&(this.touchedFilters=new Set([...this.touchedFilters,...invalid])),invalid.length===0}reset(){if(this.disabled)return;this.cancelDebounce(),this.touchedFilters=new Set;const self=this;self.value=self.resetValue,self.emit("lr-input",Object.freeze({value:self.value,filterId:void 0,appliedPreset:void 0})),self.emit("lr-reset",Object.freeze({value:self.value}))}get resetValue(){const out={};for(const def of this._filters)if(def.defaultValue!==void 0&&!this.isEmpty(def,def.defaultValue)){const value=Array.isArray(def.defaultValue)?Object.freeze([...def.defaultValue]):def.defaultValue;defineFilterValueEntry(out,def.filterId,value)}return Object.freeze(out)}setFilterValue(id,value,appliedPreset){const definition=this._filters.find(candidate=>candidate.filterId===id);if(this.disabled||!definition)return;const next={...this._value};this.isEmpty(definition,value)?delete next[id]:defineFilterValueEntry(next,id,value);const self=this;self.value=next,self.emit("lr-input",Object.freeze({value:self.value,filterId:id,appliedPreset}))}setCustomContextValue(definition,generation,value){generation!==this.schemaGeneration||this.schemaSignal.aborted||!this.isConnected||!this._filters.includes(definition)||this.setFilterValue(definition.filterId,value)}markTouched(id){this.disabled||this.touchedFilters.has(id)||(this.touchedFilters=new Set(this.touchedFilters).add(id))}isDebounced(delay){return typeof delay=="number"&&Number.isFinite(delay)&&delay>0}scheduleDebounce(id,value,delay,commit=pending=>this.setFilterValue(id,pending)){let controller=this.debounceControllers.get(id);if(!controller){const created=new DebounceController(delay,pending=>{this.debounceControllers.get(id)===created&&this.debounceControllers.delete(id),pending!==void 0&&commit(pending)});controller=created,this.debounceControllers.set(id,created)}controller.delayMs=delay,controller.push(value)}hasPendingDebounce(id){return this.debounceControllers.get(id)?.pending??!1}onTextInput(def,e){if(this.disabled)return;const next=e.target.value??"";if(!this.isDebounced(def.debounce)){this.cancelDebounce(def.filterId),this.setFilterValue(def.filterId,next);return}this.scheduleDebounce(def.filterId,next,def.debounce)}flushDebounce(id){this.debounceControllers.get(id)?.flush()}cancelDebounce(id){for(const[key,controller]of this.debounceControllers)id!==void 0&&key!==id||(controller.dispose(),this.debounceControllers.delete(key))}onFieldFocusout(id){this.flushDebounce(id),this.markTouched(id)}repairFocusAfterChipRemoval(index,filterId,shouldRepairFocus){const generation=++this.chipFocusGeneration;shouldRepairFocus&&this.updateComplete.then(()=>{if(!this.isConnected||this.disabled||generation!==this.chipFocusGeneration||deepActiveElement(this.ownerDocument)!==this.ownerDocument.body)return;const chips=this.renderRoot.querySelectorAll('[part="chip"]'),chip=chips[Math.min(index,chips.length-1)],target=chip?collectFocusableElements(chip)[0]:void 0;if(target){target.focus();return}for(const control of this.renderRoot.querySelectorAll("[data-filter-id]"))if(control.dataset.filterId===filterId){collectFocusableElements(control)[0]?.focus();return}})}clearFilter(id,shouldRepairFocus=!1){if(this.disabled)return;this.cancelDebounce(id);const index=this.activeEntries.findIndex(entry=>entry.def.filterId===id),def=this._filters.find(f=>f.filterId===id);if(!def)return;const clearValue=def.type==="custom"?def.custom.adapter.clearValue:def.type==="chip"?def.clearValue??"":def.type==="checkbox-menu"||def.type==="combobox"&&def.multiple?[]:"";this.setFilterValue(id,clearValue),this.repairFocusAfterChipRemoval(Math.max(0,index),id,shouldRepairFocus)}displayValueFor(def,value){if(def.type==="custom"){const formatted=def.custom?.adapter.formatValue?.(value,this.effectiveLocale);return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(def.type==="chip"){const formatted=typeof def.formatValue=="function"?def.formatValue(value,this.effectiveLocale):void 0;return formatted!==void 0?formatted:Array.isArray(value)?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(value):value===void 0?"":String(value)}if(isChoiceDefinition(def)){const labels=(Array.isArray(value)?value.filter(entry=>typeof entry=="string"):typeof value=="string"?[value]:[]).map(v=>def.options?.find(o=>o.value===v)?.label??v);return labels.length>1?getListFormat(this.effectiveLocale,{style:"long",type:"conjunction"}).format(labels):labels[0]??""}if(def.type==="text")return typeof value=="string"?value:"";if(typeof value!="string")return"";const formatter=getDateTimeFormat(this.effectiveLocale,{year:"numeric",month:"short",day:"numeric",timeZone:"UTC"}),parseIso=input=>{const match=/^(\d{4})-(\d{2})-(\d{2})$/.exec(input);if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(0);return date.setUTCHours(0,0,0,0),date.setUTCFullYear(year,month-1,day),date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date:void 0},segments=value.split("/");if(def.type==="date"&&segments.length!==1||def.type==="date-range"&&segments.length!==2)return value;const[startText,endText]=segments,start=parseIso(startText??""),end=endText===void 0?void 0:parseIso(endText);return!start||endText!==void 0&&(!end||end.getTime()<start.getTime())?value:end?formatter.formatRange(start,end):formatter.format(start)}get activeEntries(){return this.activeFiltersDisplay==="hidden"?[]:this._filters.filter(def=>!this.isEmpty(def,this.valueFor(def))).filter(def=>this.activeFiltersDisplay!=="changed"||!filterValueEqualsDefault(this.valueFor(def),def.defaultValue)).map(def=>({def,display:this.displayValueFor(def,this.valueFor(def))}))}disconnectedCallback(){super.disconnectedCallback(),this.cancelDebounce(),this.closeCheckboxMenus(),this.schemaAbortController?.abort(),this.schemaAbortController=void 0,this.schemaGeneration+=1}closeCheckboxMenus(){for(const menu of this.renderRoot?.querySelectorAll("lr-dropdown[data-filter-id]")??[])menu.open&&(menu.open=!1)}connectedCallback(){super.connectedCallback(),this.hasUpdated&&this.closeCheckboxMenus(),(!this.schemaAbortController||this.schemaAbortController.signal.aborted)&&(this.renewSchemaContext(),this.hasUpdated&&this.requestUpdate()),this.hasUpdated&&queueMicrotask(()=>{this.isConnected&&this.syncTextControls()})}syncTextControls(){if(!this._filters.some(def=>def.type==="text"))return;const fields=new Map;for(const node of this.renderRoot.querySelectorAll("lr-input[data-filter-id]")){const element=node,id=element.dataset.filterId;id!==void 0&&fields.set(id,element)}for(const def of this._filters){if(def.type!=="text"||this.hasPendingDebounce(def.filterId))continue;const field=fields.get(def.filterId);if(!field)continue;const raw=this._value[def.filterId],next=typeof raw=="string"?raw:"";field.value!==next&&(field.value=next)}}willUpdate(changed){super.willUpdate(changed),changed.has("disabled")&&this.disabled&&this.cancelDebounce()}updated(changed){if(super.updated(changed),this.syncTextControls(),changed.has("value")||changed.has("filters")){const invalidFilterIds=this.invalidFilterIds,valid=invalidFilterIds.length===0,key=JSON.stringify({valid,invalidFilterIds});key!==this.lastValidityKey&&(this.lastValidityKey=key,this.emit("lr-validity-change",Object.freeze({valid,invalidFilterIds:Object.freeze([...invalidFilterIds])})))}}renderStartAdornment(icon,slotName="start"){return icon==null?nothing:html`<span slot=${slotName} aria-hidden="true" inert>${icon}</span>`}renderOption(option){return html`<lr-option
|
|
2
2
|
value=${option.value}
|
|
3
3
|
search-text=${option.searchText??nothing}
|
|
4
4
|
?disabled=${option.disabled===!0}
|
|
5
5
|
>${this.renderStartAdornment(option.icon)}${option.label}</lr-option
|
|
6
|
-
>`}labelRouting(def){const hidden=def.labelVisibility==="hidden";return{label:hidden?"":def.label,placeholder:def.placeholder||(hidden?def.label:""),accessibleLabel:hidden?def.label:nothing}}onCheckboxMenuToggle(def,event){if(event.stopPropagation(),event.preventDefault(),this.disabled)return;const detail=event.detail,current=this.valueFor(def),selected=Array.isArray(current)?current.filter(entry=>typeof entry=="string"):[],next=detail.checked?selected.includes(detail.value)?selected:[...selected,detail.value]:selected.filter(entry=>entry!==detail.value);this.setFilterValue(def.filterId,Object.freeze(next))}renderCheckboxMenu(def,value,errorText){const selected=Array.isArray(value)?value.filter(entry=>typeof entry=="string"):[],size=def.size??"m",routing=this.labelRouting(def),summary=selected.length>0?this.displayValueFor(def,value):routing.placeholder,showLabel=def.labelVisibility!=="hidden"||summary!==def.label;return html`<div
|
|
6
|
+
>`}labelRouting(def){const hidden=def.labelVisibility==="hidden";return{label:hidden?"":def.label,placeholder:def.placeholder||(hidden?def.label:""),accessibleLabel:hidden?def.label:nothing}}labelAutoAttribute(def){return def.labelVisibility==="auto"}onCheckboxMenuToggle(def,event){if(event.stopPropagation(),event.preventDefault(),this.disabled)return;const detail=event.detail,current=this.valueFor(def),selected=Array.isArray(current)?current.filter(entry=>typeof entry=="string"):[],next=detail.checked?selected.includes(detail.value)?selected:[...selected,detail.value]:selected.filter(entry=>entry!==detail.value);this.setFilterValue(def.filterId,Object.freeze(next))}renderCheckboxMenu(def,value,errorText){const selected=Array.isArray(value)?value.filter(entry=>typeof entry=="string"):[],size=def.size??"m",routing=this.labelRouting(def),summary=selected.length>0?this.displayValueFor(def,value):routing.placeholder,showLabel=def.labelVisibility!=="hidden"||summary!==def.label;return html`<div
|
|
7
|
+
part="filter-control"
|
|
8
|
+
class="checkbox-menu"
|
|
9
|
+
?data-label-auto=${this.labelAutoAttribute(def)}
|
|
10
|
+
>
|
|
7
11
|
<lr-dropdown
|
|
8
12
|
exportparts=${CHECKBOX_MENU_EXPORT_PARTS}
|
|
9
13
|
data-filter-id=${def.filterId}
|
|
@@ -47,6 +51,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
47
51
|
part="filter-control"
|
|
48
52
|
exportparts=${COMBOBOX_EXPORT_PARTS}
|
|
49
53
|
data-filter-id=${def.filterId}
|
|
54
|
+
?data-label-auto=${this.labelAutoAttribute(def)}
|
|
50
55
|
.label=${routing.label}
|
|
51
56
|
aria-label=${routing.accessibleLabel}
|
|
52
57
|
placeholder=${routing.placeholder}
|
|
@@ -68,6 +73,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
68
73
|
part="filter-control"
|
|
69
74
|
exportparts=${INPUT_EXPORT_PARTS}
|
|
70
75
|
data-filter-id=${def.filterId}
|
|
76
|
+
?data-label-auto=${this.labelAutoAttribute(def)}
|
|
71
77
|
type=${def.inputType??"text"}
|
|
72
78
|
.label=${routing.label}
|
|
73
79
|
aria-label=${routing.accessibleLabel}
|
|
@@ -85,6 +91,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
85
91
|
part="filter-control"
|
|
86
92
|
exportparts=${DATE_INPUT_EXPORT_PARTS}
|
|
87
93
|
data-filter-id=${def.filterId}
|
|
94
|
+
?data-label-auto=${this.labelAutoAttribute(def)}
|
|
88
95
|
.label=${routing.label}
|
|
89
96
|
aria-label=${routing.accessibleLabel}
|
|
90
97
|
placeholder=${routing.placeholder}
|
|
@@ -107,6 +114,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
107
114
|
part="filter-control"
|
|
108
115
|
exportparts=${SELECT_EXPORT_PARTS}
|
|
109
116
|
data-filter-id=${def.filterId}
|
|
117
|
+
?data-label-auto=${this.labelAutoAttribute(def)}
|
|
110
118
|
.label=${routing.label}
|
|
111
119
|
aria-label=${routing.accessibleLabel}
|
|
112
120
|
placeholder=${routing.placeholder}
|
|
@@ -137,7 +145,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
137
145
|
<lr-button
|
|
138
146
|
part="reset-button"
|
|
139
147
|
appearance="quiet"
|
|
140
|
-
?disabled=${this.disabled||this.loading||!this.
|
|
148
|
+
?disabled=${this.disabled||this.loading||!this.hasResettableFilters}
|
|
141
149
|
@click=${()=>this.reset()}
|
|
142
150
|
>
|
|
143
151
|
${this.localize("filterBarReset")}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{css}from"lit";import{srOnly}from"../../../internal/a11y.js";const styles=css` ${srOnly} :host { display: block; min-inline-size: 0; max-inline-size: 100%; } [part='base'] { display: flex; flex-direction: column; gap: var(--lr-space-s); min-inline-size: 0; max-inline-size: 100%; } [part='controls'] { display: flex; flex-wrap: wrap; align-items: flex-end; gap: var(--lr-filter-bar-gap, var(--lr-space-s)); min-inline-size: 0; max-inline-size: 100%; } [part~='field'] { flex: 1 1 var(--lr-filter-bar-field-basis, var(--lr-size-12rem)); min-inline-size: 0; max-inline-size: 100%; } [part='end'] { flex: 0 0 auto; } [part='filter-control'] { inline-size: 100%; min-inline-size: 0; max-inline-size: 100%; } .checkbox-menu { display: flex; flex-direction: column; min-inline-size: 0; max-inline-size: 100%; } .checkbox-menu lr-dropdown::part(trigger) { display: block; min-inline-size: 0; } .checkbox-menu lr-button { inline-size: 100%; min-inline-size: 0; } .checkbox-menu lr-button::part(label) { display: flex; align-items: baseline; gap: var(--lr-space-xs); min-inline-size: 0; } .checkbox-menu [part='filter-control-label'], .checkbox-menu [part='filter-control-input'] { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .checkbox-menu [part='filter-control-error'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-danger); min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } .validation-spacer { display: block; block-size: var(--lr-size-1-5rem); } .validation-spacer[hidden] { display: none; } .reset-field { flex: 0 0 auto; } [part='status'] { flex: 0 0 auto; } [part='active-filters'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); min-inline-size: 0; max-inline-size: 100%; } [part='chips'] { flex: 1 1 auto; min-inline-size: 0; max-inline-size: 100%; inline-size: 100%; } [part='chip'] { min-inline-size: 0; max-inline-size: 100%; } :host([disabled]) [part='chip'] { opacity: var(--lr-opacity-disabled); } `;export{styles};
|
|
1
|
+
import{css}from"lit";import{srOnly}from"../../../internal/a11y.js";const styles=css` ${srOnly} :host { display: block; container-type: inline-size; contain-intrinsic-inline-size: var(--lr-size-20rem); min-inline-size: 0; max-inline-size: 100%; } [part='base'] { display: flex; flex-direction: column; gap: var(--lr-space-s); min-inline-size: 0; max-inline-size: 100%; } [part='controls'] { display: flex; flex-wrap: wrap; align-items: flex-end; gap: var(--lr-filter-bar-gap, var(--lr-space-s)); min-inline-size: 0; max-inline-size: 100%; } [part~='field'] { flex: 1 1 var(--lr-filter-bar-field-basis, var(--lr-size-12rem)); min-inline-size: 0; max-inline-size: 100%; } [part='end'] { flex: 0 0 auto; } [part='filter-control'] { inline-size: 100%; min-inline-size: 0; max-inline-size: 100%; } .checkbox-menu { display: flex; flex-direction: column; min-inline-size: 0; max-inline-size: 100%; } .checkbox-menu lr-dropdown::part(trigger) { display: block; min-inline-size: 0; } .checkbox-menu lr-button { inline-size: 100%; min-inline-size: 0; } .checkbox-menu lr-button::part(label) { display: flex; align-items: baseline; gap: var(--lr-space-xs); min-inline-size: 0; } .checkbox-menu [part='filter-control-label'], .checkbox-menu [part='filter-control-input'] { min-inline-size: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .checkbox-menu [part='filter-control-error'] { margin-block-start: var(--lr-space-xs); font-size: var(--lr-font-size-sm); color: var(--lr-color-danger); min-inline-size: 0; max-inline-size: 100%; overflow-wrap: anywhere; } .validation-spacer { display: block; block-size: var(--lr-size-1-5rem); } .validation-spacer[hidden] { display: none; } .reset-field { flex: 0 0 auto; } [part='status'] { flex: 0 0 auto; } [part='active-filters'] { display: flex; flex-wrap: wrap; align-items: center; gap: var(--lr-space-xs); min-inline-size: 0; max-inline-size: 100%; } [part='chips'] { flex: 1 1 auto; min-inline-size: 0; max-inline-size: 100%; inline-size: 100%; } [part='chip'] { min-inline-size: 0; max-inline-size: 100%; } :host([disabled]) [part='chip'] { opacity: var(--lr-opacity-disabled); } @container (max-inline-size: 30rem) { [data-label-auto]::part(form-control-label), [data-label-auto] [part='filter-control-label'] { position: absolute; inline-size: var(--lr-size-1px); block-size: var(--lr-size-1px); padding: 0; margin-inline: calc(-1 * var(--lr-size-1px)); margin-block: calc(-1 * var(--lr-size-1px)); overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; } } `;export{styles};
|
|
@@ -515,9 +515,18 @@ private viewportResizeTarget?;
|
|
|
515
515
|
* frame below rather than once per native `scroll` event. */
|
|
516
516
|
private externalMetricsPending;private ownerRealmGeneration;
|
|
517
517
|
/** True for the remainder of the frame in which any of this component's `ResizeObserver`s
|
|
518
|
-
* delivered -- so `syncRowObservers()` can tell that
|
|
519
|
-
* part of the browser's current resize-observation loop
|
|
518
|
+
* delivered -- so `syncRowObservers()` can tell that a re-render it is running inside is still
|
|
519
|
+
* part of the browser's current resize-observation loop, and the measurement callbacks can tell
|
|
520
|
+
* that folding a new height into the offsets would resize an observed box from inside one. See
|
|
521
|
+
* `beginResizeDelivery()`. */
|
|
520
522
|
private inResizeDelivery;
|
|
523
|
+
/** Row heights observed during a delivery whose offsets rebuild waits for the frame flush, keyed
|
|
524
|
+
* by row identity exactly like `measuredHeights`. A raw observation, not yet a measurement: the
|
|
525
|
+
* 0.5px compare, the cache write, and the scroll anchoring all still happen in one place, in
|
|
526
|
+
* `applyPendingRowMeasurements()`. See `beginResizeDelivery()`. */
|
|
527
|
+
private readonly pendingRowMeasurements;
|
|
528
|
+
/** The same, for real group markers, keyed by `startIndex` like `measuredGroupHeights`. */
|
|
529
|
+
private readonly pendingGroupMeasurements;
|
|
521
530
|
/** Rows that entered the window during such a re-render: already owned by `observedRows`, but not
|
|
522
531
|
* yet handed to `rowResizeObserver`. Always a subset of `observedRows` -- `syncRowObservers()`
|
|
523
532
|
* drops an entry here whenever it drops the same identity there. */
|
|
@@ -567,7 +576,16 @@ offsetForIndex(index:number):number;
|
|
|
567
576
|
* Returns `-1` when the effective source is empty. Same `row-height="auto"` estimate caveat as
|
|
568
577
|
* `offsetForIndex()`.
|
|
569
578
|
*/
|
|
570
|
-
indexAtOffset(px:number):number;private computeRange;private attachContainerListeners;private detachContainerListeners;private onExternalViewportResize;private onUserScrollIntent;private onScroll;private onRowsResized;
|
|
579
|
+
indexAtOffset(px:number):number;private computeRange;private attachContainerListeners;private detachContainerListeners;private onExternalViewportResize;private onUserScrollIntent;private onScroll;private onRowsResized;
|
|
580
|
+
/** Folds every stashed row observation into `measuredHeights`, anchoring and re-rendering once
|
|
581
|
+
* for the batch. Byte-for-byte the work `onRowsResized()` used to do inline. */
|
|
582
|
+
private applyPendingRowMeasurements;private onGroupsResized;
|
|
583
|
+
/** The group-marker half of `applyPendingRowMeasurements()`, on the same terms. */
|
|
584
|
+
private applyPendingGroupMeasurements;
|
|
585
|
+
/** True while folding a fresh measurement into the offsets would resize a box one of this
|
|
586
|
+
* component's own `ResizeObserver`s is watching, from inside that observer's own delivery.
|
|
587
|
+
* See `beginResizeDelivery()`. */
|
|
588
|
+
private get defersMeasurementApplication();
|
|
571
589
|
/**
|
|
572
590
|
* Marks the rest of this frame as "inside a resize-observation delivery", and schedules the
|
|
573
591
|
* flush that ends it. Called from every one of this component's `ResizeObserver` callbacks,
|
|
@@ -575,19 +593,32 @@ indexAtOffset(px:number):number;private computeRange;private attachContainerList
|
|
|
575
593
|
* `viewportHeight`, `stickyHeight`) and so can re-render the list -- and a re-render can move the
|
|
576
594
|
* window.
|
|
577
595
|
*
|
|
578
|
-
*
|
|
579
|
-
*
|
|
580
|
-
*
|
|
581
|
-
*
|
|
582
|
-
*
|
|
583
|
-
*
|
|
584
|
-
*
|
|
585
|
-
*
|
|
586
|
-
*
|
|
587
|
-
*
|
|
588
|
-
*
|
|
589
|
-
*
|
|
590
|
-
*
|
|
596
|
+
* Two things must not happen inside a delivery, and both end the same way. Calling `observe()`
|
|
597
|
+
* registers a brand-new observation, which is always active at a DOM depth the browser has
|
|
598
|
+
* already broadcast this frame. Changing the list's *extent* does the same from the other
|
|
599
|
+
* direction: `render()` writes it as `[part="spacer"]`'s block size, and under an external
|
|
600
|
+
* `scrollElement` `[part="base"][data-external-scroll]` takes its own block size from that spacer
|
|
601
|
+
* while `containerResizeObserver` watches it -- a box shallower in the tree than the rows just
|
|
602
|
+
* broadcast. Either way the observation is recorded as a *skipped* one, the loop ends, and an
|
|
603
|
+
* uncaught `ErrorEvent` reading "ResizeObserver loop completed with undelivered notifications" is
|
|
604
|
+
* dispatched. Nothing is actually wrong -- but the error is uncaught, so it lands on whatever is
|
|
605
|
+
* running at the time, which is why it showed up as unattributable flake in this component's
|
|
606
|
+
* *consumers* rather than here.
|
|
607
|
+
*
|
|
608
|
+
* So this frame carries the deferred `observe()` calls and the stashed measurements, and the
|
|
609
|
+
* measurement callbacks only *read* while the delivery is in flight. Renders are never held: an
|
|
610
|
+
* update that lands mid-delivery re-reads offsets nothing has changed, so it writes the extent
|
|
611
|
+
* already in the DOM, resizes no observed box, and cannot produce a skipped observation. That
|
|
612
|
+
* matters beyond this component -- holding a render would move this element's `updateComplete`
|
|
613
|
+
* out from under every parent composing it, which used to resolve in the same microtask run.
|
|
614
|
+
*
|
|
615
|
+
* Only the external-`scrollElement` case defers, because that is the only one where the extent
|
|
616
|
+
* write reaches an observed box; with this component's own viewport scrolling, `[part="base"]`
|
|
617
|
+
* takes its block size from `--lr-virtual-list-height` instead, so every measurement there stays
|
|
618
|
+
* exactly as immediate as it was. What a row whose measurement is waiting shows during that one
|
|
619
|
+
* frame is the same `DEFAULT_ROW_ESTIMATE_PX` geometry it already would have shown, and the
|
|
620
|
+
* scroll-anchor correction travels with the measurement that causes it, so no frame is ever
|
|
621
|
+
* painted with one applied and the other still pending.
|
|
591
622
|
*/
|
|
592
623
|
private beginResizeDelivery;
|
|
593
624
|
/** Keeps the row `ResizeObserver` watching exactly the currently-rendered
|
|
@@ -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,render}from"lit";import{html as staticHtml,unsafeStatic}from"lit/static-html.js";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{literalSetConverter}from"../../../internal/converters.js";import{tag}from"../../../internal/prefix.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteAdd,finiteCount,finiteInteger,finiteNumber}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}const ROW_PROJECTION=literalSetConverter(["shadow","light"],"shadow"),VIRTUAL_LIST_ROW_ATTRIBUTE=`data-${tag("virtual-list-row")}`,VIRTUAL_LIST_STICKY_ATTRIBUTE=`data-${tag("virtual-list-sticky")}`,ROW_ATTRIBUTE_STATIC=unsafeStatic(VIRTUAL_LIST_ROW_ATTRIBUTE),PROJECTION_ANCHOR_MARKER=`${tag("virtual-list")}-projection`;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)}const ELEMENT_NODE_TYPE=1;function isWindowScroller(target){return target.window===target}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._rowProjection="shadow",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.renderedWindow=[],this.projectionDeferred=!0,this.releaseRowProjection=()=>{this.projectionDeferred=!1,this.requestUpdate()},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.externalMetricsPending=!1,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.onExternalViewportResize=()=>{this.syncExternalScrollMetrics()},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.externalScroller?(this.pendingScrollTop=null,this.externalMetricsPending=!0):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))){if(this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0,this.externalMetricsPending){this.externalMetricsPending=!1;const metrics=this.readScrollMetrics();metrics&&(this.pendingScrollTop=metrics.scrollTop,this.viewportHeight!==metrics.viewportHeight&&(this.viewportHeight=metrics.viewportHeight))}if(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=this.readScrollMetrics()?.rawScrollTop??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=oldScrollTop+scrollAdjustment;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,nextScrollTop),this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,this.requestUpdate()}},this.onGroupsResized=entries=>{this.beginResizeDelivery();const base=this.scrollContainer,oldScrollTop=this.readScrollMetrics()?.rawScrollTop??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=oldScrollTop+scrollAdjustment;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,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 rowProjection(){return this._rowProjection}set rowProjection(next){const normalized=ROW_PROJECTION.normalize(next),previous=this._rowProjection;previous!==normalized&&(this._rowProjection=normalized,this.requestUpdate("rowProjection",previous))}get scrollContainer(){return this.renderRoot?.querySelector('[part="base"]')??void 0}get renderedRows(){const root=this.renderRoot;return root?[...root.querySelectorAll('[part="row"]')]:[]}get projectedRows(){const rows=[];for(const child of this.children)child.hasAttribute(VIRTUAL_LIST_ROW_ATTRIBUTE)&&rows.push(child);return rows}get externalScroller(){const target=this.scrollElement;if(target!=null)return isWindowScroller(target)||target.nodeType===ELEMENT_NODE_TYPE?target:void 0}get spacerElement(){return this.renderRoot?.querySelector('[part="spacer"]')??void 0}readScrollMetrics(){const base=this.scrollContainer;if(!base)return null;const external=this.externalScroller;if(!external)return{scrollTop:base.scrollTop,rawScrollTop:base.scrollTop,viewportHeight:base.clientHeight};const spacerTop=(this.spacerElement??base).getBoundingClientRect().top;if(isWindowScroller(external)){const documentHeight=finiteNumber(external.document?.documentElement?.clientHeight??0,0),rawScrollTop2=finiteNumber(-spacerTop,0);return{scrollTop:Math.max(0,rawScrollTop2),rawScrollTop:rawScrollTop2,viewportHeight:documentHeight>0?documentHeight:finiteNumber(external.innerHeight,0)}}const scrollerTop=external.getBoundingClientRect().top,rawScrollTop=finiteNumber(scrollerTop-spacerTop,0);return{scrollTop:Math.max(0,rawScrollTop),rawScrollTop,viewportHeight:finiteNumber(external.clientHeight,0)}}applyScrollPosition(top,behavior){const external=this.externalScroller;if(!external){const base=this.scrollContainer;if(!base)return;const next2=Math.max(0,finiteNumber(top,0));behavior===void 0?base.scrollTop=next2:base.scrollTo({top:next2,behavior});return}const metrics=this.readScrollMetrics();if(!metrics)return;const delta=finiteNumber(top,metrics.rawScrollTop)-metrics.rawScrollTop;if(isWindowScroller(external)){const options={top:Math.max(0,finiteNumber(external.scrollY+delta,0))};behavior!==void 0&&(options.behavior=behavior),external.scrollTo(options);return}const next=Math.max(0,finiteNumber(external.scrollTop+delta,0));behavior===void 0?external.scrollTop=next:external.scrollTo({top:next,behavior})}syncExternalScrollMetrics(){const metrics=this.readScrollMetrics();metrics&&(this.viewportHeight!==metrics.viewportHeight&&(this.viewportHeight=metrics.viewportHeight),this.containerScrollTop!==metrics.scrollTop&&(this.containerScrollTop=metrics.scrollTop))}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.seedFirstRenderState(this.releaseRowProjection),this.hasUpdated&&(this.projectionDeferred=!1)),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.syncRowProjection(),this.attachContainerListeners(),this.syncRowObservers(),this.syncGroupObservers(),this.syncStickyOverlay())}disconnectedCallback(){this.teardownRowProjection(),this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.teardownRowProjection(),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.externalMetricsPending=!1,this.pendingScrollCorrection=void 0,this.detachContainerListeners(),this.scrollListenerTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.attachContainerListeners()}willUpdate(changed){super.willUpdate(changed),this.projectionDeferred&&!this.hasUpdated&&this.ownerDocument?.defaultView&&this.seedFirstRenderState(this.releaseRowProjection),this.isFirstUpdate=!this.hasUpdated,(changed.has("items")||changed.has("source")||changed.has("keyFunction")||changed.has("rowHeight")||changed.has("groups")||changed.has("activeItemId")||changed.has("scrollElement"))&&(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),(changed.has("keyFunction")||isIndexedSource(this.effectiveSource)&&(changed.has("items")||changed.has("source")))&&(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.syncRowProjection(),this.syncRowObservers(),this.syncGroupObservers(),this.syncStickyOverlay(),changed.has("scrollElement")&&!this.isFirstUpdate&&this.attachContainerListeners(),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 nextScrollTop=(this.readScrollMetrics()?.rawScrollTop??this.containerScrollTop)-removedDeltaBeforeWindow;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,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.containerResizeObserver=void 0,this.detachContainerListeners();const external=this.externalScroller,scrollTarget=external??base,generation=this.ownerRealmGeneration,ResizeObserverCtor=ownerWindow.ResizeObserver;if(ResizeObserverCtor){const observer=new ResizeObserverCtor(entries=>{if(this.containerResizeObserver!==observer||this.scrollListenerTarget!==scrollTarget||!this.isCurrentOwnerWork(ownerDocument,generation))return;if(this.beginResizeDelivery(),external){this.syncExternalScrollMetrics();return}const entry=entries[0];entry&&(this.viewportHeight=entry.borderBoxSize?.[0]?.blockSize??entry.contentRect.height)});this.containerResizeObserver=observer,observer.observe(base),external&&!isWindowScroller(external)&&observer.observe(external)}scrollTarget.addEventListener("scroll",this.onScroll,{passive:!0}),scrollTarget.addEventListener("wheel",this.onUserScrollIntent,{passive:!0}),scrollTarget.addEventListener("pointerdown",this.onUserScrollIntent,{passive:!0}),scrollTarget.addEventListener("touchstart",this.onUserScrollIntent,{passive:!0}),scrollTarget.addEventListener("keydown",this.onUserScrollIntent),this.scrollListenerTarget=scrollTarget,external&&isWindowScroller(external)&&(external.addEventListener("resize",this.onExternalViewportResize,{passive:!0}),this.viewportResizeTarget=external),ownerWindow.queueMicrotask(()=>{if(this.scrollListenerTarget!==scrollTarget||this.scrollContainer!==base||!this.isCurrentOwnerWork(ownerDocument,generation))return;const metrics=this.readScrollMetrics();metrics&&(this.viewportHeight!==metrics.viewportHeight&&(this.viewportHeight=metrics.viewportHeight),this.containerScrollTop!==metrics.scrollTop&&(this.containerScrollTop=metrics.scrollTop))})}detachContainerListeners(){const viewportTarget=this.viewportResizeTarget;viewportTarget&&(viewportTarget.removeEventListener("resize",this.onExternalViewportResize),this.viewportResizeTarget=void 0);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 metrics=this.readScrollMetrics();if(!metrics)return!1;const inset=this.stickyInset,top=this.offsetAt(index),bottom=this.rowBottomAt(index),viewTop=metrics.rawScrollTop,viewBottom=viewTop+metrics.viewportHeight;let target=null;return align==="start"?target=top-inset:align==="end"?target=bottom-metrics.viewportHeight:top-inset<viewTop?target=top-inset:bottom>viewBottom&&(target=bottom-metrics.viewportHeight),target===null?!1:(this.applyScrollPosition(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"))}get projectionActive(){return!this.projectionDeferred&&this.rowProjection==="light"}rowSlotName(identity){return`${tag("virtual-list")}-row-${identity}`}syncRowProjection(){if(!this.projectionActive||!this.isConnected){this.projectionAnchor!==void 0&&this.teardownRowProjection();return}const anchor=this.ensureProjectionAnchor();this.projectionPart=render(this.renderProjectedRows(),this,{renderBefore:anchor,host:this})}ensureProjectionAnchor(){const existing=this.projectionAnchor;if(existing!==void 0&&existing.parentNode===this&&existing.ownerDocument===this.ownerDocument)return existing;existing!==void 0&&this.teardownRowProjection();const anchor=this.ownerDocument.createComment(PROJECTION_ANCHOR_MARKER);return this.append(anchor),this.projectionAnchor=anchor,this.projectionPart=void 0,anchor}teardownRowProjection(){const anchor=this.projectionAnchor,part=this.projectionPart;if(this.projectionAnchor=void 0,this.projectionPart=void 0,anchor!==void 0){if(part!==void 0){const container=anchor.parentNode;container!==null&&render(nothing,container,{renderBefore:anchor,host:this});const start=part.startNode;start?.parentNode?.removeChild(start)}anchor.parentNode?.removeChild(anchor)}}renderProjectedRows(){return repeat(this.renderedWindow,w=>w.identity,w=>staticHtml`<div
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing,render}from"lit";import{html as staticHtml,unsafeStatic}from"lit/static-html.js";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{literalSetConverter}from"../../../internal/converters.js";import{tag}from"../../../internal/prefix.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{finiteAdd,finiteCount,finiteInteger,finiteNumber}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}const ROW_PROJECTION=literalSetConverter(["shadow","light"],"shadow"),VIRTUAL_LIST_ROW_ATTRIBUTE=`data-${tag("virtual-list-row")}`,VIRTUAL_LIST_STICKY_ATTRIBUTE=`data-${tag("virtual-list-sticky")}`,ROW_ATTRIBUTE_STATIC=unsafeStatic(VIRTUAL_LIST_ROW_ATTRIBUTE),PROJECTION_ANCHOR_MARKER=`${tag("virtual-list")}-projection`;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)}const ELEMENT_NODE_TYPE=1;function isWindowScroller(target){return target.window===target}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._rowProjection="shadow",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.renderedWindow=[],this.projectionDeferred=!0,this.releaseRowProjection=()=>{this.projectionDeferred=!1,this.requestUpdate()},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.externalMetricsPending=!1,this.ownerRealmGeneration=0,this.inResizeDelivery=!1,this.pendingRowMeasurements=new Map,this.pendingGroupMeasurements=new Map,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.onExternalViewportResize=()=>{this.syncExternalScrollMetrics()},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.externalScroller?(this.pendingScrollTop=null,this.externalMetricsPending=!0):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))){if(this.scrollRafId=void 0,this.scrollRafOwner=void 0,this.scrollRafDocument=void 0,this.externalMetricsPending){this.externalMetricsPending=!1;const metrics=this.readScrollMetrics();metrics&&(this.pendingScrollTop=metrics.scrollTop,this.viewportHeight!==metrics.viewportHeight&&(this.viewportHeight=metrics.viewportHeight))}if(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){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;this.pendingRowMeasurements.set(key,{index,height})}this.defersMeasurementApplication||this.applyPendingRowMeasurements()}},this.onGroupsResized=entries=>{this.beginResizeDelivery();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;!Number.isFinite(height)||height<0||this.pendingGroupMeasurements.set(index,height)}this.defersMeasurementApplication||this.applyPendingGroupMeasurements()},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 rowProjection(){return this._rowProjection}set rowProjection(next){const normalized=ROW_PROJECTION.normalize(next),previous=this._rowProjection;previous!==normalized&&(this._rowProjection=normalized,this.requestUpdate("rowProjection",previous))}get scrollContainer(){return this.renderRoot?.querySelector('[part="base"]')??void 0}get renderedRows(){const root=this.renderRoot;return root?[...root.querySelectorAll('[part="row"]')]:[]}get projectedRows(){const rows=[];for(const child of this.children)child.hasAttribute(VIRTUAL_LIST_ROW_ATTRIBUTE)&&rows.push(child);return rows}get externalScroller(){const target=this.scrollElement;if(target!=null)return isWindowScroller(target)||target.nodeType===ELEMENT_NODE_TYPE?target:void 0}get spacerElement(){return this.renderRoot?.querySelector('[part="spacer"]')??void 0}readScrollMetrics(){const base=this.scrollContainer;if(!base)return null;const external=this.externalScroller;if(!external)return{scrollTop:base.scrollTop,rawScrollTop:base.scrollTop,viewportHeight:base.clientHeight};const spacerTop=(this.spacerElement??base).getBoundingClientRect().top;if(isWindowScroller(external)){const documentHeight=finiteNumber(external.document?.documentElement?.clientHeight??0,0),rawScrollTop2=finiteNumber(-spacerTop,0);return{scrollTop:Math.max(0,rawScrollTop2),rawScrollTop:rawScrollTop2,viewportHeight:documentHeight>0?documentHeight:finiteNumber(external.innerHeight,0)}}const scrollerTop=external.getBoundingClientRect().top,rawScrollTop=finiteNumber(scrollerTop-spacerTop,0);return{scrollTop:Math.max(0,rawScrollTop),rawScrollTop,viewportHeight:finiteNumber(external.clientHeight,0)}}applyScrollPosition(top,behavior){const external=this.externalScroller;if(!external){const base=this.scrollContainer;if(!base)return;const next2=Math.max(0,finiteNumber(top,0));behavior===void 0?base.scrollTop=next2:base.scrollTo({top:next2,behavior});return}const metrics=this.readScrollMetrics();if(!metrics)return;const delta=finiteNumber(top,metrics.rawScrollTop)-metrics.rawScrollTop;if(isWindowScroller(external)){const options={top:Math.max(0,finiteNumber(external.scrollY+delta,0))};behavior!==void 0&&(options.behavior=behavior),external.scrollTo(options);return}const next=Math.max(0,finiteNumber(external.scrollTop+delta,0));behavior===void 0?external.scrollTop=next:external.scrollTo({top:next,behavior})}syncExternalScrollMetrics(){const metrics=this.readScrollMetrics();metrics&&(this.viewportHeight!==metrics.viewportHeight&&(this.viewportHeight=metrics.viewportHeight),this.containerScrollTop!==metrics.scrollTop&&(this.containerScrollTop=metrics.scrollTop))}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.seedFirstRenderState(this.releaseRowProjection),this.hasUpdated&&(this.projectionDeferred=!1)),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.syncRowProjection(),this.attachContainerListeners(),this.syncRowObservers(),this.syncGroupObservers(),this.syncStickyOverlay())}disconnectedCallback(){this.teardownRowProjection(),this.resetOwnerRealmWork(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.teardownRowProjection(),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.pendingRowMeasurements.clear(),this.pendingGroupMeasurements.clear(),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.externalMetricsPending=!1,this.pendingScrollCorrection=void 0,this.detachContainerListeners(),this.scrollListenerTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.attachContainerListeners()}willUpdate(changed){super.willUpdate(changed),this.projectionDeferred&&!this.hasUpdated&&this.ownerDocument?.defaultView&&this.seedFirstRenderState(this.releaseRowProjection),this.isFirstUpdate=!this.hasUpdated,(changed.has("items")||changed.has("source")||changed.has("keyFunction")||changed.has("rowHeight")||changed.has("groups")||changed.has("activeItemId")||changed.has("scrollElement"))&&(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),(changed.has("keyFunction")||isIndexedSource(this.effectiveSource)&&(changed.has("items")||changed.has("source")))&&(this.measuredHeights.clear(),this.measuredIndices.clear(),this.pendingRowMeasurements.clear(),this.indexedMeasurementIndexDirty=!0),changed.has("groups")&&(this.measuredGroupHeights.clear(),this.pendingGroupMeasurements.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.pendingRowMeasurements.clear(),this.indexedMeasurementIndexDirty=!0)),this.offsetsDirty&&(this.recomputeOffsets(),this.offsetsDirty=!1),this.computeRange()}updated(changed){super.updated(changed),this.syncRowProjection(),this.syncRowObservers(),this.syncGroupObservers(),this.syncStickyOverlay(),changed.has("scrollElement")&&!this.isFirstUpdate&&this.attachContainerListeners(),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 nextScrollTop=(this.readScrollMetrics()?.rawScrollTop??this.containerScrollTop)-removedDeltaBeforeWindow;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,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.containerResizeObserver=void 0,this.detachContainerListeners();const external=this.externalScroller,scrollTarget=external??base,generation=this.ownerRealmGeneration,ResizeObserverCtor=ownerWindow.ResizeObserver;if(ResizeObserverCtor){const observer=new ResizeObserverCtor(entries=>{if(this.containerResizeObserver!==observer||this.scrollListenerTarget!==scrollTarget||!this.isCurrentOwnerWork(ownerDocument,generation))return;if(this.beginResizeDelivery(),external){this.syncExternalScrollMetrics();return}const entry=entries[0];entry&&(this.viewportHeight=entry.borderBoxSize?.[0]?.blockSize??entry.contentRect.height)});this.containerResizeObserver=observer,observer.observe(base),external&&!isWindowScroller(external)&&observer.observe(external)}scrollTarget.addEventListener("scroll",this.onScroll,{passive:!0}),scrollTarget.addEventListener("wheel",this.onUserScrollIntent,{passive:!0}),scrollTarget.addEventListener("pointerdown",this.onUserScrollIntent,{passive:!0}),scrollTarget.addEventListener("touchstart",this.onUserScrollIntent,{passive:!0}),scrollTarget.addEventListener("keydown",this.onUserScrollIntent),this.scrollListenerTarget=scrollTarget,external&&isWindowScroller(external)&&(external.addEventListener("resize",this.onExternalViewportResize,{passive:!0}),this.viewportResizeTarget=external),ownerWindow.queueMicrotask(()=>{if(this.scrollListenerTarget!==scrollTarget||this.scrollContainer!==base||!this.isCurrentOwnerWork(ownerDocument,generation))return;const metrics=this.readScrollMetrics();metrics&&(this.viewportHeight!==metrics.viewportHeight&&(this.viewportHeight=metrics.viewportHeight),this.containerScrollTop!==metrics.scrollTop&&(this.containerScrollTop=metrics.scrollTop))})}detachContainerListeners(){const viewportTarget=this.viewportResizeTarget;viewportTarget&&(viewportTarget.removeEventListener("resize",this.onExternalViewportResize),this.viewportResizeTarget=void 0);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))}applyPendingRowMeasurements(){if(this.pendingRowMeasurements.size===0)return;const observations=[...this.pendingRowMeasurements];if(this.pendingRowMeasurements.clear(),this.fixedRowHeight!=null)return;const base=this.scrollContainer,oldScrollTop=this.readScrollMetrics()?.rawScrollTop??this.containerScrollTop;let scrollAdjustment=0,changed=!1;for(const[key,{index,height}]of observations){const 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=oldScrollTop+scrollAdjustment;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,nextScrollTop),this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,this.requestUpdate()}}applyPendingGroupMeasurements(){if(this.pendingGroupMeasurements.size===0)return;const observations=[...this.pendingGroupMeasurements];this.pendingGroupMeasurements.clear();const base=this.scrollContainer,oldScrollTop=this.readScrollMetrics()?.rawScrollTop??this.containerScrollTop;let scrollAdjustment=0,changed=!1;for(const[index,height]of observations){if(!this.normalizedGroupByIndex.has(index))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=oldScrollTop+scrollAdjustment;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,nextScrollTop),this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,this.requestUpdate()}}get defersMeasurementApplication(){return this.inResizeDelivery&&this.externalScroller!==void 0}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.applyPendingRowMeasurements(),this.applyPendingGroupMeasurements()});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 metrics=this.readScrollMetrics();if(!metrics)return!1;const inset=this.stickyInset,top=this.offsetAt(index),bottom=this.rowBottomAt(index),viewTop=metrics.rawScrollTop,viewBottom=viewTop+metrics.viewportHeight;let target=null;return align==="start"?target=top-inset:align==="end"?target=bottom-metrics.viewportHeight:top-inset<viewTop?target=top-inset:bottom>viewBottom&&(target=bottom-metrics.viewportHeight),target===null?!1:(this.applyScrollPosition(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"))}get projectionActive(){return!this.projectionDeferred&&this.rowProjection==="light"}rowSlotName(identity){return`${tag("virtual-list")}-row-${identity}`}syncRowProjection(){if(!this.projectionActive||!this.isConnected){this.projectionAnchor!==void 0&&this.teardownRowProjection();return}const anchor=this.ensureProjectionAnchor();this.projectionPart=render(this.renderProjectedRows(),this,{renderBefore:anchor,host:this})}ensureProjectionAnchor(){const existing=this.projectionAnchor;if(existing!==void 0&&existing.parentNode===this&&existing.ownerDocument===this.ownerDocument)return existing;existing!==void 0&&this.teardownRowProjection();const anchor=this.ownerDocument.createComment(PROJECTION_ANCHOR_MARKER);return this.append(anchor),this.projectionAnchor=anchor,this.projectionPart=void 0,anchor}teardownRowProjection(){const anchor=this.projectionAnchor,part=this.projectionPart;if(this.projectionAnchor=void 0,this.projectionPart=void 0,anchor!==void 0){if(part!==void 0){const container=anchor.parentNode;container!==null&&render(nothing,container,{renderBefore:anchor,host:this});const start=part.startNode;start?.parentNode?.removeChild(start)}anchor.parentNode?.removeChild(anchor)}}renderProjectedRows(){return repeat(this.renderedWindow,w=>w.identity,w=>staticHtml`<div
|
|
2
2
|
${ROW_ATTRIBUTE_STATIC}
|
|
3
3
|
slot=${this.rowSlotName(w.identity)}
|
|
4
4
|
data-row-index=${w.index}
|