@aceshooting/lyra-ui 31.0.0 → 31.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.
Files changed (131) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/dist/autoloader-cdn.js +1 -1
  3. package/dist/components/agent-tools/budget-meter/budget-meter.class.d.ts +12 -1
  4. package/dist/components/agent-tools/budget-meter/budget-meter.class.js +4 -4
  5. package/dist/components/charts/chart/lite-chart.class.js +1 -1
  6. package/dist/components/conversation/chat-composer/chat-composer.class.d.ts +18 -8
  7. package/dist/components/conversation/chat-composer/chat-composer.class.js +11 -9
  8. package/dist/components/conversation/chat-composer/chat-composer.styles.js +1 -1
  9. package/dist/components/conversation/message-feedback/message-feedback.class.d.ts +11 -3
  10. package/dist/components/conversation/message-feedback/message-feedback.class.js +12 -6
  11. package/dist/components/conversation/message-feedback/message-feedback.styles.js +1 -1
  12. package/dist/components/conversation/prompt-input/prompt-input.class.d.ts +6 -3
  13. package/dist/components/conversation/prompt-input/prompt-input.class.js +3 -2
  14. package/dist/components/conversation/push-to-talk/push-to-talk.class.js +1 -1
  15. package/dist/components/conversation/thread-list/thread-list.class.d.ts +1 -1
  16. package/dist/components/conversation/thread-list/thread-list.class.js +2 -2
  17. package/dist/components/data/document-library/document-library-cursor.js +1 -0
  18. package/dist/components/data/document-library/document-library-types.d.ts +20 -0
  19. package/dist/components/data/document-library/document-library.class.d.ts +37 -26
  20. package/dist/components/data/document-library/document-library.class.js +20 -11
  21. package/dist/components/data/document-library/document-library.styles.js +1 -1
  22. package/dist/components/data/flow-canvas/flow-canvas.class.d.ts +1 -1
  23. package/dist/components/data/flow-canvas/flow-canvas.class.js +1 -1
  24. package/dist/components/data/timeline/timeline.class.js +1 -1
  25. package/dist/components/data/tree/tree-data-expansion.js +1 -0
  26. package/dist/components/data/tree/tree-item.class.d.ts +10 -4
  27. package/dist/components/data/tree/tree-item.class.js +5 -2
  28. package/dist/components/data/tree/tree-item.styles.js +1 -1
  29. package/dist/components/data/tree/tree-owner-controller.js +1 -1
  30. package/dist/components/data/tree/tree-pointer-reorder.js +1 -0
  31. package/dist/components/data/tree/tree-types.d.ts +5 -1
  32. package/dist/components/data/tree/tree.class.d.ts +27 -9
  33. package/dist/components/data/tree/tree.class.js +5 -3
  34. package/dist/components/data/tree/tree.styles.js +1 -1
  35. package/dist/components/forms/combobox/combobox.class.d.ts +20 -12
  36. package/dist/components/forms/combobox/combobox.class.js +2 -2
  37. package/dist/components/forms/select/select.class.js +1 -1
  38. package/dist/components/layout/dock-panel/dock-panel.class.d.ts +1 -1
  39. package/dist/components/layout/dock-panel/dock-panel.class.js +1 -1
  40. package/dist/components/layout/page/page.class.d.ts +3 -3
  41. package/dist/components/layout/page/page.class.js +1 -1
  42. package/dist/components/layout/segmented/segmented.class.d.ts +20 -7
  43. package/dist/components/layout/segmented/segmented.class.js +34 -24
  44. package/dist/components/layout/segmented/segmented.styles.js +1 -1
  45. package/dist/components/layout/stepper/stepper.styles.js +1 -1
  46. package/dist/components/layout/virtual-list/virtual-list.class.js +1 -1
  47. package/dist/components/media/map/map-anchor-controller.js +1 -1
  48. package/dist/components/media/map/map-canvas-target.js +1 -0
  49. package/dist/components/media/map/map.class.d.ts +10 -1
  50. package/dist/components/media/map/map.class.js +4 -4
  51. package/dist/components/media/map/map.styles.js +1 -1
  52. package/dist/components/media/sequence-playback/sequence-playback.class.d.ts +21 -9
  53. package/dist/components/media/sequence-playback/sequence-playback.class.js +7 -6
  54. package/dist/components/media/sequence-playback/sequence-playback.styles.js +1 -1
  55. package/dist/components/overlays/overlay/overlay.styles.js +1 -1
  56. package/dist/components/retrieval/graph/graph-spatial-controller.js +1 -1
  57. package/dist/components/retrieval/graph/graph.class.js +1 -1
  58. package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.d.ts +11 -0
  59. package/dist/components/retrieval/ingestion-queue/ingestion-queue-presentation.js +1 -0
  60. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.d.ts +18 -7
  61. package/dist/components/retrieval/ingestion-queue/ingestion-queue.class.js +13 -26
  62. package/dist/components/retrieval/ingestion-queue/ingestion-queue.styles.js +1 -1
  63. package/dist/components/utility/diff-view/diff-view.class.d.ts +5 -5
  64. package/dist/components/utility/diff-view/diff-view.class.js +1 -1
  65. package/dist/components/utility/icon/icon.class.js +1 -1
  66. package/dist/components/viewers/archive-viewer/archive-viewer.class.js +1 -1
  67. package/dist/components/viewers/calendar-viewer/calendar-viewer.class.js +1 -1
  68. package/dist/components/viewers/contact-viewer/contact-viewer.class.js +1 -1
  69. package/dist/components/viewers/document-preview/document-preview.class.js +2 -2
  70. package/dist/components/viewers/docx-viewer/docx-viewer.class.d.ts +1 -1
  71. package/dist/components/viewers/docx-viewer/docx-viewer.class.js +1 -1
  72. package/dist/components/viewers/email-viewer/email-viewer.class.d.ts +1 -1
  73. package/dist/components/viewers/email-viewer/email-viewer.class.js +2 -2
  74. package/dist/components/viewers/html-viewer/html-viewer.class.js +1 -1
  75. package/dist/components/viewers/notebook-viewer/notebook-viewer.class.js +2 -2
  76. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.d.ts +1 -1
  77. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  78. package/dist/components/viewers/pptx-viewer/pptx-viewer.class.js +1 -1
  79. package/dist/components/viewers/svg-viewer/svg-viewer.class.js +1 -1
  80. package/dist/components/viewers/xml-viewer/xml-viewer.class.js +2 -2
  81. package/dist/data-sources.d.ts +10 -0
  82. package/dist/events.d.ts +18 -4
  83. package/dist/framework-types.d.ts +1 -1
  84. package/dist/internal/default-strings/conversation.generated.js +1 -1
  85. package/dist/internal/default-strings/data.generated.js +1 -1
  86. package/dist/internal/default-strings/retrieval.generated.js +1 -1
  87. package/dist/internal/localization-types.d.ts +1 -1
  88. package/dist/internal/localization.js +1 -1
  89. package/dist/internal/lyra-element.js +2 -2
  90. package/dist/internal/native-modal-context.js +1 -1
  91. package/dist/internal/overlay-manager.js +1 -1
  92. package/dist/internal/overlay-order.js +1 -1
  93. package/dist/internal/overlay-stack.js +1 -1
  94. package/dist/internal/package-metadata.js +1 -1
  95. package/dist/internal/runtime-diagnostics.js +1 -0
  96. package/dist/internal/sizes.styles.js +1 -1
  97. package/dist/internal/source-cursor-controller.js +1 -0
  98. package/dist/internal/source-cursor-projection.js +1 -0
  99. package/dist/internal/source-page-scope.js +1 -1
  100. package/dist/lyra.d.ts +1 -1
  101. package/dist/theme/theme-bootstrap.js +1 -1
  102. package/dist/theme/theme.js +1 -1
  103. package/dist/utilities/overlay-manager.d.ts +2 -0
  104. package/llms/components/lr-budget-meter.md +31 -0
  105. package/llms/components/lr-chat-composer.md +13 -2
  106. package/llms/components/lr-combobox.md +27 -1
  107. package/llms/components/lr-diff-view.md +6 -0
  108. package/llms/components/lr-document-library.md +90 -6
  109. package/llms/components/lr-graph.md +5 -0
  110. package/llms/components/lr-ingestion-queue.md +76 -8
  111. package/llms/components/lr-json-viewer.md +34 -0
  112. package/llms/components/lr-lite-chart.md +2 -1
  113. package/llms/components/lr-map.md +33 -0
  114. package/llms/components/lr-message-feedback.md +38 -3
  115. package/llms/components/lr-page.md +4 -2
  116. package/llms/components/lr-prompt-input.md +5 -2
  117. package/llms/components/lr-segmented.md +30 -10
  118. package/llms/components/lr-sequence-playback.md +47 -12
  119. package/llms/components/lr-tree-item.md +1 -1
  120. package/llms/components/lr-tree.md +59 -7
  121. package/llms/components/lr-virtual-list.md +3 -1
  122. package/llms/peers.md +2 -2
  123. package/llms/shared/ai-and-peers.md +10 -1
  124. package/llms/shared/events-and-types.md +61 -2
  125. package/llms/shared/forms-and-accessibility.md +25 -0
  126. package/llms/shared/imports-and-registration.md +154 -110
  127. package/llms/shared/testing-and-utilities.md +5 -1
  128. package/llms/shared.md +255 -114
  129. package/locales.json +1 -1
  130. package/package.json +9 -9
  131. package/registrations.json +1 -1
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{devWarnOnce}from"../../../internal/dev-warning.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{VirtualListCompositionController}from"../../../internal/virtual-list-composition.js";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{ref}from"lit/directives/ref.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{VIRTUAL_LIST_ROW_ATTRIBUTE}from"./virtual-list-attributes.js";import{VIRTUAL_LIST_ROW_ATTRIBUTE as VIRTUAL_LIST_ROW_ATTRIBUTE2,VIRTUAL_LIST_STICKY_ATTRIBUTE}from"./virtual-list-attributes.js";import{MAX_OVERSCAN_ROWS}from"./virtual-list-limits.js";import{MAX_OVERSCAN_ROWS as MAX_OVERSCAN_ROWS2}from"./virtual-list-limits.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{nativePopoverSupported}from"../../../internal/native-popover.js";import{finiteAdd,finiteCount,finiteInteger,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.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,MAX_SCROLL_EXTENT_PX=8e6,DEFAULT_GROUP_ESTIMATE_PX=32,DEFAULT_OVERSCAN_ROWS=6,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"),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)}function sameSequence(a,b){return Array.isArray(a)&&Array.isArray(b)&&a.length===b.length&&a.every((item,index)=>item===b[index])}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)}`}const SCROLL_KEYS=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]);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.partCache=new Map,this.invalidateExternalGeometry=()=>{this.externalGeometry=void 0,this.isConnected&&this.syncExternalScrollMetrics()},this.scrollMetricsRefreshPending=!1,this.containerScrollTop=0,this.viewportHeight=0,this.renderUnmeasuredWindow=!0,this.offsets=[0],this.offsetDirtyStart=0,this.appendIdentityStart=-1,this.identityIndices=new Map,this.keyIndices=new Map,this.keyOccurrences=new Map,this.groupPrefixDirty=!0,this.rowKeys=[],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.identitiesDirty=!0,this.itemsChangedPendingPrune=!1,this.compositionVersion=0,this.composition=new VirtualListCompositionController(this,()=>{const previous=this.compositionVersion;this.compositionVersion++,this.composition.profile||(this.compositionScrollTarget=void 0),this.requestUpdate("compositionVersion",previous)}),this.renderStart=0,this.renderEnd=-1,this.pinnedRow=-1,this.renderedWindow=[],this.rowElements=new Map,this.groupElements=new Map,this.projectionDeferred=!0,this.releaseRowProjection=()=>{this.projectionDeferred=!1,super.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.noTopLayer=!1,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.contentRefreshPending=!1,this.onExternalViewportResize=()=>{this.externalGeometry=void 0,this.syncExternalScrollMetrics()},this.onUserScrollIntent=event=>{event.type==="keydown"&&!SCROLL_KEYS.has(event.key)||(this.waitForSmoothScroll(),this.pendingScrollCorrection=void 0,this.compositionScrollTarget=void 0,this.scrollRoundingAnchor=void 0)},this.onScroll=e=>{if(this.smoothScrollWait&&this.waitForSmoothScroll(),this.externalScroller?(this.pendingScrollTop=null,this.externalMetricsPending=!0):this.pendingScrollTop=this.logicalScroll(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.readScrollMetrics()?.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.onFocusOut=event=>{const next=event.relatedTarget;this.pinnedRow>=0&&!(next&&(this.contains(next)||this.renderRoot.contains(next)))&&super.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.collectionSupport=collectionSupport}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.cachedPart("base")}cachedPart(name){let element=this.partCache.get(name);return element?.isConnected||(element=this.renderRoot?.querySelector(`[part="${name}"]`)??void 0,element?this.partCache.set(name,element):this.partCache.delete(name)),element}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.cachedPart("spacer")}scrollScale(viewport=this.viewportHeight){const total=this.offsetAt(this.itemCount);return total<=MAX_SCROLL_EXTENT_PX?1:Math.max(1,(total-viewport)/Math.max(1,MAX_SCROLL_EXTENT_PX-viewport))}logicalScroll(physical,viewport=this.viewportHeight){if(this.scrollRoundingAnchor){if(Math.abs(physical-this.scrollRoundingAnchor.physical)<.01)return this.scrollRoundingAnchor.logical;this.scrollRoundingAnchor=void 0}return physical<0?physical:physical*this.scrollScale(viewport)}physicalScroll(logical,viewport=this.viewportHeight){return logical<0?logical:logical/this.scrollScale(viewport)}physicalRowOffset(logical){return this.scrollScale()===1?logical:(this.scrollRoundingAnchor?.logical===this.containerScrollTop?this.scrollRoundingAnchor.physical:this.physicalScroll(this.containerScrollTop))+logical-this.containerScrollTop}captureScrollRounding(logical){this.scrollRoundingAnchor=void 0;const metrics=this.readPhysicalScrollMetrics();if(!metrics||this.scrollScale(metrics.viewportHeight)===1)return;const physical=this.physicalScroll(logical,metrics.viewportHeight);Math.abs(physical-metrics.rawScrollTop)<=1.1&&(this.scrollRoundingAnchor={physical:metrics.rawScrollTop,logical})}readScrollMetrics(){const metrics=this.readPhysicalScrollMetrics();if(!metrics)return metrics;const rawScrollTop=this.logicalScroll(metrics.rawScrollTop,metrics.viewportHeight);return{...metrics,rawScrollTop,scrollTop:Math.max(0,rawScrollTop)}}readPhysicalScrollMetrics(){const base=this.scrollContainer;if(!base)return null;const external=this.externalScroller;if(!external)return{scrollTop:base.scrollTop,rawScrollTop:base.scrollTop,viewportHeight:base.clientHeight,scrollDeltaScale:1};const spacer=this.spacerElement??base,spacerRect=spacer.getBoundingClientRect(),extent=this.offsetAt(this.itemCount),cached=this.externalGeometry,valid=cached?.spacer===spacer&&cached.external===external&&cached.height===spacerRect.height&&cached.extent===extent,spacerScale=valid?cached.spacerScale:this.visualBlockScale(spacer,spacerRect),spacerTop=spacerRect.top;if(isWindowScroller(external)){this.externalGeometry={spacer,external,height:spacerRect.height,extent,spacerScale,scrollerScale:1,borderTop:0};const documentHeight=finiteNumber(external.document?.scrollingElement?.clientHeight??0,0),rawScrollTop2=finiteNumber(-spacerTop/spacerScale,0);return{scrollTop:Math.max(0,rawScrollTop2),rawScrollTop:rawScrollTop2,viewportHeight:(documentHeight>0?documentHeight:finiteNumber(external.innerHeight,0))/spacerScale,scrollDeltaScale:spacerScale}}const scrollerRect=external.getBoundingClientRect(),relativeScale=valid?null:this.relativeBlockScale(spacer,external),inferredScrollerScale=relativeScale===null?0:spacerScale/relativeScale,scrollerScale=valid?cached.scrollerScale:Number.isFinite(inferredScrollerScale)&&inferredScrollerScale>0?inferredScrollerScale:this.visualBlockScale(external,scrollerRect),scrollerStyle=valid?void 0:external.ownerDocument.defaultView?.getComputedStyle(external),borderTop=valid?cached.borderTop:Number.parseFloat(scrollerStyle?.borderTopWidth??"");this.externalGeometry={spacer,external,height:spacerRect.height,extent,spacerScale,scrollerScale,borderTop};const scrollerTop=scrollerRect.top+(Number.isFinite(borderTop)?borderTop:external.clientTop)*scrollerScale,rawScrollTop=finiteNumber((scrollerTop-spacerTop)/spacerScale,0);return{scrollTop:Math.max(0,rawScrollTop),rawScrollTop,viewportHeight:finiteNumber(external.clientHeight*scrollerScale/spacerScale,0),scrollDeltaScale:spacerScale/scrollerScale}}visualBlockScale(element,rect){const style=element.ownerDocument.defaultView?.getComputedStyle(element);if(!style)return 1;const borderBoxHeight=Number.parseFloat(style.height)+(style.boxSizing==="border-box"?0:Number.parseFloat(style.paddingTop)+Number.parseFloat(style.paddingBottom)+Number.parseFloat(style.borderTopWidth)+Number.parseFloat(style.borderBottomWidth)),layoutHeight=borderBoxHeight>0&&Number.isFinite(borderBoxHeight)?borderBoxHeight:"offsetHeight"in element&&typeof element.offsetHeight=="number"?element.offsetHeight:0,scale=rect.height/layoutHeight;return scale>0&&Number.isFinite(scale)?scale:1}relativeBlockScale(descendant,ancestor){let scale=1,current=descendant;for(;current&&current!==ancestor;){const style=current.ownerDocument.defaultView?.getComputedStyle(current);if(!style)return null;const zoom=style.zoom?style.zoom.endsWith("%")?Number.parseFloat(style.zoom)/100:Number.parseFloat(style.zoom):1;if(!Number.isFinite(zoom)||zoom<=0)return null;scale*=zoom;const transformable=style.display!=="contents"&&style.display!=="inline";if(transformable&&style.scale&&style.scale!=="none"){const values=style.scale.split(/\s+/).map(Number),blockScale=values[1]??values[0]??Number.NaN;if(!Number.isFinite(blockScale)||blockScale<=0)return null;scale*=blockScale}if(transformable&&style.rotate&&style.rotate!=="none"&&style.rotate!=="0deg")return null;if(transformable&&style.transform!=="none"){const Matrix=current.ownerDocument.defaultView?.DOMMatrixReadOnly;if(!Matrix)return null;const matrix=new Matrix(style.transform);if(matrix.m12!==0||matrix.m13!==0||matrix.m14!==0||matrix.m21!==0||matrix.m23!==0||matrix.m24!==0||matrix.m31!==0||matrix.m32!==0||matrix.m34!==0||matrix.m44!==1||matrix.m22<=0)return null;scale*=matrix.m22}const parent=current.assignedSlot??current.parentNode;current=parent?.nodeType===Node.ELEMENT_NODE?parent:parent?.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in parent?parent.host:null}return current===ancestor&&Number.isFinite(scale)&&scale>0?scale:null}applyScrollPosition(top,behavior){const external=this.externalScroller;if(!external){const base=this.scrollContainer;if(!base)return;const next2=Math.max(0,this.physicalScroll(finiteNumber(top,0),base.clientHeight));behavior===void 0?base.scrollTop=next2:base.scrollTo({top:next2,behavior}),behavior!=="smooth"&&(this.captureScrollRounding(top),this.scheduleScrollMetricsRefresh());return}const metrics=this.readPhysicalScrollMetrics();if(!metrics)return;const delta=(this.physicalScroll(finiteNumber(top,metrics.rawScrollTop),metrics.viewportHeight)-metrics.rawScrollTop)*metrics.scrollDeltaScale;if(isWindowScroller(external)){const options={top:Math.max(0,finiteNumber(external.scrollY+delta,0))};behavior!==void 0&&(options.behavior=behavior),external.scrollTo(options),behavior!=="smooth"&&(this.captureScrollRounding(top),this.scheduleScrollMetricsRefresh());return}const next=Math.max(0,finiteNumber(external.scrollTop+delta,0));behavior===void 0?external.scrollTop=next:external.scrollTo({top:next,behavior}),behavior!=="smooth"&&(this.captureScrollRounding(top),this.scheduleScrollMetricsRefresh())}scheduleScrollMetricsRefresh(){if(this.scrollMetricsRefreshPending)return;this.scrollMetricsRefreshPending=!0;const owner=this.ownerDocument.defaultView;queueMicrotask(()=>{this.scrollMetricsRefreshPending=!1,this.isConnected&&this.ownerDocument.defaultView===owner&&this.syncExternalScrollMetrics()})}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}return this.activeIndexCache=this.keyIndices.get(domKeyToken(this.activeItemId))??-1,this.activeIndexCache}connectedCallback(){super.connectedCallback(),this.ownerDocument.defaultView&&(this.seedFirstRenderState(()=>{this.renderUnmeasuredWindow=!1,super.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(),queueMicrotask(()=>{this.isConnected&&(this.noTopLayer=!nativePopoverSupported())})}requestUpdate(...args){args[0]===void 0&&(this.contentRefreshPending=!0),super.requestUpdate(...args)}willUpdate(changed){super.willUpdate(changed),this.projectionDeferred&&!this.hasUpdated&&this.ownerDocument?.defaultView&&this.seedFirstRenderState(this.releaseRowProjection),this.isFirstUpdate=!this.hasUpdated,this.hasUpdated&&(this.noTopLayer=!nativePopoverSupported());const contentRefresh=this.contentRefreshPending;this.contentRefreshPending=!1,contentRefresh&&(this.activeIndexFor=void 0);const sequence=contentRefresh||changed.has("items")&&!sameSequence(changed.get("items"),this.items)||changed.has("source")&&!sameSequence(changed.get("source"),this.source);sequence||changed.has("keyFunction")||changed.has("rowHeight")||changed.has("groups")||changed.has("activeItemId")||changed.has("scrollElement")?(this.pendingScrollCorrection=void 0,this.cancelSmoothScrollWait()):this.pendingScrollCorrection&&(this.pendingScrollCorrection.source=this.effectiveSource),this.appendIdentityStart=-1;const previous=changed.has("source")?changed.get("source"):changed.get("items"),current=this.effectiveSource;if(sequence&&Array.isArray(previous)&&Array.isArray(current)&&previous.length<current.length&&previous.length===this.rowIdentities.length&&!changed.has("keyFunction")&&!changed.has("groups")&&!changed.has("rowHeight")&&previous.every((item,index)=>Object.is(item,current[index]))&&(this.appendIdentityStart=previous.length),(sequence||changed.has("keyFunction"))&&(this.identitiesDirty=!0),(sequence||changed.has("rowHeight")||changed.has("keyFunction")||changed.has("groups"))&&(this.offsetsDirty=!0,this.offsetDirtyStart=Math.min(this.offsetDirtyStart,this.appendIdentityStart>=0?this.appendIdentityStart:0)),sequence&&(this.compositionScrollTarget=void 0,this.itemsChangedPendingPrune=!0),changed.has("keyFunction")||isIndexedSource(this.effectiveSource)&&sequence){this.measuredHeights.clear(),this.measuredIndices.clear(),this.pendingRowMeasurements.clear(),this.indexedMeasurementIndexDirty=!0;for(const row of this.observedRows.values())this.rowResizeObserver?.unobserve(row);this.observedRows.clear(),this.deferredRowObservations.clear()}if(changed.has("groups")){this.measuredGroupHeights.clear(),this.pendingGroupMeasurements.clear();for(const marker of this.observedGroups.values())this.groupResizeObserver?.unobserve(marker);this.observedGroups.clear(),this.deferredGroupObservations.clear()}if((sequence||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.offsetDirtyStart=1/0),changed.has("activeItemId")&&!this.isFirstUpdate&&this.composition.profile){const index=this.activeIndex;index>=0&&(this.compositionScrollTarget=index)}this.computeRange(),this.limitCompositionWindow()}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){return arguments.length<2&&this.keyFunction&&(item=this.itemAt(index)),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){return this.groupHeightPrefix[this.groupCountThrough(index)]??0}groupCountThrough(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 low}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&&!this.smoothScrollWait)){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.groupPrefixDirty&&(this.recomputeGroupHeightPrefix(),this.groupPrefixDirty=!1),isIndexedSource(this.effectiveSource)){this.offsets=[0],this.rowIdentities=[],this.rowKeys=[],this.identityIndices.clear(),this.keyIndices.clear(),this.keyOccurrences.clear(),this.itemsChangedPendingPrune=!1;return}const append=this.appendIdentityStart>=0,start=this.identitiesDirty&&!append?0:Math.min(n,this.offsetDirtyStart),offsets=start>0?this.offsets:new Array(n+1);let cursor=start>0?finiteAdd(this.offsets[start-1],this.rowHeightAt(start-1)):0;const liveKeys=this.itemsChangedPendingPrune&&!append&&this.fixedRowHeight==null?new Set:null,occurrences=append?this.keyOccurrences:new Map;this.identitiesDirty&&!append&&(this.identityIndices.clear(),this.keyIndices.clear(),this.rowKeys=[]);const reuse=!this.identitiesDirty&&this.rowIdentities.length===n,identities=reuse||append?this.rowIdentities:new Array(n);for(let i=start;i<n;i++){if(cursor=finiteAdd(cursor,this.groupHeightAt(i)),offsets[i]=cursor,!reuse){const key=this.keyOf(this.itemAt(i),i),token=domKeyToken(key),occurrence=occurrences.get(token)??0;occurrences.set(token,occurrence+1),identities[i]=this.rowIdentity(key,occurrence),this.rowKeys[i]=key,this.identityIndices.set(identities[i],i),this.keyIndices.has(token)||this.keyIndices.set(token,i)}const identity=identities[i];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,reuse||(this.keyOccurrences=occurrences),this.identitiesDirty=!1,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)}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()}limitCompositionWindow(){const profile=this.composition.profile;if(!profile||this.renderEnd<this.renderStart)return;const start=this.renderStart,end=this.renderEnd,focused=this.focusedRowOutsideWindow(!0),requested=this.compositionScrollTarget,anchor=requested!==void 0&&requested>=start&&requested<=end?requested:Math.max(start,this.visibleStart),range=budget=>{this.renderStart=Math.max(start,Math.min(anchor-Math.min(normalizeOverscan(this.overscan),budget-1),end-budget+1)),this.renderEnd=Math.min(end,this.renderStart+budget-1)};range(profile.maxRows),focused>=0&&(focused<this.renderStart||focused>this.renderEnd)&&range(profile.maxRows-1)}setCompositionScrollTarget(index){if(!this.composition.profile||this.compositionScrollTarget===index)return;const previous=this.compositionScrollTarget;this.compositionScrollTarget=index,this.requestUpdate("compositionScrollTarget",previous)}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;if(external&&ownerWindow.MutationObserver){const observer=new ownerWindow.MutationObserver(this.invalidateExternalGeometry);for(let ancestor=this;ancestor;ancestor=composedParentElement(ancestor))observer.observe(ancestor,{attributes:!0,attributeFilter:["style","class"]});this.externalStyleObserver=observer}const 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.externalGeometry=void 0,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(){this.cancelSmoothScrollWait(),this.scrollRoundingAnchor=void 0,this.externalStyleObserver?.disconnect(),this.externalStyleObserver=void 0,this.externalGeometry=void 0;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;const indexed=isIndexedSource(this.effectiveSource),measuredByIndex=indexed?new Map:void 0;if(measuredByIndex)for(const[identity,index]of this.measuredIndices)measuredByIndex.set(index,identity);for(const[key,observation]of observations){const index=indexed?observation.index:this.identityIndices.get(key);if(index===void 0)continue;const{height}=observation;if(indexed&&(index<0||index>=this.itemCount||this.identityAt(index)!==key))continue;const previousKey=measuredByIndex?.get(index)??key,prev=this.measuredHeights.get(previousKey),replaced=previousKey!==key;if(replaced||prev===void 0||Math.abs(prev-height)>.5){const oldHeight=prev??DEFAULT_ROW_ESTIMATE_PX,oldBottom=indexed?finiteAdd(this.offsetAt(index),oldHeight):this.rowBottomAt(index);this.offsetDirtyStart=Math.min(this.offsetDirtyStart,index),replaced&&(this.measuredHeights.delete(previousKey),this.measuredIndices.delete(previousKey)),this.measuredHeights.set(key,height),this.measuredIndices.set(key,index),measuredByIndex?.set(index,key),oldBottom<=oldScrollTop&&(scrollAdjustment+=height-oldHeight),changed=!0}}if(changed){if(this.indexedMeasurementIndexDirty=!0,base&&scrollAdjustment!==0&&!this.smoothScrollWait){const nextScrollTop=oldScrollTop+scrollAdjustment;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,nextScrollTop),this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,super.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.offsetDirtyStart=Math.min(this.offsetDirtyStart,index),this.groupPrefixDirty=!0,this.measuredGroupHeights.set(index,height),oldRowTop<=oldScrollTop&&(scrollAdjustment+=height-previous),changed=!0}if(changed){if(base&&scrollAdjustment!==0&&!this.smoothScrollWait){const nextScrollTop=oldScrollTop+scrollAdjustment;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,nextScrollTop),this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,super.requestUpdate()}}get defersMeasurementApplication(){return this.inResizeDelivery}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;for(const{identity,index}of this.renderedWindow){const el=this.rowElements.get(identity);el&&(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;for(const[index,marker]of this.groupElements)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)?"auto":"smooth";this.performScrollTo(index,"auto",behavior)&&this.beginPendingScrollCorrection(index,"auto",this.activeItemId)}scrollToIndex(index,options){const n=this.itemCount;if(n===0)return;const clamped=finiteInteger(index,0,0,n-1);this.setCompositionScrollTarget(clamped);const align=options?.align??"auto",behavior=prefersReducedMotion(this)?"auto":options?.behavior??"smooth";this.performScrollTo(clamped,align,behavior)?this.beginPendingScrollCorrection(clamped,align):this.pendingScrollCorrection=void 0}hasUnmeasuredGroupThrough(index){return this.normalizedGroups.some(group=>group.startIndex<=index&&group.label!==""&&!this.measuredGroupHeights.has(group.startIndex))}beginPendingScrollCorrection(index,align,activeItemId){if(this.fixedRowHeight!=null&&!this.hasUnmeasuredGroupThrough(index)){this.pendingScrollCorrection=void 0;return}this.pendingScrollCorrection={identity:this.identityAt(index),index,align,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:(behavior==="smooth"?this.waitForSmoothScroll():this.cancelSmoothScrollWait(),this.applyScrollPosition(target,behavior),!0)}cancelSmoothScrollWait(){const waiting=this.smoothScrollWait;this.smoothScrollWait=void 0,waiting&&waiting.owner.clearTimeout(waiting.handle)}waitForSmoothScroll(){this.cancelSmoothScrollWait();const owner=this.ownerDocument.defaultView;if(!owner||!this.isConnected)return;const waiting={owner,handle:owner.setTimeout(()=>{this.smoothScrollWait===waiting&&(this.smoothScrollWait=void 0,this.maybeCorrectPendingScroll())},150)};this.smoothScrollWait=waiting}maybeCorrectPendingScroll(){const pending=this.pendingScrollCorrection;if(!pending||this.smoothScrollWait||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.identityIndices.get(pending.identity)??-1;if(index<0||index>=this.itemCount||this.identityAt(index)!==pending.identity){this.pendingScrollCorrection=void 0;return}this.performScrollTo(index,pending.align,"auto"),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
+ import{__decorate}from"tslib";import{devWarnOnce}from"../../../internal/dev-warning.js";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{VirtualListCompositionController}from"../../../internal/virtual-list-composition.js";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{ref}from"lit/directives/ref.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{VIRTUAL_LIST_ROW_ATTRIBUTE}from"./virtual-list-attributes.js";import{VIRTUAL_LIST_ROW_ATTRIBUTE as VIRTUAL_LIST_ROW_ATTRIBUTE2,VIRTUAL_LIST_STICKY_ATTRIBUTE}from"./virtual-list-attributes.js";import{MAX_OVERSCAN_ROWS}from"./virtual-list-limits.js";import{MAX_OVERSCAN_ROWS as MAX_OVERSCAN_ROWS2}from"./virtual-list-limits.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{nativePopoverSupported}from"../../../internal/native-popover.js";import{finiteAdd,finiteCount,finiteInteger,finiteNumber}from"../../../internal/numbers.js";import{getNumberFormat}from"../../../internal/intl-cache.js";import{composedParentElement,deepActiveElementIn}from"../../../internal/active-element.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,MAX_SCROLL_EXTENT_PX=8e6,DEFAULT_GROUP_ESTIMATE_PX=32,DEFAULT_OVERSCAN_ROWS=6,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"),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)}function sameSequence(a,b){return Array.isArray(a)&&Array.isArray(b)&&a.length===b.length&&a.every((item,index)=>item===b[index])}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)}`}const SCROLL_KEYS=new Set(["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "]);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.partCache=new Map,this.invalidateExternalGeometry=()=>{this.externalGeometry=void 0,this.isConnected&&this.syncExternalScrollMetrics()},this.scrollMetricsRefreshPending=!1,this.containerScrollTop=0,this.viewportHeight=0,this.renderUnmeasuredWindow=!0,this.offsets=[0],this.offsetDirtyStart=0,this.appendIdentityStart=-1,this.identityIndices=new Map,this.keyIndices=new Map,this.keyOccurrences=new Map,this.groupPrefixDirty=!0,this.rowKeys=[],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.identitiesDirty=!0,this.itemsChangedPendingPrune=!1,this.compositionVersion=0,this.composition=new VirtualListCompositionController(this,()=>{const previous=this.compositionVersion;this.compositionVersion++,this.composition.profile||(this.compositionScrollTarget=void 0),this.requestUpdate("compositionVersion",previous)}),this.renderStart=0,this.renderEnd=-1,this.pinnedRow=-1,this.renderedWindow=[],this.rowElements=new Map,this.groupElements=new Map,this.projectionDeferred=!0,this.releaseRowProjection=()=>{this.projectionDeferred=!1,super.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.noTopLayer=!1,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.contentRefreshPending=!1,this.onExternalViewportResize=()=>{this.externalGeometry=void 0,this.syncExternalScrollMetrics()},this.onUserScrollIntent=event=>{event.type==="keydown"&&!SCROLL_KEYS.has(event.key)||(this.waitForSmoothScroll(),this.pendingScrollCorrection=void 0,this.compositionScrollTarget=void 0,this.scrollRoundingAnchor=void 0)},this.onScroll=e=>{if(this.smoothScrollWait&&this.waitForSmoothScroll(),this.externalScroller?(this.pendingScrollTop=null,this.externalMetricsPending=!0):this.pendingScrollTop=this.logicalScroll(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.readScrollMetrics()?.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.onFocusOut=event=>{const next=event.relatedTarget;this.pinnedRow>=0&&!(next&&(this.contains(next)||this.renderRoot.contains(next)))&&super.requestUpdate()},this.onStickyResized=entries=>{const entry=entries.find(entry2=>entry2.target===this.observedSticky);if(!entry)return;this.beginResizeDelivery();const height=entry.borderBoxSize?.[0]?.blockSize??entry.contentRect.height;Math.abs(this.stickyHeight-height)>.5&&(this.stickyHeight=height)}}static{this.collectionSupport=collectionSupport}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.cachedPart("base")}cachedPart(name){let element=this.partCache.get(name);return element?.isConnected||(element=this.renderRoot?.querySelector(`[part="${name}"]`)??void 0,element?this.partCache.set(name,element):this.partCache.delete(name)),element}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.cachedPart("spacer")}scrollScale(viewport=this.viewportHeight){const total=this.offsetAt(this.itemCount);return total<=MAX_SCROLL_EXTENT_PX?1:Math.max(1,(total-viewport)/Math.max(1,MAX_SCROLL_EXTENT_PX-viewport))}logicalScroll(physical,viewport=this.viewportHeight){if(this.scrollRoundingAnchor){if(Math.abs(physical-this.scrollRoundingAnchor.physical)<.01)return this.scrollRoundingAnchor.logical;this.scrollRoundingAnchor=void 0}return physical<0?physical:physical*this.scrollScale(viewport)}physicalScroll(logical,viewport=this.viewportHeight){return logical<0?logical:logical/this.scrollScale(viewport)}physicalRowOffset(logical){return this.scrollScale()===1?logical:(this.scrollRoundingAnchor?.logical===this.containerScrollTop?this.scrollRoundingAnchor.physical:this.physicalScroll(this.containerScrollTop))+logical-this.containerScrollTop}captureScrollRounding(logical){this.scrollRoundingAnchor=void 0;const metrics=this.readPhysicalScrollMetrics();if(!metrics||this.scrollScale(metrics.viewportHeight)===1)return;const physical=this.physicalScroll(logical,metrics.viewportHeight);Math.abs(physical-metrics.rawScrollTop)<=1.1&&(this.scrollRoundingAnchor={physical:metrics.rawScrollTop,logical})}readScrollMetrics(){const metrics=this.readPhysicalScrollMetrics();if(!metrics)return metrics;const rawScrollTop=this.logicalScroll(metrics.rawScrollTop,metrics.viewportHeight);return{...metrics,rawScrollTop,scrollTop:Math.max(0,rawScrollTop)}}readPhysicalScrollMetrics(){const base=this.scrollContainer;if(!base)return null;const external=this.externalScroller;if(!external)return{scrollTop:base.scrollTop,rawScrollTop:base.scrollTop,viewportHeight:base.clientHeight,scrollDeltaScale:1};const spacer=this.spacerElement??base,spacerRect=spacer.getBoundingClientRect(),extent=this.offsetAt(this.itemCount),cached=this.externalGeometry,valid=cached?.spacer===spacer&&cached.external===external&&cached.height===spacerRect.height&&cached.extent===extent,spacerScale=valid?cached.spacerScale:this.visualBlockScale(spacer,spacerRect),spacerTop=spacerRect.top;if(isWindowScroller(external)){this.externalGeometry={spacer,external,height:spacerRect.height,extent,spacerScale,scrollerScale:1,borderTop:0};const documentHeight=finiteNumber(external.document?.scrollingElement?.clientHeight??0,0),rawScrollTop2=finiteNumber(-spacerTop/spacerScale,0);return{scrollTop:Math.max(0,rawScrollTop2),rawScrollTop:rawScrollTop2,viewportHeight:(documentHeight>0?documentHeight:finiteNumber(external.innerHeight,0))/spacerScale,scrollDeltaScale:spacerScale}}const scrollerRect=external.getBoundingClientRect(),relativeScale=valid?null:this.relativeBlockScale(spacer,external),inferredScrollerScale=relativeScale===null?0:spacerScale/relativeScale,scrollerScale=valid?cached.scrollerScale:Number.isFinite(inferredScrollerScale)&&inferredScrollerScale>0?inferredScrollerScale:this.visualBlockScale(external,scrollerRect),scrollerStyle=valid?void 0:external.ownerDocument.defaultView?.getComputedStyle(external),borderTop=valid?cached.borderTop:Number.parseFloat(scrollerStyle?.borderTopWidth??"");this.externalGeometry={spacer,external,height:spacerRect.height,extent,spacerScale,scrollerScale,borderTop};const scrollerTop=scrollerRect.top+(Number.isFinite(borderTop)?borderTop:external.clientTop)*scrollerScale,rawScrollTop=finiteNumber((scrollerTop-spacerTop)/spacerScale,0);return{scrollTop:Math.max(0,rawScrollTop),rawScrollTop,viewportHeight:finiteNumber(external.clientHeight*scrollerScale/spacerScale,0),scrollDeltaScale:spacerScale/scrollerScale}}visualBlockScale(element,rect){const style=element.ownerDocument.defaultView?.getComputedStyle(element);if(!style)return 1;const borderBoxHeight=Number.parseFloat(style.height)+(style.boxSizing==="border-box"?0:Number.parseFloat(style.paddingTop)+Number.parseFloat(style.paddingBottom)+Number.parseFloat(style.borderTopWidth)+Number.parseFloat(style.borderBottomWidth)),layoutHeight=borderBoxHeight>0&&Number.isFinite(borderBoxHeight)?borderBoxHeight:"offsetHeight"in element&&typeof element.offsetHeight=="number"?element.offsetHeight:0,scale=rect.height/layoutHeight;return scale>0&&Number.isFinite(scale)?scale:1}relativeBlockScale(descendant,ancestor){let scale=1,current=descendant;for(;current&&current!==ancestor;){const style=current.ownerDocument.defaultView?.getComputedStyle(current);if(!style)return null;const zoom=style.zoom?style.zoom.endsWith("%")?Number.parseFloat(style.zoom)/100:Number.parseFloat(style.zoom):1;if(!Number.isFinite(zoom)||zoom<=0)return null;scale*=zoom;const transformable=style.display!=="contents"&&style.display!=="inline";if(transformable&&style.scale&&style.scale!=="none"){const values=style.scale.split(/\s+/).map(Number),blockScale=values[1]??values[0]??Number.NaN;if(!Number.isFinite(blockScale)||blockScale<=0)return null;scale*=blockScale}if(transformable&&style.rotate&&style.rotate!=="none"&&style.rotate!=="0deg")return null;if(transformable&&style.transform!=="none"){const Matrix=current.ownerDocument.defaultView?.DOMMatrixReadOnly;if(!Matrix)return null;const matrix=new Matrix(style.transform);if(matrix.m12!==0||matrix.m13!==0||matrix.m14!==0||matrix.m21!==0||matrix.m23!==0||matrix.m24!==0||matrix.m31!==0||matrix.m32!==0||matrix.m34!==0||matrix.m44!==1||matrix.m22<=0)return null;scale*=matrix.m22}const parent=current.assignedSlot??current.parentNode;current=parent?.nodeType===Node.ELEMENT_NODE?parent:parent?.nodeType===Node.DOCUMENT_FRAGMENT_NODE&&"host"in parent?parent.host:null}return current===ancestor&&Number.isFinite(scale)&&scale>0?scale:null}applyScrollPosition(top,behavior){const external=this.externalScroller;if(!external){const base=this.scrollContainer;if(!base)return;const next2=Math.max(0,this.physicalScroll(finiteNumber(top,0),base.clientHeight));behavior===void 0?base.scrollTop=next2:base.scrollTo({top:next2,behavior}),behavior!=="smooth"&&(this.captureScrollRounding(top),this.scheduleScrollMetricsRefresh());return}const metrics=this.readPhysicalScrollMetrics();if(!metrics)return;const delta=(this.physicalScroll(finiteNumber(top,metrics.rawScrollTop),metrics.viewportHeight)-metrics.rawScrollTop)*metrics.scrollDeltaScale;if(isWindowScroller(external)){const options={top:Math.max(0,finiteNumber(external.scrollY+delta,0))};behavior!==void 0&&(options.behavior=behavior),external.scrollTo(options),behavior!=="smooth"&&(this.captureScrollRounding(top),this.scheduleScrollMetricsRefresh());return}const next=Math.max(0,finiteNumber(external.scrollTop+delta,0));behavior===void 0?external.scrollTop=next:external.scrollTo({top:next,behavior}),behavior!=="smooth"&&(this.captureScrollRounding(top),this.scheduleScrollMetricsRefresh())}scheduleScrollMetricsRefresh(){if(this.scrollMetricsRefreshPending)return;this.scrollMetricsRefreshPending=!0;const owner=this.ownerDocument.defaultView;queueMicrotask(()=>{this.scrollMetricsRefreshPending=!1,this.isConnected&&this.ownerDocument.defaultView===owner&&this.syncExternalScrollMetrics()})}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}return this.activeIndexCache=this.keyIndices.get(domKeyToken(this.activeItemId))??-1,this.activeIndexCache}connectedCallback(){super.connectedCallback(),this.ownerDocument.defaultView&&(this.seedFirstRenderState(()=>{this.renderUnmeasuredWindow=!1,super.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(),queueMicrotask(()=>{this.isConnected&&(this.noTopLayer=!nativePopoverSupported())})}requestUpdate(...args){args[0]===void 0&&(this.contentRefreshPending=!0),super.requestUpdate(...args)}willUpdate(changed){super.willUpdate(changed),this.projectionDeferred&&!this.hasUpdated&&this.ownerDocument?.defaultView&&this.seedFirstRenderState(this.releaseRowProjection),this.isFirstUpdate=!this.hasUpdated,this.hasUpdated&&(this.noTopLayer=!nativePopoverSupported());const contentRefresh=this.contentRefreshPending;this.contentRefreshPending=!1,contentRefresh&&(this.activeIndexFor=void 0);const sequence=contentRefresh||changed.has("items")&&!sameSequence(changed.get("items"),this.items)||changed.has("source")&&!sameSequence(changed.get("source"),this.source);sequence||changed.has("keyFunction")||changed.has("rowHeight")||changed.has("groups")||changed.has("activeItemId")||changed.has("scrollElement")?(this.pendingScrollCorrection=void 0,this.cancelSmoothScrollWait()):this.pendingScrollCorrection&&(this.pendingScrollCorrection.source=this.effectiveSource),this.appendIdentityStart=-1;const previous=changed.has("source")?changed.get("source"):changed.get("items"),current=this.effectiveSource;if(sequence&&Array.isArray(previous)&&Array.isArray(current)&&previous.length<current.length&&previous.length===this.rowIdentities.length&&!changed.has("keyFunction")&&!changed.has("groups")&&!changed.has("rowHeight")&&previous.every((item,index)=>Object.is(item,current[index]))&&(this.appendIdentityStart=previous.length),(sequence||changed.has("keyFunction"))&&(this.identitiesDirty=!0),(sequence||changed.has("rowHeight")||changed.has("keyFunction")||changed.has("groups"))&&(this.offsetsDirty=!0,this.offsetDirtyStart=Math.min(this.offsetDirtyStart,this.appendIdentityStart>=0?this.appendIdentityStart:0)),sequence&&(this.compositionScrollTarget=void 0,this.itemsChangedPendingPrune=!0),changed.has("keyFunction")||isIndexedSource(this.effectiveSource)&&sequence){this.measuredHeights.clear(),this.measuredIndices.clear(),this.pendingRowMeasurements.clear(),this.indexedMeasurementIndexDirty=!0;for(const row of this.observedRows.values())this.rowResizeObserver?.unobserve(row);this.observedRows.clear(),this.deferredRowObservations.clear()}if(changed.has("groups")){this.measuredGroupHeights.clear(),this.pendingGroupMeasurements.clear();for(const marker of this.observedGroups.values())this.groupResizeObserver?.unobserve(marker);this.observedGroups.clear(),this.deferredGroupObservations.clear()}if((sequence||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.offsetDirtyStart=1/0),changed.has("activeItemId")&&!this.isFirstUpdate&&this.composition.profile){const index=this.activeIndex;index>=0&&(this.compositionScrollTarget=index)}this.computeRange(),this.limitCompositionWindow()}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();const ownerDocument=this.ownerDocument,ownerGeneration=this.ownerRealmGeneration;this.emitRangeChangeIfNeeded(),this.isCurrentOwnerWork(ownerDocument,ownerGeneration)&&(this.maybeFireLoadMore(),this.isCurrentOwnerWork(ownerDocument,ownerGeneration)&&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){return arguments.length<2&&this.keyFunction&&(item=this.itemAt(index)),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){return this.groupHeightPrefix[this.groupCountThrough(index)]??0}groupCountThrough(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 low}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&&!this.smoothScrollWait)){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.groupPrefixDirty&&(this.recomputeGroupHeightPrefix(),this.groupPrefixDirty=!1),isIndexedSource(this.effectiveSource)){this.offsets=[0],this.rowIdentities=[],this.rowKeys=[],this.identityIndices.clear(),this.keyIndices.clear(),this.keyOccurrences.clear(),this.itemsChangedPendingPrune=!1;return}const append=this.appendIdentityStart>=0,start=this.identitiesDirty&&!append?0:Math.min(n,this.offsetDirtyStart),offsets=start>0?this.offsets:new Array(n+1);let cursor=start>0?finiteAdd(this.offsets[start-1],this.rowHeightAt(start-1)):0;const liveKeys=this.itemsChangedPendingPrune&&!append&&this.fixedRowHeight==null?new Set:null,occurrences=append?this.keyOccurrences:new Map;this.identitiesDirty&&!append&&(this.identityIndices.clear(),this.keyIndices.clear(),this.rowKeys=[]);const reuse=!this.identitiesDirty&&this.rowIdentities.length===n,identities=reuse||append?this.rowIdentities:new Array(n);for(let i=start;i<n;i++){if(cursor=finiteAdd(cursor,this.groupHeightAt(i)),offsets[i]=cursor,!reuse){const key=this.keyOf(this.itemAt(i),i),token=domKeyToken(key),occurrence=occurrences.get(token)??0;occurrences.set(token,occurrence+1),identities[i]=this.rowIdentity(key,occurrence),this.rowKeys[i]=key,this.identityIndices.set(identities[i],i),this.keyIndices.has(token)||this.keyIndices.set(token,i)}const identity=identities[i];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,reuse||(this.keyOccurrences=occurrences),this.identitiesDirty=!1,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)}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()}limitCompositionWindow(){const profile=this.composition.profile;if(!profile||this.renderEnd<this.renderStart)return;const start=this.renderStart,end=this.renderEnd,focused=this.focusedRowOutsideWindow(!0),requested=this.compositionScrollTarget,anchor=requested!==void 0&&requested>=start&&requested<=end?requested:Math.max(start,this.visibleStart),range=budget=>{this.renderStart=Math.max(start,Math.min(anchor-Math.min(normalizeOverscan(this.overscan),budget-1),end-budget+1)),this.renderEnd=Math.min(end,this.renderStart+budget-1)};range(profile.maxRows),focused>=0&&(focused<this.renderStart||focused>this.renderEnd)&&range(profile.maxRows-1)}setCompositionScrollTarget(index){if(!this.composition.profile||this.compositionScrollTarget===index)return;const previous=this.compositionScrollTarget;this.compositionScrollTarget=index,this.requestUpdate("compositionScrollTarget",previous)}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;if(external&&ownerWindow.MutationObserver){const observer=new ownerWindow.MutationObserver(this.invalidateExternalGeometry);for(let ancestor=this;ancestor;ancestor=composedParentElement(ancestor))observer.observe(ancestor,{attributes:!0,attributeFilter:["style","class"]});this.externalStyleObserver=observer}const 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.externalGeometry=void 0,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(){this.cancelSmoothScrollWait(),this.scrollRoundingAnchor=void 0,this.externalStyleObserver?.disconnect(),this.externalStyleObserver=void 0,this.externalGeometry=void 0;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;const indexed=isIndexedSource(this.effectiveSource),measuredByIndex=indexed?new Map:void 0;if(measuredByIndex)for(const[identity,index]of this.measuredIndices)measuredByIndex.set(index,identity);for(const[key,observation]of observations){const index=indexed?observation.index:this.identityIndices.get(key);if(index===void 0)continue;const{height}=observation;if(indexed&&(index<0||index>=this.itemCount||this.identityAt(index)!==key))continue;const previousKey=measuredByIndex?.get(index)??key,prev=this.measuredHeights.get(previousKey),replaced=previousKey!==key;if(replaced||prev===void 0||Math.abs(prev-height)>.5){const oldHeight=prev??DEFAULT_ROW_ESTIMATE_PX,oldBottom=indexed?finiteAdd(this.offsetAt(index),oldHeight):this.rowBottomAt(index);this.offsetDirtyStart=Math.min(this.offsetDirtyStart,index),replaced&&(this.measuredHeights.delete(previousKey),this.measuredIndices.delete(previousKey)),this.measuredHeights.set(key,height),this.measuredIndices.set(key,index),measuredByIndex?.set(index,key),oldBottom<=oldScrollTop&&(scrollAdjustment+=height-oldHeight),changed=!0}}if(changed){if(this.indexedMeasurementIndexDirty=!0,base&&scrollAdjustment!==0&&!this.smoothScrollWait){const nextScrollTop=oldScrollTop+scrollAdjustment;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,nextScrollTop),this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,super.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.offsetDirtyStart=Math.min(this.offsetDirtyStart,index),this.groupPrefixDirty=!0,this.measuredGroupHeights.set(index,height),oldRowTop<=oldScrollTop&&(scrollAdjustment+=height-previous),changed=!0}if(changed){if(base&&scrollAdjustment!==0&&!this.smoothScrollWait){const nextScrollTop=oldScrollTop+scrollAdjustment;this.applyScrollPosition(nextScrollTop),this.containerScrollTop=Math.max(0,nextScrollTop),this.pendingScrollTop=null}this.offsetsDirty=!0,this.measurementGeneration+=1,super.requestUpdate()}}get defersMeasurementApplication(){return this.inResizeDelivery}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;for(const{identity,index}of this.renderedWindow){const el=this.rowElements.get(identity);el&&(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;for(const[index,marker]of this.groupElements)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.normalizedGroups.length>0?this.stickyHeight:0}scrollActiveIntoView(){const index=this.activeIndex;if(index<0)return;const behavior=prefersReducedMotion(this)?"auto":"smooth";this.performScrollTo(index,"auto",behavior)&&this.beginPendingScrollCorrection(index,"auto",this.activeItemId)}scrollToIndex(index,options){const n=this.itemCount;if(n===0)return;const clamped=finiteInteger(index,0,0,n-1);this.setCompositionScrollTarget(clamped);const align=options?.align??"auto",behavior=prefersReducedMotion(this)?"auto":options?.behavior??"smooth";this.performScrollTo(clamped,align,behavior)?this.beginPendingScrollCorrection(clamped,align):this.pendingScrollCorrection=void 0}hasUnmeasuredGroupThrough(index){return this.normalizedGroups.some(group=>group.startIndex<=index&&group.label!==""&&!this.measuredGroupHeights.has(group.startIndex))}beginPendingScrollCorrection(index,align,activeItemId){if(this.fixedRowHeight!=null&&!this.hasUnmeasuredGroupThrough(index)){this.pendingScrollCorrection=void 0;return}this.pendingScrollCorrection={identity:this.identityAt(index),index,align,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:(behavior==="smooth"?this.waitForSmoothScroll():this.cancelSmoothScrollWait(),this.applyScrollPosition(target,behavior),!0)}cancelSmoothScrollWait(){const waiting=this.smoothScrollWait;this.smoothScrollWait=void 0,waiting&&waiting.owner.clearTimeout(waiting.handle)}waitForSmoothScroll(){this.cancelSmoothScrollWait();const owner=this.ownerDocument.defaultView;if(!owner||!this.isConnected)return;const waiting={owner,handle:owner.setTimeout(()=>{this.smoothScrollWait===waiting&&(this.smoothScrollWait=void 0,this.maybeCorrectPendingScroll())},150)};this.smoothScrollWait=waiting}maybeCorrectPendingScroll(){const pending=this.pendingScrollCorrection;if(!pending||this.smoothScrollWait||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.identityIndices.get(pending.identity)??-1;if(index<0||index>=this.itemCount||this.identityAt(index)!==pending.identity){this.pendingScrollCorrection=void 0;return}this.performScrollTo(index,pending.align,"auto"),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}
@@ -1 +1 @@
1
- import{deferredPlaceSession as place}from"../../../internal/anchored-overlay-runtime.js";import{getInheritedPropertyDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{applyComposedFocusRepair,captureComposedFocusRepair,focusFirstAvailable}from"../../../internal/focus-navigation.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{finiteRange}from"../../../internal/numbers.js";import{reserveOverlayOrder}from"../../../internal/overlay-order.js";import{collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement,observeOverlayStack}from"../../../internal/overlay-stack.js";import{virtualAnchorFromRect}from"../../../internal/positioner-geometry.js";import{admitMapAnchorOptions}from"./map-anchor-options.js";import{MAP_ANCHOR_SEAM}from"./map-anchor-seam.js";import{mapOwnValue,renderedSizeKey}from"./map-readers.js";const escapeOwners=new Set,rankings=new WeakMap,RANK="--_lr-map-anchor-rank",LIMIT=16;let raises=0,insertions=0;class MapAnchorController{constructor(host){this.host=host,this.epoch=0,this.placed=!1,this.closingState=!1,this.observedBoundaries=[],this.raisedAt=0,this.order=0,this.fresh=!0,this.listening=!1}get closing(){return this.closingState}view(){return this.host.element.ownerDocument?.defaultView??null}invalidate(){this.epoch+=1,this.placed=!1,this.placedCoordinates=void 0,this.placement?.handle?.invalidate(),this.overlay?.suspend()}stop(){this.invalidate();const placement=this.placement;this.placement=void 0,placement?.handle?.()}schedule(){if(this.invalidate(),this.frame!==void 0)return;const view=this.view();if(!view||typeof view.requestAnimationFrame!="function"){this.sync();return}this.frame=view.requestAnimationFrame(()=>{this.frame=void 0,this.sync()})}cancelFrame(){this.frame!==void 0&&(this.view()?.cancelAnimationFrame?.(this.frame),this.frame=void 0)}focus(){const wrapper=this.host.wrapper();if(!wrapper||!this.isOpen())return!1;const epoch=this.epoch,targets=collectFocusableElements(wrapper);return epoch!==this.epoch||!this.isOpen()||targets.length===0||(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.isOpen())?!1:focusFirstAvailable(targets)&&epoch===this.epoch&&this.isOpen()}isOpen(){const host=this.host,wrapper=host.wrapper();return host.element.isConnected&&!!host.map()&&host.styleLoaded()&&this.placed&&!host.pending()&&this.placedCoordinates===host.request()&&!!wrapper&&!wrapper.hidden&&!host.interactionBlocked()&&this.hasContent()}captureReturnTarget(wrapper){const active=deepActiveElement(this.host.element.ownerDocument);if(!(!active||composedContains(wrapper,active)))try{const descriptor=getInheritedPropertyDescriptor(active,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=active,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}close(reason){const host=this.host,wrapper=host.wrapper();if(!wrapper||!this.isOpen())return!1;const requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=captureComposedFocusRepair(wrapper,this.returnTarget??null);if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request()||!this.isOpen())return!1;this.closingState=!0;try{host.retire()}finally{this.closingState=!1}this.hide(!1,!0);const epoch=this.epoch;return host.emitClose(Object.freeze({reason})),repair&&epoch===this.epoch&&host.request()===null&&applyComposedFocusRepair(repair),!0}hide(restore=!0,retire=!1){const host=this.host,wrapper=host.wrapper(),requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=restore&&wrapper?this.repairFrom(wrapper):null;if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request())return;this.stop(),wrapper&&(wrapper.hidden=!0),rankings.get(host.element)?.delete(this)&&(wrapper?.style.removeProperty(RANK),MapAnchorController.rank(host.element)),host.placed?.(!1);const epoch=this.epoch;if(retire){const overlay=this.overlay;this.overlay=void 0,this.returnTarget=void 0,this.fresh=!0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1})}else this.overlay?.suspend();repair&&epoch===this.epoch&&!this.placed&&this.repair(repair)}capture(){const wrapper=this.host.wrapper();return wrapper?this.repairFrom(wrapper):null}repair(snapshot){if(!snapshot)return;const repair=snapshot;applyComposedFocusRepair(repair,[repair.candidate,this.host.fallback?.()])}repairFrom(wrapper){const host=this.host,document=wrapper.ownerDocument,lost=host.lost?.(),active=deepActiveElement(document),candidate=()=>this.returnTarget??host.fallback?.()??null,target=lost&&(!active||active===document.body||active===document.documentElement)?candidate():null;return captureComposedFocusRepair(wrapper,candidate)??(lost&&target?{activeElement:lost,candidate:target,document,owner:wrapper}:null)}raise(escape=!0){!rankings.get(this.host.element)?.has(this)||!this.ranked()||(this.raisedAt=++raises,MapAnchorController.rank(this.host.element),escape&&this.reRegister())}ranked(){return!!this.host.child||[...rankings.get(this.host.element)??[]].some(member=>member.host.child)}enter(wrapper){const host=this.host,members=rankings.get(host.element)??new Set;rankings.set(host.element,members);const joined=!members.has(this);if(members.add(this),host.placed?.(!0),!host.child&&!this.listening&&(this.listening=!0,wrapper.addEventListener("pointerdown",()=>{this.raise()}),wrapper.addEventListener("focusout",()=>{queueMicrotask(()=>{this.focusOut()})})),!this.fresh){joined&&MapAnchorController.rank(host.element);return}if(this.fresh=!1,this.raise(!1),!(!host.autofocus?.()||composedContains(wrapper,deepActiveElement(wrapper.ownerDocument)))){for(const target of collectAutofocusElements(wrapper))if(focusFirstAvailable(target)||focusFirstAvailable(collectFocusableElements(target)))break}}static rank(map){const members=[...rankings.get(map)??[]],ranked=members.some(member=>member.host.child),active=deepActiveElement(map.ownerDocument),keys=new Map;for(const member of members){const wrapper=member.host.wrapper();keys.set(member,wrapper&&composedContains(wrapper,active)?raises+1:member.raisedAt)}return members.sort((a,b)=>keys.get(a)-keys.get(b)),members.forEach((member,index)=>{const style=member.host.wrapper()?.style;ranked?style?.setProperty(RANK,String(index)):style?.removeProperty(RANK)}),members}focusOut(){if(!this.ranked())return;[...MapAnchorController.rank(this.host.element)].reverse().find(member=>member.host.closable()&&member.isOpen())?.reRegister()}reRegister(){const host=this.host,overlay=this.overlay,wrapper=host.wrapper();if(!overlay||overlay.isTopmost()||!wrapper)return;let entries=[];observeOverlayStack(host.element.ownerDocument,snapshot=>{entries=snapshot.entries})();const index=entries.findIndex(entry=>entry.host===host.overlayHost),anchored=other=>[...escapeOwners].some(owner=>{const panel=owner.host.wrapper();return owner!==this&&(owner.host.overlayHost===other||!!panel&&composedContains(panel,other))});index<0||entries.slice(index+1).some(entry=>composedContains(wrapper,entry.host)||!anchored(entry.host))||(this.overlay=this.activate())}activate(below=!1){const host=this.host,document=host.element.ownerDocument,focused=below?[...escapeOwners].find(owner=>{const wrapper=owner.host.wrapper();return owner!==this&&owner.ranked()&&!!wrapper&&composedContains(wrapper,deepActiveElement(document))}):void 0,order=this.order=focused?focused.order-1/(++insertions+1):reserveOverlayOrder(document)(document);return activateNonmodalOverlay({host:host.overlayHost,panel:()=>host.wrapper()??null,onEscape:()=>{host.escape?host.escape():this.close("escape")},beforeInitialFocus:()=>!1,restoreFocusTo:()=>this.returnTarget??null,orderReservation:destination=>destination===document?order:void 0})}dispose(){this.cancelFrame(),this.hide(!0,!0),this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[]}suspendAdmission(){this.cancelFrame(),this.hide(),!(this.placement||this.placed)&&(this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[])}syncOverlay(wrapper){const host=this.host,element=host.element;if(!host.closable()){const overlay=this.overlay;this.overlay=void 0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1});return}if(this.overlay)this.overlay.resume();else{const epoch=this.epoch;if(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.placed||!element.isConnected)return;const overlay=this.activate(this.ranked());epoch===this.epoch&&this.placed&&element.isConnected&&host.closable()&&!this.overlay?(this.overlay=overlay,escapeOwners.add(this)):overlay.deactivate({restoreFocus:!1})}}hasContent(){return this.host.content()?.assignedNodes({flatten:!0}).some(node=>node.nodeType===1||node.nodeType===3&&!!node.textContent?.trim())??!1}observeBoundaries(boundaries){if(boundaries.length===this.observedBoundaries.length&&boundaries.every((value,index)=>value===this.observedBoundaries[index]))return;this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[...boundaries];const ResizeObserverClass=this.view()?.ResizeObserver;if(!ResizeObserverClass||boundaries.length===0)return;let sizes=boundaries.map(renderedSizeKey);this.boundaryObserver=new ResizeObserverClass(()=>{const next=boundaries.map(renderedSizeKey);next.every((value,index)=>value===sizes[index])||(sizes=next,this.host.element.isConnected&&this.schedule())});for(const boundary of boundaries)this.boundaryObserver.observe(boundary)}focusIn(event){const wrapper=this.host.wrapper(),previous=event.relatedTarget,view=this.view();if(wrapper&&view&&!(previous instanceof view.Element&&composedContains(wrapper,previous))&&this.raise(),!(!wrapper||!view||!(previous instanceof view.Element)||previous.ownerDocument!==this.host.element.ownerDocument||composedContains(wrapper,previous)))try{const descriptor=getInheritedPropertyDescriptor(previous,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=previous,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}point(){const host=this.host,position=host.request();if(!Array.isArray(position))return;const lng=mapOwnValue(position,"0"),lat=mapOwnValue(position,"1");if(!(typeof lng!="number"||!Number.isFinite(lng)||typeof lat!="number"||!Number.isFinite(lat)||Math.abs(lat)>90))return host.element.project([lng,lat])}sync(){const host=this.host,element=host.element;if(this.invalidate(),host.updateActive()){const[generation,connection2]=host.generations(),map2=host.map();host.afterUpdate(()=>{const[style2,current2]=host.generations();element.isConnected&&current2===connection2&&style2===generation&&host.map()===map2&&this.sync()},`${host.key}-${connection2}-${generation}`);return}const wrapper=host.wrapper(),container=host.container(),fence=host.fence();if(!wrapper||!container||!fence||!element.isConnected||!host.map()||!host.styleLoaded()||host.interactionBlocked()||!this.hasContent()){this.hide();return}const epoch=this.epoch,map=host.map(),coordinates=host.request(),document=element.ownerDocument,[style,connection]=host.generations(),boundary=host.boundary(),safeArea=host.safeArea(),direction=host.direction(),current=()=>element.isConnected&&element.ownerDocument===document&&host.map()===map&&host.styleLoaded()&&host.generations()[0]===style&&host.generations()[1]===connection&&host.wrapper()===wrapper&&host.container()===container&&host.fence()===fence&&epoch===this.epoch&&host.request()===coordinates&&host.boundary()===boundary&&host.safeArea()===safeArea&&host.direction()===direction&&!host.interactionBlocked();try{const admitted=admitMapAnchorOptions({boundary,safeArea},element.ownerDocument,{current});if(!admitted.ok||!current()){epoch===this.epoch&&this.hide();return}this.observeBoundaries(admitted.boundaries);const point=this.point();if(!current())return;const width=finiteRange(container.clientWidth,0,0),height=finiteRange(container.clientHeight,0,0);if(!current())return;const edges=admitted.safeArea,start=Math.min(width,edges.inlineStart),end=Math.min(width,edges.inlineEnd),top=Math.min(height,edges.blockStart),bottom=Math.min(height,edges.blockEnd);if(!point||!(point[0]>=0&&point[1]>=0&&point[0]<=width&&point[1]<=height)||start+end>=width||top+bottom>=height){this.hide();return}fence.style.insetInlineStart=`${start}px`,fence.style.insetInlineEnd=`${end}px`,fence.style.insetBlockStart=`${top}px`,fence.style.insetBlockEnd=`${bottom}px`,host.child&&(fence.style.direction=direction);const clip=fence.getBoundingClientRect();let left=clip.left,right=clip.right,upper=clip.top,lower=clip.bottom;for(const clipping of admitted.boundaries){const bounds=clipping.getBoundingClientRect();if(!current())return;left=Math.max(left,bounds.left),right=Math.min(right,bounds.right),upper=Math.max(upper,bounds.top),lower=Math.min(lower,bounds.bottom)}if(!(right-left>16&&lower-upper>16)){this.hide();return}wrapper.hidden=!1;const rect=container.getBoundingClientRect();if(!current())return;const pointRect=virtualAnchorFromRect({x:rect.left+point[0],y:rect.top+point[1]}).getBoundingClientRect(),publish=()=>{if(!current()||!this.hasContent())return;const first=!this.placed;first&&this.captureReturnTarget(wrapper),current()&&(this.placed=!0,this.placedCoordinates=coordinates,this.syncOverlay(wrapper),first&&current()&&this.enter(wrapper))},previous=this.placement;if(previous?.handle?.isActive()&&previous.document===document&&previous.map===map&&previous.wrapper===wrapper&&previous.container===container&&previous.fence===fence&&previous.direction===direction&&previous.style===style&&previous.connection===connection&&previous.boundaries.length===admitted.boundaries.length&&previous.boundaries.every((value,index)=>value===admitted.boundaries[index])&&previous.safeArea.blockStart===edges.blockStart&&previous.safeArea.blockEnd===edges.blockEnd&&previous.safeArea.inlineStart===edges.inlineStart&&previous.safeArea.inlineEnd===edges.inlineEnd){previous.rect=pointRect,previous.current=current,previous.publish=publish,previous.handle?.update();return}if(this.placement=void 0,previous?.handle?.(),!current())return;const placement={document,map,wrapper,container,fence,direction,style,connection,boundaries:admitted.boundaries,safeArea:edges,rect:pointRect,current,publish};this.placement=placement;const handle=place({contextElement:container,getBoundingClientRect:()=>placement.rect},wrapper,{placement:"top",strategy:"absolute",offset:12,boundary:[fence,...admitted.boundaries],padding:8,shiftCrossAxis:!0,onPlaced:()=>{this.placement===placement&&placement.publish()}});if(!current()||this.placement!==placement){this.placement===placement&&(this.placement=void 0),handle();return}placement.handle=handle,handle.ready.then(ready=>{!ready&&this.placement===placement&&placement.current()&&this.hide()})}catch{current()&&this.hide()}}}const CHILD_EVENTS=["focusin","focusout","pointerdown"];class MapAnchorChildren{constructor(host,anchors){this.host=host,this.entries=new Map,this.admittedControllers=new Set,this.serial=0;for(const anchor of anchors)this.attach(anchor)}run(anchor,operation,value){const entry=this.entries.get(anchor);switch(operation){case"attach":this.sync(this.attach(anchor));return;case"detach":if(entry){for(const type of CHILD_EVENTS)anchor.removeEventListener(type,entry.listener);this.entries.delete(anchor),entry.controller.dispose(),this.sync(entry)}return;case"capture":return entry?.controller.capture();case"retire":entry&&(entry.open=!1,entry.focused=void 0,entry.controller.hide(!1,!0));return;case"repair":if(value){const repair=value;applyComposedFocusRepair(repair,[repair.candidate,this.host.canvas()])}return;case"focus":return entry?.controller.focus()??!1;default:entry&&this.sync(entry);return}}sync(only){this.each(only,controller=>{controller.sync()})}schedule(){this.each(void 0,controller=>{controller.schedule()})}invalidate(){for(const controller of this.admittedControllers)controller.invalidate()}stop(){for(const{controller}of this.entries.values())controller.stop()}hide(){for(const{controller,open}of this.entries.values())open&&controller.hide()}dispose(){for(const{controller}of this.entries.values())controller.dispose()}each(only,place2){const changed=this.admit();for(const[anchor,entry]of this.entries)only&&entry!==only&&!changed.has(entry)||(anchor.open?(entry.open=!0,entry.admitted?place2(entry.controller):changed.has(entry)&&entry.controller.suspendAdmission()):entry.open&&(entry.open=!1,entry.controller.hide(!0,!0)))}admit(){const first=[];let open=0,overflow;for(const anchor of this.entries.keys()){if(!anchor.open||(++open>LIMIT&&(overflow??=anchor),first.length===LIMIT&&anchor.compareDocumentPosition(first[LIMIT-1])&2))continue;let low=0,high=first.length;for(;low<high;){const middle=low+high>>>1;anchor.compareDocumentPosition(first[middle])&2?low=middle+1:high=middle}first.splice(low,0,anchor),first.length>LIMIT&&first.pop()}overflow&&devWarnOnce("lyra-map-anchor-limit",`<${this.host.element.localName}>: only the first ${LIMIT} open <${overflow.localName}> children are placed; later ones stay hidden until one closes.`);const selected=new Set(first),changed=new Set;this.admittedControllers.clear();for(const[anchor,entry]of this.entries){const admitted=selected.has(anchor);admitted!==entry.admitted&&(entry.admitted=admitted,changed.add(entry)),admitted&&this.admittedControllers.add(entry.controller)}return changed}attach(anchor){const existing=this.entries.get(anchor);if(existing)return existing;const host=this.host,shadow=selector=>anchor.shadowRoot?.querySelector(selector)??void 0,controller=new MapAnchorController({...host,key:`map-anchor-child-${++this.serial}`,overlayHost:anchor,child:!0,wrapper:()=>shadow('[part~="base"]'),fence:()=>shadow(".fence"),content:()=>anchor.shadowRoot?.querySelector("slot:not([name])"),styleLoaded:()=>host.engineReady(),request:()=>anchor.open&&entry.admitted&&!anchor.hidden?anchor.lngLat:null,boundary:()=>anchor.boundary===void 0?host.element.anchorBoundary:anchor.boundary,safeArea:()=>anchor.safeArea===void 0?host.element.anchorSafeArea:anchor.safeArea,closable:()=>anchor.closable,pending:()=>anchor.isUpdatePending,retire:()=>{},emitClose:()=>{},escape:()=>{anchor[MAP_ANCHOR_SEAM]("escape")},fallback:()=>host.canvas(),lost:()=>entry.focused,placed:placed=>{anchor[MAP_ANCHOR_SEAM](placed?"placed":"unplaced")},autofocus:()=>anchor[MAP_ANCHOR_SEAM]("autofocus")}),entry={controller,admitted:!1,open:!1,listener:event=>{if(event.type==="pointerdown"){controller.raise();return}const focus=event,next=focus.relatedTarget;event.type==="focusout"&&queueMicrotask(()=>{controller.focusOut()}),event.type==="focusin"?(entry.focused=focus.composedPath()[0],controller.focusIn(focus)):next?composedContains(anchor,next)||(entry.focused=void 0):queueMicrotask(()=>{anchor.isConnected&&entry.focused?.isConnected&&!composedContains(anchor,deepActiveElement(anchor.ownerDocument))&&(entry.focused=void 0)})}};for(const type of CHILD_EVENTS)anchor.addEventListener(type,entry.listener);return this.entries.set(anchor,entry),entry}}export{MapAnchorChildren,MapAnchorController};
1
+ import{deferredPlaceSession as place}from"../../../internal/anchored-overlay-runtime.js";import{getInheritedPropertyDescriptor}from"../../../internal/data-descriptors.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{applyComposedFocusRepair,captureComposedFocusRepair,focusFirstAvailable}from"../../../internal/focus-navigation.js";import{activateNonmodalOverlay}from"../../../internal/nonmodal-overlay-manager.js";import{finiteRange}from"../../../internal/numbers.js";import{reserveOverlayOrder}from"../../../internal/overlay-order.js";import{collectAutofocusElements,collectFocusableElements,composedContains,deepActiveElement,observeOverlayStack}from"../../../internal/overlay-stack.js";import{virtualAnchorFromRect}from"../../../internal/positioner-geometry.js";import{admitMapAnchorOptions}from"./map-anchor-options.js";import{MAP_ANCHOR_SEAM}from"./map-anchor-seam.js";import{mapOwnValue,renderedSizeKey}from"./map-readers.js";const escapeOwners=new Set,rankings=new WeakMap,RANK="--_lr-map-anchor-rank",LIMIT=16;let raises=0,insertions=0;class MapAnchorController{constructor(host){this.host=host,this.epoch=0,this.placed=!1,this.closingState=!1,this.observedBoundaries=[],this.raisedAt=0,this.order=0,this.fresh=!0,this.listening=!1}get closing(){return this.closingState}view(){return this.host.element.ownerDocument?.defaultView??null}invalidate(){this.epoch+=1,this.placed=!1,this.placedCoordinates=void 0,this.placement?.handle?.invalidate(),this.overlay?.suspend()}stop(){this.invalidate();const placement=this.placement;this.placement=void 0,placement?.handle?.()}schedule(){if(this.invalidate(),this.frame!==void 0)return;const view=this.view();if(!view||typeof view.requestAnimationFrame!="function"){this.sync();return}this.frame=view.requestAnimationFrame(()=>{this.frame=void 0,this.sync()})}cancelFrame(){this.frame!==void 0&&(this.view()?.cancelAnimationFrame?.(this.frame),this.frame=void 0)}focus(){const wrapper=this.host.wrapper();if(!wrapper||!this.isOpen())return!1;const epoch=this.epoch,targets=collectFocusableElements(wrapper);return epoch!==this.epoch||!this.isOpen()||targets.length===0||(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.isOpen())?!1:focusFirstAvailable(targets)&&epoch===this.epoch&&this.isOpen()}isOpen(){const host=this.host,wrapper=host.wrapper();return host.element.isConnected&&!!host.map()&&host.styleLoaded()&&this.placed&&!host.pending()&&this.placedCoordinates===host.request()&&!!wrapper&&!wrapper.hidden&&!host.interactionBlocked()&&this.hasContent()}captureReturnTarget(wrapper){const active=deepActiveElement(this.host.element.ownerDocument);if(!(!active||composedContains(wrapper,active)))try{const descriptor=getInheritedPropertyDescriptor(active,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=active,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}close(reason){const host=this.host,wrapper=host.wrapper();if(!wrapper||!this.isOpen())return!1;const requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=captureComposedFocusRepair(wrapper,this.returnTarget??null);if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request()||!this.isOpen())return!1;this.closingState=!0;try{host.retire()}finally{this.closingState=!1}this.hide(!1,!0);const epoch=this.epoch;return host.emitClose(Object.freeze({reason})),repair&&epoch===this.epoch&&host.request()===null&&applyComposedFocusRepair(repair),!0}hide(restore=!0,retire=!1){const host=this.host,wrapper=host.wrapper(),requestEpoch=this.epoch,map=host.map(),coordinates=host.request(),repair=restore&&wrapper?this.repairFrom(wrapper):null;if(requestEpoch!==this.epoch||map!==host.map()||coordinates!==host.request())return;this.stop(),wrapper&&(wrapper.hidden=!0),rankings.get(host.element)?.delete(this)&&(wrapper?.style.removeProperty(RANK),MapAnchorController.rank(host.element)),host.placed?.(!1);const epoch=this.epoch;if(retire){const overlay=this.overlay;this.overlay=void 0,this.returnTarget=void 0,this.fresh=!0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1})}else this.overlay?.suspend();repair&&epoch===this.epoch&&!this.placed&&this.repair(repair)}capture(){const wrapper=this.host.wrapper();return wrapper?this.repairFrom(wrapper):null}repair(snapshot){if(!snapshot)return;const repair=snapshot;applyComposedFocusRepair(repair,[repair.candidate,this.host.fallback?.()])}repairFrom(wrapper){const host=this.host,document=wrapper.ownerDocument,lost=host.lost?.(),active=deepActiveElement(document),candidate=()=>this.returnTarget??host.fallback?.()??null,target=lost&&(!active||active===document.body||active===document.documentElement)?candidate():null;return captureComposedFocusRepair(wrapper,candidate)??(lost&&target?{activeElement:lost,candidate:target,document,owner:wrapper}:null)}raise(escape=!0){!rankings.get(this.host.element)?.has(this)||!this.ranked()||(this.raisedAt=++raises,MapAnchorController.rank(this.host.element),escape&&this.reRegister())}ranked(){return!!this.host.child||[...rankings.get(this.host.element)??[]].some(member=>member.host.child)}enter(wrapper){const host=this.host,members=rankings.get(host.element)??new Set;rankings.set(host.element,members);const joined=!members.has(this);if(members.add(this),host.placed?.(!0),!host.child&&!this.listening&&(this.listening=!0,wrapper.addEventListener("pointerdown",()=>{this.raise()}),wrapper.addEventListener("focusout",()=>{queueMicrotask(()=>{this.focusOut()})})),!this.fresh){joined&&MapAnchorController.rank(host.element);return}if(this.fresh=!1,this.raise(!1),!(!host.autofocus?.()||composedContains(wrapper,deepActiveElement(wrapper.ownerDocument)))){for(const target of collectAutofocusElements(wrapper))if(focusFirstAvailable(target)||focusFirstAvailable(collectFocusableElements(target)))break}}static rank(map){const members=[...rankings.get(map)??[]],ranked=members.some(member=>member.host.child),active=deepActiveElement(map.ownerDocument),keys=new Map;for(const member of members){const wrapper=member.host.wrapper();keys.set(member,wrapper&&composedContains(wrapper,active)?raises+1:member.raisedAt)}return members.sort((a,b)=>keys.get(a)-keys.get(b)),members.forEach((member,index)=>{const style=member.host.wrapper()?.style;ranked?style?.setProperty(RANK,String(index)):style?.removeProperty(RANK)}),members}focusOut(){if(!this.ranked())return;[...MapAnchorController.rank(this.host.element)].reverse().find(member=>member.host.closable()&&member.isOpen())?.reRegister()}reRegister(){const host=this.host,overlay=this.overlay,wrapper=host.wrapper();if(!overlay||overlay.isTopmost()||!wrapper)return;let entries=[];observeOverlayStack(host.element.ownerDocument,snapshot=>{entries=snapshot.entries})();const index=entries.findIndex(entry=>entry.host===host.overlayHost),anchored=other=>[...escapeOwners].some(owner=>{const panel=owner.host.wrapper();return owner!==this&&(owner.host.overlayHost===other||!!panel&&composedContains(panel,other))});index<0||entries.slice(index+1).some(entry=>composedContains(wrapper,entry.host)||!anchored(entry.host))||(this.overlay=this.activate())}activate(below=!1){const host=this.host,document=host.element.ownerDocument,focused=below?[...escapeOwners].find(owner=>{const wrapper=owner.host.wrapper();return owner!==this&&owner.ranked()&&!!wrapper&&composedContains(wrapper,deepActiveElement(document))}):void 0,order=this.order=focused?focused.order-1/(++insertions+1):reserveOverlayOrder(document)(document);return activateNonmodalOverlay({host:host.overlayHost,panel:()=>host.wrapper()??null,onEscape:()=>{host.escape?host.escape():this.close("escape")},beforeInitialFocus:()=>!1,restoreFocusTo:()=>this.returnTarget??null,orderReservation:destination=>destination===document?order:void 0})}dispose(){this.cancelFrame(),this.hide(!0,!0),this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[]}suspendAdmission(){this.cancelFrame(),this.hide(),!(this.placement||this.placed)&&(this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[])}syncOverlay(wrapper){const host=this.host,element=host.element;if(!host.closable()){const overlay=this.overlay;this.overlay=void 0,escapeOwners.delete(this),overlay?.deactivate({restoreFocus:!1});return}if(this.overlay)this.overlay.resume();else{const epoch=this.epoch;if(this.captureReturnTarget(wrapper),epoch!==this.epoch||!this.placed||!element.isConnected)return;const overlay=this.activate(this.ranked());epoch===this.epoch&&this.placed&&element.isConnected&&host.closable()&&!this.overlay?(this.overlay=overlay,escapeOwners.add(this)):overlay.deactivate({restoreFocus:!1})}}hasContent(){return this.host.content()?.assignedNodes({flatten:!0}).some(node=>node.nodeType===1||node.nodeType===3&&!!node.textContent?.trim())??!1}observeBoundaries(boundaries){if(boundaries.length===this.observedBoundaries.length&&boundaries.every((value,index)=>value===this.observedBoundaries[index]))return;this.boundaryObserver?.disconnect(),this.boundaryObserver=void 0,this.observedBoundaries=[...boundaries];const ResizeObserverClass=this.view()?.ResizeObserver;if(!ResizeObserverClass||boundaries.length===0)return;let sizes=boundaries.map(renderedSizeKey);this.boundaryObserver=new ResizeObserverClass(()=>{const next=boundaries.map(renderedSizeKey);next.every((value,index)=>value===sizes[index])||(sizes=next,this.host.element.isConnected&&this.schedule())});for(const boundary of boundaries)this.boundaryObserver.observe(boundary)}focusIn(event){const wrapper=this.host.wrapper(),previous=event.relatedTarget,view=this.view();if(wrapper&&view&&!(previous instanceof view.Element&&composedContains(wrapper,previous))&&this.raise(),!(!wrapper||!view||!(previous instanceof view.Element)||previous.ownerDocument!==this.host.element.ownerDocument||composedContains(wrapper,previous)))try{const descriptor=getInheritedPropertyDescriptor(previous,"focus");descriptor&&Object.hasOwn(descriptor,"value")&&typeof descriptor.value=="function"&&(this.returnTarget=previous,this.overlay?.updateRestoreFocusTo(this.returnTarget))}catch{}}point(){const host=this.host,position=host.request();if(!Array.isArray(position))return;const lng=mapOwnValue(position,"0"),lat=mapOwnValue(position,"1");if(!(typeof lng!="number"||!Number.isFinite(lng)||typeof lat!="number"||!Number.isFinite(lat)||Math.abs(lat)>90))return host.element.project([lng,lat])}sync(){const host=this.host,element=host.element;if(this.invalidate(),host.updateActive()){const[generation,connection2]=host.generations(),map2=host.map();host.afterUpdate(()=>{const[style2,current2]=host.generations();element.isConnected&&current2===connection2&&style2===generation&&host.map()===map2&&this.sync()},`${host.key}-${connection2}-${generation}`);return}const wrapper=host.wrapper(),container=host.container(),fence=host.fence();if(!wrapper||!container||!fence||!element.isConnected||!host.map()||!host.styleLoaded()||host.interactionBlocked()||!this.hasContent()){this.hide();return}const epoch=this.epoch,map=host.map(),coordinates=host.request(),document=element.ownerDocument,[style,connection]=host.generations(),boundary=host.boundary(),safeArea=host.safeArea(),direction=host.direction(),current=()=>element.isConnected&&element.ownerDocument===document&&host.map()===map&&host.styleLoaded()&&host.generations()[0]===style&&host.generations()[1]===connection&&host.wrapper()===wrapper&&host.container()===container&&host.fence()===fence&&epoch===this.epoch&&host.request()===coordinates&&host.boundary()===boundary&&host.safeArea()===safeArea&&host.direction()===direction&&!host.interactionBlocked();try{const admitted=admitMapAnchorOptions({boundary,safeArea},element.ownerDocument,{current});if(!admitted.ok||!current()){epoch===this.epoch&&this.hide();return}this.observeBoundaries(admitted.boundaries);const point=this.point();if(!current())return;const width=finiteRange(container.clientWidth,0,0),height=finiteRange(container.clientHeight,0,0);if(!current())return;const edges=admitted.safeArea,start=Math.min(width,edges.inlineStart),end=Math.min(width,edges.inlineEnd),top=Math.min(height,edges.blockStart),bottom=Math.min(height,edges.blockEnd);if(!point||!(point[0]>=0&&point[1]>=0&&point[0]<=width&&point[1]<=height)||start+end>=width||top+bottom>=height){this.hide();return}fence.style.insetInlineStart=`${start}px`,fence.style.insetInlineEnd=`${end}px`,fence.style.insetBlockStart=`${top}px`,fence.style.insetBlockEnd=`${bottom}px`,host.child&&(fence.style.direction=direction);const clip=fence.getBoundingClientRect();let left=clip.left,right=clip.right,upper=clip.top,lower=clip.bottom;for(const clipping of admitted.boundaries){const bounds=clipping.getBoundingClientRect();if(!current())return;left=Math.max(left,bounds.left),right=Math.min(right,bounds.right),upper=Math.max(upper,bounds.top),lower=Math.min(lower,bounds.bottom)}if(!(right-left>16&&lower-upper>16)){this.hide();return}wrapper.hidden=!1;const rect=container.getBoundingClientRect();if(!current())return;const pointRect=virtualAnchorFromRect({x:rect.left+point[0]*rect.width/width,y:rect.top+point[1]*rect.height/height}).getBoundingClientRect(),publish=()=>{if(!current()||!this.hasContent())return;const first=!this.placed;first&&this.captureReturnTarget(wrapper),current()&&(this.placed=!0,this.placedCoordinates=coordinates,this.syncOverlay(wrapper),first&&current()&&this.enter(wrapper))},previous=this.placement;if(previous?.handle?.isActive()&&previous.document===document&&previous.map===map&&previous.wrapper===wrapper&&previous.container===container&&previous.fence===fence&&previous.direction===direction&&previous.style===style&&previous.connection===connection&&previous.boundaries.length===admitted.boundaries.length&&previous.boundaries.every((value,index)=>value===admitted.boundaries[index])&&previous.safeArea.blockStart===edges.blockStart&&previous.safeArea.blockEnd===edges.blockEnd&&previous.safeArea.inlineStart===edges.inlineStart&&previous.safeArea.inlineEnd===edges.inlineEnd){previous.rect=pointRect,previous.current=current,previous.publish=publish,previous.handle?.update();return}if(this.placement=void 0,previous?.handle?.(),!current())return;const placement={document,map,wrapper,container,fence,direction,style,connection,boundaries:admitted.boundaries,safeArea:edges,rect:pointRect,current,publish};this.placement=placement;const handle=place({contextElement:container,getBoundingClientRect:()=>placement.rect},wrapper,{placement:"top",strategy:"absolute",offset:12,boundary:[fence,...admitted.boundaries],padding:8,shiftCrossAxis:!0,onPlaced:()=>{this.placement===placement&&placement.publish()}});if(!current()||this.placement!==placement){this.placement===placement&&(this.placement=void 0),handle();return}placement.handle=handle,handle.ready.then(ready=>{!ready&&this.placement===placement&&placement.current()&&this.hide()})}catch{current()&&this.hide()}}}const CHILD_EVENTS=["focusin","focusout","pointerdown"];class MapAnchorChildren{constructor(host,anchors){this.host=host,this.entries=new Map,this.admittedControllers=new Set,this.serial=0;for(const anchor of anchors)this.attach(anchor)}run(anchor,operation,value){const entry=this.entries.get(anchor);switch(operation){case"attach":this.sync(this.attach(anchor));return;case"detach":if(entry){for(const type of CHILD_EVENTS)anchor.removeEventListener(type,entry.listener);this.entries.delete(anchor),entry.controller.dispose(),this.sync(entry)}return;case"capture":return entry?.controller.capture();case"retire":entry&&(entry.open=!1,entry.focused=void 0,entry.controller.hide(!1,!0));return;case"repair":if(value){const repair=value;applyComposedFocusRepair(repair,[repair.candidate,this.host.canvas()])}return;case"focus":return entry?.controller.focus()??!1;default:entry&&this.sync(entry);return}}sync(only){this.each(only,controller=>{controller.sync()})}schedule(){this.each(void 0,controller=>{controller.schedule()})}invalidate(){for(const controller of this.admittedControllers)controller.invalidate()}stop(){for(const{controller}of this.entries.values())controller.stop()}hide(){for(const{controller,open}of this.entries.values())open&&controller.hide()}dispose(){for(const{controller}of this.entries.values())controller.dispose()}each(only,place2){const changed=this.admit();for(const[anchor,entry]of this.entries)only&&entry!==only&&!changed.has(entry)||(anchor.open?(entry.open=!0,entry.admitted?place2(entry.controller):changed.has(entry)&&entry.controller.suspendAdmission()):entry.open&&(entry.open=!1,entry.controller.hide(!0,!0)))}admit(){const first=[];let open=0,overflow;for(const anchor of this.entries.keys()){if(!anchor.open||(++open>LIMIT&&(overflow??=anchor),first.length===LIMIT&&anchor.compareDocumentPosition(first[LIMIT-1])&2))continue;let low=0,high=first.length;for(;low<high;){const middle=low+high>>>1;anchor.compareDocumentPosition(first[middle])&2?low=middle+1:high=middle}first.splice(low,0,anchor),first.length>LIMIT&&first.pop()}overflow&&devWarnOnce("lyra-map-anchor-limit",`<${this.host.element.localName}>: only the first ${LIMIT} open <${overflow.localName}> children are placed; later ones stay hidden until one closes.`);const selected=new Set(first),changed=new Set;this.admittedControllers.clear();for(const[anchor,entry]of this.entries){const admitted=selected.has(anchor);admitted!==entry.admitted&&(entry.admitted=admitted,changed.add(entry)),admitted&&this.admittedControllers.add(entry.controller)}return changed}attach(anchor){const existing=this.entries.get(anchor);if(existing)return existing;const host=this.host,shadow=selector=>anchor.shadowRoot?.querySelector(selector)??void 0,controller=new MapAnchorController({...host,key:`map-anchor-child-${++this.serial}`,overlayHost:anchor,child:!0,wrapper:()=>shadow('[part~="base"]'),fence:()=>shadow(".fence"),content:()=>anchor.shadowRoot?.querySelector("slot:not([name])"),styleLoaded:()=>host.engineReady(),request:()=>anchor.open&&entry.admitted&&!anchor.hidden?anchor.lngLat:null,boundary:()=>anchor.boundary===void 0?host.element.anchorBoundary:anchor.boundary,safeArea:()=>anchor.safeArea===void 0?host.element.anchorSafeArea:anchor.safeArea,closable:()=>anchor.closable,pending:()=>anchor.isUpdatePending,retire:()=>{},emitClose:()=>{},escape:()=>{anchor[MAP_ANCHOR_SEAM]("escape")},fallback:()=>host.canvas(),lost:()=>entry.focused,placed:placed=>{anchor[MAP_ANCHOR_SEAM](placed?"placed":"unplaced")},autofocus:()=>anchor[MAP_ANCHOR_SEAM]("autofocus")}),entry={controller,admitted:!1,open:!1,listener:event=>{if(event.type==="pointerdown"){controller.raise();return}const focus=event,next=focus.relatedTarget;event.type==="focusout"&&queueMicrotask(()=>{controller.focusOut()}),event.type==="focusin"?(entry.focused=focus.composedPath()[0],controller.focusIn(focus)):next?composedContains(anchor,next)||(entry.focused=void 0):queueMicrotask(()=>{anchor.isConnected&&entry.focused?.isConnected&&!composedContains(anchor,deepActiveElement(anchor.ownerDocument))&&(entry.focused=void 0)})}};for(const type of CHILD_EVENTS)anchor.addEventListener(type,entry.listener);return this.entries.set(anchor,entry),entry}}export{MapAnchorChildren,MapAnchorController};
@@ -0,0 +1 @@
1
+ import{flattenedParentElement}from"../../../internal/composed-tree.js";const TOLERANCE=.5;function mapCanvasAllocation(host,target,width,height){if(![host.left,host.top,host.width,host.height,target.left,target.top,target.width,target.height,width,height].every(Number.isFinite)||Math.min(host.width,host.height,target.width,target.height,width,height)<=0||host.left<target.left-TOLERANCE||host.top<target.top-TOLERANCE||host.left+host.width>target.left+target.width+TOLERANCE||host.top+host.height>target.top+target.height+TOLERANCE)return;const sx=width/host.width,sy=height/host.height,left=(target.left-host.left)*sx,top=(target.top-host.top)*sy,canvasWidth=target.width*sx,canvasHeight=target.height*sy,padding={left:Math.max(0,-left),top:Math.max(0,-top),right:Math.max(0,canvasWidth+left-width),bottom:Math.max(0,canvasHeight+top-height)};if([left,top,canvasWidth,canvasHeight,...Object.values(padding)].every(Number.isFinite))return{left,top,width:canvasWidth,height:canvasHeight,padding}}function compatibleAncestors(host,target){const view=host.ownerDocument.defaultView;if(!view)return!1;let current=host,found=target==="viewport";for(let count=0;current&&count<128;count++,current=flattenedParentElement(current)){current===target&&current!==host&&(found=!0);const style=view.getComputedStyle(current);if(style.perspective!=="none"||style.rotate!=="none"&&style.rotate!=="0deg"||style.scale!=="none"&&style.scale.split(/\s+/).some(value=>!Number.isFinite(parseFloat(value))||parseFloat(value)<=0))return!1;if(style.transform!=="none"){const matrix=new view.DOMMatrixReadOnly(style.transform);if(!matrix.is2D||matrix.a<=0||matrix.d<=0||matrix.b!==0||matrix.c!==0)return!1}}return current===null&&found}function paddingBox(base,rect,view){const style=view.getComputedStyle(base),number=value=>parseFloat(value),left=number(style.borderLeftWidth),right=number(style.borderRightWidth),top=number(style.borderTopWidth),bottom=number(style.borderBottomWidth),paddingX=number(style.paddingLeft)+number(style.paddingRight),paddingY=number(style.paddingTop)+number(style.paddingBottom),borderWidth=number(style.width)+(style.boxSizing==="border-box"?0:paddingX+left+right),borderHeight=number(style.height)+(style.boxSizing==="border-box"?0:paddingY+top+bottom),width=borderWidth-left-right,height=borderHeight-top-bottom;if(![borderWidth,borderHeight,width,height,left,right,top,bottom].every(Number.isFinite)||Math.min(borderWidth,borderHeight,width,height,rect.width,rect.height)<=0)return;const sx=rect.width/borderWidth,sy=rect.height/borderHeight;return{width,height,rect:{left:rect.left+left*sx,top:rect.top+top*sy,width:width*sx,height:height*sy}}}const VARIABLES=["left","top","width","height","inset-top","inset-right","inset-bottom","inset-left"];class MapCanvasAllocationController{constructor(host){this.host=host,this.key="",this.updating=!1,this.stopped=!1}refresh(){if(!(this.stopped||this.updating)){this.updating=!0;try{const host=this.host.element,base=this.host.base(),target=this.host.target();let allocation;const view=host.ownerDocument.defaultView;if(host.isConnected&&base&&target!==void 0&&view)try{const candidate=target;if((target==="viewport"||candidate!==null&&typeof candidate=="object"&&candidate!==host&&candidate.namespaceURI==="http://www.w3.org/1999/xhtml"&&candidate.ownerDocument===host.ownerDocument&&candidate.isConnected)&&compatibleAncestors(base,target)){const rect=base.getBoundingClientRect(),viewport=view.visualViewport,targetRect=target==="viewport"?{left:viewport?.offsetLeft??0,top:viewport?.offsetTop??0,width:viewport?.width??host.ownerDocument.documentElement.clientWidth,height:viewport?.height??host.ownerDocument.documentElement.clientHeight}:target.ownerDocument===host.ownerDocument&&target.isConnected?target.getBoundingClientRect():void 0,box=paddingBox(base,rect,view);targetRect&&box&&(allocation=mapCanvasAllocation(box.rect,targetRect,box.width,box.height))}}catch{}const values=allocation?[allocation.left,allocation.top,allocation.width,allocation.height,allocation.padding.top,allocation.padding.right,allocation.padding.bottom,allocation.padding.left]:[],key=values.map(value=>Math.round(value*1e3)/1e3).join(",");if((base!==this.base||key!==this.key)&&(this.base&&this.base!==base&&this.clear(this.base),this.base=base,this.key=key,base&&VARIABLES.forEach((name,index)=>{allocation?base.style.setProperty(`--_lr-map-canvas-${name}`,`${values[index]}px`):base.style.removeProperty(`--_lr-map-canvas-${name}`)}),this.host.changed(allocation)),this.stopped)return;host.isConnected&&this.host.target()!==void 0&&view&&host.ownerDocument.defaultView===view?this.schedule(view):this.cancel()}finally{this.updating=!1}}}schedule(view){if(this.frame?.view===view)return;this.cancel();const id=view.requestAnimationFrame(()=>{this.frame?.id!==id||this.frame.view!==view||(this.frame=void 0,this.refresh())});this.frame={view,id}}cancel(){this.frame&&this.frame.view.cancelAnimationFrame(this.frame.id),this.frame=void 0}clear(base){for(const name of VARIABLES)base.style.removeProperty(`--_lr-map-canvas-${name}`)}dispose(){this.stopped=!0,this.cancel(),this.base&&this.clear(this.base),this.base=void 0}}export{MapCanvasAllocationController,mapCanvasAllocation};
@@ -9,6 +9,8 @@ export interface LyraMapOverlays{readonly sources?:readonly LyraMapOverlaySource
9
9
  export type LyraMapSourceDataDiff=MapLibreSourceDataDiff;export type{LyraMapFeatureRequirements}from'./map-loader.js';
10
10
  /** Map engine selected before connecting the component.*/
11
11
  export type LyraMapEngine='modular'|'maplibre';
12
+ /** A containing ancestor or the visual viewport painted by the canvas while the host stays usable.*/
13
+ export type LyraMapCanvasTarget=HTMLElement|'viewport';
12
14
  /** Non-color encoding retained when a legend entry's authored color is unavailable.*/
13
15
  export type LyraMapLegendPattern='solid'|'diagonal'|'dots'|'crosshatch';
14
16
  /**
@@ -928,7 +930,14 @@ maxZoom?:number;private get zoomLimitsRequested();private get zoomLimits();
928
930
  * that `lr-map-view-change` and `lr-map-move` report (the visible box inside the padding).
929
931
  * Changing it keeps the geographic centre fixed and shifts the picture; it is not reported as a
930
932
  * camera change. Applied to the engine once it exists. */
931
- cameraPadding?:LyraMapPadding;private appliedPadding;private pendingCommand?;private readonly commandToken;private reflectingCamera;private zoomLimitRevision;private cameraUpdatePending;private deferredCameraWork;private moveFrame?;private pendingFit?;private readonly fitToken;private semanticsStale;private markerSemanticsStale;private geoJsonRefreshRequested;private refreshingGeoJson;private reflectedCamera?;private boxZoomSettling;private writingCamera;
933
+ cameraPadding?:LyraMapPadding;
934
+ /** Optional canvas extent. A connected same-document composed ancestor, or `'viewport'`,
935
+ * expands the canvas while controls, legend, camera framing and padded visible bounds use the
936
+ * host. The target must contain the whole host. Translation and positive axis-aligned scale are
937
+ * supported; rotation, skew, perspective, disconnected targets and noncontaining allocations
938
+ * restore host layout. Ordinary ancestor clipping still applies. Authored cameraPadding adds
939
+ * space inside the host; clearing this property restores the original allocation. */
940
+ canvasTarget?:LyraMapCanvasTarget;private canvasAllocationController?;private canvasAllocation?;private canvasPaddingUsable;private syncCanvasAllocation;private releaseCanvasAllocation;private appliedPadding;private pendingCommand?;private readonly commandToken;private reflectingCamera;private zoomLimitRevision;private cameraUpdatePending;private deferredCameraWork;private moveFrame?;private pendingFit?;private readonly fitToken;private semanticsStale;private markerSemanticsStale;private geoJsonRefreshRequested;private refreshingGeoJson;private reflectedCamera?;private boxZoomSettling;private writingCamera;
932
941
  /** Whether the constructed peer repeats the world horizontally. `undefined` leaves MapLibre's
933
942
  * own default in force. Construction-only; set before the map is created. */
934
943
  renderWorldCopies?:boolean;