@aceshooting/lyra-ui 11.0.0 → 11.1.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 +83 -0
- package/custom-elements.json +1 -1
- package/dist/components/charts/chart/lite-chart.class.d.ts +32 -0
- package/dist/components/charts/chart/lite-chart.class.js +17 -4
- package/dist/components/charts/chart/lite-chart.styles.js +29 -0
- package/dist/components/data/table/table.class.d.ts +19 -0
- package/dist/components/data/table/table.class.js +3 -3
- package/dist/components/forms/date-picker/date-input.class.d.ts +12 -1
- package/dist/components/forms/date-picker/date-input.class.js +4 -2
- package/dist/components/forms/date-picker/date-picker.class.d.ts +30 -4
- package/dist/components/forms/date-picker/date-picker.class.js +4 -4
- package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
- package/dist/custom-elements-jsx.d.ts +4 -2
- package/dist/internal/canvas.js +1 -1
- package/dist/internal/package-metadata.d.ts +1 -1
- package/dist/internal/package-metadata.js +1 -1
- package/dist/svelte.d.ts +4 -2
- package/dist/theme.css +32 -0
- package/dist/vue.d.ts +4 -2
- package/llms/components/lr-agent-eval-dashboard.md +1 -1
- package/llms/components/lr-agent-workspace.md +1 -1
- package/llms/components/lr-box-plot.md +2 -2
- package/llms/components/lr-chart.md +1 -1
- package/llms/components/lr-chunk-inspector.md +1 -1
- package/llms/components/lr-combobox.md +3 -3
- package/llms/components/lr-date-input.md +22 -6
- package/llms/components/lr-date-picker.md +21 -5
- package/llms/components/lr-entity-dossier.md +1 -1
- package/llms/components/lr-eval-run.md +1 -1
- package/llms/components/lr-grounding-summary.md +1 -1
- package/llms/components/lr-heatmap.md +2 -2
- package/llms/components/lr-lite-chart.md +19 -3
- package/llms/components/lr-map.md +2 -2
- package/llms/components/lr-memory-panel.md +1 -1
- package/llms/components/lr-option.md +3 -3
- package/llms/components/lr-popover.md +1 -1
- package/llms/components/lr-provenance-panel.md +1 -1
- package/llms/components/lr-rag-answer.md +1 -1
- package/llms/components/lr-rag-eval-dashboard.md +1 -1
- package/llms/components/lr-retrieval-results.md +1 -1
- package/llms/components/lr-retrieval-trace.md +1 -1
- package/llms/peers.md +8 -8
- package/llms/tokens.md +12 -0
- package/llms-full.txt +48 -16
- package/package.json +1 -1
- package/vscode-css-data.json +14 -0
- package/vscode-html-data.json +16 -2
- package/web-types.json +29 -3
|
@@ -126,6 +126,12 @@ export interface LyraLiteChartEventMap {
|
|
|
126
126
|
* @csspart legend-text - Extra per-item text after the series label, rendered only when `legendText` is set.
|
|
127
127
|
* @csspart live-region - The current mark announcement for keyboard users.
|
|
128
128
|
* @csspart data-list - A visually hidden sampled list of plotted data points (single-series only).
|
|
129
|
+
* @csspart data-table-toggle - The disclosure button rendered by `dataTableToggle`.
|
|
130
|
+
* @cssprop [--lr-lite-chart-data-table-toggle-hover-bg=var(--lr-color-brand-quiet)] - Hover
|
|
131
|
+
* background of the `dataTableToggle` disclosure button.
|
|
132
|
+
* @cssprop --lr-lite-chart-data-table-toggle-active-bg - Pressed background of the
|
|
133
|
+
* `dataTableToggle` disclosure button; defaults to a mix of the hover background with the shared
|
|
134
|
+
* active mix partner.
|
|
129
135
|
* @csspart data-table - A visually hidden sampled category×series data table, rendered instead of
|
|
130
136
|
* `data-list` when there is more than one dataset so a screen-reader user hears series grouping
|
|
131
137
|
* rather than one flattened N×M sequence.
|
|
@@ -186,6 +192,32 @@ export declare class LyraLiteChart extends LyraElement<LyraLiteChartEventMap> {
|
|
|
186
192
|
/** Adds a localized total column to the built-in multi-series accessible table for a stacked
|
|
187
193
|
* bar chart. Ignored for grouped bars and line charts. */
|
|
188
194
|
tableTotals: boolean;
|
|
195
|
+
/**
|
|
196
|
+
* Makes the generated data table visible; it stays screen-reader available when false. Same
|
|
197
|
+
* meaning as `<lr-chart>`'s property of the same name.
|
|
198
|
+
* @default false
|
|
199
|
+
*/
|
|
200
|
+
showDataTable: boolean;
|
|
201
|
+
/**
|
|
202
|
+
* Render a disclosure button above the accessible data table so a sighted reader can reveal the
|
|
203
|
+
* numbers on demand, turning `showDataTable` into the disclosure's INITIAL state rather than its
|
|
204
|
+
* whole behavior. The table stays in the DOM in both states, so assistive technology never loses
|
|
205
|
+
* it.
|
|
206
|
+
*
|
|
207
|
+
* Matters more here than on `<lr-chart>`: this component exists to avoid the Chart.js peers, so
|
|
208
|
+
* without it an app that chose it for that reason had to either hand-roll a `<details>` around a
|
|
209
|
+
* duplicated table or adopt `<lr-chart>` and pull in Chart.js for a button — the cheap component
|
|
210
|
+
* stuck with the expensive workaround.
|
|
211
|
+
* @default false
|
|
212
|
+
*/
|
|
213
|
+
dataTableToggle: boolean;
|
|
214
|
+
/** Live disclosure state; null until toggled, so an untouched control follows `showDataTable`. */
|
|
215
|
+
private dataTableExpandedOverride;
|
|
216
|
+
private readonly dataTableId;
|
|
217
|
+
/** Identical to `showDataTable` whenever `dataTableToggle` is off, keeping the unset path
|
|
218
|
+
* byte-identical to before. */
|
|
219
|
+
private get dataTableVisible();
|
|
220
|
+
private toggleDataTable;
|
|
189
221
|
/** `'fit'` (default) squeezes the plot into the measured host width, unchanged from before this
|
|
190
222
|
* property existed. `'scroll'` gives every bar a fixed `barWidth` instead, letting the plot's
|
|
191
223
|
* content width exceed the host's — the host becomes horizontally scrollable
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteAdd,finiteCount,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,MAX_SCROLL_CONTENT_WIDTH=1e6;function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const fraction=(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return lo*(1-ratio)+hi*ratio}).filter(Number.isFinite)}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const roundedLo=Math.floor(lo/step)*step,roundedHi=Math.ceil(hi/step)*step;Number.isFinite(roundedLo)&&(lo=roundedLo),Number.isFinite(roundedHi)&&(hi=roundedHi);const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=lo+index*step;Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this.labels=[],this.datasets=[],this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this.activeMarkIndex=0,this.resizeObserverGeneration=0,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.map((series,datasetIndex)=>{const value=series.data[index];return typeof value=="number"&&Number.isFinite(value)?this.formatter?.({value,surface:"export",datasetIndex,index,label,seriesLabel:series.label})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteAdd,finiteCount,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,MAX_SCROLL_CONTENT_WIDTH=1e6;function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const fraction=(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return lo*(1-ratio)+hi*ratio}).filter(Number.isFinite)}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const roundedLo=Math.floor(lo/step)*step,roundedHi=Math.ceil(hi/step)*step;Number.isFinite(roundedLo)&&(lo=roundedLo),Number.isFinite(roundedHi)&&(hi=roundedHi);const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=lo+index*step;Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this.labels=[],this.datasets=[],this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this.showDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("lite-chart-data-table"),this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this.activeMarkIndex=0,this.resizeObserverGeneration=0,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.map((series,datasetIndex)=>{const value=series.data[index];return typeof value=="number"&&Number.isFinite(value)?this.formatter?.({value,surface:"export",datasetIndex,index,label,seriesLabel:series.label})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
|
|
2
2
|
`)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.armResizeObserver(),this.armForcedColorsWatcher()}armResizeObserver(){const target=this.svgEl,ownerDocument=this.ownerDocument;if(!this.isConnected||!target||this.resizeObserver&&this.resizeObserverDocument===ownerDocument&&this.resizeObserverTarget===target)return;this.resetResizeObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.resizeObserverGeneration,observer=new ResizeObserverCtor(entries=>{if(this.resizeObserver!==observer||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.resizeObserverTarget!==target)return;const box=entries[0]?.contentBoxSize?.[0];if(box)this.plotWidth=box.inlineSize,this.plotHeight=box.blockSize;else{const rect=this.svgEl?.getBoundingClientRect();rect&&(this.plotWidth=rect.width,this.plotHeight=rect.height)}});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,this.resizeObserverTarget=target,target&&observer.observe(target)}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver(),this.disarmForcedColorsWatcher()}adoptedCallback(){super.adoptedCallback(),this.resetResizeObserver(),this.releaseAnnouncementSink(),this.syncAnnouncementSink(),this.refreshFitMeasurementAvailability(),this.armForcedColorsWatcher()}armForcedColorsWatcher(){const ownerWindow=this.ownerDocument?.defaultView??void 0;ownerWindow?.matchMedia&&(this.forcedColorsWindow===ownerWindow&&this.forcedColorsQuery||(this.disarmForcedColorsWatcher(),this.forcedColorsWindow=ownerWindow,this.forcedColorsQuery=ownerWindow.matchMedia("(forced-colors: active)"),this.forcedColorsQuery.addEventListener("change",this.onForcedColorsChange)))}disarmForcedColorsWatcher(){this.forcedColorsQuery?.removeEventListener("change",this.onForcedColorsChange),this.forcedColorsQuery=void 0,this.forcedColorsWindow=void 0}syncAnnouncementSink(){this.isConnected&&this.politeAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.politeAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.politeAnnouncementSink?.release(),this.politeAnnouncementSink=void 0}resetResizeObserver(){this.resizeObserverGeneration+=1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.resizeObserverTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver()}willUpdate(changed){if(super.willUpdate(changed),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!["type","labels","datasets","skipZero"].some(name=>changed.has(name)))return;const active=activeElementIn(this.shadowRoot)??null,hadFocusedMark=active?.matches('[part="bar"], [part="point"]')??!1,priorPosition=Number(active?.getAttribute("data-mark-index")??this.activeMarkIndex),datasetAttribute=active?.getAttribute("data-dataset-index"),indexAttribute=active?.getAttribute("data-index"),datasetIndex=Number(datasetAttribute),index=Number(indexAttribute),marks=this.interactiveMarks(),sameIdentity=datasetAttribute!=null&&indexAttribute!==null&&indexAttribute!==void 0?marks.findIndex(mark=>mark.datasetIndex===datasetIndex&&mark.index===index):-1;this.activeMarkIndex=marks.length?sameIdentity>=0?sameIdentity:Math.min(Math.max(priorPosition,0),marks.length-1):0,this.refocusMarkAfterUpdate=hadFocusedMark&&marks.length>0,this.refocusChartAfterUpdate=hadFocusedMark&&marks.length===0}updated(changed){super.updated(changed);const wasMounting=this.isMounting;if(this.isMounting=!1,changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}const dataTruncation=this.dataTruncationMessage();wasMounting?this.lastDataTruncationAnnouncement=dataTruncation:dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.politeAnnouncementSink?.announce(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus())}colorFor(index,series){return sanitizeCssColor(series.color)??DEFAULT_PALETTE[index%DEFAULT_PALETTE.length]}get effectiveType(){return normalizeLiteChartType(this.type)}forcedColors(){return forcedColorsActive(this.ownerDocument?.defaultView)}markPaint(index,series){const color=this.colorFor(index,series);return this.effectiveType==="bar"&&this.forcedColors()?`url(#${this.forcedColorPatternId}-${index})`:color}legendEncoding(index){return this.forcedColors()?forcedColorEncoding(index).name:nothing}markDash(index){if(!this.forcedColors())return nothing;const dash=forcedColorEncoding(index).dash;return dash.length?dash.join(" "):"none"}renderForcedColorPatterns(){if(this.effectiveType!=="bar"||!this.forcedColors())return nothing;const size=8,half=size/2,texture="var(--lr-color-surface)";return svg`<defs>
|
|
3
3
|
${this.recordSample().seriesIndexes.map(index=>{const series=this.datasets[index],encoding=forcedColorEncoding(index).name,shapes=(()=>{switch(encoding){case"horizontal":return svg`<rect y=${half} width=${size} height="1" fill=${texture}></rect>`;case"vertical":return svg`<rect x=${half} width="1" height=${size} fill=${texture}></rect>`;case"diagonal":return svg`<path
|
|
4
4
|
d=${`M${-half},${size} L${half},0 M${half},${size} L${size+half},0`}
|
|
@@ -155,9 +155,22 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
155
155
|
<lr-live-region part="live-region"></lr-live-region>
|
|
156
156
|
${this.description?html`<p part="description" id=${this.descriptionId} class="sr-only">${this.description}</p>`:nothing}
|
|
157
157
|
${dataTruncation?html`<p part="data-truncation">${dataTruncation}</p>`:nothing}
|
|
158
|
-
|
|
158
|
+
${this.dataTableToggle?html`<button
|
|
159
|
+
part="data-table-toggle"
|
|
160
|
+
type="button"
|
|
161
|
+
aria-expanded=${this.dataTableVisible?"true":"false"}
|
|
162
|
+
aria-controls=${this.dataTableId}
|
|
163
|
+
@click=${()=>this.toggleDataTable()}
|
|
164
|
+
>
|
|
165
|
+
${this.localize("chartData")}
|
|
166
|
+
</button>`:nothing}
|
|
167
|
+
<div
|
|
168
|
+
id=${this.dataTableId}
|
|
169
|
+
part="data-table"
|
|
170
|
+
?data-visually-hidden=${!hasCustomDataTable&&!this.dataTableVisible}
|
|
171
|
+
>
|
|
159
172
|
<slot name="data-table" @slotchange=${()=>this.requestUpdate()}></slot>
|
|
160
|
-
${hasCustomDataTable?nothing:this.datasets.length>1?html`<table part="table" class
|
|
173
|
+
${hasCustomDataTable?nothing:this.datasets.length>1?html`<table part="table" class=${this.dataTableVisible?nothing:"sr-only"}>
|
|
161
174
|
<caption>${this.localize("chartData")}</caption>
|
|
162
175
|
<thead>
|
|
163
176
|
<tr>
|
|
@@ -190,4 +203,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
190
203
|
`})}
|
|
191
204
|
</div>`:nothing}
|
|
192
205
|
</div>
|
|
193
|
-
`}}__decorate([property({converter:{fromAttribute:value=>normalizeLiteChartType(value)}})],LyraLiteChart.prototype,"type",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"labels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"datasets",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"legend",void 0),__decorate([property({attribute:"legend-position",converter:{fromAttribute:normalizeChartChromeLegendPosition}})],LyraLiteChart.prototype,"legendPosition",void 0),__decorate([property()],LyraLiteChart.prototype,"height",void 0),__decorate([property({attribute:"x-label"})],LyraLiteChart.prototype,"xLabel",void 0),__decorate([property({attribute:"y-label"})],LyraLiteChart.prototype,"yLabel",void 0),__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraLiteChart.prototype,"beginAtZero",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"stacked",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tickFormat",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tableCellFormatter",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"formatter",void 0),__decorate([property({type:Boolean,attribute:"table-totals"})],LyraLiteChart.prototype,"tableTotals",void 0),__decorate([property({reflect:!0,converter:LITE_CHART_LAYOUT})],LyraLiteChart.prototype,"layout",null),__decorate([property({type:Number,attribute:"bar-width"})],LyraLiteChart.prototype,"barWidth",void 0),__decorate([property({type:Number,attribute:"max-labels"})],LyraLiteChart.prototype,"maxLabels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"barX",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"pointText",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"legendText",void 0),__decorate([property({type:Boolean,attribute:"rounded-bars"})],LyraLiteChart.prototype,"roundedBars",void 0),__decorate([property({type:Boolean,attribute:"skip-zero"})],LyraLiteChart.prototype,"skipZero",void 0),__decorate([property({type:Number,attribute:"value-axis-gutter"})],LyraLiteChart.prototype,"valueAxisGutter",void 0),__decorate([property({type:Number,attribute:"bar-gap-ratio"})],LyraLiteChart.prototype,"barGapRatio",void 0),__decorate([property()],LyraLiteChart.prototype,"scale",void 0),__decorate([property({type:Boolean,attribute:"without-value-axis"})],LyraLiteChart.prototype,"withoutValueAxis",void 0),__decorate([property({type:Number,attribute:"min-bar-height"})],LyraLiteChart.prototype,"minBarHeight",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"selectedIndices",void 0),__decorate([property({attribute:"accessible-label"})],LyraLiteChart.prototype,"accessibleLabel",void 0),__decorate([property()],LyraLiteChart.prototype,"label",void 0),__decorate([property()],LyraLiteChart.prototype,"description",void 0),__decorate([state()],LyraLiteChart.prototype,"plotWidth",void 0),__decorate([state()],LyraLiteChart.prototype,"plotHeight",void 0),__decorate([state()],LyraLiteChart.prototype,"fitMeasurementAvailable",void 0),__decorate([state()],LyraLiteChart.prototype,"activeMarkIndex",void 0),__decorate([query("svg")],LyraLiteChart.prototype,"svgEl",void 0),__decorate([query("lr-live-region")],LyraLiteChart.prototype,"liveRegion",void 0);function formatTick(v,locale){return getNumberFormat(locale,{maximumFractionDigits:6}).format(Number(v.toFixed(6)))}export{LyraLiteChart};
|
|
206
|
+
`}}__decorate([property({converter:{fromAttribute:value=>normalizeLiteChartType(value)}})],LyraLiteChart.prototype,"type",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"labels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"datasets",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"legend",void 0),__decorate([property({attribute:"legend-position",converter:{fromAttribute:normalizeChartChromeLegendPosition}})],LyraLiteChart.prototype,"legendPosition",void 0),__decorate([property()],LyraLiteChart.prototype,"height",void 0),__decorate([property({attribute:"x-label"})],LyraLiteChart.prototype,"xLabel",void 0),__decorate([property({attribute:"y-label"})],LyraLiteChart.prototype,"yLabel",void 0),__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraLiteChart.prototype,"beginAtZero",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"stacked",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tickFormat",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tableCellFormatter",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"formatter",void 0),__decorate([property({type:Boolean,attribute:"table-totals"})],LyraLiteChart.prototype,"tableTotals",void 0),__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraLiteChart.prototype,"showDataTable",void 0),__decorate([property({type:Boolean,attribute:"data-table-toggle"})],LyraLiteChart.prototype,"dataTableToggle",void 0),__decorate([state()],LyraLiteChart.prototype,"dataTableExpandedOverride",void 0),__decorate([property({reflect:!0,converter:LITE_CHART_LAYOUT})],LyraLiteChart.prototype,"layout",null),__decorate([property({type:Number,attribute:"bar-width"})],LyraLiteChart.prototype,"barWidth",void 0),__decorate([property({type:Number,attribute:"max-labels"})],LyraLiteChart.prototype,"maxLabels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"barX",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"pointText",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"legendText",void 0),__decorate([property({type:Boolean,attribute:"rounded-bars"})],LyraLiteChart.prototype,"roundedBars",void 0),__decorate([property({type:Boolean,attribute:"skip-zero"})],LyraLiteChart.prototype,"skipZero",void 0),__decorate([property({type:Number,attribute:"value-axis-gutter"})],LyraLiteChart.prototype,"valueAxisGutter",void 0),__decorate([property({type:Number,attribute:"bar-gap-ratio"})],LyraLiteChart.prototype,"barGapRatio",void 0),__decorate([property()],LyraLiteChart.prototype,"scale",void 0),__decorate([property({type:Boolean,attribute:"without-value-axis"})],LyraLiteChart.prototype,"withoutValueAxis",void 0),__decorate([property({type:Number,attribute:"min-bar-height"})],LyraLiteChart.prototype,"minBarHeight",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"selectedIndices",void 0),__decorate([property({attribute:"accessible-label"})],LyraLiteChart.prototype,"accessibleLabel",void 0),__decorate([property()],LyraLiteChart.prototype,"label",void 0),__decorate([property()],LyraLiteChart.prototype,"description",void 0),__decorate([state()],LyraLiteChart.prototype,"plotWidth",void 0),__decorate([state()],LyraLiteChart.prototype,"plotHeight",void 0),__decorate([state()],LyraLiteChart.prototype,"fitMeasurementAvailable",void 0),__decorate([state()],LyraLiteChart.prototype,"activeMarkIndex",void 0),__decorate([query("svg")],LyraLiteChart.prototype,"svgEl",void 0),__decorate([query("lr-live-region")],LyraLiteChart.prototype,"liveRegion",void 0);function formatTick(v,locale){return getNumberFormat(locale,{maximumFractionDigits:6}).format(Number(v.toFixed(6)))}export{LyraLiteChart};
|
|
@@ -187,4 +187,33 @@ import{css}from"lit";import{forcedColorLegendSwatchStyles}from"./chart-forced-co
|
|
|
187
187
|
grid-template-columns: minmax(0, 1fr);
|
|
188
188
|
}
|
|
189
189
|
}
|
|
190
|
+
|
|
191
|
+
[part='data-table-toggle'] {
|
|
192
|
+
align-self: flex-start;
|
|
193
|
+
font: inherit;
|
|
194
|
+
font-size: var(--lr-font-size-xs);
|
|
195
|
+
min-block-size: var(--lr-icon-button-size);
|
|
196
|
+
padding: var(--lr-size-0-15rem) var(--lr-size-0-5rem);
|
|
197
|
+
border: var(--lr-border-width-thin) solid var(--lr-color-border);
|
|
198
|
+
border-radius: var(--lr-radius);
|
|
199
|
+
background: var(--lr-color-surface);
|
|
200
|
+
color: var(--lr-color-text);
|
|
201
|
+
max-inline-size: 100%;
|
|
202
|
+
white-space: normal;
|
|
203
|
+
overflow-wrap: break-word;
|
|
204
|
+
cursor: pointer;
|
|
205
|
+
}
|
|
206
|
+
[part='data-table-toggle']:hover {
|
|
207
|
+
background: var(--lr-lite-chart-data-table-toggle-hover-bg, var(--lr-color-brand-quiet));
|
|
208
|
+
}
|
|
209
|
+
[part='data-table-toggle']:active {
|
|
210
|
+
background: var(
|
|
211
|
+
--lr-lite-chart-data-table-toggle-active-bg,
|
|
212
|
+
color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active))
|
|
213
|
+
);
|
|
214
|
+
}
|
|
215
|
+
[part='data-table-toggle']:focus-visible {
|
|
216
|
+
outline: var(--lr-focus-ring);
|
|
217
|
+
outline-offset: var(--lr-focus-ring-offset);
|
|
218
|
+
}
|
|
190
219
|
`;export{styles};
|
|
@@ -973,6 +973,25 @@ export declare class LyraTable<T = unknown> extends LyraElement<LyraTableEventMa
|
|
|
973
973
|
*
|
|
974
974
|
* No `tabindex` on either: a persistent editor is a plain tab stop, exactly like the row-expand
|
|
975
975
|
* toggle rendered a few lines above, and stays outside the header/row roving model. */
|
|
976
|
+
/** Column keys already reported by `renderCellValue()`, so a 400-row table logs once, not 400
|
|
977
|
+
* times, for the same authoring mistake. */
|
|
978
|
+
private readonly reportedMissingCellColumns;
|
|
979
|
+
/**
|
|
980
|
+
* Renders one cell, tolerating a column that omits its required `cell` renderer.
|
|
981
|
+
*
|
|
982
|
+
* `TableColumn.cell` is typed and documented required, but columns arrive through a lit
|
|
983
|
+
* `.columns=${[...]}` property binding, and lit-html property bindings are not type-checked by
|
|
984
|
+
* `tsc` -- only by lit-analyzer, which many projects do not run. So required-ness is unenforced
|
|
985
|
+
* where it is actually written. Calling it unguarded meant a single malformed column threw out of
|
|
986
|
+
* lit's `repeat` directive and took the WHOLE table down, with a stack carrying only lyra and
|
|
987
|
+
* lit-html frames: no application frame, no column key, no table identity. One report described
|
|
988
|
+
* carrying it undiagnosed across two releases as 16 unattributed unhandled rejections, while the
|
|
989
|
+
* suite still passed because its assertions were on surrounding markup.
|
|
990
|
+
*
|
|
991
|
+
* So: degrade to an empty cell -- the rest of the table stays usable -- and report once per
|
|
992
|
+
* column, naming the key and the tag, because attribution was the harder half of that bug.
|
|
993
|
+
*/
|
|
994
|
+
private renderCellValue;
|
|
976
995
|
private renderCellEditor;
|
|
977
996
|
/** One rectangular placeholder, using `<lr-skeleton>`'s canonical `shape` axis. `announce` is
|
|
978
997
|
* switched off on every one of them: `<lr-skeleton>` defaults it
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{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{resolveCssLength}from"../../../internal/css-length.js";import{getCollator}from"../../../internal/intl-cache.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{styles}from"./table.styles.js";import{chevronIcon}from"../../../internal/icons.js";import{minMax}from"../heatmap/heatmap-scale.js";import"../../overlays/empty/empty.class.js";import{literalSetConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_loadMore,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_showFewerColumns,LYRA_DEFAULT_tableEditCell,LYRA_DEFAULT_tableFilterLabel,LYRA_DEFAULT_tableFilterPlaceholder,LYRA_DEFAULT_tableLoading}from"../../../internal/default-strings.generated.js";const DEFAULT_SKELETON_ROWS=3,MAX_SKELETON_ROWS=20,DEFAULT_PAGE_SIZE=100,MAX_PAGE_SIZE=500,LOW_PRIORITY_MAX_INLINE_SIZE=899.98,MEDIUM_PRIORITY_MAX_INLINE_SIZE=639.98,MAX_TABLE_COLLECTION_ENTRIES=1e4,DEFAULT_RESIZE_MIN_WIDTH_PX=48,UNBOUNDED_RESIZE_ARIA_MAX=Number.MAX_SAFE_INTEGER;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 UNSAFE_CSS_STRUCTURE=/[;{}]/,URL_FUNCTION=/url\s*\(/i,SAFE_STYLE_PROPERTY=/^-?[_a-zA-Z][\w-]*$|^--[a-zA-Z0-9_-]+$/,optionalBooleanConverter={fromAttribute(value){if(value!==null)return value!=="false"},toAttribute(value){return value===void 0?null:value?"":"false"}};function isDevelopmentRuntime(){const nodeEnv=globalThis.process?.env?.NODE_ENV;if(nodeEnv==="production")return!1;if(nodeEnv==="development")return!0;const viteEnv=import.meta.env;return typeof viteEnv?.DEV=="boolean"?viteEnv.DEV:viteEnv?.MODE==="development"}const TABLE_LAYOUT=literalSetConverter(["auto","fixed"],"auto"),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}function sanitizeCellStyle(cellStyle){if(cellStyle===void 0)return{};const safe={};for(const[rawProperty,rawValue]of Object.entries(cellStyle)){const property2=sanitizeCellStyleProperty(rawProperty),value=sanitizeCellStyleValue(rawValue);if(property2===void 0||value===void 0)continue;const normalizedProperty=normalizeStyleProperty(property2);(normalizedProperty.startsWith("--")||cssSupports(normalizedProperty,value))&&(safe[normalizedProperty]=value)}return safe}function sanitizeCellStyleProperty(property2){const normalized=property2.trim();if(!(!normalized||!SAFE_STYLE_PROPERTY.test(normalized)))return normalized}function normalizeStyleProperty(property2){return property2.startsWith("--")?property2:property2.replace(/[A-Z]/g,"-$&").toLowerCase()}function sanitizeCellStyleValue(value){if(typeof value!="string")return;const normalized=value.trim();if(!(!normalized||UNSAFE_CSS_STRUCTURE.test(normalized)||URL_FUNCTION.test(normalized)))return normalized}function cssSupports(property2,value){return typeof CSS>"u"||typeof CSS.supports!="function"?!0:CSS.supports(property2,value)}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._columns=Object.freeze([]),this._rows=Object.freeze([]),this._layout="auto",this.sortKey="",this.sortDir="asc",this.sortMode="client",this.defaultSortDir="asc",this.caption="",this.captionId=nextId("lr-table-caption"),this.selectionMode="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._expandedKeys=new Set,this.hasMore=!1,this.emptyDescription="",this.noColumnsDescription="",this.hasHiddenPriorityColumns=!1,this.priorityColumnsToggleAvailable=!1,this.priorityColumnsVisible=!1,this.persistReady=!1,this.loadingAnnouncementsReady=!1,this.activeColKey=null,this.activeRowKey=null,this.editingCell=null,this.focusedEditorCell=null,this.editorHadFocusBeforeUpdate=!1,this.rovingFocusSnapshot=null,this.resizedColumnWidths=new Map,this.rowsByKey=new Map,this.columnsByKey=new Map,this.layoutFrame=null,this.observedHeaders=new Set,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]"),resizeEventWindow=this.ownerDocument.defaultView;if(!key||!column||!header||!resizeEventWindow)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(),handle.setPointerCapture?.(event.pointerId),this.resizeEventWindow=resizeEventWindow,resizeEventWindow.addEventListener("pointermove",this.onResizePointerMove),resizeEventWindow.addEventListener("pointerup",this.onResizePointerEnd),resizeEventWindow.addEventListener("pointercancel",this.onResizePointerEnd),resizeEventWindow.addEventListener("lostpointercapture",this.onResizePointerEnd)},this.onResizePointerMove=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;const delta=isRtl(this)?state2.startX-event.clientX:event.clientX-state2.startX,width=Math.min(state2.maxWidth,Math.max(state2.minWidth,state2.startWidth+delta));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),step=event.shiftKey?50:10;let requestedWidth;event.key==="Home"?requestedWidth=minWidth:event.key==="End"&&Number.isFinite(maxWidth)?requestedWidth=maxWidth:event.key==="ArrowLeft"?requestedWidth=currentWidth+(isRtl(this)?step:-step):event.key==="ArrowRight"&&(requestedWidth=currentWidth+(isRtl(this)?-step:step)),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"),event.type==="pointerup")try{state2.handle.releasePointerCapture?.(event.pointerId)}catch{}if(this.resizeState=void 0,this.detachResizePointerListeners(),event.type!=="pointerup"){const reverted2=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted2.delete(state2.key):reverted2.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted2;return}const committedWidth=this.resizedColumnWidths.get(state2.key);if(committedWidth===void 0||committedWidth===state2.previousWidth||!this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width:committedWidth}),{cancelable:!0}).defaultPrevented)return;const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):reverted.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted},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.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({text:this.filterText}))},this.stopOwnedEvent=event=>{event.stopPropagation()},this.onNativeFocus=event=>{event.stopPropagation(),this.emit("focus")},this.onNativeBlur=event=>{event.stopPropagation(),this.emit("blur")},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))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,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,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,resizeColumn:LYRA_DEFAULT_resizeColumn,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,tableLoading:LYRA_DEFAULT_tableLoading}}static{this.styles=[LyraElement.styles,styles,srOnly]}get columns(){return this._columns}set columns(value){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){const previous=this._rows;this._rows=frozenArray(Array.isArray(value)?value:[]),this.requestUpdate("rows",previous)}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 readonlyKeySet(this._selectedKeys)}set selectedRowKeys(value){const previous=this._selectedKeys;this._selectedKeys=keySet(value??[]),this.requestUpdate("selectedRowKeys",previous)}get expandedRowKeys(){return readonlyKeySet(this._expandedKeys)}set expandedRowKeys(value){const previous=this._expandedKeys;this._expandedKeys=keySet(value??[]),this.requestUpdate("expandedRowKeys",previous)}get storageFullKey(){return this.storageKey?`lr-table:${this.storageKey}`:void 0}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 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=resolveCssLength(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)}resizeColumnTo(column,requestedWidth){const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),width=Math.min(maxWidth,Math.max(minWidth,requestedWidth)),previousWidth=this.resizedColumnWidths.get(column.key);if(previousWidth===width||(this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(column.key,width),!this.emit("lr-column-resize",Object.freeze({columnKey:column.key,width}),{cancelable:!0}).defaultPrevented))return;const reverted=new Map(this.resizedColumnWidths);previousWidth===void 0?reverted.delete(column.key):reverted.set(column.key,previousWidth),this.resizedColumnWidths=reverted}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);return html`<span
|
|
1
|
+
var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,state}from"lit/decorators.js";import{repeat}from"lit/directives/repeat.js";import{styleMap}from"lit/directives/style-map.js";import{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{resolveCssLength}from"../../../internal/css-length.js";import{getCollator}from"../../../internal/intl-cache.js";import{readPersistedState,writePersistedState}from"../../../internal/persisted-state.js";import{styles}from"./table.styles.js";import{chevronIcon}from"../../../internal/icons.js";import{minMax}from"../heatmap/heatmap-scale.js";import"../../overlays/empty/empty.class.js";import{literalSetConverter,trueDefaultSpellcheckConverter as spellcheckConverter}from"../../../internal/converters.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{LYRA_DEFAULT_collapse,LYRA_DEFAULT_details,LYRA_DEFAULT_expand,LYRA_DEFAULT_loadMore,LYRA_DEFAULT_loading,LYRA_DEFAULT_map,LYRA_DEFAULT_navigation,LYRA_DEFAULT_noColumns,LYRA_DEFAULT_noData,LYRA_DEFAULT_open,LYRA_DEFAULT_popover,LYRA_DEFAULT_progress,LYRA_DEFAULT_resizeColumn,LYRA_DEFAULT_search,LYRA_DEFAULT_select,LYRA_DEFAULT_showAllColumns,LYRA_DEFAULT_showFewerColumns,LYRA_DEFAULT_tableEditCell,LYRA_DEFAULT_tableFilterLabel,LYRA_DEFAULT_tableFilterPlaceholder,LYRA_DEFAULT_tableLoading}from"../../../internal/default-strings.generated.js";const DEFAULT_SKELETON_ROWS=3,MAX_SKELETON_ROWS=20,DEFAULT_PAGE_SIZE=100,MAX_PAGE_SIZE=500,LOW_PRIORITY_MAX_INLINE_SIZE=899.98,MEDIUM_PRIORITY_MAX_INLINE_SIZE=639.98,MAX_TABLE_COLLECTION_ENTRIES=1e4,DEFAULT_RESIZE_MIN_WIDTH_PX=48,UNBOUNDED_RESIZE_ARIA_MAX=Number.MAX_SAFE_INTEGER;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 UNSAFE_CSS_STRUCTURE=/[;{}]/,URL_FUNCTION=/url\s*\(/i,SAFE_STYLE_PROPERTY=/^-?[_a-zA-Z][\w-]*$|^--[a-zA-Z0-9_-]+$/,optionalBooleanConverter={fromAttribute(value){if(value!==null)return value!=="false"},toAttribute(value){return value===void 0?null:value?"":"false"}};function isDevelopmentRuntime(){const nodeEnv=globalThis.process?.env?.NODE_ENV;if(nodeEnv==="production")return!1;if(nodeEnv==="development")return!0;const viteEnv=import.meta.env;return typeof viteEnv?.DEV=="boolean"?viteEnv.DEV:viteEnv?.MODE==="development"}const TABLE_LAYOUT=literalSetConverter(["auto","fixed"],"auto"),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}function sanitizeCellStyle(cellStyle){if(cellStyle===void 0)return{};const safe={};for(const[rawProperty,rawValue]of Object.entries(cellStyle)){const property2=sanitizeCellStyleProperty(rawProperty),value=sanitizeCellStyleValue(rawValue);if(property2===void 0||value===void 0)continue;const normalizedProperty=normalizeStyleProperty(property2);(normalizedProperty.startsWith("--")||cssSupports(normalizedProperty,value))&&(safe[normalizedProperty]=value)}return safe}function sanitizeCellStyleProperty(property2){const normalized=property2.trim();if(!(!normalized||!SAFE_STYLE_PROPERTY.test(normalized)))return normalized}function normalizeStyleProperty(property2){return property2.startsWith("--")?property2:property2.replace(/[A-Z]/g,"-$&").toLowerCase()}function sanitizeCellStyleValue(value){if(typeof value!="string")return;const normalized=value.trim();if(!(!normalized||UNSAFE_CSS_STRUCTURE.test(normalized)||URL_FUNCTION.test(normalized)))return normalized}function cssSupports(property2,value){return typeof CSS>"u"||typeof CSS.supports!="function"?!0:CSS.supports(property2,value)}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._columns=Object.freeze([]),this._rows=Object.freeze([]),this._layout="auto",this.sortKey="",this.sortDir="asc",this.sortMode="client",this.defaultSortDir="asc",this.caption="",this.captionId=nextId("lr-table-caption"),this.selectionMode="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._expandedKeys=new Set,this.hasMore=!1,this.emptyDescription="",this.noColumnsDescription="",this.hasHiddenPriorityColumns=!1,this.priorityColumnsToggleAvailable=!1,this.priorityColumnsVisible=!1,this.persistReady=!1,this.loadingAnnouncementsReady=!1,this.activeColKey=null,this.activeRowKey=null,this.editingCell=null,this.focusedEditorCell=null,this.editorHadFocusBeforeUpdate=!1,this.rovingFocusSnapshot=null,this.resizedColumnWidths=new Map,this.rowsByKey=new Map,this.columnsByKey=new Map,this.layoutFrame=null,this.observedHeaders=new Set,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]"),resizeEventWindow=this.ownerDocument.defaultView;if(!key||!column||!header||!resizeEventWindow)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(),handle.setPointerCapture?.(event.pointerId),this.resizeEventWindow=resizeEventWindow,resizeEventWindow.addEventListener("pointermove",this.onResizePointerMove),resizeEventWindow.addEventListener("pointerup",this.onResizePointerEnd),resizeEventWindow.addEventListener("pointercancel",this.onResizePointerEnd),resizeEventWindow.addEventListener("lostpointercapture",this.onResizePointerEnd)},this.onResizePointerMove=event=>{const state2=this.resizeState;if(!state2||event.pointerId!==state2.pointerId)return;const delta=isRtl(this)?state2.startX-event.clientX:event.clientX-state2.startX,width=Math.min(state2.maxWidth,Math.max(state2.minWidth,state2.startWidth+delta));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),step=event.shiftKey?50:10;let requestedWidth;event.key==="Home"?requestedWidth=minWidth:event.key==="End"&&Number.isFinite(maxWidth)?requestedWidth=maxWidth:event.key==="ArrowLeft"?requestedWidth=currentWidth+(isRtl(this)?step:-step):event.key==="ArrowRight"&&(requestedWidth=currentWidth+(isRtl(this)?-step:step)),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"),event.type==="pointerup")try{state2.handle.releasePointerCapture?.(event.pointerId)}catch{}if(this.resizeState=void 0,this.detachResizePointerListeners(),event.type!=="pointerup"){const reverted2=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted2.delete(state2.key):reverted2.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted2;return}const committedWidth=this.resizedColumnWidths.get(state2.key);if(committedWidth===void 0||committedWidth===state2.previousWidth||!this.emit("lr-column-resize",Object.freeze({columnKey:state2.key,width:committedWidth}),{cancelable:!0}).defaultPrevented)return;const reverted=new Map(this.resizedColumnWidths);state2.previousWidth===void 0?reverted.delete(state2.key):reverted.set(state2.key,state2.previousWidth),this.resizedColumnWidths=reverted},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.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({text:this.filterText}))},this.stopOwnedEvent=event=>{event.stopPropagation()},this.onNativeFocus=event=>{event.stopPropagation(),this.emit("focus")},this.onNativeBlur=event=>{event.stopPropagation(),this.emit("blur")},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))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)},this.reportedMissingCellColumns=new Set}static{this.defaultStrings={...super.defaultStrings,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,open:LYRA_DEFAULT_open,popover:LYRA_DEFAULT_popover,progress:LYRA_DEFAULT_progress,resizeColumn:LYRA_DEFAULT_resizeColumn,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,tableLoading:LYRA_DEFAULT_tableLoading}}static{this.styles=[LyraElement.styles,styles,srOnly]}get columns(){return this._columns}set columns(value){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){const previous=this._rows;this._rows=frozenArray(Array.isArray(value)?value:[]),this.requestUpdate("rows",previous)}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 readonlyKeySet(this._selectedKeys)}set selectedRowKeys(value){const previous=this._selectedKeys;this._selectedKeys=keySet(value??[]),this.requestUpdate("selectedRowKeys",previous)}get expandedRowKeys(){return readonlyKeySet(this._expandedKeys)}set expandedRowKeys(value){const previous=this._expandedKeys;this._expandedKeys=keySet(value??[]),this.requestUpdate("expandedRowKeys",previous)}get storageFullKey(){return this.storageKey?`lr-table:${this.storageKey}`:void 0}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 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=resolveCssLength(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)}resizeColumnTo(column,requestedWidth){const minWidth=this.minimumResizeWidth(column),maxWidth=this.maximumResizeWidth(column,minWidth),width=Math.min(maxWidth,Math.max(minWidth,requestedWidth)),previousWidth=this.resizedColumnWidths.get(column.key);if(previousWidth===width||(this.resizedColumnWidths=new Map(this.resizedColumnWidths).set(column.key,width),!this.emit("lr-column-resize",Object.freeze({columnKey:column.key,width}),{cancelable:!0}).defaultPrevented))return;const reverted=new Map(this.resizedColumnWidths);previousWidth===void 0?reverted.delete(column.key):reverted.set(column.key,previousWidth),this.resizedColumnWidths=reverted}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);return html`<span
|
|
2
2
|
part="resize-handle"
|
|
3
3
|
data-col-key=${column.key}
|
|
4
4
|
role="separator"
|
|
@@ -10,7 +10,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
10
10
|
aria-valuemax=${Number.isFinite(maxWidth)?Math.round(maxWidth):UNBOUNDED_RESIZE_ARIA_MAX}
|
|
11
11
|
@pointerdown=${this.onResizePointerDown}
|
|
12
12
|
@keydown=${this.onResizeKeyDown}
|
|
13
|
-
></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;rendered&&rendered>0&&handle.setAttribute("aria-valuenow",String(Math.round(rendered)))}}detachResizePointerListeners(){const resizeEventWindow=this.resizeEventWindow;resizeEventWindow&&(resizeEventWindow.removeEventListener("pointermove",this.onResizePointerMove),resizeEventWindow.removeEventListener("pointerup",this.onResizePointerEnd),resizeEventWindow.removeEventListener("pointercancel",this.onResizePointerEnd),resizeEventWindow.removeEventListener("lostpointercapture",this.onResizePointerEnd),this.resizeEventWindow=void 0)}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;if(this.resizeState=void 0,this.detachResizePointerListeners(),!!state2){state2.handle.removeAttribute("data-resizing");try{state2.handle.releasePointerCapture?.(state2.pointerId)}catch{}this.rollbackResizePreview(state2)}}firstUpdated(changed){super.firstUpdated(changed),isDevelopmentRuntime()&&!this.accessibleLabel&&!this.hasAttribute("aria-label")&&!this.caption&&console.warn("<lr-table> has no accessible name: set `accessibleLabel`, a host `aria-label`, or `caption` so assistive technology can identify the grid.")}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink();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.observeHeaders())}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),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.observedHeaders.clear()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}localizedOverride(key,override){return override??this.localize(key)}loadingText(){return this.localizedOverride("tableLoading",this.loadingLabel)}observeBase(base){this.observedBase!==base&&(this.observedBase&&this.resizeObserver?.unobserve(this.observedBase),this.resizeObserver?.observe(base),this.observedBase=base)}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))}recomputeHiddenPriorityColumns(){const hasPriorityColumns=this.columns.some(col=>col.priority),anyPriorityHidden=hasPriorityColumns&&[...this.renderRoot.querySelectorAll("th[data-priority]")].some(el=>el.offsetParent===null),inlineSize=this.renderRoot.querySelector('[part="base"]')?.clientWidth??0,wouldHideAtAllocation=hasPriorityColumns&&inlineSize>0&&this.columns.some(column=>column.priority==="low"&&inlineSize<=LOW_PRIORITY_MAX_INLINE_SIZE||column.priority==="medium"&&inlineSize<=MEDIUM_PRIORITY_MAX_INLINE_SIZE),toggleAvailable=anyPriorityHidden||this.priorityColumnsVisible&&wouldHideAtAllocation;this.rehomeFocusedColumn(),this.priorityColumnsToggleAvailable!==toggleAvailable&&(this.priorityColumnsToggleAvailable=toggleAvailable),this.hasHiddenPriorityColumns!==anyPriorityHidden&&(this.hasHiddenPriorityColumns=anyPriorityHidden)}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 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=col.sortValue?col.sortValue(entry.row):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)}focusedColKey(){const visible=this.visibleHeaders(),visibleKeys=new Set(visible.map(el=>el.dataset.colKey).filter(key=>key!==void 0&&this.columnsByKey.has(key)));return this.activeColKey!==null&&this.columnsByKey.has(this.activeColKey)&&(visibleKeys.size===0||visibleKeys.has(this.activeColKey))?this.activeColKey:visible.find(el=>el.dataset.colKey!==void 0&&this.columnsByKey.has(el.dataset.colKey))?.dataset.colKey??this.columns[0]?.key??null}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")}captureRovingFocus(changed){this.rovingFocusSnapshot=null;const active=activeElementIn(this.shadowRoot),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.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=first===void 0?new Set:new Set([first]),this.hasUpdated){const rowKeys=Object.freeze(first===void 0?[]:[first]);this.emit("lr-selection-change",Object.freeze({rowKeys}))}}if(!this.hasUpdated){const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.priorityColumnsVisible=="boolean"&&(this.priorityColumnsVisible=parsed.priorityColumnsVisible)}if(changed.has("columns")&&(this.columnsByKey=new Map(this.columns.map(c=>[c.key,c]))),(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.rowsByKey=new Map(this.renderedEntries().map(entry=>[encodeKey(entry.key),entry]))),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&&activeElementIn(this.shadowRoot)===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 values=[];for(const entry of this.matchingEntries())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.loadingAnnouncementsReady&&changed.has("loading")&&this.loading&&this.announcementSink?.announce(this.loadingText()),this.loadingAnnouncementsReady=!0,this.persistReady&&changed.has("priorityColumnsVisible")&&writePersistedState(this.storageFullKey,{priorityColumnsVisible:this.priorityColumnsVisible}),this.persistReady=!0,(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.observeHeaders(),this.restoreRovingFocus(),this.hasAlwaysOnEditors&&this.restoreAlwaysOnEditorFocus(),changed.has("editingCell")&&this.editingCell){const{rowKey,columnKey}=this.editingCell;queueMicrotask(()=>this.editorElementFor(rowKey,columnKey)?.focus())}queueMicrotask(()=>this.recomputeHiddenPriorityColumns())}restoreRovingFocus(){const snapshot=this.rovingFocusSnapshot;if(this.rovingFocusSnapshot=null,snapshot===null)return;const internalActive=activeElementIn(this.shadowRoot);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":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-click",Object.freeze({row})),this.selectionMode==="single"){this.selectedRowKeys=new Set([selectedKey]);const rowKeys=Object.freeze([selectedKey]);this.emit("lr-selection-change",Object.freeze({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=next;const rowKeys=Object.freeze([...next]);this.emit("lr-selection-change",Object.freeze({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 input=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"&&input.value!==""?Number(input.value):input.value;this.emit("lr-cell-edit",Object.freeze({row:entry.row,columnKey,value})),isTransient&&(this.editingCell=null)}editorElementFor(rowKey,columnKey){const row=[...this.renderRoot.querySelectorAll("[data-row-key]")].find(el=>el.dataset.rowKey===rowKey);return(row?[...row.querySelectorAll("td[data-col-key]")].find(el=>el.dataset.colKey===columnKey):void 0)?.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&&activeElementIn(this.shadowRoot)!==editor&&editor.focus(),this.editorHadFocusBeforeUpdate=!1}activateExpandToggle(key){const entry=this.rowsByKey.get(encodeKey(key));entry!==void 0&&this.emit("lr-row-expand-toggle",Object.freeze({row:entry.row,rowKey:key}))}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}}onRowKeyDown(e,tr){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateRow(tr.dataset.rowKey);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}}renderCellEditor(row,col,rowKey,alwaysOn){const type=col.editType??"text",isText=type==="text",value=this.editorValue(row,col),label=this.localize("tableEditCell",void 0,{column:col.label}),spellcheck=isText?this.spellcheck:nothing,autocapitalize=isText?this.autocapitalize||nothing:nothing,autocorrect=isText?this.autoCorrect||nothing:nothing,onChange=event=>this.commitEdit(event,rowKey,col.key),onKeyDown=event=>this.onEditorKeyDown(event,rowKey,col.key);return alwaysOn?html`<input
|
|
13
|
+
></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;rendered&&rendered>0&&handle.setAttribute("aria-valuenow",String(Math.round(rendered)))}}detachResizePointerListeners(){const resizeEventWindow=this.resizeEventWindow;resizeEventWindow&&(resizeEventWindow.removeEventListener("pointermove",this.onResizePointerMove),resizeEventWindow.removeEventListener("pointerup",this.onResizePointerEnd),resizeEventWindow.removeEventListener("pointercancel",this.onResizePointerEnd),resizeEventWindow.removeEventListener("lostpointercapture",this.onResizePointerEnd),this.resizeEventWindow=void 0)}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;if(this.resizeState=void 0,this.detachResizePointerListeners(),!!state2){state2.handle.removeAttribute("data-resizing");try{state2.handle.releasePointerCapture?.(state2.pointerId)}catch{}this.rollbackResizePreview(state2)}}firstUpdated(changed){super.firstUpdated(changed),isDevelopmentRuntime()&&!this.accessibleLabel&&!this.hasAttribute("aria-label")&&!this.caption&&console.warn("<lr-table> has no accessible name: set `accessibleLabel`, a host `aria-label`, or `caption` so assistive technology can identify the grid.")}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink();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.observeHeaders())}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),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.observedHeaders.clear()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}localizedOverride(key,override){return override??this.localize(key)}loadingText(){return this.localizedOverride("tableLoading",this.loadingLabel)}observeBase(base){this.observedBase!==base&&(this.observedBase&&this.resizeObserver?.unobserve(this.observedBase),this.resizeObserver?.observe(base),this.observedBase=base)}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))}recomputeHiddenPriorityColumns(){const hasPriorityColumns=this.columns.some(col=>col.priority),anyPriorityHidden=hasPriorityColumns&&[...this.renderRoot.querySelectorAll("th[data-priority]")].some(el=>el.offsetParent===null),inlineSize=this.renderRoot.querySelector('[part="base"]')?.clientWidth??0,wouldHideAtAllocation=hasPriorityColumns&&inlineSize>0&&this.columns.some(column=>column.priority==="low"&&inlineSize<=LOW_PRIORITY_MAX_INLINE_SIZE||column.priority==="medium"&&inlineSize<=MEDIUM_PRIORITY_MAX_INLINE_SIZE),toggleAvailable=anyPriorityHidden||this.priorityColumnsVisible&&wouldHideAtAllocation;this.rehomeFocusedColumn(),this.priorityColumnsToggleAvailable!==toggleAvailable&&(this.priorityColumnsToggleAvailable=toggleAvailable),this.hasHiddenPriorityColumns!==anyPriorityHidden&&(this.hasHiddenPriorityColumns=anyPriorityHidden)}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 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=col.sortValue?col.sortValue(entry.row):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)}focusedColKey(){const visible=this.visibleHeaders(),visibleKeys=new Set(visible.map(el=>el.dataset.colKey).filter(key=>key!==void 0&&this.columnsByKey.has(key)));return this.activeColKey!==null&&this.columnsByKey.has(this.activeColKey)&&(visibleKeys.size===0||visibleKeys.has(this.activeColKey))?this.activeColKey:visible.find(el=>el.dataset.colKey!==void 0&&this.columnsByKey.has(el.dataset.colKey))?.dataset.colKey??this.columns[0]?.key??null}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")}captureRovingFocus(changed){this.rovingFocusSnapshot=null;const active=activeElementIn(this.shadowRoot),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.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=first===void 0?new Set:new Set([first]),this.hasUpdated){const rowKeys=Object.freeze(first===void 0?[]:[first]);this.emit("lr-selection-change",Object.freeze({rowKeys}))}}if(!this.hasUpdated){const parsed=readPersistedState(this.storageFullKey,v=>typeof v=="object"&&v!==null);parsed&&typeof parsed.priorityColumnsVisible=="boolean"&&(this.priorityColumnsVisible=parsed.priorityColumnsVisible)}if(changed.has("columns")&&(this.columnsByKey=new Map(this.columns.map(c=>[c.key,c]))),(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.rowsByKey=new Map(this.renderedEntries().map(entry=>[encodeKey(entry.key),entry]))),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&&activeElementIn(this.shadowRoot)===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 values=[];for(const entry of this.matchingEntries())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.loadingAnnouncementsReady&&changed.has("loading")&&this.loading&&this.announcementSink?.announce(this.loadingText()),this.loadingAnnouncementsReady=!0,this.persistReady&&changed.has("priorityColumnsVisible")&&writePersistedState(this.storageFullKey,{priorityColumnsVisible:this.priorityColumnsVisible}),this.persistReady=!0,(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.observeHeaders(),this.restoreRovingFocus(),this.hasAlwaysOnEditors&&this.restoreAlwaysOnEditorFocus(),changed.has("editingCell")&&this.editingCell){const{rowKey,columnKey}=this.editingCell;queueMicrotask(()=>this.editorElementFor(rowKey,columnKey)?.focus())}queueMicrotask(()=>this.recomputeHiddenPriorityColumns())}restoreRovingFocus(){const snapshot=this.rovingFocusSnapshot;if(this.rovingFocusSnapshot=null,snapshot===null)return;const internalActive=activeElementIn(this.shadowRoot);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":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-click",Object.freeze({row})),this.selectionMode==="single"){this.selectedRowKeys=new Set([selectedKey]);const rowKeys=Object.freeze([selectedKey]);this.emit("lr-selection-change",Object.freeze({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=next;const rowKeys=Object.freeze([...next]);this.emit("lr-selection-change",Object.freeze({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 input=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"&&input.value!==""?Number(input.value):input.value;this.emit("lr-cell-edit",Object.freeze({row:entry.row,columnKey,value})),isTransient&&(this.editingCell=null)}editorElementFor(rowKey,columnKey){const row=[...this.renderRoot.querySelectorAll("[data-row-key]")].find(el=>el.dataset.rowKey===rowKey);return(row?[...row.querySelectorAll("td[data-col-key]")].find(el=>el.dataset.colKey===columnKey):void 0)?.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&&activeElementIn(this.shadowRoot)!==editor&&editor.focus(),this.editorHadFocusBeforeUpdate=!1}activateExpandToggle(key){const entry=this.rowsByKey.get(encodeKey(key));entry!==void 0&&this.emit("lr-row-expand-toggle",Object.freeze({row:entry.row,rowKey:key}))}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}}onRowKeyDown(e,tr){if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.activateRow(tr.dataset.rowKey);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}}renderCellValue(col,row){if(typeof col.cell=="function")return col.cell(row);const key=String(col.key??"(unkeyed)");return this.reportedMissingCellColumns.has(key)||(this.reportedMissingCellColumns.add(key),console.error(`<lr-table>: column ${JSON.stringify(key)} has no \`cell\` renderer, so its cells render empty. \`cell\` is required, but a lit \`.columns=\${...}\` binding is not type-checked, so this cannot be caught by tsc alone.`)),nothing}renderCellEditor(row,col,rowKey,alwaysOn){const type=col.editType??"text",isText=type==="text",value=this.editorValue(row,col),label=this.localize("tableEditCell",void 0,{column:col.label}),spellcheck=isText?this.spellcheck:nothing,autocapitalize=isText?this.autocapitalize||nothing:nothing,autocorrect=isText?this.autoCorrect||nothing:nothing,onChange=event=>this.commitEdit(event,rowKey,col.key),onKeyDown=event=>this.onEditorKeyDown(event,rowKey,col.key);return alwaysOn?html`<input
|
|
14
14
|
part="cell-editor"
|
|
15
15
|
type=${type}
|
|
16
16
|
value=${value}
|
|
@@ -155,7 +155,7 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
|
|
|
155
155
|
title=${cellTitle||nothing}
|
|
156
156
|
style=${Object.keys(cellStyle).length?styleMap(cellStyle):nothing}
|
|
157
157
|
>
|
|
158
|
-
${editing?this.renderCellEditor(row,col,encodeKey(key),alwaysOn):
|
|
158
|
+
${editing?this.renderCellEditor(row,col,encodeKey(key),alwaysOn):this.renderCellValue(col,row)}
|
|
159
159
|
</td>`})}
|
|
160
160
|
${hasRowTotal?html`<td part="row-total-cell">${this.rowTotal?.(row)}</td>`:nothing}
|
|
161
161
|
</tr>`,rowExpanded?html`<tr part="expanded-row" role="row">
|
|
@@ -2,7 +2,7 @@ import { type TemplateResult, type PropertyValues } from 'lit';
|
|
|
2
2
|
import { LyraElement } from '../../../internal/lyra-element.js';
|
|
3
3
|
import { type WeekdayFormat } from './calendar-core.js';
|
|
4
4
|
import type { LyraAppearance, LyraSize } from '../../../internal/variants.js';
|
|
5
|
-
import { type DateRange, type LyraDatePickerDayContent, type LyraDatePickerDisabledDates, type LyraDatePickerFirstDayOfWeek, type LyraDatePickerPageBy } from './date-picker.class.js';
|
|
5
|
+
import { type DateRange, type LyraDatePickerDayContent, type LyraDatePickerDisabledDates, type LyraDatePickerFirstDayOfWeek, type LyraDatePickerPageBy, type LyraDateRangePreset } from './date-picker.class.js';
|
|
6
6
|
import './date-picker.class.js';
|
|
7
7
|
export type LyraDateInputSelectionDirection = 'forward' | 'backward' | 'none';
|
|
8
8
|
export type LyraDateInputPlacement = 'top' | 'top-start' | 'top-end' | 'right' | 'right-start' | 'right-end' | 'bottom' | 'bottom-start' | 'bottom-end' | 'left' | 'left-start' | 'left-end';
|
|
@@ -100,6 +100,8 @@ declare const LyraDateInput_base: typeof LyraDateInputBase & (new (...args: any[
|
|
|
100
100
|
* @csspart expand-icon - The calendar icon.
|
|
101
101
|
* @csspart popup - The positioned calendar popup.
|
|
102
102
|
* @csspart date-picker - The nested date picker.
|
|
103
|
+
* @csspart presets - The nested picker's quick-range row, forwarded from `<lr-date-picker>`.
|
|
104
|
+
* @csspart preset-button - One quick-range button, forwarded from `<lr-date-picker>`.
|
|
103
105
|
* @csspart hint - The hint message.
|
|
104
106
|
* @csspart error - The validation message.
|
|
105
107
|
* @cssprop [--lr-date-input-padding-block=var(--lr-space-xs)] - Block padding of the input row, scaled by `size`.
|
|
@@ -239,6 +241,15 @@ export declare class LyraDateInput extends LyraDateInput_base {
|
|
|
239
241
|
months: 1 | 2;
|
|
240
242
|
firstDayOfWeek: LyraDateInputFirstDayOfWeek;
|
|
241
243
|
weekdayFormat: WeekdayFormat;
|
|
244
|
+
/**
|
|
245
|
+
* Quick-range options forwarded verbatim to the nested `<lr-date-picker>`; see that component's
|
|
246
|
+
* own `presets` doc for the semantics. Range mode only, and unset renders nothing.
|
|
247
|
+
*
|
|
248
|
+
* Forwarded rather than reimplemented: the picker lives in this component's shadow root, so a
|
|
249
|
+
* consumer has no route to it -- a CSS part cannot set a JS property -- and this compact
|
|
250
|
+
* text-field-plus-popover shape is the one a dashboard time filter actually uses.
|
|
251
|
+
*/
|
|
252
|
+
presets: readonly LyraDateRangePreset[];
|
|
242
253
|
withOutsideDays: boolean;
|
|
243
254
|
withWeekNumbers: boolean;
|
|
244
255
|
disabledDates: LyraDatePickerDisabledDates;
|