@aceshooting/lyra-ui 28.1.2 → 28.1.3

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 CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 28.1.3
4
+
5
+ ### Patch Changes
6
+
7
+ - Preserve the original finite numeric values in heatmap and box-plot CSV exports. Default CSV numbers no longer pass through display rounding or locale-specific formatting; explicit box-plot export formatters, string formula-injection guards and no-data filtering remain in place.
8
+
9
+ Three aggregate bundle ceilings advance by only 2, 5 and 4 gzip bytes to the exact measured sizes required by the export correction. Other bundle limits remain unchanged.
10
+
11
+ - 53edd10: Package the default syntax-highlighting engine's reviewed WebAssembly asset beside its lazy loader. Markdown and code components now build without an unresolved asset warning when the optional Shiki peer is absent. The asset is fetched only when default-engine highlighting is requested and Shiki is available; JavaScript-engine and plain-text rendering do not fetch it. Include the upstream licenses and artifact provenance with the binary.
12
+
13
+ The portable asset reference and optional-engine capability check add 20–75 gzip bytes to ten direct JavaScript entries, 41 bytes to the component percentile and 46 bytes to its maximum. After removing an unnecessary loader module, those twelve breached bundle canaries advance to their exact measured bytes, with no added headroom. The release version string alone also changes gzip compression by 1–2 bytes in five entries; their breached ceilings advance by only 1–2 bytes to the exact measurements. All other ceilings, CSS budgets and optional-peer exclusions remain unchanged.
14
+
15
+ Packed consumer measurements include the reviewed 466,610-byte binary in their complete emitted-file totals. The core and code-block checks retain their existing non-asset ceilings and gain only that exact required-asset allowance; they also verify the emitted binary against the packaged asset, rejecting missing, changed, duplicate or additional WASM files. This does not grant extra JavaScript headroom. The package download grows by approximately 162 kB and remains within its unchanged delivery limits.
16
+ - @aceshooting/lyra-translations@28.1.3
17
+
3
18
  ## 28.1.2
4
19
 
5
20
  ### Patch Changes
@@ -152,5 +152,6 @@ valueFormatter?:LyraChartValueFormatter;
152
152
  formatter?:LyraChartFormatter;private loading;private loadFailed;private canvasUnavailable;private visible;private keyboardDatumIndex;private keyboardDatumAnnouncement;private intersectionObserver?;private intersectionGeneration;private readonly reducedMotionWatch;private canvasEl?;private chart?;private stopAnnotationRegistrationWatch?;private chartJsModule?;private loadGeneration;private descriptionId;private lastDrawnDirection?;private lastDrawnLocale?;private readonly announcements;private lastDataTruncationAnnouncement;private isMounting;connectedCallback():void;private onBoxPlotPluginLoaded;disconnectedCallback():void;adoptedCallback():void;private armReducedMotionWatcher;private disarmReducedMotionWatcher;private get ownerWindow();private effectiveHiddenDatasetIndexes;private applyDatasetVisibility;protected updated(changed:PropertyValues):void;private themeColors;private seriesColor;private seriesBorderColor;private seriesFillColor;private forcedColorFill;private styleColor;private styleNumber;private readonly tooltipIsolationPlugin;private buildConfig;private draw;private setCanvasUnavailable;private drawIfVisible;private rebuildAfterAnnotationRegistration;
153
153
  /** Re-reads canvas theme custom properties after an out-of-band ancestor theme change. */
154
154
  refreshTheme():void;private seriesDisplayLabel;private formatValue;
155
- /** Returns a spreadsheet-safe CSV snapshot or the current canvas PNG data URL. */
155
+ /** Returns a spreadsheet-safe CSV snapshot or the current canvas PNG data URL.
156
+ * CSV preserves raw summary precision unless `formatter` or `valueFormatter` supplies text. */
156
157
  exportData(format:'csv'|'png'):string;private boxPlotDescription;private boxDatums;private boxStatistics;private boxAnnouncement;private activateBox;private handlePointClick;private showKeyboardBox;private keyboardBoxShown;private readonly onCanvasBlur;private onCanvasFocus;private onCanvasKeyDown;private validPoint;private accessibleName;private dataTableSample;private generatedDataIsSampled;private dataTruncationMessage;private dataTableRows?;requestUpdate(...args:Parameters<LyraElement['requestUpdate']>):void;private renderDataTableRows;private renderDataTable;private hasCustomDataTable;private toggleDataset;private renderLegend;render():TemplateResult;}declare global{interface HTMLElementTagNameMap{'lr-box-plot':LyraBoxPlot;}}
@@ -1,4 +1,4 @@
1
- import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues}from"./chart-series-bounds.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createReducedMotionWatch}from"./chart-surface-shared.js";import{loadChartJs}from"./chart-core-loader.js";import{loadBoxPlotAndRegister}from"./box-plot-loader.js";import{loadBoxPlotAndRegister as loadBoxPlotAndRegister2}from"./box-plot-loader.js";import{onAnnotationPluginRegistered}from"../../../internal/chart-annotation-registration.js";import{styles}from"./box-plot.styles.js";import{chartSurfaceStyles}from"./chart-surface.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{showChartActiveDatum}from"./chart-active-datum.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{FALLBACK_GRID_COLOR,FALLBACK_LEGEND_COLOR,FALLBACK_TICK_COLOR,FALLBACK_TICK_FONT_SIZE,FALLBACK_TOOLTIP_BG,FALLBACK_TOOLTIP_TEXT}from"./chart-colors.js";import{ChartTokenCache}from"./chart-token-cache.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{canvasSentence,isolateCanvasLabel,isolateScaleTickLabels,tooltipIsolationHook,bidiStyles,isolateHtml}from"./chart-bidi.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_boxPlot,LYRA_DEFAULT_boxPlotData,LYRA_DEFAULT_boxPlotMax,LYRA_DEFAULT_boxPlotMedian,LYRA_DEFAULT_boxPlotMin,LYRA_DEFAULT_boxPlotMissingLibrary,LYRA_DEFAULT_boxPlotQ1,LYRA_DEFAULT_boxPlotQ3,LYRA_DEFAULT_boxPlotSeriesSummary,LYRA_DEFAULT_boxPlotSummaryEmpty,LYRA_DEFAULT_boxPlotSummaryWithData,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartRenderUnavailable,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";const DIRECT_PIXEL_NUMBER=new RegExp(`^(${CSS_NUMBER_SOURCE})(?:px)?$`,"i");function isBoxPlotSeries(value){return hasArraySeriesData(value)}function normalizeBoxPlotSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isBoxPlotSeries):[])}catch{return Object.freeze([])}}function summaryOf(point){return{min:point.min,q1:point.q1,median:point.median,q3:point.q3,max:point.max}}let boxPlotPlugin;function loadBoxPlotPlugin(){return boxPlotPlugin||(boxPlotPlugin=loadBoxPlotAndRegister()),boxPlotPlugin}class LyraBoxPlot extends LyraElement{static{this.defaultStrings={...super.defaultStrings,boxPlot:LYRA_DEFAULT_boxPlot,boxPlotData:LYRA_DEFAULT_boxPlotData,boxPlotMax:LYRA_DEFAULT_boxPlotMax,boxPlotMedian:LYRA_DEFAULT_boxPlotMedian,boxPlotMin:LYRA_DEFAULT_boxPlotMin,boxPlotMissingLibrary:LYRA_DEFAULT_boxPlotMissingLibrary,boxPlotQ1:LYRA_DEFAULT_boxPlotQ1,boxPlotQ3:LYRA_DEFAULT_boxPlotQ3,boxPlotSeriesSummary:LYRA_DEFAULT_boxPlotSeriesSummary,boxPlotSummaryEmpty:LYRA_DEFAULT_boxPlotSummaryEmpty,boxPlotSummaryWithData:LYRA_DEFAULT_boxPlotSummaryWithData,chartCategory:LYRA_DEFAULT_chartCategory,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartRenderUnavailable:LYRA_DEFAULT_chartRenderUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartValueLabel:LYRA_DEFAULT_chartValueLabel,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","hiddenDatasets"])}static{this.styles=[LyraElement.styles,specialistTokens,chartSurfaceStyles,styles,srOnly,bidiStyles]}static{this.immutableEventDetails=Object.freeze(["lr-legend-visibility-change-request","lr-legend-visibility-change"])}constructor(){super(),this.canvasTokens=new ChartTokenCache(this),this.labels=[],this._datasets=Object.freeze([]),this.datasetsSource=this._datasets,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.label=null,this.description=null,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("box-plot-data-table"),this.loading=!0,this.loadFailed=!1,this.canvasUnavailable=!1,this.visible=!0,this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.intersectionGeneration=0,this.reducedMotionWatch=createReducedMotionWatch(this,()=>this.drawIfVisible()),this.loadGeneration=0,this.descriptionId=nextId("box-plot-description"),this.announcements=new AnnouncementSinkController(this),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.tooltipIsolationPlugin={id:"lyra-box-plot-bidi",beforeTooltipDraw:tooltipIsolationHook(()=>this.effectiveDirection)},this.keyboardBoxShown=!1,this.onCanvasBlur=()=>{this.showKeyboardBox(void 0)},new ThemeWatcher(this,()=>{this.chart&&this.canvasTokens.hasThemeChanged()&&this.refreshTheme()})}get datasets(){return this._datasets}set datasets(value){if(Object.is(value,this.datasetsSource)||Object.is(value,this._datasets))return;const previous=this._datasets;this.datasetsSource=value,this._datasets=normalizeBoxPlotSeries(snapshotPublicCollection(boundChartSeriesValues(value,6)??value,this.ownerDocument?.defaultView)),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}connectedCallback(){super.connectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const generation=++this.loadGeneration;loadBoxPlotPlugin().then(boxMod=>this.onBoxPlotPluginLoaded(boxMod,generation));const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const ownerWindow=this.ownerWindow,observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}async onBoxPlotPluginLoaded(boxMod,generation=this.loadGeneration){if(generation!==this.loadGeneration||!this.isConnected)return;try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),generation!==this.loadGeneration||!this.isConnected)return;if(this.loading=!1,!boxMod){this.loadFailed=!0,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.chartJsModule=void 0;return}this.loadFailed=!1;const chartMod=await loadChartJs();generation!==this.loadGeneration||!this.isConnected||(this.chartJsModule=chartMod??void 0,this.drawIfVisible())}disconnectedCallback(){super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.loadGeneration+=1,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}effectiveHiddenDatasetIndexes(){return normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length)??[]}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceSeriesIndexes=this.dataTableSample().seriesIndexes,controlled=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++)this.chart.setDatasetVisibility(index,!hidden.has(sourceSeriesIndexes[index]??index));return datasetCount>0}updated(changed){super.updated(changed);const appliedVisibility=this.appliedLegendVisibility;if(this.appliedLegendVisibility=void 0,!this.isConnected)return;const wasMounting=this.isMounting;this.isMounting=!1,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("boxPlotMissingLibrary"));const dataTruncation=this.dataTruncationMessage();if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed&&!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.setAttribute("aria-busy",String(this.loading)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;const visibilityAlreadyApplied=appliedVisibility!==void 0&&appliedVisibility.chart===this.chart&&appliedVisibility.hidden===this.hiddenDatasets,contentChanged=["labels","datasets","hiddenDatasets","withLegend","legendPosition","height","xLabel","yLabel","withoutZeroBaseline","valueFormatter","formatter","locale","strings","loading"].some(name=>changed.has(name)&&(name!=="hiddenDatasets"||!visibilityAlreadyApplied)),direction=this.effectiveDirection,locale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==direction||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==locale;this.lastDrawnDirection=direction,this.lastDrawnLocale=locale,!(!contentChanged&&!contextChanged)&&this.drawIfVisible()}themeColors(){const cs=this.canvasTokens.sync()??this.style;return{grid:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE,"--_lr-chart-tick-font-size"),legend:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim(),FALLBACK_TOOLTIP_TEXT)}}seriesColor(index,palette=this.canvasTokens.palette()){const fallback=palette[index%palette.length]??"transparent",series=this.datasets[index];return series?.color?this.canvasTokens.resolve(series.color,fallback):fallback}seriesBorderColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-border-color-${index%8+1}`,base)}seriesFillColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-fill-color-${index%8+1}`,base)}forcedColorFill(index,background){return!this.ownerWindow||!forcedColorsActive(this.ownerWindow)?background:createForcedColorPattern(this.ownerDocument,index,background,this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG))}styleColor(name,fallback){const view=this.ownerWindow,value=(view?view.getComputedStyle(this):this.style).getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallback,fallbackToken){const view=this.ownerWindow,cs=view?view.getComputedStyle(this):this.style,value=cs.getPropertyValue(name).trim()||(fallbackToken?cs.getPropertyValue(fallbackToken).trim():""),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!view)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(view.getComputedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}buildConfig(){const theme=this.themeColors(),palette=this.canvasTokens.palette(),sample=this.dataTableSample(),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",afterTickToLabelConversion=scale=>isolateScaleTickLabels(scale,direction);return{type:"boxplot",data:{labels:sample.rowIndexes.map(index=>this.labels[index]??""),datasets:sample.seriesIndexes.map(sourceIndex=>{const s=this.datasets[sourceIndex],fillColor=this.seriesFillColor(sourceIndex,palette),borderColor=this.seriesBorderColor(sourceIndex,palette);return{label:s.label,data:sample.rowIndexes.map(index=>{const point=s.data[index];return this.validPoint(point)?summaryOf(point):null}),backgroundColor:this.forcedColorFill(sourceIndex,fillColor),borderColor}})},options:{locale:this.effectiveLocale,responsive:!0,maintainAspectRatio:!1,animation:prefersReducedMotion(this)?!1:void 0,onClick:(event,_elements,chart)=>this.handlePointClick(event,chart),elements:{boxandwhiskers:{borderWidth:this.styleNumber("--lr-box-plot-border-width",1,"--lr-border-width-thin"),itemRadius:this.styleNumber("--lr-box-plot-item-radius",0)}},plugins:{legend:{display:!1,labels:{color:theme.legend}},tooltip:{backgroundColor:theme.tooltipBg,titleColor:theme.tooltipText,bodyColor:theme.tooltipText,...this.formatter||this.valueFormatter?{callbacks:{label:context=>{const raw=context.raw,point=this.validPoint(raw)?raw:void 0;if(!point)return;const datasetIndex=Number.isInteger(context.datasetIndex)?sample.seriesIndexes[context.datasetIndex]:void 0,index=Number.isInteger(context.dataIndex)?sample.rowIndexes[context.dataIndex]:void 0,lines=this.boxStatistics(point).map(([statistic,name,value])=>canvasSentence(sentenceValue=>this.localize("chartValueLabel",void 0,{label:name,value:sentenceValue}),this.formatValue(value,"tooltip",{...datasetIndex===void 0?{}:{datasetIndex},...index===void 0?{}:{index,label:this.labels[index]||void 0},...datasetIndex===void 0?{}:{seriesLabel:this.datasets[datasetIndex]?.label},statistic,axis:"y"}))),label=String(context.dataset?.label??"");return label?[label,...lines]:lines}}}:{}}},scales:{x:{afterTickToLabelConversion,title:{display:!!this.xLabel,text:isolateCanvasLabel(this.xLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize}},grid:{color:theme.grid}},y:{afterTickToLabelConversion,position:this.effectiveDirection==="rtl"?"right":"left",beginAtZero:!this.withoutZeroBaseline,title:{display:!!this.yLabel,text:isolateCanvasLabel(this.yLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize},...this.formatter||this.valueFormatter?{callback:value=>this.formatValue(Number(value),"tick",{axis:"y"})}:{}},grid:{color:theme.grid}}}}}}draw(){if(!this.chartJsModule||!this.canvasEl)return;if(!this.chart&&!this.canvasEl.getContext("2d")){this.setCanvasUnavailable(!0);return}this.canvasTokens.beginThemeDraw();const config=this.buildConfig();if(this.chart){this.chart.data=config.data,this.chart.options=config.options??{},this.applyDatasetVisibility(),this.chart.update("none"),this.canvasTokens.rememberTheme();return}const candidate=new this.chartJsModule.Chart(this.canvasEl,{...config,plugins:[this.tooltipIsolationPlugin]}),context=candidate;if(context.canvas===null||context.ctx===null){candidate.destroy(),this.setCanvasUnavailable(!0);return}this.chart=candidate,this.setCanvasUnavailable(!1),this.hiddenDatasets!==void 0&&(this.applyDatasetVisibility(),this.chart.update("none")),this.canvasTokens.rememberTheme()}setCanvasUnavailable(unavailable){this.canvasUnavailable!==unavailable&&(this.canvasUnavailable=unavailable,queueMicrotask(()=>{this.isConnected&&this.requestUpdate()}),unavailable&&this.announcements.announceAssertive(this.localize("chartRenderUnavailable")))}drawIfVisible(){!this.isConnected||!this.visible||this.draw()}rebuildAfterAnnotationRegistration(){this.chart&&(this.appliedLegendVisibility=void 0,this.chart.destroy(),this.chart=void 0,this.drawIfVisible())}refreshTheme(){this.canvasTokens.clear(),this.drawIfVisible(),this.withLegend&&this.requestUpdate()}seriesDisplayLabel(series){return series.label||this.localize("chartSeriesLabel")}formatValue(value,surface,metadata={}){const legacyContext=surface==="export"||surface==="spoken"?"table":surface==="visual"?void 0:surface;return this.formatter?.({value,surface,...metadata})??(legacyContext?this.valueFormatter?.(value,legacyContext):void 0)??formatChartValue(value,this.effectiveLocale)}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const header=["category","series","min","q1","median","q3","max"].map(escapeCsvField).join(","),rows=[];return this.datasets.forEach((series,datasetIndex)=>{series.data.forEach((point,index)=>{if(!this.validPoint(point))return;const metadata={datasetIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};rows.push([this.labels[index]??"",this.seriesDisplayLabel(series),this.formatValue(point.min,"export",{...metadata,statistic:"min"}),this.formatValue(point.q1,"export",{...metadata,statistic:"q1"}),this.formatValue(point.median,"export",{...metadata,statistic:"median"}),this.formatValue(point.q3,"export",{...metadata,statistic:"q3"}),this.formatValue(point.max,"export",{...metadata,statistic:"max"})].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
1
+ import{__decorate}from"tslib";import{collectionSupport,snapshotPublicCollection}from"../../../internal/collection-snapshot.js";import{boundChartSeriesValues}from"./chart-series-bounds.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{LyraElement}from"../../../internal/lyra-element.js";import{nextId,srOnly}from"../../../internal/a11y.js";import{prefersReducedMotion}from"../../../internal/motion.js";import{createReducedMotionWatch}from"./chart-surface-shared.js";import{loadChartJs}from"./chart-core-loader.js";import{loadBoxPlotAndRegister}from"./box-plot-loader.js";import{loadBoxPlotAndRegister as loadBoxPlotAndRegister2}from"./box-plot-loader.js";import{onAnnotationPluginRegistered}from"../../../internal/chart-annotation-registration.js";import{styles}from"./box-plot.styles.js";import{chartSurfaceStyles}from"./chart-surface.styles.js";import"../../overlays/skeleton/skeleton.class.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{formatChartValue}from"./chart-number-format.js";import{isKeyboardFocusEvent}from"../../../internal/focus-modality.js";import{showChartActiveDatum}from"./chart-active-datum.js";import{sanitizeCssLength}from"../../../internal/safe-css.js";import{FALLBACK_GRID_COLOR,FALLBACK_LEGEND_COLOR,FALLBACK_TICK_COLOR,FALLBACK_TICK_FONT_SIZE,FALLBACK_TOOLTIP_BG,FALLBACK_TOOLTIP_TEXT}from"./chart-colors.js";import{ChartTokenCache}from"./chart-token-cache.js";import{chartDataTableVisible,hasSlottedChartDataTable,hasArraySeriesData}from"./chart-data-table.js";import{createForcedColorPattern,forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{specialistTokens}from"../../../internal/specialist-host-tokens.styles.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{legendVisibilityDetail,normalizeHiddenDatasets}from"./chart-legend-visibility.js";import{sampleChartTableIndexes}from"./chart-table-sampling.js";import{canvasSentence,isolateCanvasLabel,isolateScaleTickLabels,tooltipIsolationHook,bidiStyles,isolateHtml}from"./chart-bidi.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{CSS_NUMBER_SOURCE}from"../../../internal/css-number.js";import{LYRA_DEFAULT_boxPlot,LYRA_DEFAULT_boxPlotData,LYRA_DEFAULT_boxPlotMax,LYRA_DEFAULT_boxPlotMedian,LYRA_DEFAULT_boxPlotMin,LYRA_DEFAULT_boxPlotMissingLibrary,LYRA_DEFAULT_boxPlotQ1,LYRA_DEFAULT_boxPlotQ3,LYRA_DEFAULT_boxPlotSeriesSummary,LYRA_DEFAULT_boxPlotSummaryEmpty,LYRA_DEFAULT_boxPlotSummaryWithData,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartPlotSampled,LYRA_DEFAULT_chartPointLabel,LYRA_DEFAULT_chartRenderUnavailable,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartSeriesNoData,LYRA_DEFAULT_chartSummarySeparator,LYRA_DEFAULT_chartTrendDecreasing,LYRA_DEFAULT_chartTrendFlat,LYRA_DEFAULT_chartTrendIncreasing,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings/charts.generated.js";import{LYRA_DEFAULT_chartValueLabel,LYRA_DEFAULT_loading}from"../../../internal/default-strings/shared.generated.js";const DIRECT_PIXEL_NUMBER=new RegExp(`^(${CSS_NUMBER_SOURCE})(?:px)?$`,"i");function isBoxPlotSeries(value){return hasArraySeriesData(value)}function normalizeBoxPlotSeries(value){try{return Object.freeze(Array.isArray(value)?value.filter(isBoxPlotSeries):[])}catch{return Object.freeze([])}}function summaryOf(point){return{min:point.min,q1:point.q1,median:point.median,q3:point.q3,max:point.max}}let boxPlotPlugin;function loadBoxPlotPlugin(){return boxPlotPlugin||(boxPlotPlugin=loadBoxPlotAndRegister()),boxPlotPlugin}class LyraBoxPlot extends LyraElement{static{this.defaultStrings={...super.defaultStrings,boxPlot:LYRA_DEFAULT_boxPlot,boxPlotData:LYRA_DEFAULT_boxPlotData,boxPlotMax:LYRA_DEFAULT_boxPlotMax,boxPlotMedian:LYRA_DEFAULT_boxPlotMedian,boxPlotMin:LYRA_DEFAULT_boxPlotMin,boxPlotMissingLibrary:LYRA_DEFAULT_boxPlotMissingLibrary,boxPlotQ1:LYRA_DEFAULT_boxPlotQ1,boxPlotQ3:LYRA_DEFAULT_boxPlotQ3,boxPlotSeriesSummary:LYRA_DEFAULT_boxPlotSeriesSummary,boxPlotSummaryEmpty:LYRA_DEFAULT_boxPlotSummaryEmpty,boxPlotSummaryWithData:LYRA_DEFAULT_boxPlotSummaryWithData,chartCategory:LYRA_DEFAULT_chartCategory,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartPlotSampled:LYRA_DEFAULT_chartPlotSampled,chartPointLabel:LYRA_DEFAULT_chartPointLabel,chartRenderUnavailable:LYRA_DEFAULT_chartRenderUnavailable,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartSeriesNoData:LYRA_DEFAULT_chartSeriesNoData,chartSummarySeparator:LYRA_DEFAULT_chartSummarySeparator,chartTrendDecreasing:LYRA_DEFAULT_chartTrendDecreasing,chartTrendFlat:LYRA_DEFAULT_chartTrendFlat,chartTrendIncreasing:LYRA_DEFAULT_chartTrendIncreasing,chartValueLabel:LYRA_DEFAULT_chartValueLabel,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary,loading:LYRA_DEFAULT_loading}}static{this.collectionSupport=collectionSupport}static{this.ownedCollectionProperties=Object.freeze(["labels","hiddenDatasets"])}static{this.styles=[LyraElement.styles,specialistTokens,chartSurfaceStyles,styles,srOnly,bidiStyles]}static{this.immutableEventDetails=Object.freeze(["lr-legend-visibility-change-request","lr-legend-visibility-change"])}constructor(){super(),this.canvasTokens=new ChartTokenCache(this),this.labels=[],this._datasets=Object.freeze([]),this.datasetsSource=this._datasets,this.withLegend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.withoutZeroBaseline=!1,this.label=null,this.description=null,this.withDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("box-plot-data-table"),this.loading=!0,this.loadFailed=!1,this.canvasUnavailable=!1,this.visible=!0,this.keyboardDatumIndex=0,this.keyboardDatumAnnouncement="",this.intersectionGeneration=0,this.reducedMotionWatch=createReducedMotionWatch(this,()=>this.drawIfVisible()),this.loadGeneration=0,this.descriptionId=nextId("box-plot-description"),this.announcements=new AnnouncementSinkController(this),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.tooltipIsolationPlugin={id:"lyra-box-plot-bidi",beforeTooltipDraw:tooltipIsolationHook(()=>this.effectiveDirection)},this.keyboardBoxShown=!1,this.onCanvasBlur=()=>{this.showKeyboardBox(void 0)},new ThemeWatcher(this,()=>{this.chart&&this.canvasTokens.hasThemeChanged()&&this.refreshTheme()})}get datasets(){return this._datasets}set datasets(value){if(Object.is(value,this.datasetsSource)||Object.is(value,this._datasets))return;const previous=this._datasets;this.datasetsSource=value,this._datasets=normalizeBoxPlotSeries(snapshotPublicCollection(boundChartSeriesValues(value,6)??value,this.ownerDocument?.defaultView)),this.requestUpdate("datasets",previous)}get dataTableVisible(){return chartDataTableVisible(this.withDataTable,this.dataTableToggle,this.dataTableExpandedOverride)}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}connectedCallback(){super.connectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=onAnnotationPluginRegistered(()=>this.rebuildAfterAnnotationRegistration()),this.visible=!this.ownerWindow?.IntersectionObserver,this.armReducedMotionWatcher();const generation=++this.loadGeneration;loadBoxPlotPlugin().then(boxMod=>this.onBoxPlotPluginLoaded(boxMod,generation));const IntersectionObserverCtor=this.ownerWindow?.IntersectionObserver;if(IntersectionObserverCtor){const ownerWindow=this.ownerWindow,observerGeneration=++this.intersectionGeneration,observer=new IntersectionObserverCtor(entries=>{if(observerGeneration!==this.intersectionGeneration||this.intersectionObserver!==observer||!this.isConnected||this.ownerWindow!==ownerWindow)return;const wasVisible=this.visible;this.visible=entries[0]?.isIntersecting??!0,this.visible&&!wasVisible&&this.drawIfVisible()});this.intersectionObserver=observer,observer.observe(this)}}async onBoxPlotPluginLoaded(boxMod,generation=this.loadGeneration){if(generation!==this.loadGeneration||!this.isConnected)return;try{await this.updateComplete}catch{return}if(await new Promise(resolve=>this.updateBrowserDerivedState(resolve)),generation!==this.loadGeneration||!this.isConnected)return;if(this.loading=!1,!boxMod){this.loadFailed=!0,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.chartJsModule=void 0;return}this.loadFailed=!1;const chartMod=await loadChartJs();generation!==this.loadGeneration||!this.isConnected||(this.chartJsModule=chartMod??void 0,this.drawIfVisible())}disconnectedCallback(){super.disconnectedCallback(),this.stopAnnotationRegistrationWatch?.(),this.stopAnnotationRegistrationWatch=void 0,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.loadGeneration+=1,this.appliedLegendVisibility=void 0,this.chart?.destroy(),this.chart=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.intersectionGeneration+=1,this.visible=!0,this.disarmReducedMotionWatcher()}adoptedCallback(){this.canvasTokens.clear(),super.adoptedCallback(),this.announcements.adopted(),this.disarmReducedMotionWatcher(),this.armReducedMotionWatcher()}armReducedMotionWatcher(){this.reducedMotionWatch.arm()}disarmReducedMotionWatcher(){this.reducedMotionWatch.disarm()}get ownerWindow(){return this.ownerDocument?.defaultView??void 0}effectiveHiddenDatasetIndexes(){return normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length)??[]}applyDatasetVisibility(){if(!this.chart)return!1;const datasetCount=this.chart.data.datasets?.length??0,sourceSeriesIndexes=this.dataTableSample().seriesIndexes,controlled=normalizeHiddenDatasets(this.hiddenDatasets,this.datasets.length);if(controlled===void 0){for(let index=0;index<datasetCount;index++){const metadata=this.chart.getDatasetMeta?.(index);metadata&&(metadata.hidden=null)}return datasetCount>0}const hidden=new Set(controlled);for(let index=0;index<datasetCount;index++)this.chart.setDatasetVisibility(index,!hidden.has(sourceSeriesIndexes[index]??index));return datasetCount>0}updated(changed){super.updated(changed);const appliedVisibility=this.appliedLegendVisibility;if(this.appliedLegendVisibility=void 0,!this.isConnected)return;const wasMounting=this.isMounting;this.isMounting=!1,changed.has("keyboardDatumAnnouncement")&&changed.get("keyboardDatumAnnouncement")!==void 0&&this.keyboardDatumAnnouncement!==""&&this.announcements.announcePolite(this.keyboardDatumAnnouncement),changed.has("loadFailed")&&changed.get("loadFailed")!==void 0&&this.loadFailed&&this.announcements.announceAssertive(this.localize("boxPlotMissingLibrary"));const dataTruncation=this.dataTruncationMessage();if(wasMounting&&(this.lastDataTruncationAnnouncement=dataTruncation),!this.loading&&!this.loadFailed&&!wasMounting&&dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.announcements.announcePolite(dataTruncation)),this.setAttribute("aria-busy",String(this.loading)),changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}if(this.loading)return;const visibilityAlreadyApplied=appliedVisibility!==void 0&&appliedVisibility.chart===this.chart&&appliedVisibility.hidden===this.hiddenDatasets,contentChanged=["labels","datasets","hiddenDatasets","withLegend","legendPosition","height","xLabel","yLabel","withoutZeroBaseline","valueFormatter","formatter","locale","strings","loading"].some(name=>changed.has(name)&&(name!=="hiddenDatasets"||!visibilityAlreadyApplied)),direction=this.effectiveDirection,locale=this.effectiveLocale,contextChanged=this.lastDrawnDirection!==void 0&&this.lastDrawnDirection!==direction||this.lastDrawnLocale!==void 0&&this.lastDrawnLocale!==locale;this.lastDrawnDirection=direction,this.lastDrawnLocale=locale,!(!contentChanged&&!contextChanged)&&this.drawIfVisible()}themeColors(){const cs=this.canvasTokens.sync()??this.style;return{grid:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-grid-color").trim()||cs.getPropertyValue("--_lr-chart-grid-color").trim(),FALLBACK_GRID_COLOR),tick:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tick-color").trim()||cs.getPropertyValue("--_lr-chart-tick-color").trim(),FALLBACK_TICK_COLOR),tickFontSize:this.styleNumber("--lr-chart-tick-font-size",FALLBACK_TICK_FONT_SIZE,"--_lr-chart-tick-font-size"),legend:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-legend-color").trim()||cs.getPropertyValue("--_lr-chart-legend-color").trim(),FALLBACK_LEGEND_COLOR),tooltipBg:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-bg").trim()||cs.getPropertyValue("--_lr-chart-tooltip-bg").trim(),FALLBACK_TOOLTIP_BG),tooltipText:this.canvasTokens.resolve(cs.getPropertyValue("--lr-chart-tooltip-color").trim()||cs.getPropertyValue("--_lr-chart-tooltip-color").trim(),FALLBACK_TOOLTIP_TEXT)}}seriesColor(index,palette=this.canvasTokens.palette()){const fallback=palette[index%palette.length]??"transparent",series=this.datasets[index];return series?.color?this.canvasTokens.resolve(series.color,fallback):fallback}seriesBorderColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-border-color-${index%8+1}`,base)}seriesFillColor(index,palette=this.canvasTokens.palette()){const base=this.seriesColor(index,palette);return this.styleColor(`--lr-box-plot-fill-color-${index%8+1}`,base)}forcedColorFill(index,background){return!this.ownerWindow||!forcedColorsActive(this.ownerWindow)?background:createForcedColorPattern(this.ownerDocument,index,background,this.styleColor("--lr-color-surface",FALLBACK_TOOLTIP_BG))}styleColor(name,fallback){const view=this.ownerWindow,value=(view?view.getComputedStyle(this):this.style).getPropertyValue(name).trim();return value?this.canvasTokens.resolve(value,fallback):fallback}styleNumber(name,fallback,fallbackToken){const view=this.ownerWindow,cs=view?view.getComputedStyle(this):this.style,value=cs.getPropertyValue(name).trim()||(fallbackToken?cs.getPropertyValue(fallbackToken).trim():""),direct=DIRECT_PIXEL_NUMBER.exec(value);if(direct){const resolved2=Number.parseFloat(direct[1]);if(Number.isFinite(resolved2)&&resolved2>=0)return resolved2}if(!value||!view)return fallback;const resolved=this.canvasTokens.length(value,()=>{const probe=this.ownerDocument.createElement("span");probe.hidden=!0,probe.setAttribute("aria-hidden","true"),probe.style.inlineSize=value,(this.shadowRoot??this).append(probe);try{return Number.parseFloat(view.getComputedStyle(probe).inlineSize)}finally{probe.remove()}});return Number.isFinite(resolved)&&resolved>=0?resolved:fallback}buildConfig(){const theme=this.themeColors(),palette=this.canvasTokens.palette(),sample=this.dataTableSample(),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",afterTickToLabelConversion=scale=>isolateScaleTickLabels(scale,direction);return{type:"boxplot",data:{labels:sample.rowIndexes.map(index=>this.labels[index]??""),datasets:sample.seriesIndexes.map(sourceIndex=>{const s=this.datasets[sourceIndex],fillColor=this.seriesFillColor(sourceIndex,palette),borderColor=this.seriesBorderColor(sourceIndex,palette);return{label:s.label,data:sample.rowIndexes.map(index=>{const point=s.data[index];return this.validPoint(point)?summaryOf(point):null}),backgroundColor:this.forcedColorFill(sourceIndex,fillColor),borderColor}})},options:{locale:this.effectiveLocale,responsive:!0,maintainAspectRatio:!1,animation:prefersReducedMotion(this)?!1:void 0,onClick:(event,_elements,chart)=>this.handlePointClick(event,chart),elements:{boxandwhiskers:{borderWidth:this.styleNumber("--lr-box-plot-border-width",1,"--lr-border-width-thin"),itemRadius:this.styleNumber("--lr-box-plot-item-radius",0)}},plugins:{legend:{display:!1,labels:{color:theme.legend}},tooltip:{backgroundColor:theme.tooltipBg,titleColor:theme.tooltipText,bodyColor:theme.tooltipText,...this.formatter||this.valueFormatter?{callbacks:{label:context=>{const raw=context.raw,point=this.validPoint(raw)?raw:void 0;if(!point)return;const datasetIndex=Number.isInteger(context.datasetIndex)?sample.seriesIndexes[context.datasetIndex]:void 0,index=Number.isInteger(context.dataIndex)?sample.rowIndexes[context.dataIndex]:void 0,lines=this.boxStatistics(point).map(([statistic,name,value])=>canvasSentence(sentenceValue=>this.localize("chartValueLabel",void 0,{label:name,value:sentenceValue}),this.formatValue(value,"tooltip",{...datasetIndex===void 0?{}:{datasetIndex},...index===void 0?{}:{index,label:this.labels[index]||void 0},...datasetIndex===void 0?{}:{seriesLabel:this.datasets[datasetIndex]?.label},statistic,axis:"y"}))),label=String(context.dataset?.label??"");return label?[label,...lines]:lines}}}:{}}},scales:{x:{afterTickToLabelConversion,title:{display:!!this.xLabel,text:isolateCanvasLabel(this.xLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize}},grid:{color:theme.grid}},y:{afterTickToLabelConversion,position:this.effectiveDirection==="rtl"?"right":"left",beginAtZero:!this.withoutZeroBaseline,title:{display:!!this.yLabel,text:isolateCanvasLabel(this.yLabel,direction),color:theme.tick},ticks:{color:theme.tick,font:{size:theme.tickFontSize},...this.formatter||this.valueFormatter?{callback:value=>this.formatValue(Number(value),"tick",{axis:"y"})}:{}},grid:{color:theme.grid}}}}}}draw(){if(!this.chartJsModule||!this.canvasEl)return;if(!this.chart&&!this.canvasEl.getContext("2d")){this.setCanvasUnavailable(!0);return}this.canvasTokens.beginThemeDraw();const config=this.buildConfig();if(this.chart){this.chart.data=config.data,this.chart.options=config.options??{},this.applyDatasetVisibility(),this.chart.update("none"),this.canvasTokens.rememberTheme();return}const candidate=new this.chartJsModule.Chart(this.canvasEl,{...config,plugins:[this.tooltipIsolationPlugin]}),context=candidate;if(context.canvas===null||context.ctx===null){candidate.destroy(),this.setCanvasUnavailable(!0);return}this.chart=candidate,this.setCanvasUnavailable(!1),this.hiddenDatasets!==void 0&&(this.applyDatasetVisibility(),this.chart.update("none")),this.canvasTokens.rememberTheme()}setCanvasUnavailable(unavailable){this.canvasUnavailable!==unavailable&&(this.canvasUnavailable=unavailable,queueMicrotask(()=>{this.isConnected&&this.requestUpdate()}),unavailable&&this.announcements.announceAssertive(this.localize("chartRenderUnavailable")))}drawIfVisible(){!this.isConnected||!this.visible||this.draw()}rebuildAfterAnnotationRegistration(){this.chart&&(this.appliedLegendVisibility=void 0,this.chart.destroy(),this.chart=void 0,this.drawIfVisible())}refreshTheme(){this.canvasTokens.clear(),this.drawIfVisible(),this.withLegend&&this.requestUpdate()}seriesDisplayLabel(series){return series.label||this.localize("chartSeriesLabel")}formatValue(value,surface,metadata={}){const legacyContext=surface==="export"||surface==="spoken"?"table":surface==="visual"?void 0:surface;return this.formatter?.({value,surface,...metadata})??(legacyContext?this.valueFormatter?.(value,legacyContext):void 0)??(surface==="export"?value:formatChartValue(value,this.effectiveLocale))}exportData(format){if(format==="png")return this.chart?.toBase64Image?.()??"";const header=["category","series","min","q1","median","q3","max"].map(escapeCsvField).join(","),rows=[];return this.datasets.forEach((series,datasetIndex)=>{series.data.forEach((point,index)=>{if(!this.validPoint(point))return;const metadata={datasetIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};rows.push([this.labels[index]??"",this.seriesDisplayLabel(series),this.formatValue(point.min,"export",{...metadata,statistic:"min"}),this.formatValue(point.q1,"export",{...metadata,statistic:"q1"}),this.formatValue(point.median,"export",{...metadata,statistic:"median"}),this.formatValue(point.q3,"export",{...metadata,statistic:"q3"}),this.formatValue(point.max,"export",{...metadata,statistic:"max"})].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
2
2
  `)}boxPlotDescription(){if(this.description)return this.description;const summaries=this.dataTableSample().seriesIndexes.map(index=>{const series=this.datasets[index];let count=0,first=0,last=0,min=0,minIndex=0,max=0,maxIndex=0;for(const[pointIndex,point]of series.data.entries())this.validPoint(point)&&(count===0&&(first=point.median,min=point.median,minIndex=pointIndex,max=point.median,maxIndex=pointIndex),last=point.median,point.median<min&&(min=point.median,minIndex=pointIndex),point.median>max&&(max=point.median,maxIndex=pointIndex),count++);if(count===0)return this.localize("chartSeriesNoData",void 0,{label:this.seriesDisplayLabel(series)});const trend=last>first?this.localize("chartTrendIncreasing"):last<first?this.localize("chartTrendDecreasing"):this.localize("chartTrendFlat");return this.localize("boxPlotSeriesSummary",void 0,{label:this.seriesDisplayLabel(series),count:getNumberFormat(this.effectiveLocale).format(count),min:this.formatValue(min,"spoken",{datasetIndex:index,index:minIndex,label:this.labels[minIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),max:this.formatValue(max,"spoken",{datasetIndex:index,index:maxIndex,label:this.labels[maxIndex]||void 0,seriesLabel:series.label,statistic:"median",axis:"y"}),trend})});return summaries.length?this.localize("boxPlotSummaryWithData",void 0,{summaries:summaries.join(this.localize("chartSummarySeparator"))}):this.localize("boxPlotSummaryEmpty")}boxDatums(){const sample=this.dataTableSample(),datums=[];for(const datasetIndex of sample.seriesIndexes){const series=this.datasets[datasetIndex];if(series)for(const index of sample.rowIndexes){const point=series.data[index];this.validPoint(point)&&datums.push({datasetIndex,index,label:this.labels[index]||void 0,value:summaryOf(point)})}}return datums}boxStatistics(point){return[["min",this.localize("boxPlotMin"),point.min],["q1",this.localize("boxPlotQ1"),point.q1],["median",this.localize("boxPlotMedian"),point.median],["q3",this.localize("boxPlotQ3"),point.q3],["max",this.localize("boxPlotMax"),point.max]]}boxAnnouncement(datum,position,total){const numberFormat=getNumberFormat(this.effectiveLocale),point=datum.value,summary=(point?this.boxStatistics(point):[]).filter(([,,value])=>Number.isFinite(value)).map(([statistic,label,value])=>this.localize("chartValueLabel",void 0,{label,value:this.formatValue(value,"spoken",{datasetIndex:datum.datasetIndex,index:datum.index,label:datum.label,seriesLabel:this.datasets[datum.datasetIndex]?.label,statistic,axis:"y"})})).join(this.localize("chartSummarySeparator"));return this.localize("liteChartMarkSummary",void 0,{series:this.datasets[datum.datasetIndex]?.label||this.localize("chartSeriesLabel"),label:datum.label??this.localize("chartPointLabel",void 0,{n:numberFormat.format(datum.index+1)}),value:summary,index:numberFormat.format(position+1),total:numberFormat.format(total)})}activateBox(datum){const datums=this.boxDatums(),position=datums.findIndex(candidate=>candidate.datasetIndex===datum.datasetIndex&&candidate.index===datum.index);position>=0&&(this.keyboardDatumIndex=position,this.keyboardDatumAnnouncement=this.boxAnnouncement(datum,position,datums.length)),this.emit("lr-datum-activate",{...datum,kind:"box"}),this.emit("lr-point-activate",{...datum})}handlePointClick(event,chart){const hit=chart.getElementsAtEventForMode?.(event,"nearest",{intersect:!0},!0)?.[0];if(!hit)return;const sample=this.dataTableSample(),datasetIndex=sample.seriesIndexes[hit.datasetIndex],index=sample.rowIndexes[hit.index];if(datasetIndex===void 0||index===void 0)return;const point=this.datasets[datasetIndex]?.data[index];this.activateBox({datasetIndex,index,label:this.labels[index]||void 0,value:this.validPoint(point)?summaryOf(point):null})}showKeyboardBox(datum){if(!this.chart||!datum&&!this.keyboardBoxShown)return;const sample=this.dataTableSample();this.keyboardBoxShown=showChartActiveDatum(this.chart,datum&&{datasetIndex:sample.seriesIndexes.indexOf(datum.datasetIndex),index:sample.rowIndexes.indexOf(datum.index)})}onCanvasFocus(event){const datums=this.boxDatums();datums.length&&(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),isKeyboardFocusEvent(event)&&this.showKeyboardBox(datums[this.keyboardDatumIndex]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[this.keyboardDatumIndex],this.keyboardDatumIndex,datums.length))}onCanvasKeyDown(event){const datums=this.boxDatums();if(!datums.length)return;if(this.keyboardDatumIndex=Math.min(this.keyboardDatumIndex,datums.length-1),event.key==="Enter"||event.key===" "){event.preventDefault(),this.activateBox(datums[this.keyboardDatumIndex]);return}const rtl=this.effectiveDirection==="rtl",forward=rtl?"ArrowLeft":"ArrowRight",backward=rtl?"ArrowRight":"ArrowLeft";let next=this.keyboardDatumIndex;if(event.key===forward||event.key==="ArrowDown")next=Math.min(datums.length-1,next+1);else if(event.key===backward||event.key==="ArrowUp")next=Math.max(0,next-1);else if(event.key==="Home")next=0;else if(event.key==="End")next=datums.length-1;else return;event.preventDefault(),this.keyboardDatumIndex=next,this.showKeyboardBox(datums[next]),this.keyboardDatumAnnouncement=this.boxAnnouncement(datums[next],next,datums.length)}validPoint(point){return!!point&&[point.min,point.q1,point.median,point.q3,point.max].every(Number.isFinite)&&point.min<=point.q1&&point.q1<=point.median&&point.median<=point.q3&&point.q3<=point.max}accessibleName(fallback){return this.getAttribute("aria-label")??this.label??fallback}dataTableSample(){let rowCount=this.labels.length;for(const series of this.datasets)rowCount=Math.max(rowCount,series.data.length);const indexes=sampleChartTableIndexes(rowCount,this.datasets.length);return{rowCount,seriesCount:this.datasets.length,...indexes}}generatedDataIsSampled(){const sample=this.dataTableSample();return sample.rowCount===0||sample.seriesCount===0?!1:sample.rowIndexes.length<sample.rowCount||sample.seriesIndexes.length<sample.seriesCount}dataTruncationMessage(){return this.generatedDataIsSampled()?this.hasCustomDataTable()?this.localize("chartPlotSampled"):this.localize("chartDataSampled"):""}requestUpdate(...args){args[0]!=="keyboardDatumAnnouncement"&&(this.dataTableRows=void 0),super.requestUpdate(...args)}renderDataTableRows(){if(this.dataTableRows)return this.dataTableRows;const numberFormat=getNumberFormat(this.effectiveLocale),direction=this.effectiveDirection==="rtl"?"rtl":"ltr",sample=this.dataTableSample();return this.dataTableRows=sample.seriesIndexes.flatMap(seriesIndex=>{const series=this.datasets[seriesIndex];return sample.rowIndexes.map(index=>{const point=series.data[index],metadata={datasetIndex:seriesIndex,index,label:this.labels[index]||void 0,seriesLabel:series.label,axis:"y"};return this.validPoint(point)?html`
3
3
  <tr>
4
4
  <th scope="row">${isolateHtml(this.labels[index]||this.localize("chartPointLabel",void 0,{n:numberFormat.format(index+1)}),direction)}</th>
@@ -0,0 +1,65 @@
1
+ VS Code Oniguruma Bindings
2
+
3
+ MIT License
4
+
5
+ Copyright (c) Microsoft Corporation.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+
25
+ THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
26
+ Do Not Translate or Localize
27
+
28
+ This project incorporates material from the project(s) listed below (collectively, “Third Party Code”).
29
+ Microsoft is not the original author of the Third Party Code. The original copyright notice and license
30
+ under which Microsoft received such Third Party Code are set out below. This Third Party Code is licensed
31
+ to you under their original license terms set forth below. Microsoft reserves all other rights not
32
+ expressly granted, whether by implication, estoppel or otherwise.
33
+
34
+ The following files/folders contain third party software:
35
+
36
+ =========================================================================================================
37
+ deps/oniguruma/ --- oniguruma version 6.9.5_rev1 https://github.com/kkos/oniguruma/tree/v6.9.5_rev1
38
+ ---------------------------------------------------------------------------------------------------------
39
+
40
+ Oniguruma LICENSE
41
+ -----------------
42
+
43
+ Copyright (c) 2002-2020 K.Kosako <kkosako0@gmail.com>
44
+ All rights reserved.
45
+
46
+ Redistribution and use in source and binary forms, with or without
47
+ modification, are permitted provided that the following conditions
48
+ are met:
49
+ 1. Redistributions of source code must retain the above copyright
50
+ notice, this list of conditions and the following disclaimer.
51
+ 2. Redistributions in binary form must reproduce the above copyright
52
+ notice, this list of conditions and the following disclaimer in the
53
+ documentation and/or other materials provided with the distribution.
54
+
55
+ THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
56
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
57
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
58
+ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
59
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
60
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
61
+ OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
62
+ HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
63
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
64
+ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65
+ SUCH DAMAGE.
@@ -0,0 +1,8 @@
1
+ {
2
+ "source": "shiki/onig.wasm",
3
+ "sourceVersion": "4.5.0",
4
+ "upstream": "vscode-oniguruma@1.7.0",
5
+ "sha256": "fd885c2d12e5951e59d761ebd4a006e06254b1491fd6f530c92b69fb4d8d77d9",
6
+ "bytes": 466610,
7
+ "notices": "onig.LICENSE.txt"
8
+ }
@@ -1 +1 @@
1
- import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{unwrapOptionalPeerDefault}from"../../../internal/optional-peer-capabilities.js";function isShikiHighlighter(candidate){return(typeof candidate=="object"||typeof candidate=="function")&&candidate!==null&&typeof candidate.getLoadedLanguages=="function"&&typeof candidate.loadLanguage=="function"&&typeof candidate.codeToHtml=="function"}const SHIKI_LIGHT_THEME="github-light",SHIKI_DARK_THEME="github-dark",SHIKI_THEMES={light:SHIKI_LIGHT_THEME,dark:SHIKI_DARK_THEME};function normalizeShikiLanguage(lang){return lang.trim().toLowerCase().replace(/^\./,"")}function defaultOnigurumaEngineFactory(){return import("shiki/engine/oniguruma").then(({createOnigurumaEngine})=>createOnigurumaEngine(fetch(new URL("shiki/onig.wasm",import.meta.url))))}function javascriptEngineFactory(){return import("shiki/engine/javascript").then(({createJavaScriptRegexEngine})=>createJavaScriptRegexEngine())}let engineFactory=defaultOnigurumaEngineFactory;function setShikiCoreEngine(engine){engineFactory=engine==="oniguruma"?defaultOnigurumaEngineFactory:engine==="javascript"?javascriptEngineFactory:engine}function __resetShikiCoreEngineForTesting(){engineFactory=defaultOnigurumaEngineFactory}const highlighterCores=new WeakMap,recentHighlighterCores=[];function equalFrozenGrammars(left,right){let remaining=2e4;const leftSeen=new WeakSet,rightSeen=new WeakSet,equal=(a,b,depth)=>{if(--remaining<0||depth>32||typeof a!=typeof b||typeof a=="function"||typeof a=="symbol"||typeof a=="number"&&(!Number.isFinite(a)||!Number.isFinite(b)))return!1;if(a===null||b===null||typeof a!="object"||typeof b!="object")return Object.is(a,b);if(!Object.isFrozen(a)||!Object.isFrozen(b)||leftSeen.has(a)||rightSeen.has(b))return!1;const prototype=Object.getPrototypeOf(a);if(prototype!==Object.getPrototypeOf(b)||prototype!==Object.prototype&&prototype!==Array.prototype&&prototype!==null||Array.isArray(a)!==Array.isArray(b))return!1;leftSeen.add(a),rightSeen.add(b);const leftKeys=Reflect.ownKeys(a),rightKeys=Reflect.ownKeys(b);if(leftKeys.length!==rightKeys.length||leftKeys.length>remaining)return!1;for(let i=0;i<leftKeys.length;i+=1){const key=leftKeys[i];if(typeof key!="string"||key!==rightKeys[i])return!1;const first=Object.getOwnPropertyDescriptor(a,key),second=Object.getOwnPropertyDescriptor(b,key);if(!("value"in first)||!("value"in second)||first.enumerable!==second.enumerable||!equal(first.value,second.value,depth+1))return!1}return!0};try{return equal(left,right,0)}catch{return!1}}function shikiGrammarOwnNames(input){const known=new Set;let primaryName;const registrations=Array.isArray(input)?input:[input];for(const registration of registrations){if(!registration||typeof registration!="object")continue;const name=registration.name;typeof name=="string"&&name!==""&&(known.add(name),primaryName??=name);const aliases=registration.aliases;if(Array.isArray(aliases))for(const alias of aliases)typeof alias=="string"&&known.add(alias)}return{primaryName,known}}function buildShikiLangAlias(languages){let aliases;try{for(const key of Object.keys(languages)){const grammar=languages[key];if(grammar===void 0)continue;const{primaryName,known}=shikiGrammarOwnNames(grammar);!primaryName||known.has(key)||(aliases??={},aliases[key]=primaryName)}}catch{return aliases}return aliases}const coreLangAliases=new WeakMap;let highlighterCoreLoaderForTesting;const FINE_GRAINED_SHIKI_WARNING_KEY="lyra-fine-grained-shiki-highlighter-unavailable",FINE_GRAINED_SHIKI_WARNING="Lyra syntax highlighting failed to build a fine-grained shiki highlighter from the supplied grammars. Code is rendered as plain text.";function __setShikiHighlighterCoreLoaderForTesting(loader){highlighterCoreLoaderForTesting=loader}function loadShikiHighlighterCore(languages){if(highlighterCoreLoaderForTesting)return highlighterCoreLoaderForTesting(languages);const engine=engineFactory;let perEngine=highlighterCores.get(languages),cached=perEngine?.get(engine),frozen=!1;if(!cached)try{frozen=Object.isFrozen(languages)}catch{}if(frozen)for(let i=recentHighlighterCores.length-1;i>=0;i-=1){const entry=recentHighlighterCores[i],previous=entry.languages.deref(),promise=entry.promise.deref();if(!previous||!promise)recentHighlighterCores.splice(i,1);else if(entry.engine===engine&&equalFrozenGrammars(languages,previous)){cached=promise,recentHighlighterCores.splice(i,1),recentHighlighterCores.push({languages:new WeakRef(languages),engine,promise:entry.promise}),perEngine??=new Map,perEngine.set(engine,cached),highlighterCores.set(languages,perEngine);break}}if(!cached&&(cached=Promise.all([import("shiki/core"),Promise.resolve(engine()),import("shiki/themes/github-light.mjs"),import("shiki/themes/github-dark.mjs")]).then(async([{createHighlighterCore},resolvedEngine,light,dark])=>{const langAlias=buildShikiLangAlias(languages)??{},core=await createHighlighterCore({themes:[light.default,dark.default],langs:Object.values(languages),langAlias,engine:resolvedEngine});if(!isShikiHighlighter(core))throw new Error("Invalid optional peer `shiki`: `createHighlighterCore()` did not produce a usable highlighter capability.");return coreLangAliases.set(core,langAlias),core}).catch(()=>(devWarnOnce(FINE_GRAINED_SHIKI_WARNING_KEY,FINE_GRAINED_SHIKI_WARNING),null)),perEngine??=new Map,perEngine.set(engine,cached),highlighterCores.set(languages,perEngine),frozen)){recentHighlighterCores.push({languages:new WeakRef(languages),engine,promise:new WeakRef(cached)}),recentHighlighterCores.length>8&&recentHighlighterCores.shift();const pending=cached;pending.then(core=>{if(!core)for(let i=recentHighlighterCores.length-1;i>=0;i-=1)recentHighlighterCores[i].promise.deref()===pending&&recentHighlighterCores.splice(i,1)})}return cached}const resolvedLanguagesCache=new WeakMap;function resolvedShikiLanguages(languages){let hasLoader=!1;for(const key of Object.keys(languages))if(typeof languages[key]=="function"){hasLoader=!0;break}if(!hasLoader)return languages;let cached=resolvedLanguagesCache.get(languages);if(!cached){cached={};for(const key of Object.keys(languages)){const value=languages[key];value!==void 0&&typeof value!="function"&&(cached[key]=value)}resolvedLanguagesCache.set(languages,cached)}return cached}const loadedLanguageSources=new WeakMap,LAZY_LANGUAGE_SOURCE_WARNING_KEY="lyra-shiki-lazy-language-source-failed",LAZY_LANGUAGE_SOURCE_WARNING="Lyra syntax highlighting could not load a lazy `languages` grammar loader. That language renders as plain text.";function ensureShikiLanguageLoaded(core,key,source){if(typeof source!="function")return Promise.resolve(!0);let perCore=loadedLanguageSources.get(core);perCore||(perCore=new Map,loadedLanguageSources.set(core,perCore));let pending=perCore.get(key);return pending||(pending=Promise.resolve().then(source).then(async resolved=>{const grammar=unwrapOptionalPeerDefault(resolved);await core.loadLanguage(grammar);const{primaryName,known}=shikiGrammarOwnNames(grammar),aliases=coreLangAliases.get(core);aliases&&primaryName&&!known.has(key)&&(aliases[key]=primaryName)}).then(()=>!0).catch(()=>(devWarnOnce(LAZY_LANGUAGE_SOURCE_WARNING_KEY,LAZY_LANGUAGE_SOURCE_WARNING),!1)),perCore.set(key,pending)),pending}export{SHIKI_DARK_THEME,SHIKI_LIGHT_THEME,SHIKI_THEMES,__resetShikiCoreEngineForTesting,__setShikiHighlighterCoreLoaderForTesting,ensureShikiLanguageLoaded,isShikiHighlighter,loadShikiHighlighterCore,normalizeShikiLanguage,resolvedShikiLanguages,setShikiCoreEngine};
1
+ import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{unwrapOptionalPeerDefault}from"../../../internal/optional-peer-capabilities.js";function isShikiHighlighter(candidate){return(typeof candidate=="object"||typeof candidate=="function")&&candidate!==null&&typeof candidate.getLoadedLanguages=="function"&&typeof candidate.loadLanguage=="function"&&typeof candidate.codeToHtml=="function"}const SHIKI_LIGHT_THEME="github-light",SHIKI_DARK_THEME="github-dark",SHIKI_THEMES={light:SHIKI_LIGHT_THEME,dark:SHIKI_DARK_THEME};function normalizeShikiLanguage(lang){return lang.trim().toLowerCase().replace(/^\./,"")}function defaultOnigurumaEngineFactory(){return import("shiki/engine/oniguruma").then(module=>{const createEngine=(typeof module.createOnigurumaEngine=="function"?module:unwrapOptionalPeerDefault(module))?.createOnigurumaEngine;if(typeof createEngine!="function")throw new Error("Invalid optional peer shiki: an Oniguruma engine factory is required.");return createEngine(fetch(new URL("./onig.wasm",import.meta.url)))})}function javascriptEngineFactory(){return import("shiki/engine/javascript").then(({createJavaScriptRegexEngine})=>createJavaScriptRegexEngine())}let engineFactory=defaultOnigurumaEngineFactory;function setShikiCoreEngine(engine){engineFactory=engine==="oniguruma"?defaultOnigurumaEngineFactory:engine==="javascript"?javascriptEngineFactory:engine}function __resetShikiCoreEngineForTesting(){engineFactory=defaultOnigurumaEngineFactory}const highlighterCores=new WeakMap,recentHighlighterCores=[];function equalFrozenGrammars(left,right){let remaining=2e4;const leftSeen=new WeakSet,rightSeen=new WeakSet,equal=(a,b,depth)=>{if(--remaining<0||depth>32||typeof a!=typeof b||typeof a=="function"||typeof a=="symbol"||typeof a=="number"&&(!Number.isFinite(a)||!Number.isFinite(b)))return!1;if(a===null||b===null||typeof a!="object"||typeof b!="object")return Object.is(a,b);if(!Object.isFrozen(a)||!Object.isFrozen(b)||leftSeen.has(a)||rightSeen.has(b))return!1;const prototype=Object.getPrototypeOf(a);if(prototype!==Object.getPrototypeOf(b)||prototype!==Object.prototype&&prototype!==Array.prototype&&prototype!==null||Array.isArray(a)!==Array.isArray(b))return!1;leftSeen.add(a),rightSeen.add(b);const leftKeys=Reflect.ownKeys(a),rightKeys=Reflect.ownKeys(b);if(leftKeys.length!==rightKeys.length||leftKeys.length>remaining)return!1;for(let i=0;i<leftKeys.length;i+=1){const key=leftKeys[i];if(typeof key!="string"||key!==rightKeys[i])return!1;const first=Object.getOwnPropertyDescriptor(a,key),second=Object.getOwnPropertyDescriptor(b,key);if(!("value"in first)||!("value"in second)||first.enumerable!==second.enumerable||!equal(first.value,second.value,depth+1))return!1}return!0};try{return equal(left,right,0)}catch{return!1}}function shikiGrammarOwnNames(input){const known=new Set;let primaryName;const registrations=Array.isArray(input)?input:[input];for(const registration of registrations){if(!registration||typeof registration!="object")continue;const name=registration.name;typeof name=="string"&&name!==""&&(known.add(name),primaryName??=name);const aliases=registration.aliases;if(Array.isArray(aliases))for(const alias of aliases)typeof alias=="string"&&known.add(alias)}return{primaryName,known}}function buildShikiLangAlias(languages){let aliases;try{for(const key of Object.keys(languages)){const grammar=languages[key];if(grammar===void 0)continue;const{primaryName,known}=shikiGrammarOwnNames(grammar);!primaryName||known.has(key)||(aliases??={},aliases[key]=primaryName)}}catch{return aliases}return aliases}const coreLangAliases=new WeakMap;let highlighterCoreLoaderForTesting;const FINE_GRAINED_SHIKI_WARNING_KEY="lyra-fine-grained-shiki-highlighter-unavailable",FINE_GRAINED_SHIKI_WARNING="Lyra syntax highlighting failed to build a fine-grained shiki highlighter from the supplied grammars. Code is rendered as plain text.";function __setShikiHighlighterCoreLoaderForTesting(loader){highlighterCoreLoaderForTesting=loader}function loadShikiHighlighterCore(languages){if(highlighterCoreLoaderForTesting)return highlighterCoreLoaderForTesting(languages);const engine=engineFactory;let perEngine=highlighterCores.get(languages),cached=perEngine?.get(engine),frozen=!1;if(!cached)try{frozen=Object.isFrozen(languages)}catch{}if(frozen)for(let i=recentHighlighterCores.length-1;i>=0;i-=1){const entry=recentHighlighterCores[i],previous=entry.languages.deref(),promise=entry.promise.deref();if(!previous||!promise)recentHighlighterCores.splice(i,1);else if(entry.engine===engine&&equalFrozenGrammars(languages,previous)){cached=promise,recentHighlighterCores.splice(i,1),recentHighlighterCores.push({languages:new WeakRef(languages),engine,promise:entry.promise}),perEngine??=new Map,perEngine.set(engine,cached),highlighterCores.set(languages,perEngine);break}}if(!cached&&(cached=Promise.all([import("shiki/core"),Promise.resolve(engine()),import("shiki/themes/github-light.mjs"),import("shiki/themes/github-dark.mjs")]).then(async([{createHighlighterCore},resolvedEngine,light,dark])=>{const langAlias=buildShikiLangAlias(languages)??{},core=await createHighlighterCore({themes:[light.default,dark.default],langs:Object.values(languages),langAlias,engine:resolvedEngine});if(!isShikiHighlighter(core))throw new Error("Invalid optional peer `shiki`: `createHighlighterCore()` did not produce a usable highlighter capability.");return coreLangAliases.set(core,langAlias),core}).catch(()=>(devWarnOnce(FINE_GRAINED_SHIKI_WARNING_KEY,FINE_GRAINED_SHIKI_WARNING),null)),perEngine??=new Map,perEngine.set(engine,cached),highlighterCores.set(languages,perEngine),frozen)){recentHighlighterCores.push({languages:new WeakRef(languages),engine,promise:new WeakRef(cached)}),recentHighlighterCores.length>8&&recentHighlighterCores.shift();const pending=cached;pending.then(core=>{if(!core)for(let i=recentHighlighterCores.length-1;i>=0;i-=1)recentHighlighterCores[i].promise.deref()===pending&&recentHighlighterCores.splice(i,1)})}return cached}const resolvedLanguagesCache=new WeakMap;function resolvedShikiLanguages(languages){let hasLoader=!1;for(const key of Object.keys(languages))if(typeof languages[key]=="function"){hasLoader=!0;break}if(!hasLoader)return languages;let cached=resolvedLanguagesCache.get(languages);if(!cached){cached={};for(const key of Object.keys(languages)){const value=languages[key];value!==void 0&&typeof value!="function"&&(cached[key]=value)}resolvedLanguagesCache.set(languages,cached)}return cached}const loadedLanguageSources=new WeakMap,LAZY_LANGUAGE_SOURCE_WARNING_KEY="lyra-shiki-lazy-language-source-failed",LAZY_LANGUAGE_SOURCE_WARNING="Lyra syntax highlighting could not load a lazy `languages` grammar loader. That language renders as plain text.";function ensureShikiLanguageLoaded(core,key,source){if(typeof source!="function")return Promise.resolve(!0);let perCore=loadedLanguageSources.get(core);perCore||(perCore=new Map,loadedLanguageSources.set(core,perCore));let pending=perCore.get(key);return pending||(pending=Promise.resolve().then(source).then(async resolved=>{const grammar=unwrapOptionalPeerDefault(resolved);await core.loadLanguage(grammar);const{primaryName,known}=shikiGrammarOwnNames(grammar),aliases=coreLangAliases.get(core);aliases&&primaryName&&!known.has(key)&&(aliases[key]=primaryName)}).then(()=>!0).catch(()=>(devWarnOnce(LAZY_LANGUAGE_SOURCE_WARNING_KEY,LAZY_LANGUAGE_SOURCE_WARNING),!1)),perCore.set(key,pending)),pending}export{SHIKI_DARK_THEME,SHIKI_LIGHT_THEME,SHIKI_THEMES,__resetShikiCoreEngineForTesting,__setShikiHighlighterCoreLoaderForTesting,ensureShikiLanguageLoaded,isShikiHighlighter,loadShikiHighlighterCore,normalizeShikiLanguage,resolvedShikiLanguages,setShikiCoreEngine};
@@ -438,7 +438,9 @@ set calendarGeometry(_value:Readonly<LyraHeatmapCalendarGeometry> |undefined);pr
438
438
  * intentionally omitted. An empty PNG string means the component has not completed a paint yet,
439
439
  * its canvas has no dimensions, it is waiting for deferred visibility, or the browser could not
440
440
  * encode the snapshot. The CSV snapshot reads `data` directly (unbounded by the render cap) and
441
- * omits no-data cells (the `-1`/non-finite sentinel `isNoData()` already honors for painting),
441
+ * preserves finite numeric values without display rounding or locale formatting. Text cells
442
+ * remain guarded against spreadsheet formulas. It omits no-data cells (the `-1`/non-finite
443
+ * sentinel `isNoData()` already honors for painting),
442
444
  * the same way the canvas draw path skips them.
443
445
  */
444
446
  exportData(format:LyraHeatmapExportFormat):string;private exportCsv;private lastPaintedMatrixGeometry?;private get matrixPadTop();private measureColLabelHeight;private measureRowLabelWidth;private labelCache?;private withLabelCache;private labelWidth;private ellipsize;private ellipsizeLabel;private resolvedCalendarWeekdayLabelWidth;private get calendarPadLeft();private measureCalendarWeekdayLabelWidth;private get matrixRowLabels();private get matrixColLabels();private get matrixValues();private get calendarDays();private get calendarData();private _cellSize?;
@@ -1,5 +1,5 @@
1
- import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{finiteInteger,finiteNumber,finiteRange,minMax}from"../../../internal/numbers.js";import{getScratchCtx,resolveBoundedCanvasAllocation}from"../../../internal/canvas.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{linearAlpha,linearBucket,midpointAlpha,midpointBucket,sqrtStep}from"./heatmap-scale.js";import{styles}from"./heatmap.styles.js";import{resolveRgb,formatRgb}from"./heatmap-colors.js";import{hexToRgb,resolveRgb as resolveRgb2}from"./heatmap-colors.js";import{DEFAULT_BUCKET_COUNT,MAX_HEATMAP_CELLS,MAX_HEATMAP_DECORATIONS,MAX_ACCESSIBLE_HEATMAP_CELLS,normalizeBucketCount}from"./heatmap-limits.js";import{MAX_BUCKET_COUNT,MAX_HEATMAP_CELLS as MAX_HEATMAP_CELLS2,MAX_HEATMAP_DECORATIONS as MAX_HEATMAP_DECORATIONS2,MAX_ACCESSIBLE_HEATMAP_CELLS as MAX_ACCESSIBLE_HEATMAP_CELLS2,normalizeBucketCount as normalizeBucketCount2}from"./heatmap-limits.js";import{buildCalendarGrid,parseIsoDate,quartileBucket}from"./calendar-grid.js";import{accessibleMatrixCellRect,calendarCellAt as readCalendarCell,calendarCellRect,calendarDateAt as readCalendarDate,calendarValueAt as readCalendarValue,firstInteractiveCalendarCell as findFirstInteractiveCalendarCell,firstInteractiveMatrixCell as findFirstInteractiveMatrixCell,hitTestCalendar as hitTestCalendarGrid,hitTestMatrix as hitTestMatrixGrid,matrixCellRect,nextInteractiveCalendarCell as findNextInteractiveCalendarCell,nextInteractiveMatrixCell as findNextInteractiveMatrixCell}from"./heatmap-grid-navigation.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{literalSetConverter}from"../../../internal/converters.js";import{HeatmapLabelCache}from"./heatmap-label-cache.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_heatmapCalendarCellLabel,LYRA_DEFAULT_heatmapCalendarLabel,LYRA_DEFAULT_heatmapDecorationLimit,LYRA_DEFAULT_heatmapDefaultColLabel,LYRA_DEFAULT_heatmapDefaultRowLabel,LYRA_DEFAULT_heatmapMatrixCellLabel,LYRA_DEFAULT_heatmapMatrixLabel,LYRA_DEFAULT_heatmapNoDataValue,LYRA_DEFAULT_heatmapProjectionLimit,LYRA_DEFAULT_heatmapSelectedCellLabel,LYRA_DEFAULT_heatmapSelectedCount,LYRA_DEFAULT_heatmapValueLabel}from"../../../internal/default-strings/data.generated.js";const PAD_LEFT=60,PAD_TOP=20,ROW_LABEL_INSET=4,MAX_ROW_LABEL_FRACTION=.4,MAX_COL_LABEL_HEIGHT=240,COL_LABEL_INSET=6,labelExtentConverter={fromAttribute:value=>{if(value===null)return;const trimmed=value.trim();if(trimmed.toLowerCase()==="auto")return"auto";const parsed=Number.parseFloat(trimmed);return Number.isFinite(parsed)&&parsed>=0?parsed:void 0},toAttribute:value=>value===void 0?null:String(value)},STICKY_LABELS=literalSetConverter(["none","rows","cols","both"],"none"),FALLBACK_NO_DATA_FILL="rgba(128,128,128,0.25)",FALLBACK_STICKY_LABEL_BG="#ffffff",RAMP_STEPS=7,FALLBACK_SCALE_LO="#cde2fb",FALLBACK_SCALE_HI="#0969da",FALLBACK_LABEL_FONT="10px system-ui, sans-serif",CAL_PAD_LEFT=28,CAL_WEEKDAY_LABEL_INSET=2,CAL_LABEL_H=16,CAL_CELL=11,CAL_GAP=2,DEFAULT_MATRIX_CELL_SIZE=22,MAX_MATRIX_ROW_HEIGHT=4096,DEFAULT_ACCESSIBLE_TARGET_SIZE_PX=40,FIT_MIN_CELL=4,RING_LINE_WIDTH=2,FALLBACK_FOCUS_RING_COLOR="#0969da",FALLBACK_ANNOTATION_COLOR="#cf222e",FALLBACK_SELECTED_COLOR="#1a7f37",SCOPED_COLOR=/var\(|currentcolor|light-dark\(/i,MAX_CANVAS_DIMENSION=16384,MAX_CANVAS_PIXELS=16777216,ARROW_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]),GRID_KEYS=new Set([...ARROW_KEYS,"Home","End"]),MS_PER_DAY=864e5,CAL_MONTH_LABEL_GAP=2;function isoDateAtOffset(firstWeekStart,dayOffset){return new Date(firstWeekStart.getTime()+dayOffset*MS_PER_DAY).toISOString().slice(0,10)}function legendStopsChanged(value,previous){if(Object.is(value,previous))return!1;if(!Array.isArray(value)||!Array.isArray(previous)||value.length!==previous.length)return!0;for(let index=0;index<value.length;index+=1){if(Object.hasOwn(value,index)!==Object.hasOwn(previous,index))return!0;const next=value[index],before=previous[index];if(!next||!before){if(!Object.is(next,before))return!0;continue}if(!Object.is(next.value,before.value)||!Object.is(next.color,before.color)||!Object.is(next.label,before.label)||!Object.is(next.partOfRamp,before.partOfRamp))return!0}return!1}const optionalCellSizeConverter={fromAttribute(value){if(value===null||value.trim()==="")return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}},DEFAULT_MATRIX_DATA=Object.freeze({kind:"matrix",rowLabels:Object.freeze([]),colLabels:Object.freeze([]),values:Object.freeze([])});function normalizeCellSizeClamp(value){if(!(value==null||!Number.isFinite(value)))return finiteRange(value,FIT_MIN_CELL,FIT_MIN_CELL)}const bucketCountConverter={fromAttribute(value){return value===null?DEFAULT_BUCKET_COUNT:normalizeBucketCount(Number(value))}};function mixRgb(from,to,t){const clamped=Math.min(1,Math.max(0,t)),r=Math.round(from[0]+(to[0]-from[0])*clamped),g=Math.round(from[1]+(to[1]-from[1])*clamped),b=Math.round(from[2]+(to[2]-from[2])*clamped),a=from[3]+(to[3]-from[3])*clamped;return formatRgb([r,g,b,a])}const CALENDAR_SPACING_PROPERTIES=new Set(["cellGapX","cellGapY","cellRadius"]);class LyraHeatmap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,heatmapCalendarCellLabel:LYRA_DEFAULT_heatmapCalendarCellLabel,heatmapCalendarLabel:LYRA_DEFAULT_heatmapCalendarLabel,heatmapDecorationLimit:LYRA_DEFAULT_heatmapDecorationLimit,heatmapDefaultColLabel:LYRA_DEFAULT_heatmapDefaultColLabel,heatmapDefaultRowLabel:LYRA_DEFAULT_heatmapDefaultRowLabel,heatmapMatrixCellLabel:LYRA_DEFAULT_heatmapMatrixCellLabel,heatmapMatrixLabel:LYRA_DEFAULT_heatmapMatrixLabel,heatmapNoDataValue:LYRA_DEFAULT_heatmapNoDataValue,heatmapProjectionLimit:LYRA_DEFAULT_heatmapProjectionLimit,heatmapSelectedCellLabel:LYRA_DEFAULT_heatmapSelectedCellLabel,heatmapSelectedCount:LYRA_DEFAULT_heatmapSelectedCount,heatmapValueLabel:LYRA_DEFAULT_heatmapValueLabel}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}static{this.ownedCollectionProperties=Object.freeze(["data","annotations","legendStops","colorSteps","selectedCells"])}static{this.identityCollectionObjectProperties=Object.freeze(["data"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}get effectiveMode(){return this.data.kind}get stickyLabels(){return this._stickyLabels}set stickyLabels(next){const normalized=STICKY_LABELS.normalizeReflected(this,"sticky-labels",next),old=this._stickyLabels;old!==normalized&&(this._stickyLabels=normalized,this.requestUpdate("stickyLabels",old))}get effectiveStickyLabels(){return this.effectiveMode==="matrix"?this._stickyLabels:"none"}get freezesRowLabels(){const sticky=this.effectiveStickyLabels;return sticky==="rows"||sticky==="both"}get freezesColLabels(){const sticky=this.effectiveStickyLabels;return sticky==="cols"||sticky==="both"}get effectiveColLabelRotation(){if(typeof this.colLabelRotation!="number")return 0;const degrees=finiteNumber(this.colLabelRotation,0);return Math.min(90,Math.max(0,degrees))}get matrixPadLeft(){if(this.rowLabelWidth==="auto")return this.resolvedRowLabelWidth;if(typeof this.rowLabelWidth!="number")return PAD_LEFT;const resolved=finiteNumber(this.rowLabelWidth,PAD_LEFT);return resolved>=0?resolved:PAD_LEFT}get matrixGeometry(){if(this.effectiveMode==="matrix")return this.lastPaintedMatrixGeometry}set matrixGeometry(_value){}get calendarGeometry(){if(this.effectiveMode==="calendar")return this.lastPaintedCalendarGeometry}set calendarGeometry(_value){}exportData(format){if(format==="csv")return this.exportCsv();if(format!=="png"||!this.canvasHasContent||this.drawDirty||!this.canvas||this.canvas.width<=0||this.canvas.height<=0)return"";try{const rowBand=this.frozenBandCanvas("row-labels"),colBand=this.frozenBandCanvas("col-labels");if(!rowBand&&!colBand)return this.canvas.toDataURL("image/png");const composite=this.ownerDocument.createElement("canvas");composite.width=this.canvas.width,composite.height=this.canvas.height;const context=composite.getContext("2d");return context?(context.drawImage(this.canvas,0,0),rowBand&&rowBand.width>0&&rowBand.height>0&&context.drawImage(rowBand,0,0),colBand&&colBand.width>0&&colBand.height>0&&context.drawImage(colBand,0,0),composite.toDataURL("image/png")):""}catch{return""}}exportCsv(){const data=this.data;if(data.kind==="calendar"){const header2=["date","value"].map(escapeCsvField).join(","),rows2=data.days.filter(day=>!this.isNoData(day.value)).map(day=>[day.date,this.formatNumericValue(day.value)].map(escapeCsvField).join(","));return[header2,...rows2].join(`\r
2
- `)}const header=["row","column","value"].map(escapeCsvField).join(","),rows=[];return data.values.forEach((rowValues,rowIndex)=>{const rowLabel=data.rowLabels[rowIndex]??"";rowValues.forEach((value,colIndex)=>{if(this.isNoData(value))return;const colLabel=data.colLabels[colIndex]??"";rows.push([rowLabel,colLabel,this.formatNumericValue(value)].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
1
+ import{__decorate}from"tslib";import{collectionSupport}from"../../../internal/collection-snapshot.js";import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{guard}from"lit/directives/guard.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{syncAriaDescribedByElements}from"../../../internal/aria-reflection.js";import{finiteInteger,finiteNumber,finiteRange,minMax}from"../../../internal/numbers.js";import{getScratchCtx,resolveBoundedCanvasAllocation}from"../../../internal/canvas.js";import{resolveCanvasColor}from"../../../internal/canvas-color.js";import{resolveCssTokenLength}from"../../../internal/css-token-length.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{activeElementIn,shadowFocusTarget}from"../../../internal/active-element.js";import{linearAlpha,linearBucket,midpointAlpha,midpointBucket,sqrtStep}from"./heatmap-scale.js";import{styles}from"./heatmap.styles.js";import{resolveRgb,formatRgb}from"./heatmap-colors.js";import{hexToRgb,resolveRgb as resolveRgb2}from"./heatmap-colors.js";import{DEFAULT_BUCKET_COUNT,MAX_HEATMAP_CELLS,MAX_HEATMAP_DECORATIONS,MAX_ACCESSIBLE_HEATMAP_CELLS,normalizeBucketCount}from"./heatmap-limits.js";import{MAX_BUCKET_COUNT,MAX_HEATMAP_CELLS as MAX_HEATMAP_CELLS2,MAX_HEATMAP_DECORATIONS as MAX_HEATMAP_DECORATIONS2,MAX_ACCESSIBLE_HEATMAP_CELLS as MAX_ACCESSIBLE_HEATMAP_CELLS2,normalizeBucketCount as normalizeBucketCount2}from"./heatmap-limits.js";import{buildCalendarGrid,parseIsoDate,quartileBucket}from"./calendar-grid.js";import{accessibleMatrixCellRect,calendarCellAt as readCalendarCell,calendarCellRect,calendarDateAt as readCalendarDate,calendarValueAt as readCalendarValue,firstInteractiveCalendarCell as findFirstInteractiveCalendarCell,firstInteractiveMatrixCell as findFirstInteractiveMatrixCell,hitTestCalendar as hitTestCalendarGrid,hitTestMatrix as hitTestMatrixGrid,matrixCellRect,nextInteractiveCalendarCell as findNextInteractiveCalendarCell,nextInteractiveMatrixCell as findNextInteractiveMatrixCell}from"./heatmap-grid-navigation.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{literalSetConverter}from"../../../internal/converters.js";import{HeatmapLabelCache}from"./heatmap-label-cache.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import{AnnouncementSinkController}from"../../../internal/announcer.js";import{LYRA_DEFAULT_heatmapCalendarCellLabel,LYRA_DEFAULT_heatmapCalendarLabel,LYRA_DEFAULT_heatmapDecorationLimit,LYRA_DEFAULT_heatmapDefaultColLabel,LYRA_DEFAULT_heatmapDefaultRowLabel,LYRA_DEFAULT_heatmapMatrixCellLabel,LYRA_DEFAULT_heatmapMatrixLabel,LYRA_DEFAULT_heatmapNoDataValue,LYRA_DEFAULT_heatmapProjectionLimit,LYRA_DEFAULT_heatmapSelectedCellLabel,LYRA_DEFAULT_heatmapSelectedCount,LYRA_DEFAULT_heatmapValueLabel}from"../../../internal/default-strings/data.generated.js";const PAD_LEFT=60,PAD_TOP=20,ROW_LABEL_INSET=4,MAX_ROW_LABEL_FRACTION=.4,MAX_COL_LABEL_HEIGHT=240,COL_LABEL_INSET=6,labelExtentConverter={fromAttribute:value=>{if(value===null)return;const trimmed=value.trim();if(trimmed.toLowerCase()==="auto")return"auto";const parsed=Number.parseFloat(trimmed);return Number.isFinite(parsed)&&parsed>=0?parsed:void 0},toAttribute:value=>value===void 0?null:String(value)},STICKY_LABELS=literalSetConverter(["none","rows","cols","both"],"none"),FALLBACK_NO_DATA_FILL="rgba(128,128,128,0.25)",FALLBACK_STICKY_LABEL_BG="#ffffff",RAMP_STEPS=7,FALLBACK_SCALE_LO="#cde2fb",FALLBACK_SCALE_HI="#0969da",FALLBACK_LABEL_FONT="10px system-ui, sans-serif",CAL_PAD_LEFT=28,CAL_WEEKDAY_LABEL_INSET=2,CAL_LABEL_H=16,CAL_CELL=11,CAL_GAP=2,DEFAULT_MATRIX_CELL_SIZE=22,MAX_MATRIX_ROW_HEIGHT=4096,DEFAULT_ACCESSIBLE_TARGET_SIZE_PX=40,FIT_MIN_CELL=4,RING_LINE_WIDTH=2,FALLBACK_FOCUS_RING_COLOR="#0969da",FALLBACK_ANNOTATION_COLOR="#cf222e",FALLBACK_SELECTED_COLOR="#1a7f37",SCOPED_COLOR=/var\(|currentcolor|light-dark\(/i,MAX_CANVAS_DIMENSION=16384,MAX_CANVAS_PIXELS=16777216,ARROW_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]),GRID_KEYS=new Set([...ARROW_KEYS,"Home","End"]),MS_PER_DAY=864e5,CAL_MONTH_LABEL_GAP=2;function isoDateAtOffset(firstWeekStart,dayOffset){return new Date(firstWeekStart.getTime()+dayOffset*MS_PER_DAY).toISOString().slice(0,10)}function legendStopsChanged(value,previous){if(Object.is(value,previous))return!1;if(!Array.isArray(value)||!Array.isArray(previous)||value.length!==previous.length)return!0;for(let index=0;index<value.length;index+=1){if(Object.hasOwn(value,index)!==Object.hasOwn(previous,index))return!0;const next=value[index],before=previous[index];if(!next||!before){if(!Object.is(next,before))return!0;continue}if(!Object.is(next.value,before.value)||!Object.is(next.color,before.color)||!Object.is(next.label,before.label)||!Object.is(next.partOfRamp,before.partOfRamp))return!0}return!1}const optionalCellSizeConverter={fromAttribute(value){if(value===null||value.trim()==="")return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0}},DEFAULT_MATRIX_DATA=Object.freeze({kind:"matrix",rowLabels:Object.freeze([]),colLabels:Object.freeze([]),values:Object.freeze([])});function normalizeCellSizeClamp(value){if(!(value==null||!Number.isFinite(value)))return finiteRange(value,FIT_MIN_CELL,FIT_MIN_CELL)}const bucketCountConverter={fromAttribute(value){return value===null?DEFAULT_BUCKET_COUNT:normalizeBucketCount(Number(value))}};function mixRgb(from,to,t){const clamped=Math.min(1,Math.max(0,t)),r=Math.round(from[0]+(to[0]-from[0])*clamped),g=Math.round(from[1]+(to[1]-from[1])*clamped),b=Math.round(from[2]+(to[2]-from[2])*clamped),a=from[3]+(to[3]-from[3])*clamped;return formatRgb([r,g,b,a])}const CALENDAR_SPACING_PROPERTIES=new Set(["cellGapX","cellGapY","cellRadius"]);class LyraHeatmap extends LyraElement{static{this.defaultStrings={...super.defaultStrings,heatmapCalendarCellLabel:LYRA_DEFAULT_heatmapCalendarCellLabel,heatmapCalendarLabel:LYRA_DEFAULT_heatmapCalendarLabel,heatmapDecorationLimit:LYRA_DEFAULT_heatmapDecorationLimit,heatmapDefaultColLabel:LYRA_DEFAULT_heatmapDefaultColLabel,heatmapDefaultRowLabel:LYRA_DEFAULT_heatmapDefaultRowLabel,heatmapMatrixCellLabel:LYRA_DEFAULT_heatmapMatrixCellLabel,heatmapMatrixLabel:LYRA_DEFAULT_heatmapMatrixLabel,heatmapNoDataValue:LYRA_DEFAULT_heatmapNoDataValue,heatmapProjectionLimit:LYRA_DEFAULT_heatmapProjectionLimit,heatmapSelectedCellLabel:LYRA_DEFAULT_heatmapSelectedCellLabel,heatmapSelectedCount:LYRA_DEFAULT_heatmapSelectedCount,heatmapValueLabel:LYRA_DEFAULT_heatmapValueLabel}}static{this.collectionSupport=collectionSupport}static{this.immutableEventDetails=Object.freeze(["lr-selection-change"])}static{this.ownedCollectionProperties=Object.freeze(["data","annotations","legendStops","colorSteps","selectedCells"])}static{this.identityCollectionObjectProperties=Object.freeze(["data"])}static{this.styles=[LyraElement.styles,styles,srOnly]}static get observedAttributes(){return[...new Set([...super.observedAttributes,"role"])]}get effectiveMode(){return this.data.kind}get stickyLabels(){return this._stickyLabels}set stickyLabels(next){const normalized=STICKY_LABELS.normalizeReflected(this,"sticky-labels",next),old=this._stickyLabels;old!==normalized&&(this._stickyLabels=normalized,this.requestUpdate("stickyLabels",old))}get effectiveStickyLabels(){return this.effectiveMode==="matrix"?this._stickyLabels:"none"}get freezesRowLabels(){const sticky=this.effectiveStickyLabels;return sticky==="rows"||sticky==="both"}get freezesColLabels(){const sticky=this.effectiveStickyLabels;return sticky==="cols"||sticky==="both"}get effectiveColLabelRotation(){if(typeof this.colLabelRotation!="number")return 0;const degrees=finiteNumber(this.colLabelRotation,0);return Math.min(90,Math.max(0,degrees))}get matrixPadLeft(){if(this.rowLabelWidth==="auto")return this.resolvedRowLabelWidth;if(typeof this.rowLabelWidth!="number")return PAD_LEFT;const resolved=finiteNumber(this.rowLabelWidth,PAD_LEFT);return resolved>=0?resolved:PAD_LEFT}get matrixGeometry(){if(this.effectiveMode==="matrix")return this.lastPaintedMatrixGeometry}set matrixGeometry(_value){}get calendarGeometry(){if(this.effectiveMode==="calendar")return this.lastPaintedCalendarGeometry}set calendarGeometry(_value){}exportData(format){if(format==="csv")return this.exportCsv();if(format!=="png"||!this.canvasHasContent||this.drawDirty||!this.canvas||this.canvas.width<=0||this.canvas.height<=0)return"";try{const rowBand=this.frozenBandCanvas("row-labels"),colBand=this.frozenBandCanvas("col-labels");if(!rowBand&&!colBand)return this.canvas.toDataURL("image/png");const composite=this.ownerDocument.createElement("canvas");composite.width=this.canvas.width,composite.height=this.canvas.height;const context=composite.getContext("2d");return context?(context.drawImage(this.canvas,0,0),rowBand&&rowBand.width>0&&rowBand.height>0&&context.drawImage(rowBand,0,0),colBand&&colBand.width>0&&colBand.height>0&&context.drawImage(colBand,0,0),composite.toDataURL("image/png")):""}catch{return""}}exportCsv(){const data=this.data;if(data.kind==="calendar"){const header2=["date","value"].map(escapeCsvField).join(","),rows2=data.days.filter(day=>!this.isNoData(day.value)).map(day=>[day.date,day.value].map(escapeCsvField).join(","));return[header2,...rows2].join(`\r
2
+ `)}const header=["row","column","value"].map(escapeCsvField).join(","),rows=[];return data.values.forEach((rowValues,rowIndex)=>{const rowLabel=data.rowLabels[rowIndex]??"";rowValues.forEach((value,colIndex)=>{if(this.isNoData(value))return;const colLabel=data.colLabels[colIndex]??"";rows.push([rowLabel,colLabel,value].map(escapeCsvField).join(","))})}),[header,...rows].join(`\r
3
3
  `)}get matrixPadTop(){if(this.colLabelHeight==="auto")return this.resolvedColLabelHeight;if(typeof this.colLabelHeight!="number")return PAD_TOP;const resolved=finiteNumber(this.colLabelHeight,PAD_TOP);return resolved>=0?resolved:PAD_TOP}measureColLabelHeight(cs){const labels=this.matrixColLabels;if(labels.length===0)return PAD_TOP;const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return PAD_TOP;ctx.font=this.labelFont(cs);let widest=0;const interval=finiteInteger(this.colLabelInterval,1,1);for(let index=0;index<labels.length;index+=interval)widest=Math.max(widest,this.labelWidth(ctx,labels[index]));const radians=this.effectiveColLabelRotation*Math.PI/180,projected=widest*Math.sin(radians);return Math.max(PAD_TOP,Math.min(Math.ceil(projected)+COL_LABEL_INSET,MAX_COL_LABEL_HEIGHT))}measureRowLabelWidth(cs){const labels=this.matrixRowLabels;if(labels.length===0)return PAD_LEFT;const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return PAD_LEFT;ctx.font=this.labelFont(cs);let widest=0;for(const label of labels)widest=Math.max(widest,this.labelWidth(ctx,label));const hostWidth=this.clientWidth||0,cap=hostWidth>0?hostWidth*MAX_ROW_LABEL_FRACTION:Number.POSITIVE_INFINITY;return Math.min(Math.max(PAD_LEFT,Math.ceil(widest)+ROW_LABEL_INSET*2),cap)}withLabelCache(paint){const previous=this.labelCache;this.labelCache=new HeatmapLabelCache;try{paint()}finally{this.labelCache=previous}}labelWidth(ctx,label){return this.labelCache?.width(ctx,label)??ctx.measureText(label).width}ellipsize(ctx,label,maxWidth){return this.labelCache?.clip(ctx,label,maxWidth,()=>this.ellipsizeLabel(ctx,label,maxWidth))??this.ellipsizeLabel(ctx,label,maxWidth)}ellipsizeLabel(ctx,label,maxWidth){if(maxWidth<=0)return"";if(this.labelWidth(ctx,label)<=maxWidth)return label;const characters=[...label],shortened=kept=>`${characters.slice(0,kept).join("")}…`;let fits=0,most=characters.length-1;for(;fits<most;){const kept=fits+most+1>>1;this.labelWidth(ctx,shortened(kept))<=maxWidth?fits=kept:most=kept-1}return fits>0||this.labelWidth(ctx,"…")<=maxWidth?shortened(fits):""}get calendarPadLeft(){const requested=this.calendarWeekdayLabelWidth;return requested==="auto"?this.resolvedCalendarWeekdayLabelWidth:requested??CAL_PAD_LEFT}measureCalendarWeekdayLabelWidth(cs,firstWeekStart){const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return CAL_PAD_LEFT;ctx.font=this.labelFont(cs);let widest=0;for(const label of this.weekdayLabels(firstWeekStart))label&&(widest=Math.max(widest,this.labelWidth(ctx,label)));const hostWidth=this.clientWidth||0,cap=hostWidth>0?Math.max(CAL_PAD_LEFT,hostWidth*MAX_ROW_LABEL_FRACTION):Number.POSITIVE_INFINITY;return Math.min(Math.max(CAL_PAD_LEFT,Math.ceil(widest)+CAL_WEEKDAY_LABEL_INSET*2),cap)}get matrixRowLabels(){return this.cachedMatrixData.rowLabels}get matrixColLabels(){return this.cachedMatrixData.colLabels}get matrixValues(){return this.cachedMatrixData.values}get calendarDays(){return this.data.kind==="calendar"?this.data.days:[]}get calendarData(){return this.data.kind==="calendar"?this.data:void 0}get cellSize(){return this._cellSize??(this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE)}set cellSize(value){const oldValue=this._cellSize;this._cellSize=value==null?void 0:finiteRange(value,this.effectiveMode==="calendar"?CAL_CELL:DEFAULT_MATRIX_CELL_SIZE,1),this.requestUpdate("cellSize",oldValue)}get rowHeight(){return this._rowHeight}set rowHeight(value){const oldValue=this._rowHeight;this._rowHeight=value==null||!Number.isFinite(value)?void 0:finiteRange(value,1,1,MAX_MATRIX_ROW_HEIGHT),this.requestUpdate("rowHeight",oldValue)}get signedDomain(){return this.domain!==void 0||this.midpoint!==void 0}rampAlpha(value,lo,hi){const anchor=this.midpoint;return anchor===void 0?linearAlpha(value,lo,hi):midpointAlpha(value,lo,hi,anchor)}rampBucket(value,lo,hi,steps){const anchor=this.midpoint;return anchor===void 0?linearBucket(value,lo,hi,steps):midpointBucket(value,lo,hi,anchor,steps)}isNoData(value){return Number.isFinite(value)?value<0&&!this.signedDomain:!0}get maxCellSize(){return this._maxCellSize}set maxCellSize(value){const oldValue=this._maxCellSize;this._maxCellSize=normalizeCellSizeClamp(value),this.requestUpdate("maxCellSize",oldValue)}get minCellSize(){return this._minCellSize}set minCellSize(value){const oldValue=this._minCellSize;this._minCellSize=normalizeCellSizeClamp(value),this.requestUpdate("minCellSize",oldValue)}get normalizedFirstDayOfWeek(){return(finiteInteger(this.calendarData?.firstDayOfWeek??0,0)%7+7)%7}get bucketCount(){return this._bucketCount}set bucketCount(value){const oldValue=this._bucketCount;this._bucketCount=normalizeBucketCount(value),this.requestUpdate("bucketCount",oldValue)}toggleRowSelection(row){this.toggleSelectionAxis(row,!0)}toggleColumnSelection(col){this.toggleSelectionAxis(col,!1)}get calendarWeekdayLabelText(){return this.calendarData?.weekdayLabelText}get calendarWeekdayLabelWidth(){const value=this.calendarData?.weekdayLabelWidth;if(value==="auto")return value;if(typeof value!="number")return;const resolved=finiteNumber(value,CAL_PAD_LEFT);return resolved>=0?resolved:void 0}get calendarMonthLabelText(){return this.calendarData?.monthLabelText}get calendarColumnX(){return this.calendarData?.columnX}get calendarRowY(){return this.calendarData?.rowY}constructor(){super(),this.data=DEFAULT_MATRIX_DATA,this._stickyLabels="none",this.resolvedColLabelHeight=PAD_TOP,this.resolvedRowLabelWidth=PAD_LEFT,this.resolvedCalendarWeekdayLabelWidth=CAL_PAD_LEFT,this.withoutLegend=!1,this.scale="linear",this.cellGapX=1,this.cellGapY=1,this.cellRadius=0,this.colLabelInterval=1,this.fitToWidth=!1,this._bucketCount=DEFAULT_BUCKET_COUNT,this.annotations=[],this.selectedCell=null,this.multiple=!1,this.selectedCells=[],this.accessibleCells=!1,this.cachedValueRange=null,this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1},this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays),this.cachedCalendarSortedValues=[],this.cachedCalendarCellsByPos=new Map,this.cachedCalendarCellsByDate=new Map,this.cachedAnnotations=[],this.cachedLegendStops=[],this.cachedColorSteps=[],this.cachedCalendarAnnotationDates=new Set,this.cachedMatrixAnnotationPositions=new Set,this.decorationProjectionTruncated=!1,this.cachedCalendarDateByPos=[],this.cachedAccessiblePositions=[],this.cachedAccessiblePositionsByKey=new Map,this.cachedAccessiblePositionIndexByKey=new Map,this.cachedRamp=null,this.canvasHasContent=!1,this.canvasVisible=!0,this.drawDirty=!1,this.overlayRevision=0,this.hoverCell=null,this.focusedCell=null,this.liveText="",this.accessibleTargetSizePx=DEFAULT_ACCESSIBLE_TARGET_SIZE_PX,this.restoringAccessibleFocus=!1,this.accessibleFocusGeneration=0,this.announcements=new AnnouncementSinkController(this,{eager:["polite"]}),this.authorRole=null,this.authorAriaLabel=null,this.generatedAriaLabel="",this.syncingGeneratedSemantics=!1,this.hasSyncedDescribedByElements=!1,this.onDprChange=()=>{this.watchDpr(),this.requestDraw()},this.scheduleDraw=()=>{if(this.drawFrameRequest)return;const owner=this.ownerDocument.defaultView;if(!owner||!this.isConnected)return;const request={owner,handle:0};request.handle=owner.requestAnimationFrame(()=>{this.drawFrameRequest===request&&(this.drawFrameRequest=void 0,this.isConnected&&this.ownerDocument.defaultView===owner&&this.requestDraw())}),this.drawFrameRequest=request},this.selectedPositions=new Map,this.selectionAnchor=null,this.suppressSelectionClick=!1,this.onSelectionPointerDown=event=>{if(!this.multiple||event.button!==0||!event.isPrimary||this.selectionGesture)return;const pos=this.selectionPointerPosition(event);if(!pos)return;event.preventDefault(),this.suppressSelectionClick=!1,this.selectionRangeBase=void 0,this.selectionAnchor=pos,this.focusedCell=pos,this.accessibleCells?this.focusAccessibleCell(pos):this.canvas?.focus();const target=event.currentTarget;this.selectionGesture={pointerId:event.pointerId,target,start:pos,previous:pos,moved:!1,selecting:!this.selectedPositions.has(this.accessibleCellKey(pos)),cells:new Map(this.selectedPositions)};try{target.setPointerCapture(event.pointerId)}catch{}this.paintSelectionTo(pos)},this.onSelectionPointerMove=event=>{if(this.selectionGesture?.pointerId!==event.pointerId)return;const pos=this.selectionPointerPosition(event);pos&&!this.samePos(pos,this.selectionGesture.previous)&&this.paintSelectionTo(pos)},this.onSelectionPointerUp=event=>{const gesture=this.selectionGesture;if(!gesture||gesture.pointerId!==event.pointerId)return;const pos=this.selectionPointerPosition(event);pos&&this.paintSelectionTo(pos),this.cancelSelectionGesture(),this.proposeSelection(gesture.cells,"pointer"),gesture.moved||this.emitCellClick(gesture.start,"pointer",!1)},this.onSelectionPointerCancel=event=>{this.selectionGesture?.pointerId===event.pointerId&&this.cancelSelectionGesture()},this.tooltipSize={inline:0,block:0},this.onPointerMove=e=>{const next=this.hitTest(e.offsetX,e.offsetY);this.samePos(this.hoverCell,next)||(this.hoverCell=next)},this.onPointerLeave=()=>{this.hoverCell=null},this.onCanvasClick=e=>{if(this.consumeSelectionClick(e))return;const pos=this.hitTest(e.offsetX,e.offsetY);pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onKeyDown=e=>{if(this.selectionKeyDown(e,this.focusedCell))return;const previous=this.focusedCell,edge=this.edgeCell(e);if(edge?(e.preventDefault(),this.focusedCell=edge,this.scrollCellIntoView(edge)):this.effectiveMode==="calendar"?this.onCalendarKeyDown(e):this.onMatrixKeyDown(e),(edge||ARROW_KEYS.has(e.key))&&this.focusedCell){const proposedKeys=this.extendSelection(previous,this.focusedCell,e.shiftKey);this.announce(this.focusedCell,proposedKeys?.has(this.accessibleCellKey(this.focusedCell)))}},this.canvasColorCache=new Map,this.onAccessibleCellFocus=e=>{if(this.restoringAccessibleFocus)return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.samePos(pos,this.focusedCell)||(this.selectionAnchor=pos,this.selectionRangeBase=void 0),this.focusedCell=pos,this.announce(pos))},this.onAccessibleCellClick=e=>{if(this.consumeSelectionClick(e))return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos,e.detail===0?"keyboard":"pointer"))},this.onAccessibleCellKeyDown=e=>{const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.selectionKeyDown(e,pos)||GRID_KEYS.has(e.key)&&(e.preventDefault(),this.focusedCell=pos,this.onKeyDown(e),this.focusAccessibleCell(this.focusedCell)))},new ThemeWatcher(this,()=>this.onThemeSignal()),this.calendarSpacingTrackingArmed=!0}requestUpdate(name,oldValue,options){this.calendarSpacingTrackingArmed&&name!==void 0&&CALENDAR_SPACING_PROPERTIES.has(name)&&(this.explicitCalendarSpacingProperties??=new Set).add(name),super.requestUpdate(name,oldValue,options)}explicitCalendarSpacing(name){if(!this.explicitCalendarSpacingProperties?.has(name))return;const value=this[name];return value??void 0}warnOnLegendRampMismatch(){const rampColors=this.cachedColorSteps.map(color=>sanitizeCssColor(color)??color);if(rampColors.length===0)return;const legendColors=this.cachedLegendStops.filter(stop=>!!stop.color&&stop.partOfRamp!==!1).map(stop=>sanitizeCssColor(stop.color??"")??stop.color??"");legendColors.length===0||legendColors.length===rampColors.length&&legendColors.every((color,index)=>color===rampColors[index])||devWarnOnce("lyra-heatmap-legend-ramp-mismatch",`<${this.localName}>: legendStops describes ${legendColors.length} colour(s) that do not match the ${rampColors.length} colorSteps the cells are painted from, so the legend may misdescribe the ramp. Supply legendStops built from the same array as colorSteps, or omit it to keep the built-in gradient key.`)}attributeChangedCallback(name,oldValue,value){super.attributeChangedCallback(name,oldValue,value),!(oldValue===value||this.syncingGeneratedSemantics)&&(name==="role"&&(this.authorRole=value),name==="aria-label"&&(this.authorAriaLabel=value))}connectedCallback(){super.connectedCallback(),this.refreshAccessibleTargetSize();const owner=this.ownerDocument.defaultView,ResizeObserverCtor=owner?.ResizeObserver;if(owner&&ResizeObserverCtor){let observer;observer=new ResizeObserverCtor(()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.resizeObserver!==observer||this.scheduleDraw()}),this.resizeObserver=observer,observer.observe(this)}const IntersectionObserverCtor=owner?.IntersectionObserver;if(this.canvasVisible=!0,owner&&IntersectionObserverCtor){let observer;observer=new IntersectionObserverCtor(entries=>{if(!this.isConnected||this.ownerDocument.defaultView!==owner||this.intersectionObserver!==observer)return;const entry=entries.find(candidate=>candidate.target===this);!entry||entry.isIntersecting===this.canvasVisible||(this.canvasVisible=entry.isIntersecting,this.canvasVisible&&this.drawDirty&&this.scheduleDraw())}),this.intersectionObserver=observer,observer.observe(this)}this.cachedRamp=null,this.paintedTheme=void 0,this.canvasColorCache.clear(),this.watchDpr(),this.drawDirty&&!ResizeObserverCtor&&this.scheduleDraw()}disconnectedCallback(){super.disconnectedCallback(),this.cancelSelectionGesture(),this.selectionAnchor=null,this.selectionRangeBase=void 0,this.accessibleFocusGeneration++,this.pendingAccessibleFocus=void 0,this.pendingAccessibleFocusOrigin=void 0,this.restoringAccessibleFocus=!1,this.hoverCell=null,this.focusedCell=null,this.liveText="",this.canvasHasContent=!1,this.drawDirty=!0,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.intersectionObserver?.disconnect(),this.intersectionObserver=void 0,this.canvasVisible=!0,this.clearDprWatcher(),this.cancelDrawFrame()}adoptedCallback(){super.adoptedCallback(),this.announcements.adopted()}watchDpr(){this.clearDprWatcher();const owner=this.ownerDocument.defaultView;if(!owner||typeof owner.matchMedia!="function")return;const query2=owner.matchMedia(`(resolution: ${owner.devicePixelRatio}dppx)`),listener=()=>{!this.isConnected||this.ownerDocument.defaultView!==owner||this.dprQuery!==query2||this.onDprChange()};this.dprQuery=query2,this.dprChangeListener=listener,query2.addEventListener("change",listener)}clearDprWatcher(){this.dprQuery&&this.dprChangeListener&&this.dprQuery.removeEventListener("change",this.dprChangeListener),this.dprQuery=void 0,this.dprChangeListener=void 0}willUpdate(changed){super.willUpdate(changed),(changed.size!==1||!changed.has("hoverCell"))&&this.overlayRevision++,(changed.has("data")||changed.has("domain")||changed.has("midpoint")||!this.hasUpdated)&&this.rebuildCanonicalMatrixData(),(changed.has("annotations")||changed.has("legendStops")||changed.has("colorSteps")||!this.hasUpdated)&&this.rebuildBoundedDecorations();const accessibleModeChanged=changed.has("accessibleCells")&&this.hasUpdated,collectionChanged=changed.has("data")||changed.has("cellInteractive"),activeRenderedControl=collectionChanged||accessibleModeChanged?shadowFocusTarget(this):null,activeAccessibleCell=activeRenderedControl?.matches('[part="cell"]')?activeRenderedControl:null,renderedAccessibleCells=activeAccessibleCell?.matches('[part="cell"]')?[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]]:[],accessibleFocusSnapshot=activeAccessibleCell?.matches('[part="cell"]')?{identity:activeAccessibleCell.dataset.cellIdentity,index:renderedAccessibleCells.indexOf(activeAccessibleCell)}:void 0;if(collectionChanged&&(this.focusedCell=null,this.hoverCell=null,this.liveText=""),changed.has("data")||changed.has("locale")||!this.hasUpdated){this.cachedCalendarGrid=buildCalendarGrid(this.calendarDays,this.normalizedFirstDayOfWeek,this.calendarMonthLabelText,this.effectiveLocale),this.cachedCalendarSortedValues=this.cachedCalendarGrid.cells.map(cell=>cell.value).filter(value=>!this.isNoData(value)).sort((a,b)=>a-b),this.cachedCalendarCellsByPos=new Map(this.cachedCalendarGrid.cells.map(cell=>[`${cell.week}:${cell.weekday}`,cell])),this.cachedCalendarCellsByDate=new Map(this.cachedCalendarGrid.cells.map(cell=>[cell.date,cell]));const{firstWeekStart,weekCount}=this.cachedCalendarGrid;this.cachedCalendarDateByPos=Array.from({length:weekCount*7},(_,index)=>isoDateAtOffset(firstWeekStart,index))}if(changed.has("colorSteps")||changed.has("withoutLegend")||!this.hasUpdated){const colorSteps=this.withoutLegend?[]:this.cachedColorSteps.map(sanitizeCssColor);colorSteps.length>=2&&colorSteps.every(color=>color!==void 0)?this.style.setProperty("--lr-heatmap-color-steps-gradient",`linear-gradient(to right, ${colorSteps.join(", ")})`):this.style.removeProperty("--lr-heatmap-color-steps-gradient")}if((changed.has("data")||changed.has("domain")||changed.has("midpoint")||!this.hasUpdated)&&(this.cachedValueRange=this.computeValueRange()),(collectionChanged||!this.hasUpdated)&&this.rebuildAccessiblePositions(),(collectionChanged||accessibleModeChanged||changed.has("multiple"))&&(this.cancelSelectionGesture(),this.selectionAnchor=null,this.selectionRangeBase=void 0,this.proposedSelectionKeys=void 0),(collectionChanged||changed.has("selectedCells")||changed.has("multiple")||!this.hasUpdated)&&(this.rebuildSelectedPositions(),changed.has("selectedCells")&&this.selectionGesture&&this.cancelSelectionGesture(),changed.has("selectedCells")&&this.selectionRangeBase&&(this.proposedSelectionKeys?.size!==this.selectedPositions.size||[...this.selectedPositions.keys()].some(key=>!this.proposedSelectionKeys?.has(key)))&&(this.selectionAnchor=this.focusedCell,this.selectionRangeBase=void 0)),accessibleFocusSnapshot){const positions=this.accessibleCellPositions(),target=(accessibleFocusSnapshot.identity==null?void 0:positions.find(pos=>this.accessibleCellIdentity(pos)===accessibleFocusSnapshot.identity))??positions[Math.min(Math.max(accessibleFocusSnapshot.index,0),positions.length-1)]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeAccessibleCell??void 0,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}if(accessibleModeChanged){const previouslyAccessible=changed.get("accessibleCells")===!0;if(previouslyAccessible&&!this.accessibleCells&&activeAccessibleCell){const key=activeAccessibleCell.dataset.cellKey,target=key?this.accessibleCellAtKey(key):null;target&&(this.focusedCell=target,this.liveText=this.resolveCellText(target)),this.pendingAccessibleFocus="canvas",this.pendingAccessibleFocusOrigin=activeAccessibleCell,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}else if(!previouslyAccessible&&this.accessibleCells&&activeRenderedControl?.matches('[part="canvas"]')){const positions=this.accessibleCellPositions(),target=this.focusedCell?positions.find(pos=>this.samePos(pos,this.focusedCell))??positions[0]??null:positions[0]??null;this.focusedCell=target,this.liveText=target?this.resolveCellText(target):"",this.pendingAccessibleFocus=target??"base",this.pendingAccessibleFocusOrigin=activeRenderedControl,this.restoringAccessibleFocus=!0,this.accessibleFocusGeneration++}}const bounds=this.cachedValueRange,range=bounds?`${this.formatNumericValue(bounds[0])}–${this.formatNumericValue(bounds[1])}`:this.localize("heatmapNoDataValue"),valueLabel=this.localizedValueLabel();let label;if(this.effectiveMode==="calendar")label=this.localize("heatmapCalendarLabel",void 0,{days:this.formatCount(this.cachedCalendarGrid.cells.length),label:valueLabel,range});else{const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;label=this.localize("heatmapMatrixLabel",void 0,{rows:this.formatCount(rows),cols:this.formatCount(cols),label:valueLabel,range})}const selectedText=this.selectedCellDescription(),generatedAriaLabel=[label,selectedText,this.projectionDescription()].filter(Boolean).join(" ");this.generatedAriaLabel=generatedAriaLabel,this.syncingGeneratedSemantics=!0;try{this.authorRole===null&&this.getAttribute("role")!=="group"&&this.setAttribute("role","group"),this.authorAriaLabel===null&&this.getAttribute("aria-label")!==generatedAriaLabel&&this.setAttribute("aria-label",generatedAriaLabel)}finally{this.syncingGeneratedSemantics=!1}}rebuildBoundedDecorations(){this.cachedAnnotations=this.annotations.slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedLegendStops=(this.legendStops??[]).slice(0,MAX_HEATMAP_DECORATIONS).map(entry=>({...entry})),this.cachedColorSteps=(this.colorSteps??[]).slice(0,MAX_HEATMAP_DECORATIONS),this.warnOnLegendRampMismatch(),this.cachedCalendarAnnotationDates=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.date==null?[]:[annotation.date])),this.cachedMatrixAnnotationPositions=new Set(this.cachedAnnotations.flatMap(annotation=>annotation.row==null||annotation.col==null?[]:[`${annotation.row}:${annotation.col}`])),this.decorationProjectionTruncated=this.annotations.length>MAX_HEATMAP_DECORATIONS||(this.legendStops?.length??0)>MAX_HEATMAP_DECORATIONS||(this.colorSteps?.length??0)>MAX_HEATMAP_DECORATIONS}get projectionTruncated(){return this.decorationProjectionTruncated||(this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated)}get cellProjectionTruncated(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.truncated:this.cachedMatrixData.truncated}projectedCellCount(){return this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount*7:this.matrixRowLabels.length*this.matrixColLabels.length}projectionDescription(){const messages=[];return this.cellProjectionTruncated&&messages.push(this.localize("heatmapProjectionLimit",void 0,{count:this.formatCount(this.projectedCellCount())})),this.decorationProjectionTruncated&&messages.push(this.localize("heatmapDecorationLimit",void 0,{count:this.formatCount(MAX_HEATMAP_DECORATIONS)})),messages.join(" ")}rebuildCanonicalMatrixData(){if(this.data.kind!=="matrix"){this.cachedMatrixData={rowLabels:[],colLabels:[],values:[],truncated:!1};return}const colCount=Math.min(this.data.colLabels.length,MAX_HEATMAP_CELLS),rowLimit=colCount===0?Math.min(this.data.rowLabels.length,MAX_HEATMAP_CELLS):Math.floor(MAX_HEATMAP_CELLS/colCount),rowCount=Math.min(this.data.rowLabels.length,rowLimit),rowLabels=this.data.rowLabels.slice(0,rowCount).map(String),colLabels=this.data.colLabels.slice(0,colCount).map(String),source=this.data,values=Array.from({length:rowCount},(_,row)=>Array.from({length:colCount},(_2,col)=>source.values[row]?.[col]??(this.signedDomain?Number.NaN:-1)));this.cachedMatrixData={rowLabels,colLabels,values,truncated:rowCount!==this.data.rowLabels.length||colCount!==this.data.colLabels.length||this.data.values.some((row,index)=>index>=rowCount||row.length>colCount)}}selectedCellDescription(){if(this.multiple){const count=this.currentSelectedPositions.size;return count?this.localize("heatmapSelectedCount",void 0,{count:this.formatCount(count)}):""}if(!this.selectedCell)return"";if(this.effectiveMode==="calendar"){if(this.selectedCell.date==null)return"";const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);return match?this.localize("heatmapSelectedCellLabel",void 0,{cell:this.calendarCellText({week:match.week,weekday:match.weekday,date:match.date})}):""}const{row,col}=this.selectedCell;return row==null||col==null||row<0||row>=this.matrixRowLabels.length||col<0||col>=this.matrixColLabels.length?"":this.localize("heatmapSelectedCellLabel",void 0,{cell:this.matrixCellText({row,col})})}computeValueRange(){const pinned=this.domain;if(pinned){const[lo,hi]=pinned;if(Number.isFinite(lo)&&Number.isFinite(hi)&&lo!==hi)return lo<hi?[lo,hi]:[hi,lo]}const source=this.effectiveMode==="calendar"?this.cachedCalendarGrid.cells.map(cell=>cell.value):this.matrixValues.flat();return minMax(source.filter(v=>!this.isNoData(v)))}localizedValueLabel(){return this.valueLabel===void 0?this.localize("heatmapValueLabel"):this.valueLabel}formatNumericValue(value){return getNumberFormat(this.effectiveLocale||void 0).format(value)}syncExternalDescription(){const describedBy=this.getAttribute("aria-describedby");if(!describedBy&&!this.hasSyncedDescribedByElements)return;const control=this.accessibleCells?this.renderRoot.querySelector('[part="cells"]'):this.canvas;this.hasSyncedDescribedByElements=syncAriaDescribedByElements(this,control??void 0,describedBy)}updated(changed){if(super.updated(changed),this.syncExternalDescription(),this.hoverCell&&this.effectiveStickyLabels!=="none"&&this.scheduleAfterUpdate(()=>this.measureTooltip(),"heatmap-tooltip-metrics"),["data","cellSize","rowHeight","cellGapX","cellGapY","cellRadius","colLabelInterval","maxCellSize","minCellSize","valueLabel","scale","domain","midpoint","fitToWidth","rowLabelWidth","colLabelHeight","colLabelRotation","bucketCount","annotations","focusedCell","colorSteps","cellColor","selectedCell","selectedCells","multiple","selectionPreview","legendStops","accessibleCells","accessibleTargetSizePx","locale","stickyLabels"].some(name=>changed.has(name))){if(changed.has("focusedCell")&&[...changed.keys()].every(key=>key==="focusedCell"||key==="liveText")&&this.repaintFocusRing(changed.get("focusedCell")))return;this.requestDraw()}const pending=this.pendingAccessibleFocus;if(pending===void 0)return;this.pendingAccessibleFocus=void 0;const origin=this.pendingAccessibleFocusOrigin;this.pendingAccessibleFocusOrigin=void 0;const generation=this.accessibleFocusGeneration;this.scheduleAfterUpdate(()=>{try{if(generation!==this.accessibleFocusGeneration||!this.isConnected)return;if(origin){const internalActive=shadowFocusTarget(this),documentActive=activeElementIn(this.ownerDocument),focusStayedAtOrigin=internalActive===origin,originWasRemovedWithoutReplacement=internalActive===null&&(documentActive===null||documentActive===this||documentActive===this.ownerDocument.body);if(!focusStayedAtOrigin&&!originWasRemovedWithoutReplacement)return}if(pending==="base"){this.shadowRoot?.querySelector('[part="base"]')?.focus();return}if(pending==="canvas"){this.shadowRoot?.querySelector('[part="canvas"]')?.focus();return}const identity=this.accessibleCellIdentity(pending);[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellIdentity===identity)?.focus()}finally{this.restoringAccessibleFocus=!1}},"heatmap-accessible-focus")}refreshTheme(){this.cachedRamp=null,this.refreshAccessibleTargetSize()||this.requestDraw()}themeSignature(){const cs=this.ownerDocument.defaultView?.getComputedStyle(this);return cs?[...this.scaleEndpoints(cs),this.noDataFill(cs),this.labelColor(cs),this.labelFont(cs),this.focusRingColor(cs),this.annotationColor(cs),this.selectedColor(cs),this.stickyLabelBg(cs),...this.cachedColorSteps.map(step=>this.resolveColorStep(step,""))].join("\0"):""}onThemeSignal(){const signature=this.themeSignature(),resized=this.refreshAccessibleTargetSize();signature===this.paintedTheme&&!this.cellColor||(this.paintedTheme=signature,this.cachedRamp=null,resized||this.scheduleDraw())}refreshAccessibleTargetSize(){const raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-icon-button-size").trim()??"",resolved=resolveCssTokenLength(raw,{host:this}),next=resolved!==void 0&&Number.isFinite(resolved)&&resolved>0?resolved:DEFAULT_ACCESSIBLE_TARGET_SIZE_PX;return next===this.accessibleTargetSizePx?!1:(this.accessibleTargetSizePx=next,!0)}scaleEndpoints(cs){const lo=cs.getPropertyValue("--lr-heatmap-scale-lo").trim()||cs.getPropertyValue("--_lr-heatmap-scale-lo").trim()||FALLBACK_SCALE_LO,hi=cs.getPropertyValue("--lr-heatmap-scale-hi").trim()||cs.getPropertyValue("--_lr-heatmap-scale-hi").trim()||FALLBACK_SCALE_HI;return[lo,hi]}labelColor(cs){return cs.getPropertyValue("--lr-color-text-quiet").trim()||"#6b7280"}labelFont(cs){return cs.getPropertyValue("--lr-heatmap-label-font").trim()||cs.getPropertyValue("--_lr-heatmap-label-font").trim()||FALLBACK_LABEL_FONT}stickyLabelBg(cs){const raw=cs.getPropertyValue("--lr-heatmap-sticky-label-bg").trim()||cs.getPropertyValue("--_lr-heatmap-sticky-label-bg").trim()||FALLBACK_STICKY_LABEL_BG;return formatRgb(resolveRgb(raw,FALLBACK_STICKY_LABEL_BG,this.ownerDocument))}noDataFill(cs){return cs.getPropertyValue("--lr-heatmap-no-data-fill").trim()||cs.getPropertyValue("--_lr-heatmap-no-data-fill").trim()||FALLBACK_NO_DATA_FILL}focusRingColor(cs){return cs.getPropertyValue("--lr-heatmap-focus-ring-color").trim()||cs.getPropertyValue("--_lr-heatmap-focus-ring-color").trim()||FALLBACK_FOCUS_RING_COLOR}annotationColor(cs){return cs.getPropertyValue("--lr-heatmap-annotation-color").trim()||cs.getPropertyValue("--_lr-heatmap-annotation-color").trim()||FALLBACK_ANNOTATION_COLOR}selectedColor(cs){return cs.getPropertyValue("--lr-heatmap-selected-color").trim()||cs.getPropertyValue("--_lr-heatmap-selected-color").trim()||FALLBACK_SELECTED_COLOR}strokeCellState(ctx,x,y,size,state2,color,paintedShape){const shape=paintedShape??(this.effectiveMode==="matrix"?this.matrixCellShape(size):this.calendarCellShape(size)),width=shape?.custom?shape.w:size,height=shape?.custom?shape.h:size;shape?.custom&&(ctx.save(),ctx.beginPath(),ctx.roundRect(x,y,shape.w,shape.h,shape.radius),ctx.clip());const inset=Math.min(state2==="annotation"?.5:state2==="selected"?3.5:6.5,Math.max(.5,(Math.min(width,height)-RING_LINE_WIDTH-1)/2)),w=Math.max(1,width-inset*2),h=Math.max(1,height-inset*2);ctx.lineWidth=RING_LINE_WIDTH,ctx.strokeStyle=color,ctx.setLineDash?.(state2==="annotation"?[]:state2==="selected"?[4,2]:[1,2]),shape?.custom&&shape.radius>0?(ctx.beginPath(),ctx.roundRect(x+inset,y+inset,w,h,Math.max(0,shape.radius-inset)),ctx.stroke()):ctx.strokeRect(x+inset,y+inset,w,h),ctx.setLineDash?.([]),shape?.custom&&ctx.restore()}isSelectedPos(pos){return this.multiple?this.currentSelectedPositions.has(this.accessibleCellKey(pos)):this.selectedCell?"week"in pos?this.selectedCell.date==null?!1:this.calendarCellAt(pos).date===this.selectedCell.date:this.selectedCell.row===pos.row&&this.selectedCell.col===pos.col:!1}draw(){if(!this.canvasVisible){this.drawDirty=!0;return}this.syncDeferredFitFrame(!1),this.drawDirty=!1,this.canvasHasContent=!1,this.paintedTheme??=this.themeSignature(),this.effectiveMode==="calendar"?this.drawCalendar():this.drawMatrix()}requestDraw(){this.drawDirty=!0,this.isConnected&&(this.canvasVisible?this.draw():this.syncDeferredFitFrame(!0))}syncDeferredFitFrame(deferred){const base=this.shadowRoot?.querySelector('[part="base"]');if(!base)return;let contained=!1;deferred&&this.fitToWidth&&this.clientWidth>0&&(contained=(this.effectiveMode==="calendar"?this.columnXFor(Math.max(1,this.cachedCalendarGrid.weekCount)):this.matrixPadLeft+this.matrixColLabels.length*this.matrixCellSize(this.matrixColLabels.length))<=this.clientWidth),base.toggleAttribute("data-fit-frame-contained",contained)}repaintFocusRing(previous){if(!this.canvasHasContent||!this.canvas||this.drawDirty)return!1;const current=this.focusedCell;if(this.effectiveMode==="calendar"){if(previous&&!("week"in previous)||current&&!("week"in current))return!1;this.repaintCalendarFocusCell(previous&&"week"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintCalendarFocusCell(current)}else{if(previous&&!("row"in previous)||current&&!("row"in current))return!1;this.repaintMatrixFocusCell(previous&&"row"in previous?previous:null),current&&(!previous||!this.samePos(previous,current))&&this.repaintMatrixFocusCell(current)}return!0}cancelDrawFrame(){const request=this.drawFrameRequest;request&&request.owner.cancelAnimationFrame(request.handle),this.drawFrameRequest=void 0}resolveColorStep(color,fallback){const safe=sanitizeCssColor(color);return safe?resolveCanvasColor(this,safe,fallback):fallback}colorRamp(bucketCount,cs){const steps=this.cachedColorSteps;if(steps&&steps.length>=2){const key2=`steps ${steps.join(" ")}`;if(this.cachedRamp?.key===key2)return this.cachedRamp;const resolved=steps.map((color,index)=>this.resolveColorStep(color,index===steps.length-1?FALLBACK_SCALE_HI:FALLBACK_SCALE_LO)),colors2=resolved.map(color=>formatRgb(resolveRgb(color,FALLBACK_SCALE_LO,this.ownerDocument))),loRgb2=resolveRgb(resolved[0],FALLBACK_SCALE_LO,this.ownerDocument),hiRgb2=resolveRgb(resolved[resolved.length-1],FALLBACK_SCALE_HI,this.ownerDocument);return this.cachedRamp={key:key2,colors:colors2,loRgb:loRgb2,hiRgb:hiRgb2},this.cachedRamp}const[scaleLo,scaleHi]=this.scaleEndpoints(cs),normalizedBucketCount=normalizeBucketCount(bucketCount),key=`${scaleLo}\0${scaleHi}\0${normalizedBucketCount}`;if(this.cachedRamp?.key===key)return this.cachedRamp;const loRgb=resolveRgb(scaleLo,FALLBACK_SCALE_LO,this.ownerDocument),hiRgb=resolveRgb(scaleHi,FALLBACK_SCALE_HI,this.ownerDocument),colors=Array.from({length:normalizedBucketCount},(_,i)=>mixRgb(loRgb,hiRgb,i/(normalizedBucketCount-1)));return this.cachedRamp={key,colors,loRgb,hiRgb},this.cachedRamp}calendarCellSize(){return this.calendarSpacing().cellSize}calendarSpacing(){const{weekCount}=this.cachedCalendarGrid,rawGapX=this.explicitCalendarSpacing("cellGapX"),rawGapY=this.explicitCalendarSpacing("cellGapY"),rawRadius=this.explicitCalendarSpacing("cellRadius"),boundGap=(raw,size2)=>raw===void 0?CAL_GAP:finiteRange(raw,CAL_GAP,0,Math.max(0,size2-1));let size;if(this.fitToWidth&&weekCount>0){const fitGap=boundGap(rawGapX,this.cellSize),hostWidth=this.clientWidth||this.calendarPadLeft+weekCount*(this.cellSize+fitGap);size=this.clampFitCellSize((hostWidth-this.calendarPadLeft)/weekCount-fitGap)}else size=this.cellSize;return this.accessibleCells&&(size=Math.max(size,this.accessibleTargetSizePx)),{cellSize:size,gapX:boundGap(rawGapX,size),gapY:boundGap(rawGapY,size),radius:rawRadius===void 0?0:finiteRange(rawRadius,0,0,size/2)}}clampFitCellSize(size){const floored=finiteRange(size,FIT_MIN_CELL,Math.max(FIT_MIN_CELL,this.minCellSize??FIT_MIN_CELL));return this.maxCellSize==null?floored:Math.min(floored,this.maxCellSize)}columnXFor(week){return this.calendarColumnPositions()[week]??this.calendarPadLeft}rowYFor(weekday){return this.calendarRowPositions()[weekday]??CAL_LABEL_H}calendarColumnPositions(){const{cellSize,gapX:gap}=this.calendarSpacing(),weekCount=this.cachedCalendarGrid.weekCount,callback=this.calendarColumnX,padLeft=this.calendarPadLeft,cached=this.cachedColumnGeometry;if(cached!==void 0&&cached.callback===callback&&cached.padLeft===padLeft&&cached.cellSize===cellSize&&cached.gap===gap&&cached.weekCount===weekCount)return cached.positions;const positions=[];for(let index=0;index<=weekCount;index++){const fallback=index===0?padLeft:positions[index-1]+cellSize+gap;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedColumnGeometry={callback,padLeft,cellSize,gap,weekCount,positions},positions}calendarRowPositions(){const{cellSize,gapY:gap}=this.calendarSpacing(),callback=this.calendarRowY,cached=this.cachedRowGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize&&cached.gap===gap)return cached.positions;const positions=[];for(let index=0;index<=7;index++){const fallback=index===0?CAL_LABEL_H:positions[index-1]+cellSize+gap;let candidate=fallback;if(callback)try{const supplied=callback(index);Number.isFinite(supplied)&&supplied>=0&&(index===0||supplied>=positions[index-1]+cellSize)&&(candidate=supplied)}catch{candidate=fallback}positions.push(candidate)}return this.cachedRowGeometry={callback,cellSize,gap,positions},positions}weekdayLabels(firstWeekStart){const formatter=getDateTimeFormat(this.effectiveLocale||void 0,{weekday:"short",timeZone:"UTC"}),labels=["","","","","","",""];for(const weekday of[1,3,5]){const row=(weekday-this.normalizedFirstDayOfWeek+7)%7;labels[row]=this.calendarWeekdayLabelText?.(weekday)??formatter.format(new Date(firstWeekStart.getTime()+row*MS_PER_DAY))}return labels}paintCalendarAxisLabels(ctx,cellSize,cs,firstWeekStart,monthLabels,months=!0,weekdays=!0){if(ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs),months){const canvasRight=this.columnXFor(Math.max(1,this.cachedCalendarGrid.weekCount)),placed=[];monthLabels.forEach((month,index)=>{const label=this.ellipsize(ctx,month.label,canvasRight);if(!label)return;const width=this.labelWidth(ctx,label),x=Math.max(0,Math.min(this.columnXFor(month.week),canvasRight-width)),nextWeek=monthLabels[index+1]?.week??Math.max(month.week+1,this.cachedCalendarGrid.weekCount),entry={label,x,end:x+width+CAL_MONTH_LABEL_GAP,span:nextWeek-month.week};let previous=placed[placed.length-1];for(;previous&&entry.x<previous.end&&entry.span>previous.span;)placed.pop(),previous=placed[placed.length-1];previous&&entry.x<previous.end||placed.push(entry)});for(const{label,x}of placed)ctx.fillText(label,x,CAL_LABEL_H-4)}if(weekdays){const available=this.calendarPadLeft-CAL_WEEKDAY_LABEL_INSET*2;this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{const shown=label?this.ellipsize(ctx,label,available):"";shown&&ctx.fillText(shown,CAL_WEEKDAY_LABEL_INSET,this.rowYFor(weekday)+cellSize-1)})}}drawCalendar(){this.withLabelCache(()=>this.paintCalendar())}paintCalendar(){if(!this.canvas)return;const{weekCount,firstWeekStart,monthLabels}=this.cachedCalendarGrid,cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;this.calendarWeekdayLabelWidth==="auto"&&(this.resolvedCalendarWeekdayLabelWidth=this.measureCalendarWeekdayLabelWidth(cs,firstWeekStart));const spacing=this.calendarSpacing(),cellSize=spacing.cellSize,w=this.columnXFor(Math.max(1,weekCount)),h=this.rowYFor(7),ctx=this.sizeCanvas(this.canvas,w,h);if(!ctx)return;ctx.clearRect(0,0,w,h);const buckets=normalizeBucketCount(this.bucketCount),ramp=this.colorRamp(buckets,cs).colors,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const value=this.calendarValueAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday),override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCellColor(override,cs);else if(this.isNoData(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=this.rampBucket(value,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,buckets)];this.fillCalendarCell(ctx,x,y,cellSize,spacing.radius)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.date==null)continue;const match=this.cachedCalendarCellsByDate.get(ann.date);if(!match)continue;const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}for(const match of this.selectedPaintPositions())if("week"in match){const x=this.columnXFor(match.week),y=this.rowYFor(match.weekday);this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}if(this.focusedCell&&"week"in this.focusedCell){const{week,weekday}=this.focusedCell;if(week<weekCount&&weekday<7){const x=this.columnXFor(week),y=this.rowYFor(weekday);this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}this.paintCalendarAxisLabels(ctx,cellSize,cs,firstWeekStart,monthLabels),this.canvasHasContent=!0,this.recordCalendarGeometry(spacing,weekCount)&&this.accessibleCells&&this.scheduleAfterUpdate(()=>this.requestUpdate(),"heatmap-calendar-accessible-geometry")}matrixCellSize(cols){let size;if(this.fitToWidth&&cols>0){const padLeft=this.matrixPadLeft,hostWidth=this.clientWidth||padLeft+cols*this.cellSize;size=this.clampFitCellSize((hostWidth-padLeft)/cols)}else size=this.cellSize;if(!this.accessibleCells)return size;const target=this.accessibleTargetSizePx,custom=finiteNumber(this.cellGapX,1)!==1||finiteNumber(this.cellGapY,1)!==1||finiteRange(this.cellRadius,0,0)>0,gap=this.rowHeight!==void 0?finiteRange(this.cellGapX,1,0,target):custom?Math.max(finiteRange(this.cellGapX,1,0,target),finiteRange(this.cellGapY,1,0,target)):0;return Math.max(size,target+gap)}matrixRowHeight(cellSize){if(this.rowHeight===void 0)return cellSize;const height=finiteRange(this.rowHeight,cellSize,1);if(!this.accessibleCells)return height;const target=this.accessibleTargetSizePx;return Math.max(height,target+finiteRange(this.cellGapY,1,0,target))}matrixCellShape(size,height=this.matrixRowHeight(size)){if(height===size&&finiteNumber(this.cellGapX,1)===1&&finiteNumber(this.cellGapY,1)===1&&finiteRange(this.cellRadius,0,0)===0)return{w:size-1,h:size-1,radius:0,custom:!1};const target=this.accessibleCells?this.accessibleTargetSizePx:1,w=size-finiteRange(this.cellGapX,1,0,Math.max(0,size-Math.min(size,target))),h=height-finiteRange(this.cellGapY,1,0,Math.max(0,height-Math.min(height,target))),radius=finiteRange(this.cellRadius,0,0,Math.min(w,h)/2);return{w,h,radius,custom:height!==size||w!==size-1||h!==size-1||radius!==0}}calendarCellShape(size){const radius=this.calendarSpacing().radius;return radius>0?{w:size,h:size,radius:Math.min(radius,size/2),custom:!0}:void 0}fillMatrixCell(ctx,x,y,shape){shape.radius===0?ctx.fillRect(x,y,shape.w,shape.h):(ctx.beginPath(),ctx.roundRect(x,y,shape.w,shape.h,shape.radius),ctx.fill())}paintMatrixCell(ctx,row,col,cellSize,rowHeight,shape,cs,rampData,noDataFill){const value=this.matrixValues[row]?.[col]??Number.NaN,bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.({row,col},value);if(override!=null)ctx.fillStyle=this.resolveCellColor(override,cs);else if(this.isNoData(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,rampData.colors.length);ctx.fillStyle=step<0?noDataFill:rampData.colors[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=rampData.colors[this.rampBucket(value,lo,hi,rampData.colors.length)]:ctx.fillStyle=mixRgb(rampData.loRgb,rampData.hiRgb,this.rampAlpha(value,lo,hi));this.fillMatrixCell(ctx,this.matrixPadLeft+col*cellSize,this.matrixPadTop+row*rowHeight,shape)}paintMatrixFocusOverlays(ctx,row,col,cellSize,rowHeight,shape,cs,state2){const x=this.matrixPadLeft+col*cellSize,y=this.matrixPadTop+row*rowHeight;state2==="annotation"&&this.cachedMatrixAnnotationPositions.has(`${row}:${col}`)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs),shape),state2==="selected"&&this.isSelectedPos({row,col})&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs),shape),state2==="focus"&&this.focusedCell&&"row"in this.focusedCell&&this.focusedCell.row===row&&this.focusedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs),shape)}focusRepaintBounds(ctx,x,y,cellSize,cellHeight=cellSize){const padding=RING_LINE_WIDTH+1,dpr=ctx.getTransform().a,left=Math.floor((x-padding)*dpr)/dpr,top=Math.floor((y-padding)*dpr)/dpr,right=Math.ceil((x+cellSize+padding)*dpr)/dpr,bottom=Math.ceil((y+cellHeight+padding)*dpr)/dpr;return{left,top,width:right-left,height:bottom-top,radius:Math.ceil((2*padding+1/dpr)/cellSize),rowRadius:Math.ceil((2*padding+1/dpr)/cellHeight)}}repaintMatrixFocusCell(pos){this.withLabelCache(()=>this.paintMatrixFocusCell(pos))}paintMatrixFocusCell(pos){if(!pos||!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(pos.row<0||pos.row>=rows||pos.col<0||pos.col>=cols)return;const cellSize=this.matrixCellSize(cols),rowHeight=this.matrixRowHeight(cellSize),shape=this.matrixCellShape(cellSize,rowHeight),x=this.matrixPadLeft+pos.col*cellSize,y=this.matrixPadTop+pos.row*rowHeight,ctx=this.canvas.getContext("2d");if(!ctx)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const{left,top,width,height,radius,rowRadius}=this.focusRepaintBounds(ctx,x,y,cellSize,rowHeight),firstRow=Math.max(0,pos.row-rowRadius),lastRow=Math.min(rows-1,pos.row+rowRadius),firstCol=Math.max(0,pos.col-radius),lastCol=Math.min(cols-1,pos.col+radius),ramp=this.colorRamp(RAMP_STEPS,cs),noData=this.noDataFill(cs),scratch=rowHeight===cellSize?void 0:this.ownerDocument.createElement("canvas"),dpr=ctx.getTransform().a,scratchLeft=Math.floor((this.matrixPadLeft+firstCol*cellSize-RING_LINE_WIDTH-1)*dpr)/dpr,scratchTop=Math.floor((this.matrixPadTop+firstRow*rowHeight-RING_LINE_WIDTH-1)*dpr)/dpr;if(scratch){const right=Math.ceil((this.matrixPadLeft+(lastCol+1)*cellSize+RING_LINE_WIDTH+1)*dpr),bottom=Math.ceil((this.matrixPadTop+(lastRow+1)*rowHeight+RING_LINE_WIDTH+1)*dpr);scratch.width=right-Math.round(scratchLeft*dpr),scratch.height=bottom-Math.round(scratchTop*dpr)}const paintCtx=scratch?.getContext("2d")??ctx;if(scratch&&paintCtx===ctx){this.drawMatrix();return}paintCtx.save();try{scratch?paintCtx.setTransform(dpr,0,0,dpr,-scratchLeft*dpr,-scratchTop*dpr):(paintCtx.beginPath(),paintCtx.rect(left,top,width,height),paintCtx.clip(),paintCtx.clearRect(left,top,width,height));for(let row=firstRow;row<=lastRow;row++)for(let col=firstCol;col<=lastCol;col++)this.paintMatrixCell(paintCtx,row,col,cellSize,rowHeight,shape,cs,ramp,noData);for(const state2 of["annotation","selected","focus"])for(let row=firstRow;row<=lastRow;row++)for(let col=firstCol;col<=lastCol;col++)this.paintMatrixFocusOverlays(paintCtx,row,col,cellSize,rowHeight,shape,cs,state2);left<this.matrixPadLeft&&this.paintMatrixRowLabels(paintCtx,this.matrixPadLeft,this.matrixPadTop,rowHeight,cs,{top,bottom:top+height}),top<this.matrixPadTop&&this.paintMatrixColLabels(paintCtx,this.matrixPadLeft,this.matrixPadTop,cellSize,cs,{first:firstCol,last:lastCol})}finally{paintCtx.restore()}if(scratch){ctx.save();try{ctx.setTransform(1,0,0,1,0,0),ctx.clearRect(left*dpr,top*dpr,width*dpr,height*dpr),ctx.drawImage(scratch,Math.round((left-scratchLeft)*dpr),Math.round((top-scratchTop)*dpr),Math.round(width*dpr),Math.round(height*dpr),Math.round(left*dpr),Math.round(top*dpr),Math.round(width*dpr),Math.round(height*dpr))}finally{ctx.restore()}}}paintCalendarCell(ctx,week,weekday,cellSize,cs,ramp,noDataFill){const value=this.calendarValueAt(week,weekday),bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCellColor(override,cs);else if(this.isNoData(value))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(value,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else this.cachedColorSteps.length>=2?ctx.fillStyle=ramp[this.rampBucket(value,lo,hi,ramp.length)]:ctx.fillStyle=ramp[quartileBucket(value,this.cachedCalendarSortedValues,ramp.length)];this.fillCalendarCell(ctx,this.columnXFor(week),this.rowYFor(weekday),cellSize,this.calendarSpacing().radius)}fillCalendarCell(ctx,x,y,size,radius){radius===0?ctx.fillRect(x,y,size,size):(ctx.beginPath(),ctx.roundRect(x,y,size,size,radius),ctx.fill())}recordCalendarGeometry(spacing,weekCount){const next={padLeft:this.calendarPadLeft,padTop:CAL_LABEL_H,cellSize:spacing.cellSize,cellWidth:spacing.cellSize,cellHeight:spacing.cellSize,cellGapX:spacing.gapX,cellGapY:spacing.gapY,cellRadius:spacing.radius,weekCount,firstDayOfWeek:this.normalizedFirstDayOfWeek},previous=this.lastPaintedCalendarGeometry;if(previous&&Object.keys(next).every(key=>previous[key]===next[key]))return!1;const frozen=Object.freeze(next);return this.lastPaintedCalendarGeometry=frozen,this.emit("lr-calendar-geometry-change",frozen),!0}paintCalendarFocusOverlays(ctx,week,weekday,cellSize,cs,state2){const date=this.calendarDateAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday);state2==="annotation"&&this.cachedCalendarCellsByDate.has(date)&&this.cachedCalendarAnnotationDates.has(date)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),state2==="selected"&&(this.multiple||this.cachedCalendarCellsByDate.has(date))&&this.isSelectedPos({week,weekday,date})&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),state2==="focus"&&this.focusedCell&&"week"in this.focusedCell&&this.focusedCell.week===week&&this.focusedCell.weekday===weekday&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintCalendarFocusCell(pos){this.withLabelCache(()=>this.paintCalendarFocusCell(pos))}paintCalendarFocusCell(pos){if(!pos||!this.canvas)return;const{weekCount,firstWeekStart}=this.cachedCalendarGrid;if(pos.week<0||pos.week>=weekCount||pos.weekday<0||pos.weekday>=7)return;const cellSize=this.calendarCellSize(),x=this.columnXFor(pos.week),y=this.rowYFor(pos.weekday),ctx=this.canvas.getContext("2d");if(!ctx)return;const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const{left,top,width,height,radius}=this.focusRepaintBounds(ctx,x,y,cellSize),firstWeek=Math.max(0,pos.week-radius),lastWeek=Math.min(weekCount-1,pos.week+radius),firstDay=Math.max(0,pos.weekday-radius),lastDay=Math.min(6,pos.weekday+radius),ramp=this.colorRamp(normalizeBucketCount(this.bucketCount),cs).colors,noData=this.noDataFill(cs);ctx.save();try{ctx.beginPath(),ctx.rect(left,top,width,height),ctx.clip(),ctx.clearRect(left,top,width,height);for(let week=firstWeek;week<=lastWeek;week++)for(let day=firstDay;day<=lastDay;day++)this.paintCalendarCell(ctx,week,day,cellSize,cs,ramp,noData);for(const state2 of["annotation","selected","focus"])for(let week=firstWeek;week<=lastWeek;week++)for(let day=firstDay;day<=lastDay;day++)this.paintCalendarFocusOverlays(ctx,week,day,cellSize,cs,state2);this.paintCalendarAxisLabels(ctx,cellSize,cs,firstWeekStart,this.cachedCalendarGrid.monthLabels,top<CAL_LABEL_H,left<this.calendarPadLeft)}finally{ctx.restore()}}drawMatrix(){this.withLabelCache(()=>this.paintMatrix())}paintMatrix(){if(!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length,cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;this.rowLabelWidth==="auto"&&(this.resolvedRowLabelWidth=this.measureRowLabelWidth(cs)),this.colLabelHeight==="auto"&&(this.resolvedColLabelHeight=this.measureColLabelHeight(cs));const padLeft=this.matrixPadLeft,padTop=this.matrixPadTop,cellSize=this.matrixCellSize(cols),rowHeight=this.matrixRowHeight(cellSize),shape=this.matrixCellShape(cellSize,rowHeight),dimensions=shape.custom?{cellWidth:shape.w,cellHeight:shape.h,cellRadius:shape.radius}:{},previous=this.lastPaintedMatrixGeometry,geometry=previous&&previous.padLeft===padLeft&&previous.padTop===padTop&&previous.cellSize===cellSize&&previous.rowHeight===(rowHeight===cellSize?void 0:rowHeight)&&previous.cellWidth===dimensions.cellWidth&&previous.cellHeight===dimensions.cellHeight&&previous.cellRadius===dimensions.cellRadius?previous:Object.freeze({padLeft,padTop,cellSize,...rowHeight===cellSize?{}:{rowHeight},...dimensions});this.lastPaintedMatrixGeometry=geometry;const geometryChanged=geometry!==previous;geometryChanged&&this.emit("lr-matrix-geometry-change",geometry);const w=padLeft+cols*cellSize,h=padTop+rows*rowHeight,ctx=this.sizeCanvas(this.canvas,w,h);if(!ctx)return;ctx.clearRect(0,0,w,h);const bounds=this.cachedValueRange,lo=bounds?bounds[0]:0,hi=bounds?bounds[1]:1,rampData=this.colorRamp(RAMP_STEPS,cs),ramp=rampData.colors,{loRgb,hiRgb}=rampData,noDataFill=this.noDataFill(cs);this.canvasColorCache.clear();for(let r=0;r<rows;r++)for(let c=0;c<cols;c++){const v=this.matrixValues[r]?.[c]??Number.NaN,x=padLeft+c*cellSize,y=padTop+r*rowHeight,override=this.cellColor?.({row:r,col:c},v);if(override!=null)ctx.fillStyle=this.resolveCellColor(override,cs);else if(this.isNoData(v))ctx.fillStyle=noDataFill;else if(this.scale==="sqrt"){const step=sqrtStep(v,hi,ramp.length);ctx.fillStyle=step<0?noDataFill:ramp[step]}else if(this.cachedColorSteps.length>=2){const step=this.rampBucket(v,lo,hi,ramp.length);ctx.fillStyle=ramp[step]}else{const t=this.rampAlpha(v,lo,hi);ctx.fillStyle=mixRgb(loRgb,hiRgb,t)}this.fillMatrixCell(ctx,x,y,shape)}if(this.cachedAnnotations.length)for(const ann of this.cachedAnnotations){if(ann.row==null||ann.col==null||ann.row<0||ann.row>=rows||ann.col<0||ann.col>=cols)continue;const x=padLeft+ann.col*cellSize,y=padTop+ann.row*rowHeight;this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs),shape)}for(const selected of this.selectedPaintPositions()){if(!("row"in selected))continue;const{row,col}=selected;if(row>=0&&row<rows&&col>=0&&col<cols){const x=padLeft+col*cellSize,y=padTop+row*rowHeight;this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs),shape)}}if(this.focusedCell&&"row"in this.focusedCell){const{row,col}=this.focusedCell;if(row<rows&&col<cols){const x=padLeft+col*cellSize,y=padTop+row*rowHeight;this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs),shape)}}this.paintMatrixRowLabels(ctx,padLeft,padTop,rowHeight,cs),this.paintMatrixColLabels(ctx,padLeft,padTop,cellSize,cs),this.paintFrozenLabelBands(padLeft,padTop,cellSize,rowHeight,w,h,ctx.getTransform().a,cs),this.canvasHasContent=!0,geometryChanged&&this.accessibleCells&&this.scheduleAfterUpdate(()=>this.requestUpdate(),"heatmap-matrix-accessible-geometry")}paintMatrixRowLabels(ctx,padLeft,padTop,cellSize,cs,dirty){ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);const rowLabelSpace=padLeft-ROW_LABEL_INSET*2;let first=0,last=this.matrixRowLabels.length-1;if(dirty){const{fontBoundingBoxAscent,fontBoundingBoxDescent}=ctx.measureText("M"),baseline=padTop+cellSize/2+3;first=Math.max(first,Math.floor((dirty.top-fontBoundingBoxDescent-baseline)/cellSize)),last=Math.min(last,Math.ceil((dirty.bottom+fontBoundingBoxAscent-baseline)/cellSize))}for(let r=first;r<=last;r++){const shown=this.ellipsize(ctx,this.matrixRowLabels[r],rowLabelSpace);shown&&ctx.fillText(shown,ROW_LABEL_INSET,padTop+r*cellSize+cellSize/2+3)}}paintMatrixColLabels(ctx,padLeft,padTop,cellSize,cs,columns){ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);const colRotation=this.effectiveColLabelRotation,interval=finiteInteger(this.colLabelInterval,1,1);if(colRotation===0){const cols=this.matrixColLabels.length;this.matrixColLabels.forEach((label,c)=>{if(c%interval!==0||columns&&(c<columns.first-interval+1||c>columns.last))return;const shown=this.ellipsize(ctx,label,Math.min(interval,cols-c)*cellSize-2);shown&&ctx.fillText(shown,padLeft+c*cellSize+2,padTop-COL_LABEL_INSET)});return}const radians=colRotation*Math.PI/180,previousAlign=ctx.textAlign;ctx.textAlign="right",this.matrixColLabels.forEach((label,c)=>{c%interval===0&&(ctx.save(),ctx.translate(padLeft+c*cellSize+cellSize/2,padTop-COL_LABEL_INSET),ctx.rotate(radians),ctx.fillText(label,0,0),ctx.restore())}),ctx.textAlign=previousAlign}paintFrozenLabelBands(padLeft,padTop,cellSize,rowHeight,width,height,scale,cs){if(this.effectiveStickyLabels==="none")return;const backdrop=this.stickyLabelBg(cs),rowBand=this.frozenBandCanvas("row-labels");rowBand&&this.paintFrozenBand(rowBand,padLeft,height,scale,backdrop,bandCtx=>this.paintMatrixRowLabels(bandCtx,padLeft,padTop,rowHeight,cs));const colBand=this.frozenBandCanvas("col-labels");colBand&&this.paintFrozenBand(colBand,width,padTop,scale,backdrop,bandCtx=>this.paintMatrixColLabels(bandCtx,padLeft,padTop,cellSize,cs))}frozenBandCanvas(part){return this.shadowRoot?.querySelector(`[part="${part}"]`)??null}sizeCanvas(canvas,width,height,desiredScale=this.ownerDocument.defaultView?.devicePixelRatio){const{pixelWidth,pixelHeight,scale}=resolveBoundedCanvasAllocation({cssWidth:width,cssHeight:height,desiredScale,maxDimension:MAX_CANVAS_DIMENSION,maxPixels:MAX_CANVAS_PIXELS});canvas.width=pixelWidth,canvas.height=pixelHeight,canvas.style.width=`${width}px`,canvas.style.height=`${height}px`;const ctx=canvas.getContext("2d");return ctx?.scale(scale,scale),ctx}paintFrozenBand(canvas,width,height,scale,backdrop,paint){const ctx=this.sizeCanvas(canvas,width,height,scale);ctx&&(ctx.clearRect(0,0,width,height),ctx.fillStyle=backdrop,ctx.fillRect(0,0,width,height),paint(ctx))}hitTest(x,y){return this.effectiveMode==="calendar"?this.hitTestCalendar(x,y):this.hitTestMatrix(x,y)}matrixNavigationGeometry(rows,cols){const painted=this.lastPaintedMatrixGeometry;if(painted)return{rows,cols,padLeft:painted.padLeft,padTop:painted.padTop,cellSize:painted.cellSize,rowHeight:painted.rowHeight??painted.cellSize,cellWidth:painted.cellWidth??painted.cellSize-1,cellHeight:painted.cellHeight??painted.cellSize-1,customShape:painted.cellWidth!==void 0};const cellSize=this.matrixCellSize(cols),rowHeight=this.matrixRowHeight(cellSize),shape=this.matrixCellShape(cellSize,rowHeight);return{rows,cols,padLeft:this.matrixPadLeft,padTop:this.matrixPadTop,cellSize,rowHeight,cellWidth:shape.w,cellHeight:shape.h,customShape:shape.custom}}calendarNavigationGeometry(){const cellSize=this.calendarCellSize(),columnPositions=this.calendarColumnPositions(),rowPositions=this.calendarRowPositions();return{weekCount:this.cachedCalendarGrid.weekCount,cellSize,columnPositions,rowPositions,padLeft:this.calendarPadLeft,padTop:CAL_LABEL_H}}hitTestMatrix(x,y){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;return rows===0||cols===0?null:hitTestMatrixGrid(x,y,this.matrixNavigationGeometry(rows,cols),pos=>this.isCellInteractive(pos))}firstInteractiveMatrixCell(rows,cols){return findFirstInteractiveMatrixCell(rows,cols,pos=>this.isCellInteractive(pos))}nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols){return findNextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols,pos=>this.isCellInteractive(pos))}firstInteractiveCalendarCell(weekCount){return findFirstInteractiveCalendarCell(weekCount,(week,weekday)=>this.calendarPos(week,weekday),pos=>this.isCellInteractive(pos))}nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount){return findNextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount,(nextWeek,nextWeekday)=>this.calendarPos(nextWeek,nextWeekday),pos=>this.isCellInteractive(pos))}hitTestCalendar(x,y){const weekCount=this.cachedCalendarGrid.weekCount;if(weekCount===0)return null;const columnPositions=this.calendarColumnPositions();return hitTestCalendarGrid(x,y,weekCount,columnPositions,()=>this.calendarCellSize(),()=>this.calendarRowPositions(),(week,weekday)=>this.calendarPos(week,weekday),pos=>this.isCellInteractive(pos))}calendarCellAt(pos){return readCalendarCell(pos.week,pos.weekday,this.cachedCalendarCellsByPos,this.cachedCalendarDateByPos,this.cachedCalendarGrid.firstWeekStart,this.signedDomain)}calendarValueAt(week,weekday){return readCalendarValue(week,weekday,this.cachedCalendarCellsByPos,this.signedDomain)}calendarDateAt(week,weekday){return readCalendarDate(week,weekday,this.cachedCalendarDateByPos,this.cachedCalendarGrid.firstWeekStart)}calendarPos(week,weekday){return{week,weekday,date:this.calendarDateAt(week,weekday)}}cellRect(pos){return"week"in pos?calendarCellRect(pos.week,pos.weekday,this.calendarNavigationGeometry()):matrixCellRect(pos,this.matrixNavigationGeometry(this.matrixRowLabels.length,this.matrixColLabels.length))}accessibleCellRect(pos){return"week"in pos||!this.lastPaintedMatrixGeometry?this.cellRect(pos):accessibleMatrixCellRect(pos,this.lastPaintedMatrixGeometry)}defaultCellText(pos){return"week"in pos?this.calendarCellText(pos):this.matrixCellText(pos)}matrixCellText(pos){const rowLabel=this.matrixRowLabels[pos.row]??this.localize("heatmapDefaultRowLabel",void 0,{n:this.formatCount(pos.row+1)}),colLabel=this.matrixColLabels[pos.col]??this.localize("heatmapDefaultColLabel",void 0,{n:this.formatCount(pos.col+1)}),v=this.matrixValues[pos.row]?.[pos.col],valueText=v==null||this.isNoData(v)?this.localize("heatmapNoDataValue"):this.formatNumericValue(v);return this.localize("heatmapMatrixCellLabel",void 0,{row:rowLabel,col:colLabel,value:valueText})}calendarCellText(pos){const{date,value}=this.calendarCellAt(pos),label=getDateTimeFormat(this.effectiveLocale||void 0,{month:"short",day:"numeric",timeZone:"UTC"}).format(parseIsoDate(date)),valueText=this.isNoData(value)?this.localize("heatmapNoDataValue"):this.formatNumericValue(value);return this.localize("heatmapCalendarCellLabel",void 0,{date:label,value:valueText})}valueAt(pos){return"week"in pos?this.calendarCellAt(pos).value:this.matrixValues[pos.row]?.[pos.col]??-1}resolveCellText(pos){return this.cellText?this.cellText(pos,this.valueAt(pos)):this.defaultCellText(pos)}isCellInteractive(pos){return this.cellInteractive?.(pos,this.valueAt(pos))??!0}announce(pos,isSelectedOverride){const text=this.resolveCellText(pos),announcement=isSelectedOverride??this.isSelectedPos(pos)?this.localize("heatmapSelectedCellLabel",void 0,{cell:text}):text;this.liveText=announcement,this.announcements.announcePolite(announcement)}emitCellClick(pos,source="pointer",select=!0){if(!this.isCellInteractive(pos))return;this.multiple&&select&&(this.selectionAnchor=pos,this.selectionRangeBase=void 0,this.toggleSelectionPositions([pos],source));let detail;if("week"in pos){const{date,value}=this.calendarCellAt(pos);detail={date,value}}else{const value=this.matrixValues[pos.row]?.[pos.col]??-1;detail={row:pos.row,col:pos.col,value}}this.emit("lr-cell-activate",{...detail})}get currentSelectedPositions(){return this.selectionPreview??this.selectedPositions}selectedPaintPositions(){if(this.multiple)return[...this.currentSelectedPositions.values()];const selected=this.selectedCell;if(!selected)return[];if(this.effectiveMode==="calendar"){const match=selected.date?this.cachedCalendarCellsByDate.get(selected.date):void 0;return match?[match]:[]}return selected.row!=null&&selected.col!=null?[{row:selected.row,col:selected.col}]:[]}rebuildSelectedPositions(){const positions=new Map,dates=this.effectiveMode==="calendar"?new Map(this.cachedAccessiblePositions.map(pos=>[this.accessibleCellIdentity(pos),pos])):void 0,input=Array.isArray(this.selectedCells)?this.selectedCells:[];for(const cell of input.slice(0,MAX_HEATMAP_CELLS)){if(!cell||typeof cell!="object")continue;const pos=dates?typeof cell.date=="string"?dates.get(cell.date):void 0:Number.isInteger(cell.row)&&Number.isInteger(cell.col)?this.cachedAccessiblePositionsByKey.get(`matrix-${cell.row}-${cell.col}`):void 0;pos&&positions.set(this.accessibleCellKey(pos),pos)}this.selectedPositions=positions}selectionCoordinates(pos){return"week"in pos?{row:pos.weekday,col:pos.week}:pos}proposeSelection(positions,source){if(positions.size===this.selectedPositions.size&&[...positions.keys()].every(key=>this.selectedPositions.has(key)))return;this.proposedSelectionKeys=new Set(positions.keys());const selectedCells=[...positions.values()].sort((a,b)=>{const first=this.selectionCoordinates(a),second=this.selectionCoordinates(b);return first.row-second.row||first.col-second.col}).map(pos=>"week"in pos?{date:pos.date}:{row:pos.row,col:pos.col});this.emit("lr-selection-change",{selectedCells,source})}toggleSelectionPositions(positions,source){if(!this.multiple||positions.length===0)return;const next=new Map(this.selectedPositions),remove=positions.every(pos=>next.has(this.accessibleCellKey(pos)));for(const pos of positions){const key=this.accessibleCellKey(pos);remove?next.delete(key):next.set(key,pos)}this.proposeSelection(next,source)}toggleSelectionAxis(index,row){!this.multiple||!Number.isInteger(index)||index<0||(this.cancelSelectionGesture(),this.selectionRangeBase=void 0,this.toggleSelectionPositions(this.cachedAccessiblePositions.filter(pos=>{const coordinates=this.selectionCoordinates(pos);return(row?coordinates.row:coordinates.col)===index}),row?"row":"column"))}selectionKeyDown(event,pos){if(!this.multiple)return!1;if(event.key==="Escape"&&this.selectionGesture)return event.preventDefault(),this.cancelSelectionGesture(),!0;if(event.key!==" "||!pos||!(event.shiftKey||event.ctrlKey||event.metaKey))return!1;event.preventDefault();const coordinates=this.selectionCoordinates(pos);return event.ctrlKey||event.metaKey?this.toggleColumnSelection(coordinates.col):this.toggleRowSelection(coordinates.row),!0}extendSelection(previous,next,range){if(!this.multiple)return;if(!range){this.selectionAnchor=next,this.selectionRangeBase=void 0;return}this.selectionAnchor??=previous??next,this.selectionRangeBase??=new Map(this.selectedPositions);const from=this.selectionCoordinates(this.selectionAnchor),to=this.selectionCoordinates(next),selected=new Map(this.selectionRangeBase);for(const pos of this.cachedAccessiblePositions){const{row,col}=this.selectionCoordinates(pos);row>=Math.min(from.row,to.row)&&row<=Math.max(from.row,to.row)&&col>=Math.min(from.col,to.col)&&col<=Math.max(from.col,to.col)&&selected.set(this.accessibleCellKey(pos),pos)}return this.proposeSelection(selected,"keyboard"),new Set(selected.keys())}selectionPointerPosition(event){if(!this.canvas)return null;const rect=this.canvas.getBoundingClientRect();return this.hitTest(event.clientX-rect.left,event.clientY-rect.top)}paintSelectionTo(pos){const gesture=this.selectionGesture;if(!gesture)return;this.samePos(pos,gesture.previous)||(gesture.moved=!0);const from=this.selectionCoordinates(gesture.previous),to=this.selectionCoordinates(pos),steps=Math.max(Math.abs(to.row-from.row),Math.abs(to.col-from.col),1),changed=[];for(let step=0;step<=steps;step++){const row=Math.round(from.row+(to.row-from.row)*step/steps),col=Math.round(from.col+(to.col-from.col)*step/steps),key=this.effectiveMode==="calendar"?`calendar-${col}-${row}`:`matrix-${row}-${col}`,candidate=this.cachedAccessiblePositionsByKey.get(key);candidate&&(gesture.cells.has(key)!==gesture.selecting&&changed.push(candidate),gesture.selecting?gesture.cells.set(key,candidate):gesture.cells.delete(key))}if(gesture.previous=pos,this.selectionPreview!==gesture.cells){this.selectionPreview=gesture.cells;return}this.requestUpdate(),(changed.length>16||!changed.every(cell=>this.repaintCell(cell)))&&this.requestDraw()}repaintCell(pos){return!this.canvasHasContent||!this.canvas||this.drawDirty?!1:("week"in pos?this.repaintCalendarFocusCell(pos):this.repaintMatrixFocusCell(pos),!0)}cancelSelectionGesture(){const gesture=this.selectionGesture;if(this.selectionGesture=void 0,this.selectionPreview=void 0,!!gesture){this.suppressSelectionClick=!0;try{gesture.target.hasPointerCapture(gesture.pointerId)&&gesture.target.releasePointerCapture(gesture.pointerId)}catch{}}}consumeSelectionClick(event){return!this.suppressSelectionClick||event.detail===0?!1:(this.suppressSelectionClick=!1,!0)}get gridScrollport(){return this.shadowRoot?.querySelector('[part="grid"]')??null}measureTooltip(){if(!this.gridScrollport)return;const tooltip=this.shadowRoot?.querySelector('[part="tooltip"]');if(!tooltip||tooltip.hidden)return;const view=this.ownerDocument.defaultView,gap=view?Math.abs(finiteNumber(Number.parseFloat(view.getComputedStyle(tooltip).marginBlockStart),0)):0,inline=tooltip.offsetWidth,block=tooltip.offsetHeight+gap;inline===this.tooltipSize.inline&&block===this.tooltipSize.block||(this.tooltipSize={inline,block},this.requestUpdate())}tooltipAnchor(pos){const rect=this.cellRect(pos),center=rect.x+rect.w/2,port=this.gridScrollport;if(!port)return{style:{left:`${center}px`,top:`${rect.y}px`},below:!1};const{inline,block}=this.tooltipSize,windowStart=port.scrollLeft+(this.freezesRowLabels?this.matrixPadLeft:0),windowEnd=port.scrollLeft+port.clientWidth,windowTop=port.scrollTop+(this.freezesColLabels?this.matrixPadTop:0),windowBottom=port.scrollTop+port.clientHeight,below=rect.y-block<windowTop&&rect.y+rect.h+block<=windowBottom;return{style:{left:`${Math.max(windowStart+inline/2,Math.min(center,windowEnd-inline/2))}px`,top:`${below?rect.y+rect.h:rect.y}px`},below}}scrollCellIntoView(pos){const port=this.gridScrollport;if(!port)return;const rect=this.cellRect(pos),bandInline=this.freezesRowLabels?this.matrixPadLeft:0,bandBlock=this.freezesColLabels?this.matrixPadTop:0,left=Math.min(Math.max(port.scrollLeft,rect.x+rect.w-port.clientWidth),rect.x-bandInline),top=Math.min(Math.max(port.scrollTop,rect.y+rect.h-port.clientHeight),rect.y-bandBlock);left!==port.scrollLeft&&(port.scrollLeft=left),top!==port.scrollTop&&(port.scrollTop=top)}samePos(a,b){return a===b?!0:!a||!b?!1:"week"in a&&"week"in b?a.week===b.week&&a.weekday===b.weekday:"row"in a&&"row"in b?a.row===b.row&&a.col===b.col:!1}edgeCell(e){if(e.key!=="Home"&&e.key!=="End")return null;const row=this.focusedCell&&!(e.ctrlKey||e.metaKey)?this.selectionCoordinates(this.focusedCell).row:void 0,cells=this.cachedAccessiblePositions.filter(pos=>row===void 0||this.selectionCoordinates(pos).row===row);return cells[e.key==="Home"?0:cells.length-1]??null}onMatrixKeyDown(e){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell,"keyboard");return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("row"in this.focusedCell)){const next2=this.firstInteractiveMatrixCell(rows,cols);if(!next2)return;this.focusedCell=next2,this.scrollCellIntoView(next2);return}const{row,col}=this.focusedCell;let dRow=0,dCol=0;e.key==="ArrowUp"?dRow=-1:e.key==="ArrowDown"?dRow=1:e.key==="ArrowLeft"?dCol=-1:e.key==="ArrowRight"&&(dCol=1);const next=this.nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols);this.focusedCell=next,this.scrollCellIntoView(next)}onCalendarKeyDown(e){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return;if(e.key==="Enter"||e.key===" "){e.preventDefault(),this.focusedCell&&this.emitCellClick(this.focusedCell,"keyboard");return}if(!ARROW_KEYS.has(e.key))return;if(e.preventDefault(),!this.focusedCell||!("week"in this.focusedCell)){const next2=this.firstInteractiveCalendarCell(weekCount);if(!next2)return;this.focusedCell=next2;return}const{week,weekday}=this.focusedCell;let dWeek=0,dWeekday=0;e.key==="ArrowUp"?dWeekday=-1:e.key==="ArrowDown"?dWeekday=1:e.key==="ArrowLeft"?dWeek=-1:e.key==="ArrowRight"&&(dWeek=1);const next=this.nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount);this.focusedCell=next}resolveCellColor(value,cs){let color=this.canvasColorCache.get(value);if(color===void 0){const ctx=SCOPED_COLOR.test(value)?null:getScratchCtx(this.ownerDocument);if(ctx){ctx.fillStyle="rgb(1, 2, 3)";const rejected=ctx.fillStyle;ctx.fillStyle=value,ctx.fillStyle!==rejected&&(color=ctx.fillStyle)}color??=resolveCanvasColor(this,value,this.noDataFill(cs)),this.canvasColorCache.set(value,color)}return color}rebuildAccessiblePositions(){const positions=[];if(this.effectiveMode==="calendar"){const{weekCount}=this.cachedCalendarGrid;for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);this.isCellInteractive(pos)&&positions.push(pos)}}else for(let row=0;row<this.matrixRowLabels.length;row++)for(let col=0;col<this.matrixColLabels.length;col++){const pos={row,col};this.isCellInteractive(pos)&&positions.push(pos)}this.cachedAccessiblePositions=positions,this.cachedAccessiblePositionsByKey=new Map(positions.map(position=>[this.accessibleCellKey(position),position])),this.cachedAccessiblePositionIndexByKey=new Map(positions.map((position,index)=>[this.accessibleCellKey(position),index]))}accessibleCellPositions(){return this.cachedAccessiblePositions}accessibleCellKey(pos){return"week"in pos?`calendar-${pos.week}-${pos.weekday}`:`matrix-${pos.row}-${pos.col}`}accessibleCellIdentity(pos){return"week"in pos?pos.date:this.accessibleCellKey(pos)}accessibleCellAtKey(key){return this.cachedAccessiblePositionsByKey.get(key)??null}focusAccessibleCell(pos){pos&&this.updateComplete.then(()=>{[...this.shadowRoot?.querySelectorAll('[part="cell"]')??[]].find(candidate=>candidate.dataset.cellKey===this.accessibleCellKey(pos))?.focus()})}renderAccessibleCells(){if(!this.accessibleCells)return html``;const positions=this.accessibleCellPositions(),tabStop=this.focusedCell??positions[0]??null,focusIndex=tabStop?this.cachedAccessiblePositionIndexByKey.get(this.accessibleCellKey(tabStop))??0:0,start=Math.max(0,Math.min(Math.max(0,positions.length-MAX_ACCESSIBLE_HEATMAP_CELLS),focusIndex-Math.floor(MAX_ACCESSIBLE_HEATMAP_CELLS/2))),renderedPositions=positions.slice(start,start+MAX_ACCESSIBLE_HEATMAP_CELLS),renderedRows=new Map;for(const pos of renderedPositions){const rowIndex="week"in pos?pos.weekday+1:pos.row+1,row=renderedRows.get(rowIndex);row?row.push(pos):renderedRows.set(rowIndex,[pos])}const rowCount=this.effectiveMode==="calendar"?7:this.matrixRowLabels.length,colCount=this.effectiveMode==="calendar"?this.cachedCalendarGrid.weekCount:this.matrixColLabels.length,calendar=this.effectiveMode==="calendar"?this.calendarNavigationGeometry():void 0;return html`
4
4
  <div
5
5
  part="cells"
@@ -1 +1 @@
1
- const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="28.1.2";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
1
+ const LYRA_PACKAGE_NAME="@aceshooting/lyra-ui",LYRA_PACKAGE_VERSION="28.1.3";export{LYRA_PACKAGE_NAME,LYRA_PACKAGE_VERSION};
@@ -123,8 +123,8 @@ for the full rationale, including why `<lr-markdown>`/`<lr-markdown-core>` must
123
123
  fallback separately. `base` is a flex column and `body` grows to fill whatever block space a
124
124
  explicitly sized host gives it too, identically to `<lr-code-block>` above.
125
125
 
126
- **Optional peer deps:** `shiki` (specifically its `shiki/core`, `shiki/engine/oniguruma`, the binary
127
- `shiki/onig.wasm` asset (the default; select `shiki/engine/javascript` instead via
126
+ **Optional peer deps:** `shiki` (specifically its `shiki/core`, `shiki/engine/oniguruma`, Lyra’s packaged
127
+ Oniguruma binary (the default; select `shiki/engine/javascript` instead via
128
128
  `setShikiCoreEngine('javascript')`), and `shiki/themes/github-{light,dark}.mjs` subpaths — never
129
129
  `shiki`'s main entry point, which is what carries the ~200-language table this component exists to
130
130
  avoid). Building the
@@ -129,8 +129,8 @@ shared tokens `--lr-color-border`/`-border-subtle`/`-surface`/`-success`/`-succe
129
129
  `-danger-quiet`/`-text`, `--lr-radius`, `--lr-space-xs`/`-s`, `--lr-font-size-sm`,
130
130
  `--lr-line-height-snug`, `--lr-focus-ring-*`.
131
131
 
132
- **Optional peer deps:** `shiki` (the same fine-grained `shiki/core`/`shiki/engine/oniguruma`/binary
133
- `shiki/onig.wasm` subset `lr-code-block-core` uses by default, never `shiki`'s full ~200-language
132
+ **Optional peer deps:** `shiki` (the same fine-grained `shiki/core`/`shiki/engine/oniguruma` subset and packaged Oniguruma
133
+ binary `lr-code-block-core` uses by default, never `shiki`'s full ~200-language
134
134
  main entry point) — only loaded once both `language` and a matching `languages` entry are set;
135
135
  unset/unmatched leaves the plain unhighlighted diff text untouched.
136
136
 
@@ -380,7 +380,9 @@ color?: string; label?: string; partOfRamp?: boolean }`: a discrete legend key r
380
380
  **Getters/methods:** `exportData('csv'|'png')` returns a spreadsheet-safe CSV snapshot of the
381
381
  underlying matrix/calendar values or a PNG data URL for the most recently completed canvas paint.
382
382
  The CSV form reads `data` directly (not any bounded render cache) and omits no-data cells — one
383
- `row,column,value` row per real matrix cell, or `date,value` per real calendar day. The PNG form
383
+ `row,column,value` row per real matrix cell, or `date,value` per real calendar day. Finite numeric
384
+ values retain their precision without display rounding or locale formatting; text cells remain
385
+ guarded against spreadsheet formulas. The PNG form
384
386
  includes the painted axes, cells, focus/selection/annotation overlays, and frozen
385
387
  label bands while `stickyLabels` is enabled; the DOM legend, tooltip, and accessible-cell buttons
386
388
  are deliberately excluded. It returns `''` before a completed paint, while rendering is deferred or
@@ -110,7 +110,7 @@ rendered code and defaults to `var(--lr-font-mono)`.
110
110
 
111
111
  **Optional peer deps:** `marked`, `dompurify` (both lazy-loaded, same as `<lr-markdown>`), `katex`
112
112
  (for `math`). Does _not_ depend on the full `shiki` package's default entry point — only
113
- `shiki/core`, `shiki/engine/oniguruma`, the binary `shiki/onig.wasm` asset (the default; select
113
+ `shiki/core`, `shiki/engine/oniguruma`, Lyra’s packaged Oniguruma binary (the default; select
114
114
  `shiki/engine/javascript` instead via `setShikiCoreEngine('javascript')`), and
115
115
  `shiki/themes/github-{light,dark}.mjs`, the same fine-grained subset `<lr-code-block-core>` depends
116
116
  on.
package/llms/peers.md CHANGED
@@ -38,7 +38,7 @@ for the page.
38
38
  | Peer | Range | Needed by |
39
39
  |---|---|---|
40
40
  | `@aceshooting/lyra-flags` | `^2.3.0` | _(loaded by a shared internal module)_ |
41
- | `@aceshooting/lyra-translations` | `^28.1.2` | _(not referenced by any component)_ |
41
+ | `@aceshooting/lyra-translations` | `^28.1.3` | _(not referenced by any component)_ |
42
42
  | `@aiden0z/pptx-renderer` | `^1.3.0` | `lr-pptx-viewer` |
43
43
  | `@sgratzl/chartjs-chart-boxplot` | `^4.0.0` | `lr-box-plot` |
44
44
  | `chart.js` | `^4.0.1` | `lr-bar-chart`, `lr-box-plot`, `lr-bubble-chart`, `lr-chart`, `lr-doughnut-chart`, `lr-histogram`, `lr-line-chart`, `lr-pie-chart`, `lr-polar-area-chart`, `lr-radar-chart`, `lr-scatter-chart` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aceshooting/lyra-ui",
3
- "version": "28.1.2",
3
+ "version": "28.1.3",
4
4
  "description": "Free, independent Lit web components: an open-source alternative to Shoelace and Web Awesome with accessible forms, dashboards, charts, and agent UI.",
5
5
  "keywords": [
6
6
  "web-components",
@@ -2598,7 +2598,7 @@
2598
2598
  },
2599
2599
  "peerDependencies": {
2600
2600
  "@aceshooting/lyra-flags": "^2.3.0",
2601
- "@aceshooting/lyra-translations": "^28.1.2",
2601
+ "@aceshooting/lyra-translations": "^28.1.3",
2602
2602
  "@aiden0z/pptx-renderer": "^1.3.0",
2603
2603
  "@sgratzl/chartjs-chart-boxplot": "^4.0.0",
2604
2604
  "chart.js": "^4.0.1",
@@ -2766,7 +2766,7 @@
2766
2766
  "mammoth": "^1.13.0",
2767
2767
  "maplibre-gl": "^6.14.0",
2768
2768
  "marked": "^18.1.1",
2769
- "oxc-parser": "^0.153.0",
2769
+ "oxc-parser": "^0.154.0",
2770
2770
  "papaparse": "^5.7.0",
2771
2771
  "pdfjs-dist": "^6.4.299",
2772
2772
  "pixelmatch": "^8.0.0",
@@ -2778,13 +2778,13 @@
2778
2778
  "shiki": "^4.5.0",
2779
2779
  "svelte": "^5.57.2",
2780
2780
  "typescript": "^7.0.2",
2781
- "vue": "^3.5.43",
2781
+ "vue": "^3.5.44",
2782
2782
  "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
2783
2783
  },
2784
2784
  "scripts": {
2785
2785
  "build": "node scripts/build.mjs && pnpm run check:build-artifacts && pnpm run check:theme-bootstrap",
2786
2786
  "regen": "pnpm run archive-changelog && pnpm run package-metadata && pnpm run default-string-slices && pnpm run translation-slices && pnpm run translation-review-fixture && pnpm run locale-manifest && pnpm run manifest && pnpm run component-inventory && pnpm run tag-aliases && pnpm run manifest && pnpm run component-metadata && pnpm run registrations && pnpm run manifest && pnpm run component-inventory && pnpm run visual-manifest && pnpm run framework-types && pnpm run events && pnpm run testing-event-registry && pnpm run autoloader-manifest && pnpm run registration-graph && pnpm run scoped-definitions && pnpm run palette && pnpm run chart-palette && pnpm run terminal-palette && pnpm run style-axes && pnpm run option-presets && pnpm run design-tokens && pnpm run theme-scopes && pnpm run generate-reservation-styles && pnpm run generate-editor-data && pnpm run llms",
2787
- "check:build-artifacts": "node scripts/check-build-artifacts.mjs && node scripts/check-host-token-declarations.mjs && node --test scripts/ai-compile-contract.test.mjs && node --test scripts/theme-bootstrap-build-check.test.mjs",
2787
+ "check:build-artifacts": "node scripts/generate-shiki-wasm.mjs --check && node --test scripts/generate-shiki-wasm.test.mjs && node scripts/check-build-artifacts.mjs && node scripts/check-host-token-declarations.mjs && node --test scripts/ai-compile-contract.test.mjs && node --test scripts/theme-bootstrap-build-check.test.mjs",
2788
2788
  "pretest": "pnpm run build",
2789
2789
  "test": "wtr",
2790
2790
  "test:ssr": "node --test scripts/ssr-fixture.test.mjs && node scripts/check-ssr.mjs && node scripts/check-ssr-tokens.mjs && node --conditions=browser scripts/check-jsdom.mjs && node --conditions=browser scripts/check-happy-dom.mjs",