@aceshooting/lyra-ui 28.1.6 → 29.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -180
- package/README.md +10 -2
- package/dist/components/charts/chart/chart.class.js +2 -2
- package/dist/components/data/data-grid/data-grid.class.js +1 -1
- package/dist/components/data/table/table.class.js +2 -2
- package/dist/components/forms/combobox/option.class.js +1 -1
- package/dist/components/forms/select/select.class.js +1 -1
- package/dist/components/media/map/map-loader.d.ts +9 -1
- package/dist/components/media/map/map-loader.js +1 -1
- package/dist/components/media/map/map.class.d.ts +20 -11
- package/dist/components/media/map/map.class.js +4 -4
- package/dist/components/retrieval/graph/graph-model.d.ts +10 -1
- package/dist/components/retrieval/graph/graph-spatial-controller.js +30 -0
- package/dist/components/retrieval/graph/graph-spatial.js +1 -0
- package/dist/components/retrieval/graph/graph.class.d.ts +45 -6
- package/dist/components/retrieval/graph/graph.class.js +2 -2
- package/dist/components/retrieval/graph/graph.styles.js +1 -1
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.d.ts +22 -5
- package/dist/components/retrieval/knowledge-graph-explorer/knowledge-graph-explorer.class.js +6 -2
- package/dist/events.d.ts +10 -5
- package/dist/framework-types.d.ts +1 -1
- package/dist/internal/accessible-text-controller.js +1 -1
- package/dist/internal/autoloader-manifest.js +1 -1
- package/dist/internal/collection-source-tracker.js +1 -0
- package/dist/internal/default-strings/media.generated.js +1 -1
- package/dist/internal/default-strings/retrieval.generated.js +1 -1
- package/dist/internal/localization-types.d.ts +1 -1
- package/dist/internal/localization.js +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/internal/positioner.js +1 -1
- package/dist/lyra.d.ts +1 -1
- package/llms/components/lr-geojson-viewer.md +1 -1
- package/llms/components/lr-graph.md +78 -8
- package/llms/components/lr-knowledge-graph-explorer.md +15 -2
- package/llms/components/lr-map.md +60 -25
- package/llms/index.md +1 -1
- package/llms/peers.md +4 -3
- package/llms/shared/ai-and-peers.md +4 -3
- package/llms/shared/imports-and-registration.md +1 -1
- package/llms/shared.md +5 -4
- package/locales.json +138 -138
- package/package.json +12 -6
- package/registrations.json +1 -1
- package/skills/lyra-ui/SKILL.md +8 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{sanitizeCssDeclarationValue,sanitizeCssLength}from"../../../internal/safe-css.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{srOnly,nextId}from"../../../internal/a11y.js";import{finiteCount,finiteInteger,finiteRatio}from"../../../internal/numbers.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{getCollator,getNumberFormat}from"../../../internal/intl-cache.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{definePersistedProperty,isPersistedPropertyExplicitlySet}from"../../../internal/persisted-restore.js";import{styles}from"./table.styles.js";import{chevronIcon,closeIcon,sortIcon}from"../../../internal/icons.js";import{minMax}from"../../../internal/numbers.js";import{literalSetConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{normalizeSize,optionalSizeConverter}from"../../../internal/variants.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{ColumnResizePointerSession,columnResizeAriaValues,columnResizeKeyboardWidth,columnResizePointerWidth,columnResizeWidth}from"../../../internal/column-resize.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{LYRA_DEFAULT_noColumns,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_showFewerColumns,LYRA_DEFAULT_tableEditCell,LYRA_DEFAULT_tableFilterLabel,LYRA_DEFAULT_tableFilterPlaceholder,LYRA_DEFAULT_tableLoading,LYRA_DEFAULT_tableLoadingMore,LYRA_DEFAULT_tableRowLimit,LYRA_DEFAULT_tableRowTotal}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_loadMore,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_resizeValuePixels,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_SKELETON_ROWS=3,MAX_SKELETON_ROWS=20,DEFAULT_PAGE_SIZE=100,MAX_PAGE_SIZE=500,MAX_TABLE_COLLECTION_ENTRIES=1e4,TABLE_SCROLL_OVERFLOW_TOLERANCE_PX=1,DEFAULT_RESIZE_MIN_WIDTH_PX=48,MISSING_CELL_RENDERER_WARNING="lyra-table-missing-cell-renderer",MISSING_ACCESSIBLE_NAME_WARNING="lyra-table-missing-accessible-name",INERT_PRIORITY_COLUMN_CONFIG_WARNING="lyra-table-inert-priority-column-config";function frozenArray(values){const snapshot=[];try{for(const value of values)if(snapshot.push(value),snapshot.length>=MAX_TABLE_COLLECTION_ENTRIES)break}catch{}return Object.freeze(snapshot)}function keySet(values){const snapshot=new Set;try{for(const value of values){if(typeof value=="string"){if(value.trim().length===0)continue}else if(typeof value!="number")continue;if(snapshot.add(value),snapshot.size>=MAX_TABLE_COLLECTION_ENTRIES)break}}catch{}return snapshot}function readonlyKeySet(values){const snapshot=keySet(values);let facade;return facade={get size(){return snapshot.size},has:value=>snapshot.has(value),entries:()=>snapshot.entries(),keys:()=>snapshot.keys(),values:()=>snapshot.values(),[Symbol.iterator]:()=>snapshot[Symbol.iterator](),forEach(callback,thisArg){snapshot.forEach(value=>callback.call(thisArg,value,value,facade))}},Object.freeze(facade)}const keySetFacades=new WeakMap;function storedKeySetFacade(values){let facade=keySetFacades.get(values);return facade||(facade=readonlyKeySet(values),keySetFacades.set(values,facade)),facade}const COMPACT_EMPTY_SIZES=new Set(["2xs","xs","s"]),isCompactEmptySize=size=>COMPACT_EMPTY_SIZES.has(normalizeSize(size)),TABLE_LAYOUT=literalSetConverter(["auto","fixed"],"auto"),TABLE_PAGINATION_FORMAT=literalSetConverter(["standard","compact"],"compact"),INTERACTIVE_SELECTOR='button, a[href], input, select, textarea, summary, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"]), [role="button"], [role="checkbox"], [role="combobox"], [role="listbox"], [role="menu"], [role="menuitem"], [role="option"], [role="radio"], [role="separator"], [role="slider"], [role="spinbutton"], [role="switch"], [role="tab"], [role="textbox"]';function stickyDirection(sticky){if(sticky==="start"||sticky==="end")return sticky}const cellDeclarationVerdicts=new Map,CELL_DECLARATION_CACHE_LIMIT=1e3;function sanitizeCellStyle(cellStyle){const safe={};for(const[rawProperty,value]of Object.entries(cellStyle??{})){if(typeof value!="string")continue;const property2=normalizeStyleProperty(rawProperty.trim()),key=`${property2}\0${value}`;let verdict=cellDeclarationVerdicts.get(key);verdict===void 0&&(verdict=sanitizeCssDeclarationValue(property2,value)??"",cellDeclarationVerdicts.size>=CELL_DECLARATION_CACHE_LIMIT&&cellDeclarationVerdicts.clear(),cellDeclarationVerdicts.set(key,verdict)),verdict&&(safe[property2]=verdict)}return safe}function normalizeStyleProperty(property2){return property2.startsWith("--")?property2:property2.replace(/[A-Z]/g,"-$&").toLowerCase()}function normalizedEditTrigger(editTrigger){if(editTrigger==="always"||editTrigger==="double-click")return editTrigger}function encodeKey(key){return`${typeof key}:${key}`}function safeStringifyForFilter(row){const seen=new WeakSet;try{return JSON.stringify(row,(_key,value)=>{if(typeof value=="bigint")return value.toString();if(typeof value=="object"&&value!==null){if(seen.has(value))return"[Circular]";seen.add(value)}return value})??""}catch{return""}}function asElement(value){return typeof value!="object"||!("nodeType"in value)||value.nodeType!==1||!("matches"in value)?null:value}function eventInteractiveTarget(event,boundary){for(const value of event.composedPath()){if(value===boundary)break;const element=asElement(value);if(element!==null&&(element.matches("[data-table-interactive]")||element.matches(INTERACTIVE_SELECTOR)&&!element.matches("[data-row-key], th[data-col-key]")))return element}return null}class LyraTable extends LyraElement{constructor(){super(...arguments),this.assignedSources=new Map,this._columns=Object.freeze([]),this._rows=Object.freeze([]),this._rowsTruncated=!1,this._layout="auto",this.sortKey="",this.sortDir="asc",this.sortIndicators="active",this.sortMode="client",this.defaultSortDir="asc",this.hostAccessibleLabel=null,this.caption="",this.captionId=nextId("lr-table-caption"),this.selectionMode="none",this.expansionMode="none",this.scrollMode="self",this._selectedKeys=new Set,this.filterable=!1,this.filterText="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.loading=!1,this.loadingAppearance="spinner",this.skeletonRows=0,this.pageSize=DEFAULT_PAGE_SIZE,this.page=1,this.totalItems=-1,this.paginationMode="client",this.unknownTotal=!1,this.paginationWithSummary=!1,this.paginationFormat="compact",this.hasNext=!0,this._expandedKeys=new Set,this.hasMore=!1,this.loadingMore=!1,this.error=!1,this.errorDescription="",this.announce=!1,this.emptyDescription="",this.emptyColumnsDescription="",this.hasHiddenPriorityColumns=!1,this.priorityToggleAvailable=!1,this.persistReady=!1,this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.firstUpdateAnnouncementsReady=!1,this.activeColKey=null,this.activeRowKey=null,this.editingCell=null,this.focusedEditorCell=null,this.editorHadFocusBeforeUpdate=!1,this.rovingFocusSnapshot=null,this._resizedColumnWidths=new Map,this.resizeWriteGuard=new VetoWriteGuard,this.resizePointer=new ColumnResizePointerSession(event=>this.onResizePointerMove(event),event=>this.onResizePointerEnd(event),event=>this.onResizePointerEnd(event)),this.rowsByKey=new Map,this.columnsByKey=new Map,this.layoutFrame=null,this.observedHeaders=new Set,this.priorityTierNaturalWidth=new Map,this.priorityTierHiddenAllocation=new Map,this.priorityTierRevealAllocation=new Map,this.onResizePointerDown=event=>{const handle=event.currentTarget,key=handle.dataset.colKey,column=key?this.columnsByKey.get(key):void 0,header=handle.closest("th[data-col-key]");if(!key||!column||!header||!this.ownerDocument.defaultView)return;const replacedStartWidth=this.resizeState?.key===key?this.resizeState.startWidth:void 0;this.cancelResizeGesture();const minWidth=this.minimumResizeWidth(column);this.resizeState={key,pointerId:event.pointerId,startX:event.clientX,startWidth:replacedStartWidth??header.getBoundingClientRect().width,minWidth,maxWidth:this.maximumResizeWidth(column,minWidth),handle,previousWidth:this.resizedColumnWidths.get(key)},handle.toggleAttribute("data-resizing",!0),event.preventDefault(),event.stopPropagation(),this.resizePointer.start(event,handle)},this.onResizePointerMove=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;const width=columnResizePointerWidth(state2.startWidth,state2.startX,event.clientX,isRtl(this),state2.minWidth,state2.maxWidth);this.resizedColumnWidths.get(state2.key)!==width&&(this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(state2.key,width),this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width})))},this.onResizeKeyDown=event=>{const handle=event.currentTarget,key=handle.dataset.colKey,column=key?this.columnsByKey.get(key):void 0;if(!column)return;const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),currentWidth=this.currentResizeWidth(column,handle),requestedWidth=columnResizeKeyboardWidth(event,currentWidth,minWidth,maxWidth,isRtl(this));requestedWidth!==void 0&&(event.preventDefault(),event.stopPropagation(),this.resizeColumnTo(column,requestedWidth))},this.onResizePointerEnd=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;if(state2.handle.removeAttribute("data-resizing"),this.resizeState=void 0,this.resizePointer.stop(),event.type!=="pointerup"){const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):reverted.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted;return}const committedWidth=this.resizedColumnWidths.get(state2.key);if(committedWidth===void 0||committedWidth===state2.previousWidth)return;this.resizeWriteGuard.open();const request=this.emit("lr-column-resize-request",Object.freeze({columnKey:state2.key,width:committedWidth}),{cancelable:!0});if(!this.resizeWriteGuard.touched){if(request.defaultPrevented){this.rollbackResizePreview(state2);return}this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width:committedWidth}))}},this.scheduleLayoutSync=()=>{if(this.layoutFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{this.layoutFrame===frame&&(this.layoutFrame=null,!(!this.isConnected||this.ownerDocument.defaultView!==owner)&&(this.syncAutoScrollMode(),this.recomputeHiddenPriorityColumns(),this.applyStickyOffsets(),this.syncResizeHandleValues()))}),this.layoutFrame=frame},this.cachedCanonicalRowEntries=null,this.canonicalRowEntriesInputs=null,this.cachedMatchingEntries=null,this.matchingEntriesInputs=null,this.cachedSortedEntries=null,this.sortedEntriesInputs=null,this.onFilterInput=event=>{event.stopPropagation();const input=event.currentTarget;this.filterText=input.value,this.emit("lr-filter-change",Object.freeze({filterText:this.filterText}))},this.onClearFilter=()=>{this.filterText!==""&&(this.filterText="",this.emit("lr-filter-change",Object.freeze({filterText:""})),this.renderRoot.querySelector('[part="filter"]')?.focus())},this.stopOwnedEvent=event=>{event.stopPropagation()},this.onNativeFocus=event=>{event.stopPropagation(),relayNativeEvent(this,event)},this.onNativeBlur=event=>{event.stopPropagation(),relayNativeEvent(this,event)},this.onPaginationChange=event=>{event.stopPropagation();const{page}=event.detail;this.paginationMode==="client"&&(this.page=page),this.emit("lr-page-change",Object.freeze({page}))},this.onTableFocusIn=event=>{const target=event.target,cell=target?.closest?.("td[data-col-key]"),row=target?.closest?.("[data-row-key]"),columnKey=cell?.dataset.colKey,rowKey=row?.dataset.rowKey;this.focusedEditorCell=target?.getAttribute("part")==="cell-editor"&&columnKey!==void 0&&rowKey!==void 0&&normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="always"?{rowKey,columnKey}:null},this.onEditorKeyDown=(event,rowKey,columnKey)=>{event.stopPropagation();const alwaysOn=normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="always";event.key==="Enter"?(event.preventDefault(),this.commitEdit(event,rowKey,columnKey)):event.key==="Escape"&&!alwaysOn&&(event.preventDefault(),this.editingCell=null)},this.onTableDoubleClick=event=>{const target=event.target,table=event.currentTarget;if(eventInteractiveTarget(event,table))return;const cell=target.closest('[part="cell"][data-col-key]'),row=target.closest("[data-row-key]");cell&&row?.dataset.rowKey&&cell.dataset.colKey&&this.startEditing(row.dataset.rowKey,cell.dataset.colKey)},this.toggleColumns=()=>{this.priorityColumnsVisible=!this.priorityColumnsVisible,this.emit("lr-priority-columns-visibility-change",Object.freeze({visible:this.priorityColumnsVisible}))},this.onTableClick=e=>{const target=e.target,table=e.currentTarget;if(eventInteractiveTarget(e,table))return;const th=target.closest("th[data-col-key]");if(th)return this.activateColumn(th.dataset.colKey);const tr=target.closest("[data-row-key]");tr&&this.activateRow(tr.dataset.rowKey)},this.onTableKeyDown=e=>{const target=e.target,table=e.currentTarget;if(eventInteractiveTarget(e,table)||(e.altKey||e.metaKey)&&e.key.startsWith("Arrow"))return;const th=target.closest("th[data-col-key]");if(th)return this.onHeaderKeyDown(e,th);const tr=target.closest("[data-row-key]");tr&&this.onRowKeyDown(e,tr)}}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,loadMore:LYRA_DEFAULT_loadMore,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,resizeColumn:LYRA_DEFAULT_resizeColumn,resizeValuePixels:LYRA_DEFAULT_resizeValuePixels,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showAllColumns:LYRA_DEFAULT_showAllColumns,showFewerColumns:LYRA_DEFAULT_showFewerColumns,tableEditCell:LYRA_DEFAULT_tableEditCell,tableFilterLabel:LYRA_DEFAULT_tableFilterLabel,tableFilterPlaceholder:LYRA_DEFAULT_tableFilterPlaceholder,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,tableLoading:LYRA_DEFAULT_tableLoading,tableLoadingMore:LYRA_DEFAULT_tableLoadingMore,tableRowLimit:LYRA_DEFAULT_tableRowLimit,tableRowTotal:LYRA_DEFAULT_tableRowTotal}}static{this.styles=[LyraElement.styles,styles,srOnly]}isRebind(name,value,current){return value===current||this.assignedSources.has(name)&&this.assignedSources.get(name)===value?!0:(this.assignedSources.set(name,value),!1)}get columns(){return this._columns}set columns(value){if(this.isRebind("columns",value,this._columns))return;const previous=this._columns,columns=[],seen=new Set;let length=0;try{if(Array.isArray(value)){const descriptor=Object.getOwnPropertyDescriptor(value,"length"),sourceLength=descriptor&&"value"in descriptor?descriptor.value:0;typeof sourceLength=="number"&&Number.isSafeInteger(sourceLength)&&sourceLength>=0&&(length=Math.min(sourceLength,MAX_TABLE_COLLECTION_ENTRIES))}}catch{length=0}for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;const column=descriptor.value;try{const key=column?.key;if(typeof key!="string"||key.trim().length===0||seen.has(key))continue;seen.add(key),columns.push(column)}catch{}}this._columns=frozenArray(columns),this.requestUpdate("columns",previous)}get rows(){return this._rows}set rows(value){if(this.isRebind("rows",value,this._rows))return;const previous=this._rows;this._rows=frozenArray(Array.isArray(value)?value:[]),this._rowsTruncated=Array.isArray(value)&&value.length>this._rows.length,this.requestUpdate("rows",previous)}get rowsTruncated(){return this._rowsTruncated}get layout(){return this._layout}set layout(next){const normalized=TABLE_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}get selectedRowKeys(){return storedKeySetFacade(this._selectedKeys)}set selectedRowKeys(value){if(this.isRebind("selectedRowKeys",value,storedKeySetFacade(this._selectedKeys)))return;const previous=this._selectedKeys;this._selectedKeys=keySet(value??[]),this.requestUpdate("selectedRowKeys",previous)}get expandedRowKeys(){return storedKeySetFacade(this._expandedKeys)}set expandedRowKeys(value){if(this.isRebind("expandedRowKeys",value,storedKeySetFacade(this._expandedKeys)))return;const previous=this._expandedKeys;this._expandedKeys=keySet(value??[]),this.requestUpdate("expandedRowKeys",previous)}asKeySet(keys){return keys}asKeyList(keys){return keys}get emptySize(){return this._emptySize}set emptySize(value){const previous=this._emptySize,next=optionalSizeConverter.normalize(value);next!==previous&&(this._emptySize=next,this.requestUpdate("emptySize",previous))}get priorityColumnsToggleAvailable(){return this.priorityToggleAvailable}static{definePersistedProperty(this.prototype,"priorityColumnsVisible",{initial:!1,attribute:"priority-columns-visible",type:Boolean,reflect:!0})}get storageFullKey(){return this.storageKey?`lr-table:${this.storageKey}`:void 0}get resizedColumnWidths(){return this._resizedColumnWidths}set resizedColumnWidths(value){const previous=this._resizedColumnWidths;this._resizedColumnWidths=value,markVetoGuardWrite(this.resizeWriteGuard),this.requestUpdate("resizedColumnWidths",previous)}parsePixelLength(value){if(!value)return;const trimmed=value.trim();if(!trimmed.endsWith("px"))return;const parsed=Number.parseFloat(trimmed);return Number.isFinite(parsed)?parsed:void 0}minimumResizeWidth(column){const explicit=this.parsePixelLength(column.minWidth);if(explicit!==void 0)return Math.max(0,explicit);const cached=this.themedResizeMinWidth;if(cached&&cached.document===this.ownerDocument)return cached.width;const width=this.resolveThemedResizeMinWidth();return this.themedResizeMinWidth={document:this.ownerDocument,width},width}resolveThemedResizeMinWidth(){const hostStyle=this.ownerDocument.defaultView?.getComputedStyle(this),themed=hostStyle?.getPropertyValue("--lr-table-resize-min-width").trim()||hostStyle?.getPropertyValue("--_lr-table-resize-min-width-default").trim()||"",resolved=resolveCssTokenLength(themed,{host:this});return resolved===void 0?DEFAULT_RESIZE_MIN_WIDTH_PX:Math.max(0,resolved)}maximumResizeWidth(column,minWidth){const explicit=this.parsePixelLength(column.maxWidth);return explicit===void 0?Number.POSITIVE_INFINITY:Math.max(minWidth,explicit)}currentResizeWidth(column,handle){const resized=this.resizedColumnWidths.get(column.key);if(resized!==void 0)return resized;const explicit=this.parsePixelLength(column.width);if(explicit!==void 0)return explicit;const rendered=handle?.closest("th[data-col-key]")?.getBoundingClientRect().width;return rendered&&rendered>0?rendered:this.minimumResizeWidth(column)}resizeValueText(width){return this.localize("resizeValuePixels",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(width))})}resizeColumnTo(column,requestedWidth){const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),width=columnResizeWidth(requestedWidth,minWidth,maxWidth);this.resizedColumnWidths.get(column.key)!==width&&requestThenCommit({requestDetail:Object.freeze({columnKey:column.key,width}),emitRequest:(detail,init)=>this.emit("lr-column-resize-request",detail,init),guard:this.resizeWriteGuard,commit:()=>{this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(column.key,width),this.emit("lr-column-resize",Object.freeze({columnKey:column.key,width})),markVetoGuardWrite(this.resizeWriteGuard)}})}renderedColumnWidth(column){const resized=this.resizedColumnWidths.get(column.key);return resized===void 0?sanitizeCssLength(column.width,"height"):`${resized}px`}renderResizeHandle(column){if(!column.resizable)return nothing;const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),width=this.currentResizeWidth(column),aria=columnResizeAriaValues(width,minWidth,maxWidth);return html`<span
|
|
1
|
+
import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/native-event-relay.js";import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{sanitizeCssDeclarationValue,sanitizeCssLength}from"../../../internal/safe-css.js";import{LyraElement}from"../../../internal/lyra-element.js";import{isRtl}from"../../../internal/rtl.js";import{srOnly,nextId}from"../../../internal/a11y.js";import{finiteCount,finiteInteger,finiteRatio}from"../../../internal/numbers.js";import{trueDefaultBooleanConverter}from"../../../internal/converters.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{getCollator,getNumberFormat}from"../../../internal/intl-cache.js";import{CollectionSourceTracker}from"../../../internal/collection-source-tracker.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{definePersistedProperty,isPersistedPropertyExplicitlySet}from"../../../internal/persisted-restore.js";import{styles}from"./table.styles.js";import{chevronIcon,closeIcon,sortIcon}from"../../../internal/icons.js";import{minMax}from"../../../internal/numbers.js";import{literalSetConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{normalizeSize,optionalSizeConverter}from"../../../internal/variants.js";import{markVetoGuardWrite,VetoWriteGuard}from"../../../internal/veto-write-guard.js";import{requestThenCommit}from"../../../internal/request-commit.js";import{ColumnResizePointerSession,columnResizeAriaValues,columnResizeKeyboardWidth,columnResizePointerWidth,columnResizeWidth}from"../../../internal/column-resize.js";import{renderDataState}from"../../../internal/data-state-renderer.js";import{LYRA_DEFAULT_noColumns,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_showFewerColumns,LYRA_DEFAULT_tableEditCell,LYRA_DEFAULT_tableFilterLabel,LYRA_DEFAULT_tableFilterPlaceholder,LYRA_DEFAULT_tableLoading,LYRA_DEFAULT_tableLoadingMore,LYRA_DEFAULT_tableRowLimit,LYRA_DEFAULT_tableRowTotal}from"../../../internal/default-strings/data.generated.js";import{LYRA_DEFAULT_clear,LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_loadMore,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noData,LYRA_DEFAULT_noMatches,LYRA_DEFAULT_open,LYRA_DEFAULT_resizeValuePixels,LYRA_DEFAULT_retry,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_tableLoadFailed}from"../../../internal/default-strings/shared.generated.js";const DEFAULT_SKELETON_ROWS=3,MAX_SKELETON_ROWS=20,DEFAULT_PAGE_SIZE=100,MAX_PAGE_SIZE=500,MAX_TABLE_COLLECTION_ENTRIES=1e4,TABLE_SCROLL_OVERFLOW_TOLERANCE_PX=1,DEFAULT_RESIZE_MIN_WIDTH_PX=48,MISSING_CELL_RENDERER_WARNING="lyra-table-missing-cell-renderer",MISSING_ACCESSIBLE_NAME_WARNING="lyra-table-missing-accessible-name",INERT_PRIORITY_COLUMN_CONFIG_WARNING="lyra-table-inert-priority-column-config";function frozenArray(values){const snapshot=[];try{for(const value of values)if(snapshot.push(value),snapshot.length>=MAX_TABLE_COLLECTION_ENTRIES)break}catch{}return Object.freeze(snapshot)}function keySet(values){const snapshot=new Set;try{for(const value of values){if(typeof value=="string"){if(value.trim().length===0)continue}else if(typeof value!="number")continue;if(snapshot.add(value),snapshot.size>=MAX_TABLE_COLLECTION_ENTRIES)break}}catch{}return snapshot}function readonlyKeySet(values){const snapshot=keySet(values);let facade;return facade={get size(){return snapshot.size},has:value=>snapshot.has(value),entries:()=>snapshot.entries(),keys:()=>snapshot.keys(),values:()=>snapshot.values(),[Symbol.iterator]:()=>snapshot[Symbol.iterator](),forEach(callback,thisArg){snapshot.forEach(value=>callback.call(thisArg,value,value,facade))}},Object.freeze(facade)}const keySetFacades=new WeakMap;function storedKeySetFacade(values){let facade=keySetFacades.get(values);return facade||(facade=readonlyKeySet(values),keySetFacades.set(values,facade)),facade}const COMPACT_EMPTY_SIZES=new Set(["2xs","xs","s"]),isCompactEmptySize=size=>COMPACT_EMPTY_SIZES.has(normalizeSize(size)),TABLE_LAYOUT=literalSetConverter(["auto","fixed"],"auto"),TABLE_PAGINATION_FORMAT=literalSetConverter(["standard","compact"],"compact"),INTERACTIVE_SELECTOR='button, a[href], input, select, textarea, summary, audio[controls], video[controls], [contenteditable]:not([contenteditable="false"]), [tabindex]:not([tabindex="-1"]), [role="button"], [role="checkbox"], [role="combobox"], [role="listbox"], [role="menu"], [role="menuitem"], [role="option"], [role="radio"], [role="separator"], [role="slider"], [role="spinbutton"], [role="switch"], [role="tab"], [role="textbox"]';function stickyDirection(sticky){if(sticky==="start"||sticky==="end")return sticky}const cellDeclarationVerdicts=new Map,CELL_DECLARATION_CACHE_LIMIT=1e3;function sanitizeCellStyle(cellStyle){const safe={};for(const[rawProperty,value]of Object.entries(cellStyle??{})){if(typeof value!="string")continue;const property2=normalizeStyleProperty(rawProperty.trim()),key=`${property2}\0${value}`;let verdict=cellDeclarationVerdicts.get(key);verdict===void 0&&(verdict=sanitizeCssDeclarationValue(property2,value)??"",cellDeclarationVerdicts.size>=CELL_DECLARATION_CACHE_LIMIT&&cellDeclarationVerdicts.clear(),cellDeclarationVerdicts.set(key,verdict)),verdict&&(safe[property2]=verdict)}return safe}function normalizeStyleProperty(property2){return property2.startsWith("--")?property2:property2.replace(/[A-Z]/g,"-$&").toLowerCase()}function normalizedEditTrigger(editTrigger){if(editTrigger==="always"||editTrigger==="double-click")return editTrigger}function encodeKey(key){return`${typeof key}:${key}`}function createFilterStringifier(){let first,seen;const replace=(_key,value)=>{if(typeof value=="bigint")return value.toString();if(typeof value=="object"&&value!==null)if(first===void 0)first=value;else{if(value===first||(seen??=new Set,seen.has(value)))return"[Circular]";seen.add(value)}return value};return row=>{try{return JSON.stringify(row,replace)??""}catch{return""}finally{first=void 0,seen?.clear()}}}function asElement(value){return typeof value!="object"||!("nodeType"in value)||value.nodeType!==1||!("matches"in value)?null:value}function eventInteractiveTarget(event,boundary){for(const value of event.composedPath()){if(value===boundary)break;const element=asElement(value);if(element!==null&&(element.matches("[data-table-interactive]")||element.matches(INTERACTIVE_SELECTOR)&&!element.matches("[data-row-key], th[data-col-key]")))return element}return null}class LyraTable extends LyraElement{constructor(){super(...arguments),this.assignedSources=new CollectionSourceTracker,this._columns=Object.freeze([]),this._rows=Object.freeze([]),this._rowsTruncated=!1,this._layout="auto",this.sortKey="",this.sortDir="asc",this.sortIndicators="active",this.sortMode="client",this.defaultSortDir="asc",this.hostAccessibleLabel=null,this.caption="",this.captionId=nextId("lr-table-caption"),this.selectionMode="none",this.expansionMode="none",this.scrollMode="self",this._selectedKeys=new Set,this.filterable=!1,this.filterText="",this.spellcheck=!0,this.autocapitalize="",this.autoCorrect="",this.loading=!1,this.loadingAppearance="spinner",this.skeletonRows=0,this.pageSize=DEFAULT_PAGE_SIZE,this.page=1,this.totalItems=-1,this.paginationMode="client",this.unknownTotal=!1,this.paginationWithSummary=!1,this.paginationFormat="compact",this.hasNext=!0,this._expandedKeys=new Set,this.hasMore=!1,this.loadingMore=!1,this.error=!1,this.errorDescription="",this.announce=!1,this.emptyDescription="",this.emptyColumnsDescription="",this.hasHiddenPriorityColumns=!1,this.priorityToggleAvailable=!1,this.persistReady=!1,this.announcements=new AnnouncementSinkController(this,{eager:["polite","assertive"]}),this.firstUpdateAnnouncementsReady=!1,this.activeColKey=null,this.activeRowKey=null,this.editingCell=null,this.focusedEditorCell=null,this.editorHadFocusBeforeUpdate=!1,this.rovingFocusSnapshot=null,this._resizedColumnWidths=new Map,this.resizeWriteGuard=new VetoWriteGuard,this.resizePointer=new ColumnResizePointerSession(event=>this.onResizePointerMove(event),event=>this.onResizePointerEnd(event),event=>this.onResizePointerEnd(event)),this.rowsByKey=new Map,this.columnsByKey=new Map,this.layoutFrame=null,this.observedHeaders=new Set,this.priorityTierNaturalWidth=new Map,this.priorityTierHiddenAllocation=new Map,this.priorityTierRevealAllocation=new Map,this.onResizePointerDown=event=>{const handle=event.currentTarget,key=handle.dataset.colKey,column=key?this.columnsByKey.get(key):void 0,header=handle.closest("th[data-col-key]");if(!key||!column||!header||!this.ownerDocument.defaultView)return;const replacedStartWidth=this.resizeState?.key===key?this.resizeState.startWidth:void 0;this.cancelResizeGesture();const minWidth=this.minimumResizeWidth(column);this.resizeState={key,pointerId:event.pointerId,startX:event.clientX,startWidth:replacedStartWidth??header.getBoundingClientRect().width,minWidth,maxWidth:this.maximumResizeWidth(column,minWidth),handle,previousWidth:this.resizedColumnWidths.get(key)},handle.toggleAttribute("data-resizing",!0),event.preventDefault(),event.stopPropagation(),this.resizePointer.start(event,handle)},this.onResizePointerMove=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;const width=columnResizePointerWidth(state2.startWidth,state2.startX,event.clientX,isRtl(this),state2.minWidth,state2.maxWidth);this.resizedColumnWidths.get(state2.key)!==width&&(this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(state2.key,width),this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width})))},this.onResizeKeyDown=event=>{const handle=event.currentTarget,key=handle.dataset.colKey,column=key?this.columnsByKey.get(key):void 0;if(!column)return;const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),currentWidth=this.currentResizeWidth(column,handle),requestedWidth=columnResizeKeyboardWidth(event,currentWidth,minWidth,maxWidth,isRtl(this));requestedWidth!==void 0&&(event.preventDefault(),event.stopPropagation(),this.resizeColumnTo(column,requestedWidth))},this.onResizePointerEnd=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;if(state2.handle.removeAttribute("data-resizing"),this.resizeState=void 0,this.resizePointer.stop(),event.type!=="pointerup"){const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):reverted.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted;return}const committedWidth=this.resizedColumnWidths.get(state2.key);if(committedWidth===void 0||committedWidth===state2.previousWidth)return;this.resizeWriteGuard.open();const request=this.emit("lr-column-resize-request",Object.freeze({columnKey:state2.key,width:committedWidth}),{cancelable:!0});if(!this.resizeWriteGuard.touched){if(request.defaultPrevented){this.rollbackResizePreview(state2);return}this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width:committedWidth}))}},this.scheduleLayoutSync=()=>{if(this.layoutFrame)return;const owner=this.ownerDocument.defaultView;if(!owner)return;const frame={owner,handle:0};frame.handle=owner.requestAnimationFrame(()=>{this.layoutFrame===frame&&(this.layoutFrame=null,!(!this.isConnected||this.ownerDocument.defaultView!==owner)&&(this.syncAutoScrollMode(),this.recomputeHiddenPriorityColumns(),this.applyStickyOffsets(),this.syncResizeHandleValues()))}),this.layoutFrame=frame},this.cachedCanonicalRowEntries=null,this.canonicalRowEntriesInputs=null,this.cachedMatchingEntries=null,this.matchingEntriesInputs=null,this.cachedSortedEntries=null,this.sortedEntriesInputs=null,this.onFilterInput=event=>{event.stopPropagation();const input=event.currentTarget;this.filterText=input.value,this.emit("lr-filter-change",Object.freeze({filterText:this.filterText}))},this.onClearFilter=()=>{this.filterText!==""&&(this.filterText="",this.emit("lr-filter-change",Object.freeze({filterText:""})),this.renderRoot.querySelector('[part="filter"]')?.focus())},this.stopOwnedEvent=event=>{event.stopPropagation()},this.onNativeFocus=event=>{event.stopPropagation(),relayNativeEvent(this,event)},this.onNativeBlur=event=>{event.stopPropagation(),relayNativeEvent(this,event)},this.onPaginationChange=event=>{event.stopPropagation();const{page}=event.detail;this.paginationMode==="client"&&(this.page=page),this.emit("lr-page-change",Object.freeze({page}))},this.onTableFocusIn=event=>{const target=event.target,cell=target?.closest?.("td[data-col-key]"),row=target?.closest?.("[data-row-key]"),columnKey=cell?.dataset.colKey,rowKey=row?.dataset.rowKey;this.focusedEditorCell=target?.getAttribute("part")==="cell-editor"&&columnKey!==void 0&&rowKey!==void 0&&normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="always"?{rowKey,columnKey}:null},this.onEditorKeyDown=(event,rowKey,columnKey)=>{event.stopPropagation();const alwaysOn=normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="always";event.key==="Enter"?(event.preventDefault(),this.commitEdit(event,rowKey,columnKey)):event.key==="Escape"&&!alwaysOn&&(event.preventDefault(),this.editingCell=null)},this.onTableDoubleClick=event=>{const target=event.target,table=event.currentTarget;if(eventInteractiveTarget(event,table))return;const cell=target.closest('[part="cell"][data-col-key]'),row=target.closest("[data-row-key]");cell&&row?.dataset.rowKey&&cell.dataset.colKey&&this.startEditing(row.dataset.rowKey,cell.dataset.colKey)},this.toggleColumns=()=>{this.priorityColumnsVisible=!this.priorityColumnsVisible,this.emit("lr-priority-columns-visibility-change",Object.freeze({visible:this.priorityColumnsVisible}))},this.onTableClick=e=>{const target=e.target,table=e.currentTarget;if(eventInteractiveTarget(e,table))return;const th=target.closest("th[data-col-key]");if(th)return this.activateColumn(th.dataset.colKey);const tr=target.closest("[data-row-key]");tr&&this.activateRow(tr.dataset.rowKey)},this.onTableKeyDown=e=>{const target=e.target,table=e.currentTarget;if(eventInteractiveTarget(e,table)||(e.altKey||e.metaKey)&&e.key.startsWith("Arrow"))return;const th=target.closest("th[data-col-key]");if(th)return this.onHeaderKeyDown(e,th);const tr=target.closest("[data-row-key]");tr&&this.onRowKeyDown(e,tr)}}static{this.defaultStrings={...super.defaultStrings,clear:LYRA_DEFAULT_clear,collapse:LYRA_DEFAULT_collapse,details:LYRA_DEFAULT_details,expand:LYRA_DEFAULT_expand,loadMore:LYRA_DEFAULT_loadMore,loading:LYRA_DEFAULT_loading,map:LYRA_DEFAULT_map,navigation:LYRA_DEFAULT_navigation,noColumns:LYRA_DEFAULT_noColumns,noData:LYRA_DEFAULT_noData,noMatches:LYRA_DEFAULT_noMatches,open:LYRA_DEFAULT_open,resizeColumn:LYRA_DEFAULT_resizeColumn,resizeValuePixels:LYRA_DEFAULT_resizeValuePixels,retry:LYRA_DEFAULT_retry,search:LYRA_DEFAULT_search,select:LYRA_DEFAULT_select,showAllColumns:LYRA_DEFAULT_showAllColumns,showFewerColumns:LYRA_DEFAULT_showFewerColumns,tableEditCell:LYRA_DEFAULT_tableEditCell,tableFilterLabel:LYRA_DEFAULT_tableFilterLabel,tableFilterPlaceholder:LYRA_DEFAULT_tableFilterPlaceholder,tableLoadFailed:LYRA_DEFAULT_tableLoadFailed,tableLoading:LYRA_DEFAULT_tableLoading,tableLoadingMore:LYRA_DEFAULT_tableLoadingMore,tableRowLimit:LYRA_DEFAULT_tableRowLimit,tableRowTotal:LYRA_DEFAULT_tableRowTotal}}static{this.styles=[LyraElement.styles,styles,srOnly]}isRebind(name,value,current){return this.assignedSources.isRebind(name,value,current)}get columns(){return this._columns}set columns(value){if(this.isRebind("columns",value,this._columns))return;const previous=this._columns,columns=[],seen=new Set;let length=0;try{if(Array.isArray(value)){const descriptor=Object.getOwnPropertyDescriptor(value,"length"),sourceLength=descriptor&&"value"in descriptor?descriptor.value:0;typeof sourceLength=="number"&&Number.isSafeInteger(sourceLength)&&sourceLength>=0&&(length=Math.min(sourceLength,MAX_TABLE_COLLECTION_ENTRIES))}}catch{length=0}for(let index=0;index<length;index+=1){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(value,String(index))}catch{continue}if(!descriptor||!("value"in descriptor))continue;const column=descriptor.value;try{const key=column?.key;if(typeof key!="string"||key.trim().length===0||seen.has(key))continue;seen.add(key),columns.push(column)}catch{}}this._columns=frozenArray(columns),this.requestUpdate("columns",previous)}get rows(){return this._rows}set rows(value){if(this.isRebind("rows",value,this._rows))return;const previous=this._rows;this._rows=frozenArray(Array.isArray(value)?value:[]),this._rowsTruncated=Array.isArray(value)&&value.length>this._rows.length,this.requestUpdate("rows",previous)}get rowsTruncated(){return this._rowsTruncated}get layout(){return this._layout}set layout(next){const normalized=TABLE_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}get selectedRowKeys(){return storedKeySetFacade(this._selectedKeys)}set selectedRowKeys(value){if(this.isRebind("selectedRowKeys",value,storedKeySetFacade(this._selectedKeys)))return;const previous=this._selectedKeys;this._selectedKeys=keySet(value??[]),this.requestUpdate("selectedRowKeys",previous)}get expandedRowKeys(){return storedKeySetFacade(this._expandedKeys)}set expandedRowKeys(value){if(this.isRebind("expandedRowKeys",value,storedKeySetFacade(this._expandedKeys)))return;const previous=this._expandedKeys;this._expandedKeys=keySet(value??[]),this.requestUpdate("expandedRowKeys",previous)}asKeySet(keys){return keys}asKeyList(keys){return keys}get emptySize(){return this._emptySize}set emptySize(value){const previous=this._emptySize,next=optionalSizeConverter.normalize(value);next!==previous&&(this._emptySize=next,this.requestUpdate("emptySize",previous))}get priorityColumnsToggleAvailable(){return this.priorityToggleAvailable}static{definePersistedProperty(this.prototype,"priorityColumnsVisible",{initial:!1,attribute:"priority-columns-visible",type:Boolean,reflect:!0})}get storageFullKey(){return this.storageKey?`lr-table:${this.storageKey}`:void 0}get resizedColumnWidths(){return this._resizedColumnWidths}set resizedColumnWidths(value){const previous=this._resizedColumnWidths;this._resizedColumnWidths=value,markVetoGuardWrite(this.resizeWriteGuard),this.requestUpdate("resizedColumnWidths",previous)}parsePixelLength(value){if(!value)return;const trimmed=value.trim();if(!trimmed.endsWith("px"))return;const parsed=Number.parseFloat(trimmed);return Number.isFinite(parsed)?parsed:void 0}minimumResizeWidth(column){const explicit=this.parsePixelLength(column.minWidth);if(explicit!==void 0)return Math.max(0,explicit);const cached=this.themedResizeMinWidth;if(cached&&cached.document===this.ownerDocument)return cached.width;const width=this.resolveThemedResizeMinWidth();return this.themedResizeMinWidth={document:this.ownerDocument,width},width}resolveThemedResizeMinWidth(){const hostStyle=this.ownerDocument.defaultView?.getComputedStyle(this),themed=hostStyle?.getPropertyValue("--lr-table-resize-min-width").trim()||hostStyle?.getPropertyValue("--_lr-table-resize-min-width-default").trim()||"",resolved=resolveCssTokenLength(themed,{host:this});return resolved===void 0?DEFAULT_RESIZE_MIN_WIDTH_PX:Math.max(0,resolved)}maximumResizeWidth(column,minWidth){const explicit=this.parsePixelLength(column.maxWidth);return explicit===void 0?Number.POSITIVE_INFINITY:Math.max(minWidth,explicit)}currentResizeWidth(column,handle){const resized=this.resizedColumnWidths.get(column.key);if(resized!==void 0)return resized;const explicit=this.parsePixelLength(column.width);if(explicit!==void 0)return explicit;const rendered=handle?.closest("th[data-col-key]")?.getBoundingClientRect().width;return rendered&&rendered>0?rendered:this.minimumResizeWidth(column)}resizeValueText(width){return this.localize("resizeValuePixels",void 0,{value:getNumberFormat(this.effectiveLocale).format(Math.round(width))})}resizeColumnTo(column,requestedWidth){const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),width=columnResizeWidth(requestedWidth,minWidth,maxWidth);this.resizedColumnWidths.get(column.key)!==width&&requestThenCommit({requestDetail:Object.freeze({columnKey:column.key,width}),emitRequest:(detail,init)=>this.emit("lr-column-resize-request",detail,init),guard:this.resizeWriteGuard,commit:()=>{this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(column.key,width),this.emit("lr-column-resize",Object.freeze({columnKey:column.key,width})),markVetoGuardWrite(this.resizeWriteGuard)}})}renderedColumnWidth(column){const resized=this.resizedColumnWidths.get(column.key);return resized===void 0?sanitizeCssLength(column.width,"height"):`${resized}px`}renderResizeHandle(column){if(!column.resizable)return nothing;const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),width=this.currentResizeWidth(column),aria=columnResizeAriaValues(width,minWidth,maxWidth);return html`<span
|
|
2
2
|
part="resize-handle"
|
|
3
3
|
data-col-key=${column.key}
|
|
4
4
|
role="separator"
|
|
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{relayNativeEvent}from"../../../internal/nat
|
|
|
11
11
|
aria-valuemax=${aria.max}
|
|
12
12
|
@pointerdown=${this.onResizePointerDown}
|
|
13
13
|
@keydown=${this.onResizeKeyDown}
|
|
14
|
-
></span>`}syncResizeHandleValues(){for(const handle of this.renderRoot.querySelectorAll('[part="resize-handle"]')){const key=handle.dataset.colKey;if(!key)continue;const column=this.columnsByKey.get(key);if(!column||this.resizedColumnWidths.has(key)||this.parsePixelLength(column.width)!==void 0)continue;const rendered=handle.closest("th[data-col-key]")?.getBoundingClientRect().width;if(rendered&&rendered>0){const width=Math.round(rendered);handle.setAttribute("aria-valuenow",String(width)),handle.setAttribute("aria-valuetext",this.resizeValueText(width))}}}rollbackResizePreview(state2){const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):reverted.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted}cancelResizeGesture(){const state2=this.resizeState;this.resizeState=void 0,this.resizePointer.stop(),state2&&(state2.handle.removeAttribute("data-resizing"),this.rollbackResizePreview(state2))}firstUpdated(changed){super.firstUpdated(changed),!this.hasAttribute("aria-label")&&!this.caption&&devWarnOnce(MISSING_ACCESSIBLE_NAME_WARNING,"<lr-table> has no accessible name: set a host `aria-label` or `caption` so assistive technology can identify the grid.")}connectedCallback(){super.connectedCallback();const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;let observer;ResizeObserverCtor&&(observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.resizeObserver!==observer||this.scheduleLayoutSync()})),this.resizeObserver=observer;const base=this.renderRoot?.querySelector('[part="base"]');base&&(this.observeBase(base),this.observeTable(this.renderRoot.querySelector('[part="table"]')??void 0),this.observeHeaders())}disconnectedCallback(){super.disconnectedCallback(),this.cancelResizeGesture(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0;const frame=this.layoutFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.layoutFrame=null,this.observedBase=void 0,this.observedTable=void 0,this.observedHeaders.clear()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}localizedOverride(key,override){return override??this.localize(key)}loadingText(){return this.localizedOverride("tableLoading",this.loadingLabel)}loadingMoreText(){return this.localizedOverride("tableLoadingMore",this.loadingMoreLabel)}onLoadMore(){this.loadingMore||this.emit("lr-load-more")}observeBase(base){this.observedBase!==base&&(this.observedBase&&this.resizeObserver?.unobserve(this.observedBase),this.resizeObserver?.observe(base),this.observedBase=base)}observeTable(table){this.observedTable!==table&&(this.observedTable&&this.resizeObserver?.unobserve(this.observedTable),table&&this.resizeObserver?.observe(table),this.observedTable=table)}syncAutoScrollMode(){const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const overflows=(this.scrollMode==="auto"||this.scrollMode==="page")&&base.scrollWidth-base.clientWidth>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX;base.toggleAttribute("data-scroll-overflow",overflows)}observeHeaders(){const headers=new Set(this.columns.some(column=>column.sticky||column.resizable)?this.renderRoot.querySelectorAll("th[data-col-key]"):[]);for(const header of this.observedHeaders)headers.has(header)||(this.resizeObserver?.unobserve(header),this.observedHeaders.delete(header));for(const header of headers)this.observedHeaders.has(header)||(this.observedHeaders.add(header),this.resizeObserver?.observe(header))}priorityTierHeaders(tier){return[...this.renderRoot.querySelectorAll(`th[data-priority="${tier}"]`)]}recomputeHiddenPriorityColumns(){const hasLowColumn=this.columns.some(col=>col.priority==="low"),hasMediumColumn=this.columns.some(col=>col.priority==="medium"),base=this.renderRoot.querySelector('[part="base"]');if(!hasLowColumn&&!hasMediumColumn){this.priorityTierNaturalWidth.clear(),this.alwaysVisibleNaturalWidth=void 0,this.priorityTierHiddenAllocation.clear(),this.priorityTierRevealAllocation.clear(),base?.removeAttribute("data-hide-priority-low"),base?.removeAttribute("data-hide-priority-medium"),this.rehomeFocusedColumn(),this.priorityToggleAvailable&&(this.priorityToggleAvailable=!1),this.hasHiddenPriorityColumns&&(this.hasHiddenPriorityColumns=!1);return}if(!base||base.clientWidth<=0){this.rehomeFocusedColumn();return}const genuineOverflow=base.scrollWidth-base.clientWidth>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX,lowHeaders=hasLowColumn?this.priorityTierHeaders("low"):[],mediumHeaders=hasMediumColumn?this.priorityTierHeaders("medium"):[],refreshNaturalWidth=(tier,headers)=>{if(headers.length===0)return!1;const currentlyHidden=headers.every(header=>header.offsetParent===null);if(!currentlyHidden&&genuineOverflow){const width=headers.reduce((sum,header)=>sum+header.getBoundingClientRect().width,0);width>0&&this.priorityTierNaturalWidth.set(tier,width)}return currentlyHidden},lowActuallyHidden=refreshNaturalWidth("low",lowHeaders),mediumActuallyHidden=refreshNaturalWidth("medium",mediumHeaders);if(genuineOverflow){const alwaysWidth=[...this.renderRoot.querySelectorAll('[part="head"] > tr > th')].filter(header=>!header.hasAttribute("data-priority")).reduce((sum,header)=>sum+header.getBoundingClientRect().width,0);alwaysWidth>0&&(this.alwaysVisibleNaturalWidth=alwaysWidth)}const lowNaturalWidth=this.priorityTierNaturalWidth.get("low")??0,mediumNaturalWidth=this.priorityTierNaturalWidth.get("medium")??0,overflowAtFull=(lowActuallyHidden||mediumActuallyHidden?(this.alwaysVisibleNaturalWidth??0)+lowNaturalWidth+mediumNaturalWidth:base.scrollWidth)-base.clientWidth,measuredLow=hasLowColumn&&overflowAtFull>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX,overflowAfterLow=measuredLow?overflowAtFull-lowNaturalWidth:overflowAtFull,measuredMedium=hasMediumColumn&&overflowAfterLow>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX,allocation=base.offsetWidth,needsMedium=this.settlePriorityTier(base,"medium",measuredMedium,mediumActuallyHidden,allocation),needsLow=this.settlePriorityTier(base,"low",hasLowColumn&&(measuredLow||needsMedium),lowActuallyHidden,allocation);this.rehomeFocusedColumn();const toggleAvailable=needsLow||needsMedium,anyPriorityHidden=toggleAvailable&&!this.priorityColumnsVisible;this.priorityToggleAvailable!==toggleAvailable&&(this.priorityToggleAvailable=toggleAvailable),this.hasHiddenPriorityColumns!==anyPriorityHidden&&(this.hasHiddenPriorityColumns=anyPriorityHidden)}settlePriorityTier(base,tier,measured,actuallyHidden,allocation){const attribute=tier==="low"?"data-hide-priority-low":"data-hide-priority-medium",wasMarked=base.hasAttribute(attribute),revealedAt=this.priorityTierRevealAllocation.get(tier);this.priorityTierRevealAllocation.delete(tier);const hiddenAt=this.priorityTierHiddenAllocation.get(tier),held=actuallyHidden&&hiddenAt!==void 0&&allocation<=hiddenAt+TABLE_SCROLL_OVERFLOW_TOLERANCE_PX,hide=measured||held;return hide?(!wasMarked||hiddenAt===void 0)&&this.priorityTierHiddenAllocation.set(tier,Math.max(allocation,revealedAt??allocation)):(this.priorityTierHiddenAllocation.delete(tier),wasMarked&&actuallyHidden&&this.priorityTierRevealAllocation.set(tier,allocation)),base.toggleAttribute(attribute,hide),hide}rehomeFocusedColumn(){const visible=this.visibleHeaders();visible.length===0||this.activeColKey===null||visible.some(header=>header.dataset.colKey===this.activeColKey)||(this.activeColKey=visible[0].dataset.colKey??null)}keyOf(row,index){try{const key=this.rowKey?this.rowKey(row):index;return typeof key=="string"?key.trim().length===0?void 0:key:typeof key=="number"?key:void 0}catch{return}}canonicalRowEntries(){const inputs=this.canonicalRowEntriesInputs;if(this.cachedCanonicalRowEntries!==null&&inputs?.rows===this.rows&&inputs.rowKey===this.rowKey)return this.cachedCanonicalRowEntries;const entries=[],seen=new Set;return this.rows.forEach((row,index)=>{const key=this.keyOf(row,index);if(key===void 0)return;const encoded=encodeKey(key);seen.has(encoded)||(seen.add(encoded),entries.push({row,index,key}))}),this.canonicalRowEntriesInputs={rows:this.rows,rowKey:this.rowKey},this.cachedCanonicalRowEntries=entries,entries}matchingEntries(){const text=(this.filterText??"").trim(),locale=text===""?"":this.effectiveLocale,canonicalEntries=this.canonicalRowEntries(),inputs=this.matchingEntriesInputs;if(this.cachedMatchingEntries!==null&&inputs!==null&&inputs.entries===canonicalEntries&&inputs.filter===this.filter&&inputs.text===text&&inputs.locale===locale)return this.cachedMatchingEntries;let entries;if(text==="")entries=canonicalEntries;else{const intlLocale=this.effectiveLocale,normalized=text.toLocaleLowerCase(intlLocale);entries=canonicalEntries.filter(({row})=>this.filter?this.filter(row,text):safeStringifyForFilter(row).toLocaleLowerCase(intlLocale).includes(normalized))}return this.matchingEntriesInputs={entries:canonicalEntries,filter:this.filter,text,locale},this.cachedMatchingEntries=entries,entries}get normalizedPageSize(){return finiteInteger(this.pageSize,DEFAULT_PAGE_SIZE,1,MAX_PAGE_SIZE)}get effectiveSkeletonRows(){const explicit=finiteCount(this.skeletonRows,0,MAX_SKELETON_ROWS);if(explicit>0)return explicit;const pageSize=this.normalizedPageSize;return pageSize===DEFAULT_PAGE_SIZE?DEFAULT_SKELETON_ROWS:Math.min(pageSize,MAX_SKELETON_ROWS)}get matchingTotalItems(){const totalItems=finiteInteger(this.totalItems,-1);return totalItems>=0?totalItems:this.matchingEntries().length}get serverUnknownTotal(){return this.paginationMode==="server"&&this.unknownTotal}get pageCount(){const pageSize=this.normalizedPageSize;return pageSize>0?Math.ceil(this.matchingTotalItems/pageSize):0}get appliedPage(){return this.pageCount===0?1:finiteInteger(this.page,1,1,this.pageCount)}sortedEntries(){const entries=this.matchingEntries();if(this.sortMode!=="client"||this.sortKey==="")return entries;const col=this.columnsByKey.get(this.sortKey);if(!col?.sortable)return entries;const locale=this.effectiveLocale,inputs=this.sortedEntriesInputs;if(this.cachedSortedEntries!==null&&inputs!==null&&inputs.entries===entries&&inputs.columns===this.columns&&inputs.mode===this.sortMode&&inputs.key===this.sortKey&&inputs.dir===this.sortDir&&inputs.locale===locale&&inputs.groupBy===this.groupBy)return this.cachedSortedEntries;const collator=getCollator(locale,{numeric:!0}),dir=this.sortDir==="desc"?-1:1,decorated=entries.map(entry=>{const raw=typeof col.sortValue=="function"?col.sortValue(entry.row):typeof col.cell=="function"?String(col.cell(entry.row)??""):"";return{entry,value:typeof raw=="number"&&!Number.isFinite(raw)?null:raw}}),compare=(a,b)=>{const av=a.value,bv=b.value;return av==null&&bv==null?0:av==null?1:bv==null?-1:typeof av=="number"&&typeof bv=="number"?(av-bv)*dir:collator.compare(String(av),String(bv))*dir};let sorted;const groupBy=this.groupBy;if(groupBy===void 0)decorated.sort(compare),sorted=decorated.map(decoration=>decoration.entry);else{const buckets=new Map;for(const decoration of decorated){const groupKey=groupBy(decoration.entry.row),bucket=buckets.get(groupKey);bucket===void 0?buckets.set(groupKey,[decoration]):bucket.push(decoration)}const ordered=[...buckets.values()],constantWithinEveryGroup=ordered.every(bucket=>bucket.every(decoration=>compare(decoration,bucket[0])===0));constantWithinEveryGroup&&ordered.sort((a,b)=>compare(a[0],b[0])),sorted=[];for(const bucket of ordered){constantWithinEveryGroup||bucket.sort(compare);for(const decoration of bucket)sorted.push(decoration.entry)}}return this.sortedEntriesInputs={entries,columns:this.columns,mode:this.sortMode,key:this.sortKey,dir:this.sortDir,locale,groupBy},this.cachedSortedEntries=sorted,sorted}renderedEntries(){const entries=this.sortedEntries();if(this.paginationMode==="server")return entries.slice(0,this.normalizedPageSize);const start=(this.appliedPage-1)*this.normalizedPageSize;return entries.slice(start,start+this.normalizedPageSize)}get viewRows(){return Object.freeze(this.sortedEntries().map(entry=>entry.row))}get pageRows(){return Object.freeze(this.renderedEntries().map(entry=>entry.row))}focusedColKey(displayed){const visibleKeys=displayed??this.visibleHeaders().map(el=>el.dataset.colKey).filter(key=>key!==void 0&&this.columnsByKey.has(key));return this.activeColKey!==null&&this.columnsByKey.has(this.activeColKey)&&(visibleKeys.length===0||visibleKeys.includes(this.activeColKey))?this.activeColKey:visibleKeys[0]??this.columns[0]?.key??null}displayedColumnKeys(){const base=this.renderRoot?.querySelector?.('[part="base"]'),hideLow=!this.priorityColumnsVisible&&!!base?.hasAttribute("data-hide-priority-low"),hideMedium=!this.priorityColumnsVisible&&!!base?.hasAttribute("data-hide-priority-medium");return this.columns.filter(col=>!(hideLow&&col.priority==="low")&&!(hideMedium&&col.priority==="medium")).map(col=>col.key)}focusedRowKey(){if(this.activeRowKey!==null&&this.rowsByKey.has(this.activeRowKey))return this.activeRowKey;const selectedKey=this._selectedKeys.values().next().value;if(selectedKey!==void 0){const selected=encodeKey(selectedKey);if(this.rowsByKey.has(selected))return selected}const first=this.renderedEntries()[0];return first?encodeKey(first.key):null}rowsAffectingRovingFocusChanged(changed){return changed.has("rows")||changed.has("rowKey")||changed.has("filterText")||changed.has("filter")||changed.has("page")||changed.has("pageSize")||changed.has("paginationMode")||changed.has("totalItems")||changed.has("columns")||changed.has("sortKey")||changed.has("sortDir")||changed.has("sortMode")||changed.has("groupBy")||this.rowsLocale!==this.effectiveLocale}captureRovingFocus(changed){this.rovingFocusSnapshot=null;const active=shadowFocusTarget(this),HTMLElementCtor=this.ownerDocument?.defaultView?.HTMLElement;if(!(!HTMLElementCtor||!(active instanceof HTMLElementCtor))){if(changed.has("columns")&&active.matches("th[data-col-key]")){const headers=this.visibleHeaders(),key=active.dataset.colKey,index=headers.indexOf(active);key!==void 0&&index>=0&&(this.rovingFocusSnapshot={kind:"header",key,index,targetKey:null,element:active});return}if(this.rowsAffectingRovingFocusChanged(changed)&&active.matches("tr[data-row-key]")){const renderedRows=[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")],key=active.dataset.rowKey,index=renderedRows.indexOf(active);key!==void 0&&index>=0&&(this.rovingFocusSnapshot={kind:"row",key,index,targetKey:null,element:active})}}}resolveRovingFocusTarget(){const snapshot=this.rovingFocusSnapshot;if(snapshot===null)return;const keys=snapshot.kind==="header"?this.columns.map(column=>column.key):[...this.rowsByKey.keys()];snapshot.targetKey=keys.includes(snapshot.key)?snapshot.key:keys[Math.min(snapshot.index,keys.length-1)]??null,snapshot.kind==="header"?this.activeColKey=snapshot.targetKey:this.activeRowKey=snapshot.targetKey}willUpdate(changed){if(super.willUpdate(changed),this.themedResizeMinWidth=void 0,this.captureRovingFocus(changed),this.selectionMode==="single"&&this._selectedKeys.size>1&&(changed.has("selectionMode")||changed.has("selectedRowKeys"))){const first=this._selectedKeys.values().next().value;if(this.selectedRowKeys=this.asKeySet(first===void 0?new Set:new Set([first])),this.hasUpdated){const rowKeys=this.asKeyList(Object.freeze(first===void 0?[]:[first]));this.emit("lr-selection-change",Object.freeze({selectedRowKeys:rowKeys}))}}if(this.expansionMode==="single"&&this._expandedKeys.size>1&&(changed.has("expansionMode")||changed.has("expandedRowKeys"))){const first=this._expandedKeys.values().next().value;this.expandedRowKeys=this.asKeySet(first===void 0?new Set:new Set([first]))}if(!this.hasUpdated){const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.priorityColumnsVisible=="boolean"&&!isPersistedPropertyExplicitlySet(this,"priorityColumnsVisible")&&(this.priorityColumnsVisible=parsed.priorityColumnsVisible)}if(changed.has("columns")&&(this.columnsByKey=new Map(this.columns.map(c=>[c.key,c]))),this.rowsAffectingRovingFocusChanged(changed)&&(this.rowsByKey=new Map(this.renderedEntries().map(entry=>[encodeKey(entry.key),entry])),this.rowsLocale=this.effectiveLocale),this.resolveRovingFocusTarget(),this.editingCell!==null){const column=this.columnsByKey.get(this.editingCell.columnKey);(!this.rowsByKey.has(this.editingCell.rowKey)||normalizedEditTrigger(column?.editTrigger)!=="double-click")&&(this.editingCell=null)}this.editorHadFocusBeforeUpdate=this.focusedEditorCell!==null&&shadowFocusTarget(this)===this.editorElementFor(this.focusedEditorCell.rowKey,this.focusedEditorCell.columnKey)}stickyOffsets(){const offsets=new Map,headerWidths=new Map;for(const el of this.renderRoot.querySelectorAll("th[data-col-key]")){const key=el.dataset.colKey;key!==void 0&&!headerWidths.has(key)&&headerWidths.set(key,el.offsetWidth)}const headerWidth=key=>headerWidths.get(key)??0;let runningStart=0;for(const col of this.columns)stickyDirection(col.sticky)==="start"&&(offsets.set(col.key,runningStart),runningStart+=headerWidth(col.key));let runningEnd=0;for(let i=this.columns.length-1;i>=0;i--){const col=this.columns[i];col&&stickyDirection(col.sticky)==="end"&&(offsets.set(col.key,runningEnd),runningEnd+=headerWidth(col.key))}return offsets}computeHeatDomain(hasHeatTint){if(!hasHeatTint)return null;const entries=this.matchingEntries(),min=this.heatTintScale?.min,max=this.heatTintScale?.max,cached=this.heatDomainCache;if(cached&&cached.entries===entries&&cached.columns===this.columns&&cached.min===min&&cached.max===max)return cached.domain;const domain=this.deriveHeatDomain(entries);return this.heatDomainCache={entries,columns:this.columns,min,max,domain},domain}deriveHeatDomain(entries){const values=[];for(const entry of entries)for(const col of this.columns){const v=col.heatValue?.(entry.row);v!=null&&Number.isFinite(v)&&values.push(v)}const auto=minMax(values),lo=this.heatTintScale?.min??auto?.[0],hi=this.heatTintScale?.max??auto?.[1];return lo===void 0||hi===void 0?null:[lo,hi]}heatShare(col,row,domain){if(!col.heatValue||!domain)return null;const v=col.heatValue(row);if(v==null||!Number.isFinite(v))return null;const[lo,hi]=domain;return`${(finiteRatio(v,lo,hi)*100).toFixed(2)}%`}applyStickyOffsets(){if(!this.columns.some(c=>c.sticky))return;const offsets=this.stickyOffsets();this.renderRoot.querySelectorAll("[data-col-key]").forEach(el=>{const key=el.dataset.colKey;key!==void 0&&offsets.has(key)&&el.style.setProperty("--lr-table-sticky-offset",`${offsets.get(key)}px`)})}updated(changed){super.updated(changed),this.firstUpdateAnnouncementsReady&&changed.has("loading")&&this.loading&&this.announcements.announcePolite(this.loadingText()),this.firstUpdateAnnouncementsReady&&changed.has("loadingMore")&&this.loadingMore&&!this.loading&&this.shadowRoot?.querySelector('[part="more-button"]')&&this.announcements.announcePolite(this.loadingMoreText());const announcesErrorTransition=this.firstUpdateAnnouncementsReady&&changed.has("error")&&this.error,announcesMountedError=!this.firstUpdateAnnouncementsReady&&this.announce&&this.error;if((announcesErrorTransition||announcesMountedError)&&this.announcements.announceAssertive(this.localizedOverride("tableLoadFailed",this.errorHeading)),this.firstUpdateAnnouncementsReady=!0,this.persistReady&&changed.has("priorityColumnsVisible")&&writePersistedState(this.storageFullKey,{priorityColumnsVisible:this.priorityColumnsVisible}),this.persistReady=!0,changed.has("columns")||changed.has("revealColumnsLabel")||changed.has("columnsHideLabel")||changed.has("priorityColumnsVisible")||changed.has("storageKey")){const inertMembers=[],labelsInert=this.revealColumnsLabel!==void 0||this.columnsHideLabel!==void 0;labelsInert&&inertMembers.push("`revealColumnsLabel`/`columnsHideLabel`"),isPersistedPropertyExplicitlySet(this,"priorityColumnsVisible")&&inertMembers.push("`priorityColumnsVisible`"),this.storageKey&&inertMembers.push("`storageKey`"),inertMembers.length>0&&this.columns.length>0&&!this.columns.some(col=>col.priority)&&devWarnOnce(INERT_PRIORITY_COLUMN_CONFIG_WARNING,`<lr-table>: ${inertMembers.join(", ")} `+(inertMembers.length>1||labelsInert?"have":"has")+" no effect unless at least one column declares `priority`.")}(changed.has("columns")||changed.has("rows")||changed.has("rowKey"))&&this.applyStickyOffsets(),this.syncResizeHandleValues();const base=this.renderRoot.querySelector('[part="base"]');if(base&&this.observeBase(base),this.observeTable(this.renderRoot.querySelector('[part="table"]')??void 0),this.syncAutoScrollMode(),this.observeHeaders(),this.restoreRovingFocus(),this.hasAlwaysOnEditors&&this.restoreAlwaysOnEditorFocus(),changed.has("editingCell"))if(this.editingCell){const{rowKey,columnKey}=this.editingCell;queueMicrotask(()=>this.editorElementFor(rowKey,columnKey)?.focus())}else{const previous=changed.get("editingCell");if(previous){const{rowKey,columnKey}=previous;queueMicrotask(()=>this.cellElementForToken(rowKey,columnKey)?.focus())}}queueMicrotask(()=>this.recomputeHiddenPriorityColumns())}restoreRovingFocus(){const snapshot=this.rovingFocusSnapshot;if(this.rovingFocusSnapshot=null,snapshot===null)return;const internalActive=shadowFocusTarget(this);if(internalActive!==null&&internalActive!==snapshot.element)return;const documentActive=activeElementIn(this.ownerDocument);if(documentActive!==null&&documentActive!==this&&documentActive!==this.ownerDocument.body)return;const candidates=snapshot.kind==="header"?this.visibleHeaders():[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")],target=candidates.find(candidate=>snapshot.kind==="header"?candidate.dataset.colKey===snapshot.targetKey:candidate.dataset.rowKey===snapshot.targetKey)??candidates[Math.min(snapshot.index,candidates.length-1)]??null;snapshot.kind==="header"?this.focusHeader(target):this.focusRow(target)}activateColumn(key){this.activeColKey=key;const col=this.columnsByKey.get(key);if(!col?.sortable)return;const sortDir=this.sortKey===key?this.sortDir==="asc"?"desc":"asc":col.defaultSortDir??this.defaultSortDir,request=Object.freeze({phase:"request",sortKey:col.key,sortDir});this.emit("lr-sort-request",request,{cancelable:!0}).defaultPrevented||(this.sortMode==="client"&&(this.sortKey=col.key,this.sortDir=sortDir),this.emit("lr-sort",Object.freeze({phase:"commit",sortKey:col.key,sortDir})))}activateRow(key){this.activeRowKey=key;const entry=this.rowsByKey.get(key);if(entry===void 0)return;const{row,key:selectedKey}=entry;if(this.emit("lr-row-activate",Object.freeze({row})),this.selectionMode==="single"){this.selectedRowKeys=this.asKeySet(new Set([selectedKey]));const rowKeys=this.asKeyList(Object.freeze([selectedKey]));this.emit("lr-selection-change",Object.freeze({selectedRowKeys:rowKeys}))}else if(this.selectionMode==="multiple"){const rawKey=selectedKey,next=new Set(this._selectedKeys);next.has(rawKey)?next.delete(rawKey):next.add(rawKey),this.selectedRowKeys=this.asKeySet(next);const rowKeys=this.asKeyList(Object.freeze([...next]));this.emit("lr-selection-change",Object.freeze({selectedRowKeys:rowKeys}))}}get hasAlwaysOnEditors(){return this.columns.some(col=>normalizedEditTrigger(col.editTrigger)==="always")}editorValue(row,column){const value=column.editValue?.(row)??row[column.key]??"";return String(value)}startEditing(rowKey,columnKey){const column=this.columnsByKey.get(columnKey);normalizedEditTrigger(column?.editTrigger)!=="double-click"||!this.rowsByKey.has(rowKey)||(this.editingCell={rowKey,columnKey})}commitEdit(event,rowKey,columnKey){event.stopPropagation();const field=event.currentTarget,entry=this.rowsByKey.get(rowKey),column=this.columnsByKey.get(columnKey),isTransient=this.editingCell?.rowKey===rowKey&&this.editingCell.columnKey===columnKey;if(!entry||!column||normalizedEditTrigger(column.editTrigger)===void 0){isTransient&&(this.editingCell=null);return}const value=column.editType==="number"&&field.value!==""?Number(field.value):field.value;this.emit("lr-cell-edit",Object.freeze({row:entry.row,columnKey,value})),isTransient&&(this.editingCell=null)}editorElementFor(rowKey,columnKey){return this.cellElementForToken(rowKey,columnKey)?.querySelector('[part="cell-editor"]')??null}restoreAlwaysOnEditorFocus(){const cell=this.focusedEditorCell;if(cell===null)return;const editor=this.editorElementFor(cell.rowKey,cell.columnKey);editor===null?this.focusedEditorCell=null:this.editorHadFocusBeforeUpdate&&shadowFocusTarget(this)!==editor&&editor.focus(),this.editorHadFocusBeforeUpdate=!1}activateExpandToggle(key){const entry=this.rowsByKey.get(encodeKey(key));if(entry===void 0)return;const expanded=!this._expandedKeys.has(key),detail=Object.freeze({row:entry.row,rowKey:key,expanded});if(this.expansionMode!=="single"&&this.expansionMode!=="multiple"){this.emit("lr-row-expand-toggle",detail);return}requestThenCommit({requestDetail:detail,emitRequest:(requestDetail,init)=>this.emit("lr-row-expand-request",requestDetail,init),commit:()=>{const next=this.expansionMode==="single"?new Set:new Set(this._expandedKeys);expanded?next.add(key):next.delete(key);const displaced=[...this._expandedKeys].filter(other=>other!==key&&!next.has(other));this.expandedRowKeys=this.asKeySet(next);for(const other of displaced){const displacedEntry=this.rowsByKey.get(encodeKey(other));displacedEntry!==void 0&&this.emit("lr-row-expand-toggle",Object.freeze({row:displacedEntry.row,rowKey:other,expanded:!1}))}this.emit("lr-row-expand-toggle",detail)}})}rowElement(rowKey){return this.rowElementForToken(encodeKey(rowKey))}cellElement(rowKey,columnKey){return this.cellElementForToken(encodeKey(rowKey),columnKey)}editCell(rowKey,columnKey){const token=encodeKey(rowKey),trigger=normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger);if(!(trigger===void 0||!this.rowsByKey.has(token))){if(trigger==="always"){this.editorElementFor(token,columnKey)?.focus();return}this.startEditing(token,columnKey)}}expandedContentElement(rowKey){const token=encodeKey(rowKey);return[...this.renderRoot.querySelectorAll("tbody tr[data-expanded-row-key]")].find(el=>el.dataset.expandedRowKey===token)?.querySelector('[part="expanded-cell"]')??null}rowElementForToken(token){return[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")].find(el=>el.dataset.rowKey===token)??null}cellElementForToken(token,columnKey){return[...this.rowElementForToken(token)?.querySelectorAll("td[data-col-key]")??[]].find(el=>el.dataset.colKey===columnKey)??null}visibleHeaders(){return[...this.renderRoot?.querySelectorAll("th[data-col-key]")??[]].filter(el=>el.offsetParent!==null)}focusHeader(el){el?.dataset.colKey&&(this.activeColKey=el.dataset.colKey,el.focus())}focusRow(el){el?.dataset.rowKey&&(this.activeRowKey=el.dataset.rowKey,el.focus())}onHeaderKeyDown(e,th){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateColumn(th.dataset.colKey);return}const headers=this.visibleHeaders(),index=headers.indexOf(th);if(index<0)return;const rtl=isRtl(this);switch(e.key){case"ArrowLeft":e.preventDefault(),this.focusHeader(headers[rtl?Math.min(headers.length-1,index+1):Math.max(0,index-1)]??null);return;case"ArrowRight":e.preventDefault(),this.focusHeader(headers[rtl?Math.max(0,index-1):Math.min(headers.length-1,index+1)]??null);return;case"Home":e.preventDefault(),this.focusHeader(headers[0]??null);return;case"End":e.preventDefault(),this.focusHeader(headers[headers.length-1]??null);return;case"ArrowDown":{e.preventDefault();const rows=[...this.renderRoot.querySelectorAll("[data-row-key]")],key=this.focusedRowKey();this.focusRow(rows.find(r=>r.dataset.rowKey===key)??rows[0]??null);return}default:return}}editableCellFor(target){const columnKey=target.dataset.colKey;return target.tagName!=="TD"||columnKey===void 0?null:normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="double-click"?{element:target,columnKey}:null}editableCellsInRow(tr){return[...tr.querySelectorAll("td[data-editable]")].filter(td=>td.offsetParent!==null&&!td.inert&&!td.closest("[inert]"))}onRowKeyDown(e,tr){const cell=this.editableCellFor(e.target);if((e.key==="Enter"||e.key==="F2")&&cell){e.preventDefault(),this.startEditing(tr.dataset.rowKey,cell.columnKey);return}if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateRow(tr.dataset.rowKey);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){this.onRowLateralKeyDown(e,tr,cell);return}const bodyRows=[...this.renderRoot.querySelectorAll("[data-row-key]")],index=bodyRows.indexOf(tr);if(!(index<0))switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(bodyRows[Math.min(bodyRows.length-1,index+1)]??null);return;case"ArrowUp":if(e.preventDefault(),index===0){const headers=this.visibleHeaders(),key=this.focusedColKey();this.focusHeader(headers.find(h=>h.dataset.colKey===key)??headers[0]??null)}else this.focusRow(bodyRows[index-1]??null);return;case"Home":e.preventDefault(),this.focusRow(bodyRows[0]??null);return;case"End":e.preventDefault(),this.focusRow(bodyRows[bodyRows.length-1]??null);return;default:return}}onRowLateralKeyDown(e,tr,cell){const cells=this.editableCellsInRow(tr);if(cells.length===0)return;e.preventDefault();const forward=e.key===(isRtl(this)?"ArrowLeft":"ArrowRight");if(cell===null){(forward?cells[0]:cells[cells.length-1])?.focus();return}const index=cells.indexOf(cell.element);forward?cells[index+1]?.focus():index<=0?this.focusRow(tr):cells[index-1]?.focus()}renderCellValue(col,row){return typeof col.cell=="function"?col.cell(row):(devWarnOnce(MISSING_CELL_RENDERER_WARNING,"<lr-table>: a column has no required `cell` renderer, so its cells render empty. Supply a `cell` callback for every column."),nothing)}renderCellEditor(row,col,rowKey,alwaysOn){const type=col.editType??"text",value=this.editorValue(row,col),label=col.editLabel?.(row)??this.localize("tableEditCell",void 0,{column:col.label}),onChange=event=>this.commitEdit(event,rowKey,col.key),onKeyDown=event=>this.onEditorKeyDown(event,rowKey,col.key);if(type==="select"){const options=col.editOptions??[];return html`<select
|
|
14
|
+
></span>`}syncResizeHandleValues(){for(const handle of this.renderRoot.querySelectorAll('[part="resize-handle"]')){const key=handle.dataset.colKey;if(!key)continue;const column=this.columnsByKey.get(key);if(!column||this.resizedColumnWidths.has(key)||this.parsePixelLength(column.width)!==void 0)continue;const rendered=handle.closest("th[data-col-key]")?.getBoundingClientRect().width;if(rendered&&rendered>0){const width=Math.round(rendered);handle.setAttribute("aria-valuenow",String(width)),handle.setAttribute("aria-valuetext",this.resizeValueText(width))}}}rollbackResizePreview(state2){const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):reverted.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted}cancelResizeGesture(){const state2=this.resizeState;this.resizeState=void 0,this.resizePointer.stop(),state2&&(state2.handle.removeAttribute("data-resizing"),this.rollbackResizePreview(state2))}firstUpdated(changed){super.firstUpdated(changed),!this.hasAttribute("aria-label")&&!this.caption&&devWarnOnce(MISSING_ACCESSIBLE_NAME_WARNING,"<lr-table> has no accessible name: set a host `aria-label` or `caption` so assistive technology can identify the grid.")}connectedCallback(){super.connectedCallback();const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;let observer;ResizeObserverCtor&&(observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.resizeObserver!==observer||this.scheduleLayoutSync()})),this.resizeObserver=observer;const base=this.renderRoot?.querySelector('[part="base"]');base&&(this.observeBase(base),this.observeTable(this.renderRoot.querySelector('[part="table"]')??void 0),this.observeHeaders())}disconnectedCallback(){super.disconnectedCallback(),this.cancelResizeGesture(),this.resizeObserver?.disconnect(),this.resizeObserver=void 0;const frame=this.layoutFrame;frame&&frame.owner.cancelAnimationFrame(frame.handle),this.layoutFrame=null,this.observedBase=void 0,this.observedTable=void 0,this.observedHeaders.clear()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}localizedOverride(key,override){return override??this.localize(key)}loadingText(){return this.localizedOverride("tableLoading",this.loadingLabel)}loadingMoreText(){return this.localizedOverride("tableLoadingMore",this.loadingMoreLabel)}onLoadMore(){this.loadingMore||this.emit("lr-load-more")}observeBase(base){this.observedBase!==base&&(this.observedBase&&this.resizeObserver?.unobserve(this.observedBase),this.resizeObserver?.observe(base),this.observedBase=base)}observeTable(table){this.observedTable!==table&&(this.observedTable&&this.resizeObserver?.unobserve(this.observedTable),table&&this.resizeObserver?.observe(table),this.observedTable=table)}syncAutoScrollMode(){const base=this.renderRoot.querySelector('[part="base"]');if(!base)return;const overflows=(this.scrollMode==="auto"||this.scrollMode==="page")&&base.scrollWidth-base.clientWidth>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX;base.toggleAttribute("data-scroll-overflow",overflows)}observeHeaders(){const headers=new Set(this.columns.some(column=>column.sticky||column.resizable)?this.renderRoot.querySelectorAll("th[data-col-key]"):[]);for(const header of this.observedHeaders)headers.has(header)||(this.resizeObserver?.unobserve(header),this.observedHeaders.delete(header));for(const header of headers)this.observedHeaders.has(header)||(this.observedHeaders.add(header),this.resizeObserver?.observe(header))}priorityTierHeaders(tier){return[...this.renderRoot.querySelectorAll(`th[data-priority="${tier}"]`)]}recomputeHiddenPriorityColumns(){const hasLowColumn=this.columns.some(col=>col.priority==="low"),hasMediumColumn=this.columns.some(col=>col.priority==="medium"),base=this.renderRoot.querySelector('[part="base"]');if(!hasLowColumn&&!hasMediumColumn){this.priorityTierNaturalWidth.clear(),this.alwaysVisibleNaturalWidth=void 0,this.priorityTierHiddenAllocation.clear(),this.priorityTierRevealAllocation.clear(),base?.removeAttribute("data-hide-priority-low"),base?.removeAttribute("data-hide-priority-medium"),this.rehomeFocusedColumn(),this.priorityToggleAvailable&&(this.priorityToggleAvailable=!1),this.hasHiddenPriorityColumns&&(this.hasHiddenPriorityColumns=!1);return}if(!base||base.clientWidth<=0){this.rehomeFocusedColumn();return}const genuineOverflow=base.scrollWidth-base.clientWidth>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX,lowHeaders=hasLowColumn?this.priorityTierHeaders("low"):[],mediumHeaders=hasMediumColumn?this.priorityTierHeaders("medium"):[],refreshNaturalWidth=(tier,headers)=>{if(headers.length===0)return!1;const currentlyHidden=headers.every(header=>header.offsetParent===null);if(!currentlyHidden&&genuineOverflow){const width=headers.reduce((sum,header)=>sum+header.getBoundingClientRect().width,0);width>0&&this.priorityTierNaturalWidth.set(tier,width)}return currentlyHidden},lowActuallyHidden=refreshNaturalWidth("low",lowHeaders),mediumActuallyHidden=refreshNaturalWidth("medium",mediumHeaders);if(genuineOverflow){const alwaysWidth=[...this.renderRoot.querySelectorAll('[part="head"] > tr > th')].filter(header=>!header.hasAttribute("data-priority")).reduce((sum,header)=>sum+header.getBoundingClientRect().width,0);alwaysWidth>0&&(this.alwaysVisibleNaturalWidth=alwaysWidth)}const lowNaturalWidth=this.priorityTierNaturalWidth.get("low")??0,mediumNaturalWidth=this.priorityTierNaturalWidth.get("medium")??0,overflowAtFull=(lowActuallyHidden||mediumActuallyHidden?(this.alwaysVisibleNaturalWidth??0)+lowNaturalWidth+mediumNaturalWidth:base.scrollWidth)-base.clientWidth,measuredLow=hasLowColumn&&overflowAtFull>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX,overflowAfterLow=measuredLow?overflowAtFull-lowNaturalWidth:overflowAtFull,measuredMedium=hasMediumColumn&&overflowAfterLow>TABLE_SCROLL_OVERFLOW_TOLERANCE_PX,allocation=base.offsetWidth,needsMedium=this.settlePriorityTier(base,"medium",measuredMedium,mediumActuallyHidden,allocation),needsLow=this.settlePriorityTier(base,"low",hasLowColumn&&(measuredLow||needsMedium),lowActuallyHidden,allocation);this.rehomeFocusedColumn();const toggleAvailable=needsLow||needsMedium,anyPriorityHidden=toggleAvailable&&!this.priorityColumnsVisible;this.priorityToggleAvailable!==toggleAvailable&&(this.priorityToggleAvailable=toggleAvailable),this.hasHiddenPriorityColumns!==anyPriorityHidden&&(this.hasHiddenPriorityColumns=anyPriorityHidden)}settlePriorityTier(base,tier,measured,actuallyHidden,allocation){const attribute=tier==="low"?"data-hide-priority-low":"data-hide-priority-medium",wasMarked=base.hasAttribute(attribute),revealedAt=this.priorityTierRevealAllocation.get(tier);this.priorityTierRevealAllocation.delete(tier);const hiddenAt=this.priorityTierHiddenAllocation.get(tier),held=actuallyHidden&&hiddenAt!==void 0&&allocation<=hiddenAt+TABLE_SCROLL_OVERFLOW_TOLERANCE_PX,hide=measured||held;return hide?(!wasMarked||hiddenAt===void 0)&&this.priorityTierHiddenAllocation.set(tier,Math.max(allocation,revealedAt??allocation)):(this.priorityTierHiddenAllocation.delete(tier),wasMarked&&actuallyHidden&&this.priorityTierRevealAllocation.set(tier,allocation)),base.toggleAttribute(attribute,hide),hide}rehomeFocusedColumn(){const visible=this.visibleHeaders();visible.length===0||this.activeColKey===null||visible.some(header=>header.dataset.colKey===this.activeColKey)||(this.activeColKey=visible[0].dataset.colKey??null)}keyOf(row,index){try{const key=this.rowKey?this.rowKey(row):index;return typeof key=="string"?key.trim().length===0?void 0:key:typeof key=="number"?key:void 0}catch{return}}canonicalRowEntries(){const inputs=this.canonicalRowEntriesInputs;if(this.cachedCanonicalRowEntries!==null&&inputs?.rows===this.rows&&inputs.rowKey===this.rowKey)return this.cachedCanonicalRowEntries;const entries=[],seen=new Set;return this.rows.forEach((row,index)=>{const key=this.keyOf(row,index);if(key===void 0)return;const encoded=encodeKey(key);seen.has(encoded)||(seen.add(encoded),entries.push({row,index,key}))}),this.canonicalRowEntriesInputs={rows:this.rows,rowKey:this.rowKey},this.cachedCanonicalRowEntries=entries,entries}matchingEntries(){const text=(this.filterText??"").trim(),locale=text===""?"":this.effectiveLocale,canonicalEntries=this.canonicalRowEntries(),inputs=this.matchingEntriesInputs;if(this.cachedMatchingEntries!==null&&inputs!==null&&inputs.entries===canonicalEntries&&inputs.filter===this.filter&&inputs.text===text&&inputs.locale===locale)return this.cachedMatchingEntries;let entries;if(text==="")entries=canonicalEntries;else{const stringify=createFilterStringifier(),intlLocale=this.effectiveLocale,normalized=text.toLocaleLowerCase(intlLocale);entries=canonicalEntries.filter(({row})=>this.filter?this.filter(row,text):stringify(row).toLocaleLowerCase(intlLocale).includes(normalized))}return this.matchingEntriesInputs={entries:canonicalEntries,filter:this.filter,text,locale},this.cachedMatchingEntries=entries,entries}get normalizedPageSize(){return finiteInteger(this.pageSize,DEFAULT_PAGE_SIZE,1,MAX_PAGE_SIZE)}get effectiveSkeletonRows(){const explicit=finiteCount(this.skeletonRows,0,MAX_SKELETON_ROWS);if(explicit>0)return explicit;const pageSize=this.normalizedPageSize;return pageSize===DEFAULT_PAGE_SIZE?DEFAULT_SKELETON_ROWS:Math.min(pageSize,MAX_SKELETON_ROWS)}get matchingTotalItems(){const totalItems=finiteInteger(this.totalItems,-1);return totalItems>=0?totalItems:this.matchingEntries().length}get serverUnknownTotal(){return this.paginationMode==="server"&&this.unknownTotal}get pageCount(){const pageSize=this.normalizedPageSize;return pageSize>0?Math.ceil(this.matchingTotalItems/pageSize):0}get appliedPage(){return this.pageCount===0?1:finiteInteger(this.page,1,1,this.pageCount)}sortedEntries(){const entries=this.matchingEntries();if(this.sortMode!=="client"||this.sortKey==="")return entries;const col=this.columnsByKey.get(this.sortKey);if(!col?.sortable)return entries;const locale=this.effectiveLocale,inputs=this.sortedEntriesInputs;if(this.cachedSortedEntries!==null&&inputs!==null&&inputs.entries===entries&&inputs.columns===this.columns&&inputs.mode===this.sortMode&&inputs.key===this.sortKey&&inputs.dir===this.sortDir&&inputs.locale===locale&&inputs.groupBy===this.groupBy)return this.cachedSortedEntries;const collator=getCollator(locale,{numeric:!0}),dir=this.sortDir==="desc"?-1:1,decorated=entries.map(entry=>{const raw=typeof col.sortValue=="function"?col.sortValue(entry.row):typeof col.cell=="function"?String(col.cell(entry.row)??""):"";return{entry,value:typeof raw=="number"&&!Number.isFinite(raw)?null:raw}}),compare=(a,b)=>{const av=a.value,bv=b.value;return av==null&&bv==null?0:av==null?1:bv==null?-1:typeof av=="number"&&typeof bv=="number"?(av-bv)*dir:collator.compare(String(av),String(bv))*dir};let sorted;const groupBy=this.groupBy;if(groupBy===void 0)decorated.sort(compare),sorted=decorated.map(decoration=>decoration.entry);else{const buckets=new Map;for(const decoration of decorated){const groupKey=groupBy(decoration.entry.row),bucket=buckets.get(groupKey);bucket===void 0?buckets.set(groupKey,[decoration]):bucket.push(decoration)}const ordered=[...buckets.values()],constantWithinEveryGroup=ordered.every(bucket=>bucket.every(decoration=>compare(decoration,bucket[0])===0));constantWithinEveryGroup&&ordered.sort((a,b)=>compare(a[0],b[0])),sorted=[];for(const bucket of ordered){constantWithinEveryGroup||bucket.sort(compare);for(const decoration of bucket)sorted.push(decoration.entry)}}return this.sortedEntriesInputs={entries,columns:this.columns,mode:this.sortMode,key:this.sortKey,dir:this.sortDir,locale,groupBy},this.cachedSortedEntries=sorted,sorted}renderedEntries(){const entries=this.sortedEntries();if(this.paginationMode==="server")return entries.slice(0,this.normalizedPageSize);const start=(this.appliedPage-1)*this.normalizedPageSize;return entries.slice(start,start+this.normalizedPageSize)}get viewRows(){return Object.freeze(this.sortedEntries().map(entry=>entry.row))}get pageRows(){return Object.freeze(this.renderedEntries().map(entry=>entry.row))}focusedColKey(displayed){const visibleKeys=displayed??this.visibleHeaders().map(el=>el.dataset.colKey).filter(key=>key!==void 0&&this.columnsByKey.has(key));return this.activeColKey!==null&&this.columnsByKey.has(this.activeColKey)&&(visibleKeys.length===0||visibleKeys.includes(this.activeColKey))?this.activeColKey:visibleKeys[0]??this.columns[0]?.key??null}displayedColumnKeys(){const base=this.renderRoot?.querySelector?.('[part="base"]'),hideLow=!this.priorityColumnsVisible&&!!base?.hasAttribute("data-hide-priority-low"),hideMedium=!this.priorityColumnsVisible&&!!base?.hasAttribute("data-hide-priority-medium");return this.columns.filter(col=>!(hideLow&&col.priority==="low")&&!(hideMedium&&col.priority==="medium")).map(col=>col.key)}focusedRowKey(){if(this.activeRowKey!==null&&this.rowsByKey.has(this.activeRowKey))return this.activeRowKey;const selectedKey=this._selectedKeys.values().next().value;if(selectedKey!==void 0){const selected=encodeKey(selectedKey);if(this.rowsByKey.has(selected))return selected}const first=this.renderedEntries()[0];return first?encodeKey(first.key):null}rowsAffectingRovingFocusChanged(changed){return changed.has("rows")||changed.has("rowKey")||changed.has("filterText")||changed.has("filter")||changed.has("page")||changed.has("pageSize")||changed.has("paginationMode")||changed.has("totalItems")||changed.has("columns")||changed.has("sortKey")||changed.has("sortDir")||changed.has("sortMode")||changed.has("groupBy")||this.rowsLocale!==this.effectiveLocale}captureRovingFocus(changed){this.rovingFocusSnapshot=null;const active=shadowFocusTarget(this),HTMLElementCtor=this.ownerDocument?.defaultView?.HTMLElement;if(!(!HTMLElementCtor||!(active instanceof HTMLElementCtor))){if(changed.has("columns")&&active.matches("th[data-col-key]")){const headers=this.visibleHeaders(),key=active.dataset.colKey,index=headers.indexOf(active);key!==void 0&&index>=0&&(this.rovingFocusSnapshot={kind:"header",key,index,targetKey:null,element:active});return}if(this.rowsAffectingRovingFocusChanged(changed)&&active.matches("tr[data-row-key]")){const renderedRows=[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")],key=active.dataset.rowKey,index=renderedRows.indexOf(active);key!==void 0&&index>=0&&(this.rovingFocusSnapshot={kind:"row",key,index,targetKey:null,element:active})}}}resolveRovingFocusTarget(){const snapshot=this.rovingFocusSnapshot;if(snapshot===null)return;const keys=snapshot.kind==="header"?this.columns.map(column=>column.key):[...this.rowsByKey.keys()];snapshot.targetKey=keys.includes(snapshot.key)?snapshot.key:keys[Math.min(snapshot.index,keys.length-1)]??null,snapshot.kind==="header"?this.activeColKey=snapshot.targetKey:this.activeRowKey=snapshot.targetKey}willUpdate(changed){if(super.willUpdate(changed),this.themedResizeMinWidth=void 0,this.captureRovingFocus(changed),this.selectionMode==="single"&&this._selectedKeys.size>1&&(changed.has("selectionMode")||changed.has("selectedRowKeys"))){const first=this._selectedKeys.values().next().value;if(this.selectedRowKeys=this.asKeySet(first===void 0?new Set:new Set([first])),this.hasUpdated){const rowKeys=this.asKeyList(Object.freeze(first===void 0?[]:[first]));this.emit("lr-selection-change",Object.freeze({selectedRowKeys:rowKeys}))}}if(this.expansionMode==="single"&&this._expandedKeys.size>1&&(changed.has("expansionMode")||changed.has("expandedRowKeys"))){const first=this._expandedKeys.values().next().value;this.expandedRowKeys=this.asKeySet(first===void 0?new Set:new Set([first]))}if(!this.hasUpdated){const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.priorityColumnsVisible=="boolean"&&!isPersistedPropertyExplicitlySet(this,"priorityColumnsVisible")&&(this.priorityColumnsVisible=parsed.priorityColumnsVisible)}if(changed.has("columns")&&(this.columnsByKey=new Map(this.columns.map(c=>[c.key,c]))),this.rowsAffectingRovingFocusChanged(changed)&&(this.rowsByKey=new Map(this.renderedEntries().map(entry=>[encodeKey(entry.key),entry])),this.rowsLocale=this.effectiveLocale),this.resolveRovingFocusTarget(),this.editingCell!==null){const column=this.columnsByKey.get(this.editingCell.columnKey);(!this.rowsByKey.has(this.editingCell.rowKey)||normalizedEditTrigger(column?.editTrigger)!=="double-click")&&(this.editingCell=null)}this.editorHadFocusBeforeUpdate=this.focusedEditorCell!==null&&shadowFocusTarget(this)===this.editorElementFor(this.focusedEditorCell.rowKey,this.focusedEditorCell.columnKey)}stickyOffsets(){const offsets=new Map,headerWidths=new Map;for(const el of this.renderRoot.querySelectorAll("th[data-col-key]")){const key=el.dataset.colKey;key!==void 0&&!headerWidths.has(key)&&headerWidths.set(key,el.offsetWidth)}const headerWidth=key=>headerWidths.get(key)??0;let runningStart=0;for(const col of this.columns)stickyDirection(col.sticky)==="start"&&(offsets.set(col.key,runningStart),runningStart+=headerWidth(col.key));let runningEnd=0;for(let i=this.columns.length-1;i>=0;i--){const col=this.columns[i];col&&stickyDirection(col.sticky)==="end"&&(offsets.set(col.key,runningEnd),runningEnd+=headerWidth(col.key))}return offsets}computeHeatDomain(hasHeatTint){if(!hasHeatTint)return null;const entries=this.matchingEntries(),min=this.heatTintScale?.min,max=this.heatTintScale?.max,cached=this.heatDomainCache;if(cached&&cached.entries===entries&&cached.columns===this.columns&&cached.min===min&&cached.max===max)return cached.domain;const domain=this.deriveHeatDomain(entries);return this.heatDomainCache={entries,columns:this.columns,min,max,domain},domain}deriveHeatDomain(entries){const values=[];for(const entry of entries)for(const col of this.columns){const v=col.heatValue?.(entry.row);v!=null&&Number.isFinite(v)&&values.push(v)}const auto=minMax(values),lo=this.heatTintScale?.min??auto?.[0],hi=this.heatTintScale?.max??auto?.[1];return lo===void 0||hi===void 0?null:[lo,hi]}heatShare(col,row,domain){if(!col.heatValue||!domain)return null;const v=col.heatValue(row);if(v==null||!Number.isFinite(v))return null;const[lo,hi]=domain;return`${(finiteRatio(v,lo,hi)*100).toFixed(2)}%`}applyStickyOffsets(){if(!this.columns.some(c=>c.sticky))return;const offsets=this.stickyOffsets();this.renderRoot.querySelectorAll("[data-col-key]").forEach(el=>{const key=el.dataset.colKey;key!==void 0&&offsets.has(key)&&el.style.setProperty("--lr-table-sticky-offset",`${offsets.get(key)}px`)})}updated(changed){super.updated(changed),this.firstUpdateAnnouncementsReady&&changed.has("loading")&&this.loading&&this.announcements.announcePolite(this.loadingText()),this.firstUpdateAnnouncementsReady&&changed.has("loadingMore")&&this.loadingMore&&!this.loading&&this.shadowRoot?.querySelector('[part="more-button"]')&&this.announcements.announcePolite(this.loadingMoreText());const announcesErrorTransition=this.firstUpdateAnnouncementsReady&&changed.has("error")&&this.error,announcesMountedError=!this.firstUpdateAnnouncementsReady&&this.announce&&this.error;if((announcesErrorTransition||announcesMountedError)&&this.announcements.announceAssertive(this.localizedOverride("tableLoadFailed",this.errorHeading)),this.firstUpdateAnnouncementsReady=!0,this.persistReady&&changed.has("priorityColumnsVisible")&&writePersistedState(this.storageFullKey,{priorityColumnsVisible:this.priorityColumnsVisible}),this.persistReady=!0,changed.has("columns")||changed.has("revealColumnsLabel")||changed.has("columnsHideLabel")||changed.has("priorityColumnsVisible")||changed.has("storageKey")){const inertMembers=[],labelsInert=this.revealColumnsLabel!==void 0||this.columnsHideLabel!==void 0;labelsInert&&inertMembers.push("`revealColumnsLabel`/`columnsHideLabel`"),isPersistedPropertyExplicitlySet(this,"priorityColumnsVisible")&&inertMembers.push("`priorityColumnsVisible`"),this.storageKey&&inertMembers.push("`storageKey`"),inertMembers.length>0&&this.columns.length>0&&!this.columns.some(col=>col.priority)&&devWarnOnce(INERT_PRIORITY_COLUMN_CONFIG_WARNING,`<lr-table>: ${inertMembers.join(", ")} `+(inertMembers.length>1||labelsInert?"have":"has")+" no effect unless at least one column declares `priority`.")}(changed.has("columns")||changed.has("rows")||changed.has("rowKey"))&&this.applyStickyOffsets(),this.syncResizeHandleValues();const base=this.renderRoot.querySelector('[part="base"]');if(base&&this.observeBase(base),this.observeTable(this.renderRoot.querySelector('[part="table"]')??void 0),this.syncAutoScrollMode(),this.observeHeaders(),this.restoreRovingFocus(),this.hasAlwaysOnEditors&&this.restoreAlwaysOnEditorFocus(),changed.has("editingCell"))if(this.editingCell){const{rowKey,columnKey}=this.editingCell;queueMicrotask(()=>this.editorElementFor(rowKey,columnKey)?.focus())}else{const previous=changed.get("editingCell");if(previous){const{rowKey,columnKey}=previous;queueMicrotask(()=>this.cellElementForToken(rowKey,columnKey)?.focus())}}queueMicrotask(()=>this.recomputeHiddenPriorityColumns())}restoreRovingFocus(){const snapshot=this.rovingFocusSnapshot;if(this.rovingFocusSnapshot=null,snapshot===null)return;const internalActive=shadowFocusTarget(this);if(internalActive!==null&&internalActive!==snapshot.element)return;const documentActive=activeElementIn(this.ownerDocument);if(documentActive!==null&&documentActive!==this&&documentActive!==this.ownerDocument.body)return;const candidates=snapshot.kind==="header"?this.visibleHeaders():[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")],target=candidates.find(candidate=>snapshot.kind==="header"?candidate.dataset.colKey===snapshot.targetKey:candidate.dataset.rowKey===snapshot.targetKey)??candidates[Math.min(snapshot.index,candidates.length-1)]??null;snapshot.kind==="header"?this.focusHeader(target):this.focusRow(target)}activateColumn(key){this.activeColKey=key;const col=this.columnsByKey.get(key);if(!col?.sortable)return;const sortDir=this.sortKey===key?this.sortDir==="asc"?"desc":"asc":col.defaultSortDir??this.defaultSortDir,request=Object.freeze({phase:"request",sortKey:col.key,sortDir});this.emit("lr-sort-request",request,{cancelable:!0}).defaultPrevented||(this.sortMode==="client"&&(this.sortKey=col.key,this.sortDir=sortDir),this.emit("lr-sort",Object.freeze({phase:"commit",sortKey:col.key,sortDir})))}activateRow(key){this.activeRowKey=key;const entry=this.rowsByKey.get(key);if(entry===void 0)return;const{row,key:selectedKey}=entry;if(this.emit("lr-row-activate",Object.freeze({row})),this.selectionMode==="single"){this.selectedRowKeys=this.asKeySet(new Set([selectedKey]));const rowKeys=this.asKeyList(Object.freeze([selectedKey]));this.emit("lr-selection-change",Object.freeze({selectedRowKeys:rowKeys}))}else if(this.selectionMode==="multiple"){const rawKey=selectedKey,next=new Set(this._selectedKeys);next.has(rawKey)?next.delete(rawKey):next.add(rawKey),this.selectedRowKeys=this.asKeySet(next);const rowKeys=this.asKeyList(Object.freeze([...next]));this.emit("lr-selection-change",Object.freeze({selectedRowKeys:rowKeys}))}}get hasAlwaysOnEditors(){return this.columns.some(col=>normalizedEditTrigger(col.editTrigger)==="always")}editorValue(row,column){const value=column.editValue?.(row)??row[column.key]??"";return String(value)}startEditing(rowKey,columnKey){const column=this.columnsByKey.get(columnKey);normalizedEditTrigger(column?.editTrigger)!=="double-click"||!this.rowsByKey.has(rowKey)||(this.editingCell={rowKey,columnKey})}commitEdit(event,rowKey,columnKey){event.stopPropagation();const field=event.currentTarget,entry=this.rowsByKey.get(rowKey),column=this.columnsByKey.get(columnKey),isTransient=this.editingCell?.rowKey===rowKey&&this.editingCell.columnKey===columnKey;if(!entry||!column||normalizedEditTrigger(column.editTrigger)===void 0){isTransient&&(this.editingCell=null);return}const value=column.editType==="number"&&field.value!==""?Number(field.value):field.value;this.emit("lr-cell-edit",Object.freeze({row:entry.row,columnKey,value})),isTransient&&(this.editingCell=null)}editorElementFor(rowKey,columnKey){return this.cellElementForToken(rowKey,columnKey)?.querySelector('[part="cell-editor"]')??null}restoreAlwaysOnEditorFocus(){const cell=this.focusedEditorCell;if(cell===null)return;const editor=this.editorElementFor(cell.rowKey,cell.columnKey);editor===null?this.focusedEditorCell=null:this.editorHadFocusBeforeUpdate&&shadowFocusTarget(this)!==editor&&editor.focus(),this.editorHadFocusBeforeUpdate=!1}activateExpandToggle(key){const entry=this.rowsByKey.get(encodeKey(key));if(entry===void 0)return;const expanded=!this._expandedKeys.has(key),detail=Object.freeze({row:entry.row,rowKey:key,expanded});if(this.expansionMode!=="single"&&this.expansionMode!=="multiple"){this.emit("lr-row-expand-toggle",detail);return}requestThenCommit({requestDetail:detail,emitRequest:(requestDetail,init)=>this.emit("lr-row-expand-request",requestDetail,init),commit:()=>{const next=this.expansionMode==="single"?new Set:new Set(this._expandedKeys);expanded?next.add(key):next.delete(key);const displaced=[...this._expandedKeys].filter(other=>other!==key&&!next.has(other));this.expandedRowKeys=this.asKeySet(next);for(const other of displaced){const displacedEntry=this.rowsByKey.get(encodeKey(other));displacedEntry!==void 0&&this.emit("lr-row-expand-toggle",Object.freeze({row:displacedEntry.row,rowKey:other,expanded:!1}))}this.emit("lr-row-expand-toggle",detail)}})}rowElement(rowKey){return this.rowElementForToken(encodeKey(rowKey))}cellElement(rowKey,columnKey){return this.cellElementForToken(encodeKey(rowKey),columnKey)}editCell(rowKey,columnKey){const token=encodeKey(rowKey),trigger=normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger);if(!(trigger===void 0||!this.rowsByKey.has(token))){if(trigger==="always"){this.editorElementFor(token,columnKey)?.focus();return}this.startEditing(token,columnKey)}}expandedContentElement(rowKey){const token=encodeKey(rowKey);return[...this.renderRoot.querySelectorAll("tbody tr[data-expanded-row-key]")].find(el=>el.dataset.expandedRowKey===token)?.querySelector('[part="expanded-cell"]')??null}rowElementForToken(token){return[...this.renderRoot.querySelectorAll("tbody tr[data-row-key]")].find(el=>el.dataset.rowKey===token)??null}cellElementForToken(token,columnKey){return[...this.rowElementForToken(token)?.querySelectorAll("td[data-col-key]")??[]].find(el=>el.dataset.colKey===columnKey)??null}visibleHeaders(){return[...this.renderRoot?.querySelectorAll("th[data-col-key]")??[]].filter(el=>el.offsetParent!==null)}focusHeader(el){el?.dataset.colKey&&(this.activeColKey=el.dataset.colKey,el.focus())}focusRow(el){el?.dataset.rowKey&&(this.activeRowKey=el.dataset.rowKey,el.focus())}onHeaderKeyDown(e,th){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateColumn(th.dataset.colKey);return}const headers=this.visibleHeaders(),index=headers.indexOf(th);if(index<0)return;const rtl=isRtl(this);switch(e.key){case"ArrowLeft":e.preventDefault(),this.focusHeader(headers[rtl?Math.min(headers.length-1,index+1):Math.max(0,index-1)]??null);return;case"ArrowRight":e.preventDefault(),this.focusHeader(headers[rtl?Math.max(0,index-1):Math.min(headers.length-1,index+1)]??null);return;case"Home":e.preventDefault(),this.focusHeader(headers[0]??null);return;case"End":e.preventDefault(),this.focusHeader(headers[headers.length-1]??null);return;case"ArrowDown":{e.preventDefault();const rows=[...this.renderRoot.querySelectorAll("[data-row-key]")],key=this.focusedRowKey();this.focusRow(rows.find(r=>r.dataset.rowKey===key)??rows[0]??null);return}default:return}}editableCellFor(target){const columnKey=target.dataset.colKey;return target.tagName!=="TD"||columnKey===void 0?null:normalizedEditTrigger(this.columnsByKey.get(columnKey)?.editTrigger)==="double-click"?{element:target,columnKey}:null}editableCellsInRow(tr){return[...tr.querySelectorAll("td[data-editable]")].filter(td=>td.offsetParent!==null&&!td.inert&&!td.closest("[inert]"))}onRowKeyDown(e,tr){const cell=this.editableCellFor(e.target);if((e.key==="Enter"||e.key==="F2")&&cell){e.preventDefault(),this.startEditing(tr.dataset.rowKey,cell.columnKey);return}if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateRow(tr.dataset.rowKey);return}if(e.key==="ArrowLeft"||e.key==="ArrowRight"){this.onRowLateralKeyDown(e,tr,cell);return}const bodyRows=[...this.renderRoot.querySelectorAll("[data-row-key]")],index=bodyRows.indexOf(tr);if(!(index<0))switch(e.key){case"ArrowDown":e.preventDefault(),this.focusRow(bodyRows[Math.min(bodyRows.length-1,index+1)]??null);return;case"ArrowUp":if(e.preventDefault(),index===0){const headers=this.visibleHeaders(),key=this.focusedColKey();this.focusHeader(headers.find(h=>h.dataset.colKey===key)??headers[0]??null)}else this.focusRow(bodyRows[index-1]??null);return;case"Home":e.preventDefault(),this.focusRow(bodyRows[0]??null);return;case"End":e.preventDefault(),this.focusRow(bodyRows[bodyRows.length-1]??null);return;default:return}}onRowLateralKeyDown(e,tr,cell){const cells=this.editableCellsInRow(tr);if(cells.length===0)return;e.preventDefault();const forward=e.key===(isRtl(this)?"ArrowLeft":"ArrowRight");if(cell===null){(forward?cells[0]:cells[cells.length-1])?.focus();return}const index=cells.indexOf(cell.element);forward?cells[index+1]?.focus():index<=0?this.focusRow(tr):cells[index-1]?.focus()}renderCellValue(col,row){return typeof col.cell=="function"?col.cell(row):(devWarnOnce(MISSING_CELL_RENDERER_WARNING,"<lr-table>: a column has no required `cell` renderer, so its cells render empty. Supply a `cell` callback for every column."),nothing)}renderCellEditor(row,col,rowKey,alwaysOn){const type=col.editType??"text",value=this.editorValue(row,col),label=col.editLabel?.(row)??this.localize("tableEditCell",void 0,{column:col.label}),onChange=event=>this.commitEdit(event,rowKey,col.key),onKeyDown=event=>this.onEditorKeyDown(event,rowKey,col.key);if(type==="select"){const options=col.editOptions??[];return html`<select
|
|
15
15
|
part="cell-editor"
|
|
16
16
|
aria-label=${label}
|
|
17
17
|
@change=${onChange}
|
|
@@ -11,7 +11,7 @@ import{__decorate}from"tslib";import{html,svg}from"lit";import{property}from"lit
|
|
|
11
11
|
aria-hidden="true"
|
|
12
12
|
focusable="false"
|
|
13
13
|
><polyline points="5 12.5 10 17.5 19 6.5"></polyline></svg>
|
|
14
|
-
`}class LyraOption extends LyraElement{constructor(){super(...arguments),this.slotPresence=new SlotPresenceController(this),this.optionInternals=attachInternalsSafely(this),this.hasHover=!1,this.hasCurrent=!1,this._label="",this.selectedValue=!1,this.defaultSelectedValue=!1,this.selectedDirty=!1,this.value="",this.disabled=!1,this.title="",this.group="",this.searchText="",this.sub="",this.dotColor="",this.labelTextObserver=new AccessibleTextController(this,[],records=>this.handleLabelRecords([...records]),["slot","title"]),this.observedDefaultLabel="",this.handlePointerEnter=()=>{this.hasHover=!0,this.syncOptionState()},this.handlePointerLeave=()=>{this.hasHover=!1,this.syncOptionState()},this.handleFocusIn=()=>{this.hasCurrent=!0,this.syncOptionState()},this.handleFocusOut=()=>{this.hasCurrent=!1,this.syncOptionState()},this.handleLabelMutation=(presentationChanged=!1)=>{const next=this.defaultLabel;next===this.observedDefaultLabel&&!presentationChanged||(this.observedDefaultLabel=next,this.requestUpdate(),this.emit("lr-option-change"))},this.handleLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.cachedDefaultLabel=void 0,this.labelTextObserver.bind(),this.handleLabelMutation())}}static{this.styles=[LyraElement.styles,styles]}get selected(){return this.selectedValue}set selected(next){this.setLiveSelected(next,!0),notifyOptionSelectedWrite(this,()=>this.emit("lr-option-change"))}get defaultSelected(){return this.defaultSelectedValue}set defaultSelected(next){const normalized=!!next,old=this.defaultSelectedValue;old!==normalized&&(this.defaultSelectedValue=normalized,this.selectedDirty||this.setLiveSelected(normalized,!1),this.requestUpdate("defaultSelected",old))}setLiveSelected(next,dirty){dirty&&(this.selectedDirty=!0,markOptionSelectedDirty(this,!0));const normalized=!!next,old=this.selectedValue;old!==normalized&&(this.selectedValue=normalized,this.requestUpdate("selected",old))}[SET_OPTION_SELECTED_FROM_OWNER](next){this.selectedDirty||markOptionSelectedDirty(this,!1),this.setLiveSelected(next,!1)}[RESET_OPTION_SELECTED_FROM_OWNER](next){this.selectedDirty=!1,markOptionSelectedDirty(this,!1),this.setLiveSelected(next,!1)}get label(){return this._label.trim()||this.defaultLabel}set label(next){const normalized=String(next??""),old=this._label;old!==normalized&&(this._label=normalized,this.requestUpdate("label",old))}get defaultLabel(){if(!("childNodes"in this))return"";const pending=this.labelTextObserver.takeRecords();if(pending.length){this.cachedDefaultLabel=void 0;const ownerDocument=this.ownerDocument;queueMicrotask(()=>{this.isConnected&&this.ownerDocument===ownerDocument&&this.handleLabelRecords(pending)})}return this.isConnected?this.cachedDefaultLabel??=this.computeDefaultLabel():this.computeDefaultLabel()}computeDefaultLabel(){const roots=Array.from(this.childNodes??[]).filter(node=>this.isDefaultLabelNode(node));return composedAccessibilityText(roots,{requireRendered:!1,shouldPruneNode:node=>!this.contains(node)&&!this.isSourceLabelVisible(node),skipRootAncestorValidation:!0}).replace(/\s+/g," ").trim()}isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}sourceParentForLabelNode(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root&&root.host.nodeType===1?root.host:null}isClosedSourceDetailsBranch(details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;const summary=Array.from(details.children).find(child=>child.localName==="summary");return branch!==summary}isSourceLabelVisible(node){const target=node.nodeType===1?node:this.sourceParentForLabelNode(node);if(!target?.isConnected||isAccessibilitySubtreeExcluded(target)||isAccessibilityVisibilityHidden(target))return!1;let branch=target,ancestor=this.sourceParentForLabelNode(target);for(;ancestor;){if(isAccessibilitySubtreeExcluded(ancestor)||this.isClosedSourceDetailsBranch(ancestor,branch))return!1;branch=ancestor,ancestor=this.sourceParentForLabelNode(ancestor)}return!0}connectedCallback(){super.connectedCallback(),this.addEventListener("pointerenter",this.handlePointerEnter),this.addEventListener("pointerleave",this.handlePointerLeave),this.addEventListener("focusin",this.handleFocusIn),this.addEventListener("focusout",this.handleFocusOut),this.syncOptionState(),this.addEventListener("slotchange",this.handleLabelSlotChange),this.cachedDefaultLabel=void 0,this.observedDefaultLabel=this.defaultLabel}disconnectedCallback(){this.removeEventListener("pointerenter",this.handlePointerEnter),this.removeEventListener("pointerleave",this.handlePointerLeave),this.removeEventListener("focusin",this.handleFocusIn),this.removeEventListener("focusout",this.handleFocusOut),this.removeEventListener("slotchange",this.handleLabelSlotChange),this.hasHover=!1,this.hasCurrent=!1,this.syncOptionState(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cachedDefaultLabel=void 0,this.labelTextObserver.adopted()}handleLabelRecords(records){this.cachedDefaultLabel=void 0;const presentationChanged=records.some(record=>{if(record.type==="attributes"&&record.attributeName==="inert"||record.type==="attributes"&&record.attributeName==="slot"&&this.contains(record.target))return!0;let node=record.target;for(;node&&node!==this&&node.parentNode!==this;)node=node.parentNode;return node&&node!==this&&!this.isDefaultLabelNode(node)?!0:record.type==="childList"&&record.target===this&&[...record.addedNodes,...record.removedNodes].some(child=>!this.isDefaultLabelNode(child))});this.handleLabelMutation(presentationChanged)}
|
|
14
|
+
`}class LyraOption extends LyraElement{constructor(){super(...arguments),this.slotPresence=new SlotPresenceController(this),this.optionInternals=attachInternalsSafely(this),this.hasHover=!1,this.hasCurrent=!1,this._label="",this.selectedValue=!1,this.defaultSelectedValue=!1,this.selectedDirty=!1,this.value="",this.disabled=!1,this.title="",this.group="",this.searchText="",this.sub="",this.dotColor="",this.labelTextObserver=new AccessibleTextController(this,[],records=>this.handleLabelRecords([...records]),["slot","title"]),this.observedDefaultLabel="",this.handlePointerEnter=()=>{this.hasHover=!0,this.syncOptionState()},this.handlePointerLeave=()=>{this.hasHover=!1,this.syncOptionState()},this.handleFocusIn=()=>{this.hasCurrent=!0,this.syncOptionState()},this.handleFocusOut=()=>{this.hasCurrent=!1,this.syncOptionState()},this.handleLabelMutation=(presentationChanged=!1)=>{const next=this.defaultLabel;next===this.observedDefaultLabel&&!presentationChanged||(this.observedDefaultLabel=next,this.requestUpdate(),this.emit("lr-option-change"))},this.handleLabelSlotChange=event=>{const target=event.target;target?.nodeType!==1||target.localName!=="slot"||target.getRootNode()!==this.renderRoot&&!this.labelForwardingSlots().includes(target)||(this.cachedDefaultLabel=void 0,this.labelTextObserver.bind(),this.handleLabelMutation())}}static{this.styles=[LyraElement.styles,styles]}get selected(){return this.selectedValue}set selected(next){this.setLiveSelected(next,!0),notifyOptionSelectedWrite(this,()=>this.emit("lr-option-change"))}get defaultSelected(){return this.defaultSelectedValue}set defaultSelected(next){const normalized=!!next,old=this.defaultSelectedValue;old!==normalized&&(this.defaultSelectedValue=normalized,this.selectedDirty||this.setLiveSelected(normalized,!1),this.requestUpdate("defaultSelected",old))}setLiveSelected(next,dirty){dirty&&(this.selectedDirty=!0,markOptionSelectedDirty(this,!0));const normalized=!!next,old=this.selectedValue;old!==normalized&&(this.selectedValue=normalized,this.requestUpdate("selected",old))}[SET_OPTION_SELECTED_FROM_OWNER](next){this.selectedDirty||markOptionSelectedDirty(this,!1),this.setLiveSelected(next,!1)}[RESET_OPTION_SELECTED_FROM_OWNER](next){this.selectedDirty=!1,markOptionSelectedDirty(this,!1),this.setLiveSelected(next,!1)}get label(){return this._label.trim()||this.defaultLabel}set label(next){const normalized=String(next??""),old=this._label;old!==normalized&&(this._label=normalized,this.requestUpdate("label",old))}get defaultLabel(){if(!("childNodes"in this))return"";const pending=this.labelTextObserver.takeRecords();if(pending.length){this.cachedDefaultLabel=void 0;const ownerDocument=this.ownerDocument;queueMicrotask(()=>{this.isConnected&&this.ownerDocument===ownerDocument&&this.handleLabelRecords(pending)})}return this.isConnected?this.cachedDefaultLabel??=this.computeDefaultLabel():this.computeDefaultLabel()}computeDefaultLabel(){const roots=Array.from(this.childNodes??[]).filter(node=>this.isDefaultLabelNode(node));return composedAccessibilityText(roots,{requireRendered:!1,shouldPruneNode:node=>!this.contains(node)&&!this.isSourceLabelVisible(node),skipRootAncestorValidation:!0}).replace(/\s+/g," ").trim()}isDefaultLabelNode(node){if(node.nodeType!==1)return!0;const slotName=node.getAttribute("slot");return slotName===null||slotName===""}labelForwardingSlots(){return Array.from(this.querySelectorAll("slot")).filter(slot=>{let top=slot;for(;top.parentNode&&top.parentNode!==this;)top=top.parentNode;return top.parentNode===this&&this.isDefaultLabelNode(top)})}sourceParentForLabelNode(node){if(node.parentElement)return node.parentElement;const root=node.getRootNode();return"host"in root&&root.host.nodeType===1?root.host:null}isClosedSourceDetailsBranch(details,branch){if(details.localName!=="details"||details.hasAttribute("open")||branch===null)return!1;const summary=Array.from(details.children).find(child=>child.localName==="summary");return branch!==summary}isSourceLabelVisible(node){const target=node.nodeType===1?node:this.sourceParentForLabelNode(node);if(!target?.isConnected||isAccessibilitySubtreeExcluded(target)||isAccessibilityVisibilityHidden(target))return!1;let branch=target,ancestor=this.sourceParentForLabelNode(target);for(;ancestor;){if(isAccessibilitySubtreeExcluded(ancestor)||this.isClosedSourceDetailsBranch(ancestor,branch))return!1;branch=ancestor,ancestor=this.sourceParentForLabelNode(ancestor)}return!0}connectedCallback(){super.connectedCallback(),this.addEventListener("pointerenter",this.handlePointerEnter),this.addEventListener("pointerleave",this.handlePointerLeave),this.addEventListener("focusin",this.handleFocusIn),this.addEventListener("focusout",this.handleFocusOut),this.syncOptionState(),this.addEventListener("slotchange",this.handleLabelSlotChange),this.cachedDefaultLabel=void 0,this.observedDefaultLabel=this.defaultLabel}disconnectedCallback(){this.removeEventListener("pointerenter",this.handlePointerEnter),this.removeEventListener("pointerleave",this.handlePointerLeave),this.removeEventListener("focusin",this.handleFocusIn),this.removeEventListener("focusout",this.handleFocusOut),this.removeEventListener("slotchange",this.handleLabelSlotChange),this.hasHover=!1,this.hasCurrent=!1,this.syncOptionState(),super.disconnectedCallback()}adoptedCallback(){super.adoptedCallback(),this.cachedDefaultLabel=void 0,this.labelTextObserver.adopted()}handleLabelRecords(records){this.cachedDefaultLabel=void 0;const presentationChanged=records.some(record=>{if(record.type==="attributes"&&record.attributeName==="inert"||record.type==="attributes"&&record.attributeName==="slot"&&this.contains(record.target))return!0;let node=record.target;for(;node&&node!==this&&node.parentNode!==this;)node=node.parentNode;return node&&node!==this&&!this.isDefaultLabelNode(node)?!0:record.type==="childList"&&record.target===this&&[...record.addedNodes,...record.removedNodes].some(child=>!this.isDefaultLabelNode(child))});this.handleLabelMutation(presentationChanged)}shouldUpdate(changed){return this.hasUpdated&&changed.size===1&&changed.has("label")&&!this.labelTextObserver.hasDrainedRecords()?(queueMicrotask(()=>this.emit("lr-option-change")),!1):super.shouldUpdate(changed)}updated(changed){super.updated(changed),changed.has("disabled")&&this.disabled&&(this.hasCurrent=!1),this.syncOptionState(),(changed.has("value")||changed.has("disabled")||changed.has("group")||changed.has("title")||changed.has("searchText")||changed.has("sub")||changed.has("dotColor")||changed.has("label")||changed.has("defaultSelected")||changed.has("data"))&&this.emit("lr-option-change")}syncOptionState(){this.optionInternals.role="option",this.optionInternals.ariaSelected=this.selected?"true":"false",this.optionInternals.ariaDisabled=this.disabled?"true":"false",setCustomState(this.optionInternals,"current",this.hasCurrent&&!this.disabled),setCustomState(this.optionInternals,"selected",this.selected),setCustomState(this.optionInternals,"disabled",this.disabled),setCustomState(this.optionInternals,"hover",this.hasHover&&!this.disabled)}getTextLabel(){return this.defaultLabel}render(){const hasStart=this.slotPresence.has("start")||this.slotPresence.has("prefix"),hasEnd=this.slotPresence.has("end")||this.slotPresence.has("suffix");return html`
|
|
15
15
|
<div part="base">
|
|
16
16
|
<span part="checked-icon" aria-hidden="true" inert ?hidden=${!this.selected}>
|
|
17
17
|
${checkmarkGlyph()}
|
|
@@ -38,7 +38,7 @@ import{__decorate}from"tslib";import{requestThenCommit}from"../../../internal/re
|
|
|
38
38
|
>
|
|
39
39
|
${closeIcon()}
|
|
40
40
|
</button>
|
|
41
|
-
</span>`}render(){const options=this.listboxOptions,navigable=this.navigableOptions(options),active=this.activeIndex>=0?navigable[this.activeIndex]:void 0,activeId=active?`${this.listId}-opt-${options.indexOf(active)}`:"",selectedLabel=this._selected.length>0?this.labelFor(this._selected[0]):"",selectedLabels=this._selected.map((value,index)=>this.labelFor(value,index)).join(", "),hasValue=this._selected.length>0&&(this.multiple||this._selected[0]!==""||this.resolvedLabelFor("",0)!==void 0),emptyDisplayText=this.loading?this.localize("loading"):this.placeholder,singleValueUnknown=hasValue&&!this.multiple&&this.isUnknownValue(this._selected[0]),shownValues=this.maxOptionsVisible>0?this._selected.slice(0,this.maxOptionsVisible):this._selected,overflow=this._selected.length-shownValues.length,showClear=(this.withClear||this.clearable)&&hasValue,hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,isSingleOption=this.autoCommitSingleOption&&navigable.length===1,requiredTextId=`${this.triggerId}-required`,describedBy=this.localDescriptionIds=[this.required&&isSingleOption?requiredTextId:"",this.multiple&&hasValue?this.valueTextId:"",hasError?"select-error":"",hasHint?"select-hint":""].filter(Boolean).join(" ");return html`
|
|
41
|
+
</span>`}render(){const options=this.listboxOptions,navigable=this.open||this.autoCommitSingleOption||this.activeIndex>=0?this.navigableOptions(options):[],active=this.activeIndex>=0?navigable[this.activeIndex]:void 0,activeId=active?`${this.listId}-opt-${options.indexOf(active)}`:"",selectedLabel=this._selected.length>0?this.labelFor(this._selected[0]):"",selectedLabels=this._selected.map((value,index)=>this.labelFor(value,index)).join(", "),hasValue=this._selected.length>0&&(this.multiple||this._selected[0]!==""||this.resolvedLabelFor("",0)!==void 0),emptyDisplayText=this.loading?this.localize("loading"):this.placeholder,singleValueUnknown=hasValue&&!this.multiple&&this.isUnknownValue(this._selected[0]),shownValues=this.maxOptionsVisible>0?this._selected.slice(0,this.maxOptionsVisible):this._selected,overflow=this._selected.length-shownValues.length,showClear=(this.withClear||this.clearable)&&hasValue,hasHint=this.slotPresence.has("hint")||this.slotPresence.has("help-text")||(this.hint??"").length>0||(this.helpText??"").length>0||this.withHint,hasError=this.slotPresence.has("error")||(this.errorText??"").length>0,hasLabel=this.slotPresence.has("label")||(this.label??"").length>0||this.withLabel,isSingleOption=this.autoCommitSingleOption&&navigable.length===1,requiredTextId=`${this.triggerId}-required`,describedBy=this.localDescriptionIds=[this.required&&isSingleOption?requiredTextId:"",this.multiple&&hasValue?this.valueTextId:"",hasError?"select-error":"",hasHint?"select-hint":""].filter(Boolean).join(" ");return html`
|
|
42
42
|
<div part="form-control">
|
|
43
43
|
<label
|
|
44
44
|
part="form-control-label"
|
|
@@ -2,7 +2,11 @@ import type{Feature}from'geojson';export interface MapLibreGeoJsonSource{setData
|
|
|
2
2
|
/** maplibre-gl 3+ incremental update. Optional because older peers lack it. */
|
|
3
3
|
updateData?(diff:MapLibreGeoJsonDiff):void;}
|
|
4
4
|
/** The subset of maplibre-gl's GeoJSON diff this component emits. */
|
|
5
|
-
export interface MapLibreGeoJsonDiff{readonly remove?:readonly(string|number)[];readonly add?:readonly Feature[];readonly update:readonly{readonly id:string|number;readonly addOrUpdateProperties:readonly{readonly key:string;readonly value:unknown;}[];readonly removeProperties:readonly string[];}[];}export interface MapLibrePopupCapability{setHTML(html:string):this;setText(text:string):this;on?(type:'open'|'close',listener:()=>void):this;isOpen?():boolean;getElement?():HTMLElement|undefined;options?:{focusAfterOpen?:boolean;};}export interface MapLibreMarkerCapability{setLngLat(lngLat:[number,number]):this;setPopup(popup?:MapLibrePopupCapability):this;getPopup():MapLibrePopupCapability|undefined;addTo(map:MapLibreMapCapability):this;remove():void;getElement?():HTMLElement;}
|
|
5
|
+
export interface MapLibreGeoJsonDiff{readonly remove?:readonly(string|number)[];readonly add?:readonly Feature[];readonly update:readonly{readonly id:string|number;readonly addOrUpdateProperties:readonly{readonly key:string;readonly value:unknown;}[];readonly removeProperties:readonly string[];}[];}export interface MapLibrePopupCapability{setHTML(html:string):this;setText(text:string):this;on?(type:'open'|'close',listener:()=>void):this;isOpen?():boolean;getElement?():HTMLElement|undefined;options?:{focusAfterOpen?:boolean;};}export interface MapLibreMarkerCapability{setLngLat(lngLat:[number,number]):this;setPopup(popup?:MapLibrePopupCapability):this;getPopup():MapLibrePopupCapability|undefined;addTo(map:MapLibreMapCapability):this;remove():void;getElement?():HTMLElement;}
|
|
6
|
+
/** Actual source, layer, projection and terrain descriptors to prepare before synchronous mutations. */
|
|
7
|
+
export interface LyraMapFeatureRequirements{readonly sources?:Readonly<Record<string,unknown>>;readonly layers?:readonly unknown[];readonly projection?:unknown;readonly terrain?:unknown;}export interface MapLibreMapCapability{
|
|
8
|
+
/** Present on the modular engine; canonical MapLibre does not expose this method. */
|
|
9
|
+
prepareFeatures?(requirements:LyraMapFeatureRequirements,options?:{signal?:AbortSignal;}):Promise<void>;
|
|
6
10
|
/** Required, unlike setMaxBounds below: the loader validates getCanvas is callable and rejects a
|
|
7
11
|
* peer without it, so holding this type already implies the method is present. Call sites still
|
|
8
12
|
* guard with `?.()` against a peer that satisfies the shape check and then lies at runtime. */
|
|
@@ -27,3 +31,7 @@ export interface MaplibreModule{Map:new(options:Record<string,unknown>)=>MapLibr
|
|
|
27
31
|
* for their bundler once they install the peer; v5's standard build includes its worker.
|
|
28
32
|
*/
|
|
29
33
|
export declare function loadMaplibre():Promise<MaplibreModule|null>;
|
|
34
|
+
/** The companion additionally provides per-map main-thread and worker readiness. */
|
|
35
|
+
export interface ModularMapModule extends MaplibreModule{Map:new(options:Record<string,unknown>)=>MapLibreMapCapability&{prepareFeatures(requirements:LyraMapFeatureRequirements,options?:{signal?:AbortSignal;}):Promise<void>;};}
|
|
36
|
+
/** Lazily loads the modular companion once per page. A failed load never selects another engine. */
|
|
37
|
+
export declare function loadModularMap():Promise<ModularMapModule|null>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolveOptionalPeerCapability,unwrapOptionalPeerDefault}from"../../../internal/optional-peer-capabilities.js";const MAP_METHODS=["getCanvas","getCenter","getZoom","setCenter","setZoom","resize","remove","on","once","setStyle","getSource","addSource","removeSource","getLayer","addLayer","removeLayer","setPaintProperty","queryRenderedFeatures"],MARKER_METHODS=["setLngLat","setPopup","getPopup","addTo","remove"],POPUP_METHODS=["setHTML","setText"];function isObjectLike(value){return(typeof value=="object"||typeof value=="function")&&value!==null}function isConstructor(value){if(typeof value!="function")return!1;try{return Reflect.construct(Object,[],value),!0}catch{return!1}}function missingConstructorCapability(module,name,methods){const Constructor=module[name];if(!isConstructor(Constructor))return name;const prototype=Constructor.prototype;if(!isObjectLike(prototype))return`${name}.prototype`;for(const method of methods)if(typeof prototype[method]!="function")return`${name}.prototype.${method}`}function missingMaplibreCapability(candidate){return isObjectLike(candidate)?missingConstructorCapability(candidate,"Map",MAP_METHODS)??missingConstructorCapability(candidate,"Marker",MARKER_METHODS)??missingConstructorCapability(candidate,"Popup",POPUP_METHODS):"module namespace"}function isMaplibreModule(candidate){return missingMaplibreCapability(candidate)===void 0}function resolveMaplibreModule(value){const module=resolveOptionalPeerCapability(value,isMaplibreModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"module namespace";throw new Error(`Invalid optional peer \`maplibre-gl\`: missing or invalid \`${missing}\` capability.`)}let maplibre;async function loadMaplibreModule(importer=()=>import("maplibre-gl")){try{return resolveMaplibreModule(await importer())}catch(error){return console.warn("<lr-map> needs the optional peer dependency `maplibre-gl` — install it with `pnpm add maplibre-gl`.",error),null}}function loadMaplibre(){return maplibre||(maplibre=loadMaplibreModule()),maplibre}export{loadMaplibre,loadMaplibreModule};
|
|
1
|
+
import{resolveOptionalPeerCapability,unwrapOptionalPeerDefault}from"../../../internal/optional-peer-capabilities.js";const MAP_METHODS=["getCanvas","getCenter","getZoom","setCenter","setZoom","resize","remove","on","once","setStyle","getSource","addSource","removeSource","getLayer","addLayer","removeLayer","setPaintProperty","queryRenderedFeatures"],MARKER_METHODS=["setLngLat","setPopup","getPopup","addTo","remove"],POPUP_METHODS=["setHTML","setText"];function isObjectLike(value){return(typeof value=="object"||typeof value=="function")&&value!==null}function isConstructor(value){if(typeof value!="function")return!1;try{return Reflect.construct(Object,[],value),!0}catch{return!1}}function missingConstructorCapability(module,name,methods){const Constructor=module[name];if(!isConstructor(Constructor))return name;const prototype=Constructor.prototype;if(!isObjectLike(prototype))return`${name}.prototype`;for(const method of methods)if(typeof prototype[method]!="function")return`${name}.prototype.${method}`}function missingMaplibreCapability(candidate){return isObjectLike(candidate)?missingConstructorCapability(candidate,"Map",MAP_METHODS)??missingConstructorCapability(candidate,"Marker",MARKER_METHODS)??missingConstructorCapability(candidate,"Popup",POPUP_METHODS):"module namespace"}function isMaplibreModule(candidate){return missingMaplibreCapability(candidate)===void 0}function resolveMaplibreModule(value){const module=resolveOptionalPeerCapability(value,isMaplibreModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"module namespace";throw new Error(`Invalid optional peer \`maplibre-gl\`: missing or invalid \`${missing}\` capability.`)}let maplibre,maplibreCapabilities;async function loadMaplibreModule(importer=()=>import("maplibre-gl").then(source=>maplibreCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup},get setWorkerUrl(){return source.setWorkerUrl},get getVersion(){return source.getVersion},get default(){return source.default}}))){try{return resolveMaplibreModule(await importer())}catch(error){return console.warn("<lr-map> needs the optional peer dependency `maplibre-gl` — install it with `pnpm add maplibre-gl`.",error),null}}function loadMaplibre(){return maplibre||(maplibre=loadMaplibreModule()),maplibre}function isModularMapModule(candidate){return isMaplibreModule(candidate)&&typeof candidate.Map.prototype.prepareFeatures=="function"}let modularMapCapabilities;async function loadModularMapModule(importer=()=>import("@aceshooting/lyra-map").then(source=>modularMapCapabilities??=Object.freeze({get Map(){return source.Map},get Marker(){return source.Marker},get Popup(){return source.Popup}}))){try{const value=await importer(),module=resolveOptionalPeerCapability(value,isModularMapModule);if(module)return module;const candidate=unwrapOptionalPeerDefault(value),missing=missingMaplibreCapability(candidate)??"Map.prototype.prepareFeatures";throw new Error(`Invalid optional peer \`@aceshooting/lyra-map\`: missing or invalid \`${missing}\` capability.`)}catch(error){return console.warn("<lr-map> needs the optional peer dependency `@aceshooting/lyra-map` — install it with `pnpm add @aceshooting/lyra-map`.",error),null}}let modularMap;function loadModularMap(){return modularMap??=loadModularMapModule()}export{loadMaplibre,loadMaplibreModule,loadModularMap,loadModularMapModule};
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import{type TemplateResult,type PropertyValues}from'lit';import type{Feature,FeatureCollection}from'geojson';import{LyraElement}from'../../../internal/lyra-element.js';export{buildGeoJsonPropertyDiff}from'./map-geojson-diff.js';import'../../overlays/skeleton/skeleton.class.js';
|
|
1
|
+
import{type TemplateResult,type PropertyValues}from'lit';import type{Feature,FeatureCollection}from'geojson';import{LyraElement}from'../../../internal/lyra-element.js';import{type LyraMapFeatureRequirements}from'./map-loader.js';export{buildGeoJsonPropertyDiff}from'./map-geojson-diff.js';import'../../overlays/skeleton/skeleton.class.js';export type{LyraMapFeatureRequirements}from'./map-loader.js';
|
|
2
|
+
/** Map engine selected before connecting the component. */
|
|
3
|
+
export type LyraMapEngine='modular'|'maplibre';
|
|
2
4
|
/** Non-color encoding retained when a legend entry's authored color is unavailable. */
|
|
3
5
|
export type LyraMapLegendPattern='solid'|'diagonal'|'dots'|'crosshatch';
|
|
4
6
|
/**
|
|
@@ -352,12 +354,15 @@ readonly marker:LyraMapMarker;
|
|
|
352
354
|
/** Whether activation came through click/pointer semantics or the keyboard contract. */
|
|
353
355
|
readonly source:LyraMapMarkerActivationSource;}
|
|
354
356
|
/** Peer-neutral subset of a MapLibre style accepted by `mapStyle`. */
|
|
355
|
-
export interface LyraMapStyleSpecification{readonly version:8;readonly sources:Readonly<Record<string,unknown>>;readonly layers:readonly unknown[];readonly name?:string;readonly sprite?:string|readonly Readonly<{id:string;url:string;}>[];readonly glyphs?:string;}
|
|
357
|
+
export interface LyraMapStyleSpecification{readonly version:8;readonly sources:Readonly<Record<string,unknown>>;readonly layers:readonly unknown[];readonly name?:string;readonly sprite?:string|readonly Readonly<{id:string;url:string;}>[];readonly glyphs?:string;readonly projection?:unknown;readonly terrain?:unknown;}
|
|
356
358
|
/**
|
|
357
359
|
* Common imperative map capability returned by `LyraMap.map` without making
|
|
358
360
|
* `maplibre-gl` a declaration dependency for consumers.
|
|
359
361
|
*/
|
|
360
|
-
export interface LyraMapInstance{
|
|
362
|
+
export interface LyraMapInstance{
|
|
363
|
+
/** Modular-engine readiness before imperative source/layer/projection/terrain mutations.
|
|
364
|
+
* Absent when `engine="maplibre"` selects the canonical engine. */
|
|
365
|
+
prepareFeatures?(requirements:LyraMapFeatureRequirements,options?:{signal?:AbortSignal;}):Promise<void>;getCanvas():HTMLCanvasElement;getCenter():{lng:number;lat:number;};getZoom():number;setCenter(center:[number,number]):unknown;setZoom(zoom:number):unknown;resize():unknown;
|
|
361
366
|
/**
|
|
362
367
|
* Deliberately `unknown` rather than `LyraMapBounds | null`. This interface is the peer-neutral
|
|
363
368
|
* surface the real maplibre `Map` must structurally satisfy, and maplibre spells this parameter
|
|
@@ -434,16 +439,16 @@ readonly origin:'choropleth'|'data-layer'|'cluster'|undefined;
|
|
|
434
439
|
* (which has only one possible source) and when nothing was hit. */
|
|
435
440
|
readonly sourceId:string|undefined;}>;}
|
|
436
441
|
/**
|
|
437
|
-
* `<lr-map>` — a
|
|
442
|
+
* `<lr-map>` — a modular MapLibre-compatible wrapper with a declarative legend, choropleth
|
|
438
443
|
* GeoJSON layer, markers, and additive `dataLayers` GeoJSON overlays
|
|
439
444
|
* (arbitrary shapes rendered as a source plus fill/line/circle layers, or — opting in per entry —
|
|
440
445
|
* as a natively clustered point set or a `heatmap` density surface,
|
|
441
446
|
* independent of `choropleth`'s field/stops color-interpolation), plus a peer-neutral
|
|
442
447
|
* `map` getter for common imperative operations. Its runtime value is the underlying MapLibre
|
|
443
|
-
* map, while its declaration stays independent of the optional peer.
|
|
444
|
-
*
|
|
445
|
-
*
|
|
446
|
-
*
|
|
448
|
+
* map, while its declaration stays independent of the optional peer. The default engine requires
|
|
449
|
+
* `@aceshooting/lyra-map` with its bundler plugin or an explicit worker URL. `engine="maplibre"`
|
|
450
|
+
* selects the full optional `maplibre-gl` peer (v5 or v6). Both engines require WebGL2; the
|
|
451
|
+
* component styles generated canvas, marker, popup, and control DOM inside its shadow root.
|
|
447
452
|
*
|
|
448
453
|
* The underlying `maplibregl.Map` — and the WebGL context it opens — isn't
|
|
449
454
|
* constructed until this element is first visible in the viewport (tracked
|
|
@@ -608,7 +613,7 @@ protected static readonly identityCollectionProperties:readonly string[];protect
|
|
|
608
613
|
/** Starts the shared optional-peer import without constructing a map. Returns false when the
|
|
609
614
|
* peer is unavailable, so applications can decide whether to render their own fallback before
|
|
610
615
|
* connecting an element. */
|
|
611
|
-
static preload():Promise<boolean>;constructor();
|
|
616
|
+
static preload(engine?:LyraMapEngine):Promise<boolean>;constructor();
|
|
612
617
|
/** Initial and controlled map center as `[longitude, latitude]`. Once the camera settles after
|
|
613
618
|
* a user gesture or `fitBounds()`, it holds that camera (see `lr-map-view-change`), so a map
|
|
614
619
|
* rebuilt after a reconnect opens where the user left it. Assigning a value the map already
|
|
@@ -758,7 +763,11 @@ markers:readonly LyraMapMarker[];
|
|
|
758
763
|
dataLayers:readonly LyraMapGeoJsonDataLayer[];private _canonicalChoroplethSource;private _canonicalChoropleth;private _canonicalDataLayersSource;private _canonicalDataLayers;private _canonicalMarkersSource;private _canonicalMarkers;private get canonicalChoropleth();private get canonicalDataLayers();private get canonicalMarkers();
|
|
759
764
|
/** Accessible name for MapLibre's focusable canvas; a host `aria-label` wins. Defaults to the
|
|
760
765
|
* localized `map` message, which an explicit empty string suppresses. */
|
|
761
|
-
label?:string;
|
|
766
|
+
label?:string;
|
|
767
|
+
/** Optional engine. Set before connecting; changes take effect after disconnect/reconnect.
|
|
768
|
+
* `modular` loads `@aceshooting/lyra-map`; `maplibre` explicitly selects the full `maplibre-gl`
|
|
769
|
+
* peer. No engine is substituted when the selected peer is unavailable. */
|
|
770
|
+
engine:LyraMapEngine;private loading;private failure?;private readonly announcements;private loadLibrary;private visible;private intersectionObserver?;private containerEl?;private _map?;private _styleLoaded;private _appliedChoroplethSourceId?;private _appliedFillLayerId?;private _appliedDataLayerIds;private _appliedDataLayerShapes;private _appliedGeoJson;private _nextDataLayerId;private nextPointIconId;private appliedPointPaint;private appliedPointMuting;private appliedPointIcons;private _maplibreModule?;private _webglReady;private _markerInstances;private _markerLabels;private _markerPopupIds;private readonly markerActivationDetails;private _configuredPopups;private _nextPopupId;private peerChromeObserver?;private observedPeerContainer?;private mapResizeObserver?;private observedMapContainer?;private _markerColors;private _markerSources;private _connectGeneration;private _styleGeneration;private featureGeneration;private featureAbort?;private preparingFeatures;private preparedFeatureSignature?;private pendingMapLoad;private rebuildGeneratedLayers;
|
|
762
771
|
/** The underlying runtime `maplibregl.Map`, declared through Lyra's peer-neutral common-method
|
|
763
772
|
* subset so consumers do not acquire a mandatory `maplibre-gl` type dependency. Consumers that
|
|
764
773
|
* install the optional peer may explicitly narrow this value to its full `Map` type. */
|
|
@@ -797,7 +806,7 @@ get map():LyraMapInstance|undefined;private pushGeoJson;private get safeMaxBound
|
|
|
797
806
|
* Returns `false`, without moving or queueing anything, when `bounds` is unusable or the loaded
|
|
798
807
|
* peer cannot fit a box, and `true` once the fit is running or queued.
|
|
799
808
|
*/
|
|
800
|
-
fitBounds(bounds:LyraMapBounds,options?:LyraMapFitBoundsOptions):boolean;private applyFit;private applyPendingFit;private reflectCamera;private pushCamera;private writeCamera;connectedCallback():void;disconnectedCallback():void;private failureMessage;private failInitialization;private scheduleStyleRequiredFailure;private disposeMap;adoptedCallback():void;private tryConstructMap;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;protected updated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;private refreshThemePaint;private applyChoropleth;private choroplethColorExpression;private resolveChoroplethSourceId;private removeChoropleth;private applyDataLayers;private applyDataLayerRendering;private paintDataLayer;private applyGeometryLayers;private paintGeometryLayers;private lineColor;private mutedPointOpacity;private paintPoints;private pointIconColor;private removePointIcons;private applyPointIcons;private paintPointIcons;private clusterColorExpression;private applyClusterLayers;private paintClusterLayers;private applyHeatmapLayer;private paintHeatmapLayer;private heatmapColorExpression;private styleProvidesGlyphs;private resolveDataLayerSourceId;private removeDataLayer;private applyMarkers;private readonly configuredMarkerElements;private configureMarkerInteraction;private emitMarkerActivation;private get effectiveMapLabel();private popupId;private configurePopupSemantics;private stopObservingMapAllocation;private observeMapAllocation;private stopObservingPeerChrome;private peerControlsResizeObserver?;private peerControlsResizeFrame?;private schedulePeerControlInsets;private measurePeerControlInsets;private syncPeerChromeParts;private observePeerChrome;private syncPopupSemantics;private syncMapSemantics;private formatCount;private legendLimitText;private onLegendSlotChange;
|
|
809
|
+
fitBounds(bounds:LyraMapBounds,options?:LyraMapFitBoundsOptions):boolean;private applyFit;private applyPendingFit;private reflectCamera;private pushCamera;private writeCamera;connectedCallback():void;disconnectedCallback():void;private failureMessage;private failInitialization;private scheduleStyleRequiredFailure;private disposeMap;adoptedCallback():void;private tryConstructMap;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;protected updated(changed:PropertyValues):void;protected willUpdate(changed:PropertyValues):void;private refreshThemePaint;private cancelFeaturePreparation;private generatedFeatureRequirements;private reconcileGeneratedLayers;private applyChoropleth;private choroplethColorExpression;private resolveChoroplethSourceId;private removeChoropleth;private applyDataLayers;private applyDataLayerRendering;private paintDataLayer;private applyGeometryLayers;private paintGeometryLayers;private lineColor;private mutedPointOpacity;private paintPoints;private pointIconColor;private removePointIcons;private applyPointIcons;private paintPointIcons;private clusterColorExpression;private applyClusterLayers;private paintClusterLayers;private applyHeatmapLayer;private paintHeatmapLayer;private heatmapColorExpression;private styleProvidesGlyphs;private resolveDataLayerSourceId;private removeDataLayer;private applyMarkers;private readonly configuredMarkerElements;private configureMarkerInteraction;private emitMarkerActivation;private get effectiveMapLabel();private popupId;private configurePopupSemantics;private stopObservingMapAllocation;private observeMapAllocation;private stopObservingPeerChrome;private peerControlsResizeObserver?;private peerControlsResizeFrame?;private schedulePeerControlInsets;private measurePeerControlInsets;private syncPeerChromeParts;private observePeerChrome;private syncPopupSemantics;private syncMapSemantics;private formatCount;private legendLimitText;private onLegendSlotChange;
|
|
801
810
|
/**
|
|
802
811
|
* The continuous gradient bar plus its two endpoint captions, or nothing when `legendGradient`
|
|
803
812
|
* holds fewer than two usable stops. Part names mirror `lr-heatmap`'s
|