@aceshooting/lyra-ui 10.0.1 → 11.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/CHANGELOG.md +271 -0
  2. package/custom-elements.json +1 -1
  3. package/design-tokens.json +13 -0
  4. package/dist/cli/migrate-wa.mjs +164 -1
  5. package/dist/cli/migration-contract.json +1 -1
  6. package/dist/components/charts/chart/box-plot.class.d.ts +27 -0
  7. package/dist/components/charts/chart/box-plot.class.js +14 -4
  8. package/dist/components/charts/chart/box-plot.styles.js +28 -0
  9. package/dist/components/charts/chart/chart.class.d.ts +27 -0
  10. package/dist/components/charts/chart/chart.class.js +15 -5
  11. package/dist/components/charts/chart/chart.styles.js +28 -0
  12. package/dist/components/charts/chart/lite-chart.class.d.ts +32 -0
  13. package/dist/components/charts/chart/lite-chart.class.js +17 -4
  14. package/dist/components/charts/chart/lite-chart.styles.js +29 -0
  15. package/dist/components/data/heatmap/heatmap.class.d.ts +35 -2
  16. package/dist/components/data/heatmap/heatmap.class.js +2 -2
  17. package/dist/components/data/table/table.class.d.ts +19 -0
  18. package/dist/components/data/table/table.class.js +3 -3
  19. package/dist/components/forms/combobox/combobox.class.d.ts +71 -3
  20. package/dist/components/forms/combobox/combobox.class.js +4 -2
  21. package/dist/components/forms/combobox/combobox.styles.js +9 -0
  22. package/dist/components/forms/date-picker/date-input.class.d.ts +12 -1
  23. package/dist/components/forms/date-picker/date-input.class.js +4 -2
  24. package/dist/components/forms/date-picker/date-picker.class.d.ts +72 -0
  25. package/dist/components/forms/date-picker/date-picker.class.js +15 -3
  26. package/dist/components/forms/date-picker/date-picker.styles.js +46 -0
  27. package/dist/components/media/flag/flag.class.d.ts +3 -1
  28. package/dist/components/media/flag/flag.class.js +1 -1
  29. package/dist/components/media/map/map.class.d.ts +39 -2
  30. package/dist/components/media/map/map.class.js +1 -1
  31. package/dist/components/overlays/dialog/dialog.class.d.ts +20 -0
  32. package/dist/components/overlays/overlay/popover.class.d.ts +19 -3
  33. package/dist/components/overlays/overlay/popover.class.js +1 -1
  34. package/dist/components/viewers/pdf-viewer/pdf-viewer.class.js +1 -1
  35. package/dist/custom-elements-jsx.d.ts +31 -16
  36. package/dist/internal/canvas.js +1 -1
  37. package/dist/internal/package-metadata.d.ts +1 -1
  38. package/dist/internal/package-metadata.js +1 -1
  39. package/dist/internal/tokens.styles.js +1 -0
  40. package/dist/lyra.d.ts +1 -1
  41. package/dist/svelte.d.ts +31 -16
  42. package/dist/theme.css +32 -0
  43. package/dist/vue.d.ts +31 -16
  44. package/llms/components/lr-agent-eval-dashboard.md +1 -1
  45. package/llms/components/lr-agent-workspace.md +1 -1
  46. package/llms/components/lr-bar-chart.md +4 -3
  47. package/llms/components/lr-box-plot.md +15 -4
  48. package/llms/components/lr-bubble-chart.md +4 -3
  49. package/llms/components/lr-chart.md +13 -3
  50. package/llms/components/lr-chunk-inspector.md +1 -1
  51. package/llms/components/lr-combobox.md +42 -6
  52. package/llms/components/lr-date-input.md +40 -4
  53. package/llms/components/lr-date-picker.md +40 -4
  54. package/llms/components/lr-dialog.md +2 -1
  55. package/llms/components/lr-doughnut-chart.md +4 -3
  56. package/llms/components/lr-entity-dossier.md +1 -1
  57. package/llms/components/lr-eval-run.md +1 -1
  58. package/llms/components/lr-flag.md +10 -3
  59. package/llms/components/lr-grounding-summary.md +1 -1
  60. package/llms/components/lr-heatmap.md +20 -2
  61. package/llms/components/lr-histogram.md +4 -3
  62. package/llms/components/lr-line-chart.md +4 -3
  63. package/llms/components/lr-lite-chart.md +19 -3
  64. package/llms/components/lr-map.md +21 -4
  65. package/llms/components/lr-memory-panel.md +1 -1
  66. package/llms/components/lr-option.md +41 -5
  67. package/llms/components/lr-pie-chart.md +4 -3
  68. package/llms/components/lr-polar-area-chart.md +4 -3
  69. package/llms/components/lr-popover.md +20 -1
  70. package/llms/components/lr-provenance-panel.md +1 -1
  71. package/llms/components/lr-radar-chart.md +4 -3
  72. package/llms/components/lr-rag-answer.md +1 -1
  73. package/llms/components/lr-rag-eval-dashboard.md +1 -1
  74. package/llms/components/lr-retrieval-results.md +1 -1
  75. package/llms/components/lr-retrieval-trace.md +1 -1
  76. package/llms/components/lr-scatter-chart.md +4 -3
  77. package/llms/peers.md +8 -8
  78. package/llms/tokens.md +27 -1
  79. package/llms-full.txt +231 -28
  80. package/package.json +1 -1
  81. package/vscode-css-data.json +70 -0
  82. package/vscode-html-data.json +131 -20
  83. package/web-types.json +190 -23
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteAdd,finiteCount,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,MAX_SCROLL_CONTENT_WIDTH=1e6;function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const fraction=(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return lo*(1-ratio)+hi*ratio}).filter(Number.isFinite)}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const roundedLo=Math.floor(lo/step)*step,roundedHi=Math.ceil(hi/step)*step;Number.isFinite(roundedLo)&&(lo=roundedLo),Number.isFinite(roundedHi)&&(hi=roundedHi);const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=lo+index*step;Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this.labels=[],this.datasets=[],this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this.activeMarkIndex=0,this.resizeObserverGeneration=0,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.map((series,datasetIndex)=>{const value=series.data[index];return typeof value=="number"&&Number.isFinite(value)?this.formatter?.({value,surface:"export",datasetIndex,index,label,seriesLabel:series.label})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,svg,nothing}from"lit";import{property,state,query}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{specialistTokens}from"../../../internal/specialist-tokens.styles.js";import{hostAriaLabel,nextId,srOnly}from"../../../internal/a11y.js";import{getListFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{finiteAdd,finiteCount,finiteRange}from"../../../internal/numbers.js";import{escapeCsvField}from"../../utility/export-button/csv.js";import"../../utility/live-region/live-region.class.js";import{styles}from"./lite-chart.styles.js";import{forcedColorEncoding,forcedColorsActive}from"./chart-forced-colors.js";import{literalSetConverter,trueDefaultBooleanFromAttributeConverter as trueDefaultBooleanConverter}from"../../../internal/converters.js";import{sanitizeCssColor,sanitizeCssLength}from"../../../internal/safe-css.js";import{activeElementIn}from"../../../internal/active-element.js";import{acquireAnnouncementSink}from"../../../internal/announcer.js";import{MAX_RENDERED_CHART_RECORDS,sampleChartTableIndexes}from"./chart-table-sampling.js";import{chartChromeLegendPlacement,normalizeChartChromeLegendPosition}from"./chart-chrome.js";import{LYRA_DEFAULT_chart,LYRA_DEFAULT_chartCategory,LYRA_DEFAULT_chartData,LYRA_DEFAULT_chartDataSampled,LYRA_DEFAULT_chartSeriesLabel,LYRA_DEFAULT_chartTotal,LYRA_DEFAULT_liteChartBarLabel,LYRA_DEFAULT_liteChartCustomMarkSummary,LYRA_DEFAULT_liteChartMarkSummary}from"../../../internal/default-strings.generated.js";function normalizeLiteChartType(value){return value==="line"||value==="bar"?value:"bar"}const LITE_CHART_LAYOUT=literalSetConverter(["fit","scroll"],"fit"),DEFAULT_PALETTE=["var(--lr-chart-color-1, var(--lr-color-chart-1))","var(--lr-chart-color-2, var(--lr-color-chart-2))","var(--lr-chart-color-3, var(--lr-color-chart-3))","var(--lr-chart-color-4, var(--lr-color-chart-4))","var(--lr-chart-color-5, var(--lr-color-chart-5))","var(--lr-chart-color-6, var(--lr-color-chart-6))","var(--lr-chart-color-7, var(--lr-color-chart-7))","var(--lr-chart-color-8, var(--lr-color-chart-8))"],PAD_LEFT=36,PAD_RIGHT=8,PAD_TOP=8,PAD_BOTTOM=30,CATEGORY_LABEL_OFFSET=24,AXIS_TITLE_SPACE=14,TICK_COUNT=4,BAR_GROUP_GAP=.2,BAR_GAP=.08,BAR_CORNER_RADIUS=4,APPROX_LABEL_CHARACTER_WIDTH=7,MAX_SCROLL_CONTENT_WIDTH=1e6;function niceStep(span,count){const rough=span/Math.max(1,count),magnitude=10**Math.floor(Math.log10(rough)),residual=rough/magnitude;return(residual<1.5?1:residual<3?2:residual<7?5:10)*magnitude}function logDomainFraction(value,lo,hi){const top=Math.max(hi,0);if(!Number.isFinite(top)||top<=0)return domainFraction(value,lo,hi);const bottom=lo>0?lo:top/10;if(!Number.isFinite(bottom)||bottom<=0||bottom>=top)return domainFraction(value,lo,hi);if(!Number.isFinite(value)||value<=bottom)return 0;if(value>=top)return 1;const fraction=(Math.log10(value)-Math.log10(bottom))/(Math.log10(top)-Math.log10(bottom));return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function domainFraction(value,lo,hi){const span=hi-lo;if(Number.isFinite(span)&&span>0)return Math.min(1,Math.max(0,(value-lo)/span));const scale=Math.max(Math.abs(value),Math.abs(lo),Math.abs(hi),1),scaledSpan=hi/scale-lo/scale;if(!Number.isFinite(scaledSpan)||scaledSpan<=0)return 0;const fraction=(value/scale-lo/scale)/scaledSpan;return Number.isFinite(fraction)?Math.min(1,Math.max(0,fraction)):0}function safeDomainTicks(lo,hi,count){return Array.from({length:Math.max(1,count)+1},(_,index)=>{if(index===0)return lo;if(index===count)return hi;const ratio=index/count;return lo*(1-ratio)+hi*ratio}).filter(Number.isFinite)}function niceDomain(dataLo,dataHi,beginAtZero,count){let lo=beginAtZero?Math.min(0,dataLo):dataLo,hi=beginAtZero?Math.max(0,dataHi):dataHi;lo===hi&&(Math.abs(lo)>Number.MAX_VALUE/2?(lo=lo>0?lo/2:lo,hi=hi<0?hi/2:hi):(lo-=1,hi+=1));const span=hi-lo;if(!Number.isFinite(span))return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const step=niceStep(span,count);if(!Number.isFinite(step)||step<=0)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const roundedLo=Math.floor(lo/step)*step,roundedHi=Math.ceil(hi/step)*step;Number.isFinite(roundedLo)&&(lo=roundedLo),Number.isFinite(roundedHi)&&(hi=roundedHi);const slots=Math.floor((hi-lo)/step);if(!Number.isFinite(slots)||slots<0||slots>100)return{lo,hi,ticks:safeDomainTicks(lo,hi,count)};const ticks=[];for(let index=0;index<=slots;index++){const value=lo+index*step;Number.isFinite(value)&&ticks.push(value)}return ticks.at(-1)!==hi&&ticks.push(hi),{lo,hi,ticks}}class LyraLiteChart extends LyraElement{constructor(){super(...arguments),this.type="bar",this.labels=[],this.datasets=[],this.legend=!1,this.legendPosition="bottom",this.height="280px",this.xLabel="",this.yLabel="",this.beginAtZero=!0,this.stacked=!1,this.tableTotals=!1,this.showDataTable=!1,this.dataTableToggle=!1,this.dataTableExpandedOverride=null,this.dataTableId=nextId("lite-chart-data-table"),this._layout="fit",this.barWidth=32,this.roundedBars=!1,this.skipZero=!1,this.scale="linear",this.withoutValueAxis=!1,this.selectedIndices=[],this.label=null,this.description=null,this.forcedColorPatternId=nextId("lite-chart-pattern"),this.descriptionId=nextId("lite-chart-description"),this.plotWidth=0,this.plotHeight=0,this.fitMeasurementAvailable=!1,this.activeMarkIndex=0,this.resizeObserverGeneration=0,this.refocusMarkAfterUpdate=!1,this.refocusChartAfterUpdate=!1,this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.onForcedColorsChange=()=>{!this.isConnected||this.ownerDocument.defaultView!==this.forcedColorsWindow||this.requestUpdate()}}static{this.defaultStrings={...super.defaultStrings,chart:LYRA_DEFAULT_chart,chartCategory:LYRA_DEFAULT_chartCategory,chartData:LYRA_DEFAULT_chartData,chartDataSampled:LYRA_DEFAULT_chartDataSampled,chartSeriesLabel:LYRA_DEFAULT_chartSeriesLabel,chartTotal:LYRA_DEFAULT_chartTotal,liteChartBarLabel:LYRA_DEFAULT_liteChartBarLabel,liteChartCustomMarkSummary:LYRA_DEFAULT_liteChartCustomMarkSummary,liteChartMarkSummary:LYRA_DEFAULT_liteChartMarkSummary}}static{this.ownedCollectionProperties=Object.freeze(["labels","datasets","selectedIndices"])}static{this.styles=[LyraElement.styles,specialistTokens,styles,srOnly]}get dataTableVisible(){return this.dataTableToggle?this.dataTableExpandedOverride??this.showDataTable:this.showDataTable}toggleDataTable(){this.dataTableExpandedOverride=!this.dataTableVisible}get layout(){return this._layout}set layout(next){const normalized=LITE_CHART_LAYOUT.normalizeReflected(this,"layout",next),old=this._layout;old!==normalized&&(this._layout=normalized,this.requestUpdate("layout",old))}appendData(label,values,maxPoints=0){const limit=Math.max(0,finiteCount(maxPoints,0));let domainLength=this.labels.length;for(const series of this.datasets)domainLength=Math.max(domainLength,series.data.length);const labels=[...this.labels,...Array.from({length:Math.max(0,domainLength-this.labels.length)},()=>""),label],datasets=this.datasets.map((series,index)=>({...series,data:[...series.data,...Array.from({length:Math.max(0,domainLength-series.data.length)},()=>null),values[index]??null]}));this.labels=limit>0?labels.slice(-limit):labels,this.datasets=limit>0?datasets.map(series=>({...series,data:series.data.slice(-limit)})):datasets}exportData(format){if(format==="svg"){const XMLSerializerCtor=this.ownerDocument.defaultView?.XMLSerializer;return!this.svgEl||typeof XMLSerializerCtor!="function"?"":new XMLSerializerCtor().serializeToString(this.svgEl)}const header=["label",...this.datasets.map(series=>series.label)].map(escapeCsvField).join(","),rows=Array.from({length:this.recordCount()},(_,index)=>{const label=this.labels[index]??"";return[label,...this.datasets.map((series,datasetIndex)=>{const value=series.data[index];return typeof value=="number"&&Number.isFinite(value)?this.formatter?.({value,surface:"export",datasetIndex,index,label,seriesLabel:series.label})??value:""})].map(escapeCsvField).join(",")});return[header,...rows].join(`\r
2
2
  `)}connectedCallback(){super.connectedCallback(),this.syncAnnouncementSink(),this.armResizeObserver(),this.armForcedColorsWatcher()}armResizeObserver(){const target=this.svgEl,ownerDocument=this.ownerDocument;if(!this.isConnected||!target||this.resizeObserver&&this.resizeObserverDocument===ownerDocument&&this.resizeObserverTarget===target)return;this.resetResizeObserver();const ResizeObserverCtor=ownerDocument.defaultView?.ResizeObserver;if(!ResizeObserverCtor)return;const generation=this.resizeObserverGeneration,observer=new ResizeObserverCtor(entries=>{if(this.resizeObserver!==observer||this.resizeObserverGeneration!==generation||!this.isConnected||this.ownerDocument!==ownerDocument||this.resizeObserverTarget!==target)return;const box=entries[0]?.contentBoxSize?.[0];if(box)this.plotWidth=box.inlineSize,this.plotHeight=box.blockSize;else{const rect=this.svgEl?.getBoundingClientRect();rect&&(this.plotWidth=rect.width,this.plotHeight=rect.height)}});this.resizeObserver=observer,this.resizeObserverDocument=ownerDocument,this.resizeObserverTarget=target,target&&observer.observe(target)}disconnectedCallback(){super.disconnectedCallback(),this.releaseAnnouncementSink(),this.lastDataTruncationAnnouncement="",this.isMounting=!0,this.resetResizeObserver(),this.disarmForcedColorsWatcher()}adoptedCallback(){super.adoptedCallback(),this.resetResizeObserver(),this.releaseAnnouncementSink(),this.syncAnnouncementSink(),this.refreshFitMeasurementAvailability(),this.armForcedColorsWatcher()}armForcedColorsWatcher(){const ownerWindow=this.ownerDocument?.defaultView??void 0;ownerWindow?.matchMedia&&(this.forcedColorsWindow===ownerWindow&&this.forcedColorsQuery||(this.disarmForcedColorsWatcher(),this.forcedColorsWindow=ownerWindow,this.forcedColorsQuery=ownerWindow.matchMedia("(forced-colors: active)"),this.forcedColorsQuery.addEventListener("change",this.onForcedColorsChange)))}disarmForcedColorsWatcher(){this.forcedColorsQuery?.removeEventListener("change",this.onForcedColorsChange),this.forcedColorsQuery=void 0,this.forcedColorsWindow=void 0}syncAnnouncementSink(){this.isConnected&&this.politeAnnouncementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.politeAnnouncementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}releaseAnnouncementSink(){this.politeAnnouncementSink?.release(),this.politeAnnouncementSink=void 0}resetResizeObserver(){this.resizeObserverGeneration+=1,this.resizeObserver?.disconnect(),this.resizeObserver=void 0,this.resizeObserverDocument=void 0,this.resizeObserverTarget=void 0}firstUpdated(changed){super.firstUpdated(changed),this.armResizeObserver()}willUpdate(changed){if(super.willUpdate(changed),this.seedFirstRenderState(()=>{this.refreshFitMeasurementAvailability()}),!["type","labels","datasets","skipZero"].some(name=>changed.has(name)))return;const active=activeElementIn(this.shadowRoot)??null,hadFocusedMark=active?.matches('[part="bar"], [part="point"]')??!1,priorPosition=Number(active?.getAttribute("data-mark-index")??this.activeMarkIndex),datasetAttribute=active?.getAttribute("data-dataset-index"),indexAttribute=active?.getAttribute("data-index"),datasetIndex=Number(datasetAttribute),index=Number(indexAttribute),marks=this.interactiveMarks(),sameIdentity=datasetAttribute!=null&&indexAttribute!==null&&indexAttribute!==void 0?marks.findIndex(mark=>mark.datasetIndex===datasetIndex&&mark.index===index):-1;this.activeMarkIndex=marks.length?sameIdentity>=0?sameIdentity:Math.min(Math.max(priorPosition,0),marks.length-1):0,this.refocusMarkAfterUpdate=hadFocusedMark&&marks.length>0,this.refocusChartAfterUpdate=hadFocusedMark&&marks.length===0}updated(changed){super.updated(changed);const wasMounting=this.isMounting;if(this.isMounting=!1,changed.has("height")){const height=sanitizeCssLength(this.height,"height");height?this.style.setProperty("--_lr-chart-height",height):this.style.removeProperty("--_lr-chart-height")}const dataTruncation=this.dataTruncationMessage();wasMounting?this.lastDataTruncationAnnouncement=dataTruncation:dataTruncation!==this.lastDataTruncationAnnouncement&&(this.lastDataTruncationAnnouncement=dataTruncation,dataTruncation&&this.politeAnnouncementSink?.announce(dataTruncation)),this.refocusMarkAfterUpdate&&(this.refocusMarkAfterUpdate=!1,this.renderRoot.querySelectorAll('[part="bar"], [part="point"]')[this.normalizedMarkIndex()]?.focus()),this.refocusChartAfterUpdate&&(this.refocusChartAfterUpdate=!1,this.svgEl?.focus())}colorFor(index,series){return sanitizeCssColor(series.color)??DEFAULT_PALETTE[index%DEFAULT_PALETTE.length]}get effectiveType(){return normalizeLiteChartType(this.type)}forcedColors(){return forcedColorsActive(this.ownerDocument?.defaultView)}markPaint(index,series){const color=this.colorFor(index,series);return this.effectiveType==="bar"&&this.forcedColors()?`url(#${this.forcedColorPatternId}-${index})`:color}legendEncoding(index){return this.forcedColors()?forcedColorEncoding(index).name:nothing}markDash(index){if(!this.forcedColors())return nothing;const dash=forcedColorEncoding(index).dash;return dash.length?dash.join(" "):"none"}renderForcedColorPatterns(){if(this.effectiveType!=="bar"||!this.forcedColors())return nothing;const size=8,half=size/2,texture="var(--lr-color-surface)";return svg`<defs>
3
3
  ${this.recordSample().seriesIndexes.map(index=>{const series=this.datasets[index],encoding=forcedColorEncoding(index).name,shapes=(()=>{switch(encoding){case"horizontal":return svg`<rect y=${half} width=${size} height="1" fill=${texture}></rect>`;case"vertical":return svg`<rect x=${half} width="1" height=${size} fill=${texture}></rect>`;case"diagonal":return svg`<path
4
4
  d=${`M${-half},${size} L${half},0 M${half},${size} L${size+half},0`}
@@ -155,9 +155,22 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
155
155
  <lr-live-region part="live-region"></lr-live-region>
156
156
  ${this.description?html`<p part="description" id=${this.descriptionId} class="sr-only">${this.description}</p>`:nothing}
157
157
  ${dataTruncation?html`<p part="data-truncation">${dataTruncation}</p>`:nothing}
158
- <div part="data-table" ?data-visually-hidden=${!hasCustomDataTable}>
158
+ ${this.dataTableToggle?html`<button
159
+ part="data-table-toggle"
160
+ type="button"
161
+ aria-expanded=${this.dataTableVisible?"true":"false"}
162
+ aria-controls=${this.dataTableId}
163
+ @click=${()=>this.toggleDataTable()}
164
+ >
165
+ ${this.localize("chartData")}
166
+ </button>`:nothing}
167
+ <div
168
+ id=${this.dataTableId}
169
+ part="data-table"
170
+ ?data-visually-hidden=${!hasCustomDataTable&&!this.dataTableVisible}
171
+ >
159
172
  <slot name="data-table" @slotchange=${()=>this.requestUpdate()}></slot>
160
- ${hasCustomDataTable?nothing:this.datasets.length>1?html`<table part="table" class="sr-only">
173
+ ${hasCustomDataTable?nothing:this.datasets.length>1?html`<table part="table" class=${this.dataTableVisible?nothing:"sr-only"}>
161
174
  <caption>${this.localize("chartData")}</caption>
162
175
  <thead>
163
176
  <tr>
@@ -190,4 +203,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
190
203
  `})}
191
204
  </div>`:nothing}
192
205
  </div>
193
- `}}__decorate([property({converter:{fromAttribute:value=>normalizeLiteChartType(value)}})],LyraLiteChart.prototype,"type",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"labels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"datasets",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"legend",void 0),__decorate([property({attribute:"legend-position",converter:{fromAttribute:normalizeChartChromeLegendPosition}})],LyraLiteChart.prototype,"legendPosition",void 0),__decorate([property()],LyraLiteChart.prototype,"height",void 0),__decorate([property({attribute:"x-label"})],LyraLiteChart.prototype,"xLabel",void 0),__decorate([property({attribute:"y-label"})],LyraLiteChart.prototype,"yLabel",void 0),__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraLiteChart.prototype,"beginAtZero",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"stacked",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tickFormat",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tableCellFormatter",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"formatter",void 0),__decorate([property({type:Boolean,attribute:"table-totals"})],LyraLiteChart.prototype,"tableTotals",void 0),__decorate([property({reflect:!0,converter:LITE_CHART_LAYOUT})],LyraLiteChart.prototype,"layout",null),__decorate([property({type:Number,attribute:"bar-width"})],LyraLiteChart.prototype,"barWidth",void 0),__decorate([property({type:Number,attribute:"max-labels"})],LyraLiteChart.prototype,"maxLabels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"barX",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"pointText",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"legendText",void 0),__decorate([property({type:Boolean,attribute:"rounded-bars"})],LyraLiteChart.prototype,"roundedBars",void 0),__decorate([property({type:Boolean,attribute:"skip-zero"})],LyraLiteChart.prototype,"skipZero",void 0),__decorate([property({type:Number,attribute:"value-axis-gutter"})],LyraLiteChart.prototype,"valueAxisGutter",void 0),__decorate([property({type:Number,attribute:"bar-gap-ratio"})],LyraLiteChart.prototype,"barGapRatio",void 0),__decorate([property()],LyraLiteChart.prototype,"scale",void 0),__decorate([property({type:Boolean,attribute:"without-value-axis"})],LyraLiteChart.prototype,"withoutValueAxis",void 0),__decorate([property({type:Number,attribute:"min-bar-height"})],LyraLiteChart.prototype,"minBarHeight",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"selectedIndices",void 0),__decorate([property({attribute:"accessible-label"})],LyraLiteChart.prototype,"accessibleLabel",void 0),__decorate([property()],LyraLiteChart.prototype,"label",void 0),__decorate([property()],LyraLiteChart.prototype,"description",void 0),__decorate([state()],LyraLiteChart.prototype,"plotWidth",void 0),__decorate([state()],LyraLiteChart.prototype,"plotHeight",void 0),__decorate([state()],LyraLiteChart.prototype,"fitMeasurementAvailable",void 0),__decorate([state()],LyraLiteChart.prototype,"activeMarkIndex",void 0),__decorate([query("svg")],LyraLiteChart.prototype,"svgEl",void 0),__decorate([query("lr-live-region")],LyraLiteChart.prototype,"liveRegion",void 0);function formatTick(v,locale){return getNumberFormat(locale,{maximumFractionDigits:6}).format(Number(v.toFixed(6)))}export{LyraLiteChart};
206
+ `}}__decorate([property({converter:{fromAttribute:value=>normalizeLiteChartType(value)}})],LyraLiteChart.prototype,"type",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"labels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"datasets",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"legend",void 0),__decorate([property({attribute:"legend-position",converter:{fromAttribute:normalizeChartChromeLegendPosition}})],LyraLiteChart.prototype,"legendPosition",void 0),__decorate([property()],LyraLiteChart.prototype,"height",void 0),__decorate([property({attribute:"x-label"})],LyraLiteChart.prototype,"xLabel",void 0),__decorate([property({attribute:"y-label"})],LyraLiteChart.prototype,"yLabel",void 0),__decorate([property({type:Boolean,attribute:"begin-at-zero",converter:trueDefaultBooleanConverter})],LyraLiteChart.prototype,"beginAtZero",void 0),__decorate([property({type:Boolean})],LyraLiteChart.prototype,"stacked",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tickFormat",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"tableCellFormatter",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"formatter",void 0),__decorate([property({type:Boolean,attribute:"table-totals"})],LyraLiteChart.prototype,"tableTotals",void 0),__decorate([property({type:Boolean,attribute:"show-data-table"})],LyraLiteChart.prototype,"showDataTable",void 0),__decorate([property({type:Boolean,attribute:"data-table-toggle"})],LyraLiteChart.prototype,"dataTableToggle",void 0),__decorate([state()],LyraLiteChart.prototype,"dataTableExpandedOverride",void 0),__decorate([property({reflect:!0,converter:LITE_CHART_LAYOUT})],LyraLiteChart.prototype,"layout",null),__decorate([property({type:Number,attribute:"bar-width"})],LyraLiteChart.prototype,"barWidth",void 0),__decorate([property({type:Number,attribute:"max-labels"})],LyraLiteChart.prototype,"maxLabels",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"barX",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"pointText",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"legendText",void 0),__decorate([property({type:Boolean,attribute:"rounded-bars"})],LyraLiteChart.prototype,"roundedBars",void 0),__decorate([property({type:Boolean,attribute:"skip-zero"})],LyraLiteChart.prototype,"skipZero",void 0),__decorate([property({type:Number,attribute:"value-axis-gutter"})],LyraLiteChart.prototype,"valueAxisGutter",void 0),__decorate([property({type:Number,attribute:"bar-gap-ratio"})],LyraLiteChart.prototype,"barGapRatio",void 0),__decorate([property()],LyraLiteChart.prototype,"scale",void 0),__decorate([property({type:Boolean,attribute:"without-value-axis"})],LyraLiteChart.prototype,"withoutValueAxis",void 0),__decorate([property({type:Number,attribute:"min-bar-height"})],LyraLiteChart.prototype,"minBarHeight",void 0),__decorate([property({attribute:!1})],LyraLiteChart.prototype,"selectedIndices",void 0),__decorate([property({attribute:"accessible-label"})],LyraLiteChart.prototype,"accessibleLabel",void 0),__decorate([property()],LyraLiteChart.prototype,"label",void 0),__decorate([property()],LyraLiteChart.prototype,"description",void 0),__decorate([state()],LyraLiteChart.prototype,"plotWidth",void 0),__decorate([state()],LyraLiteChart.prototype,"plotHeight",void 0),__decorate([state()],LyraLiteChart.prototype,"fitMeasurementAvailable",void 0),__decorate([state()],LyraLiteChart.prototype,"activeMarkIndex",void 0),__decorate([query("svg")],LyraLiteChart.prototype,"svgEl",void 0),__decorate([query("lr-live-region")],LyraLiteChart.prototype,"liveRegion",void 0);function formatTick(v,locale){return getNumberFormat(locale,{maximumFractionDigits:6}).format(Number(v.toFixed(6)))}export{LyraLiteChart};
@@ -187,4 +187,33 @@ import{css}from"lit";import{forcedColorLegendSwatchStyles}from"./chart-forced-co
187
187
  grid-template-columns: minmax(0, 1fr);
188
188
  }
189
189
  }
190
+
191
+ [part='data-table-toggle'] {
192
+ align-self: flex-start;
193
+ font: inherit;
194
+ font-size: var(--lr-font-size-xs);
195
+ min-block-size: var(--lr-icon-button-size);
196
+ padding: var(--lr-size-0-15rem) var(--lr-size-0-5rem);
197
+ border: var(--lr-border-width-thin) solid var(--lr-color-border);
198
+ border-radius: var(--lr-radius);
199
+ background: var(--lr-color-surface);
200
+ color: var(--lr-color-text);
201
+ max-inline-size: 100%;
202
+ white-space: normal;
203
+ overflow-wrap: break-word;
204
+ cursor: pointer;
205
+ }
206
+ [part='data-table-toggle']:hover {
207
+ background: var(--lr-lite-chart-data-table-toggle-hover-bg, var(--lr-color-brand-quiet));
208
+ }
209
+ [part='data-table-toggle']:active {
210
+ background: var(
211
+ --lr-lite-chart-data-table-toggle-active-bg,
212
+ color-mix(in oklab, var(--lr-color-brand-quiet), var(--lr-color-mix-partner) var(--lr-color-mix-active))
213
+ );
214
+ }
215
+ [part='data-table-toggle']:focus-visible {
216
+ outline: var(--lr-focus-ring);
217
+ outline-offset: var(--lr-focus-ring-offset);
218
+ }
190
219
  `;export{styles};
@@ -311,13 +311,46 @@ export declare class LyraHeatmap extends LyraElement<LyraHeatmapEventMap> {
311
311
  * Calendar mode is unaffected; it has its own fixed weekday gutter.
312
312
  */
313
313
  rowLabelWidth?: number | 'auto';
314
- /** Height, in CSS px, of the matrix column-label band. Unset keeps the built-in 20px. */
315
- colLabelHeight?: number;
314
+ /**
315
+ * Height, in CSS px, of the matrix column-label band, or `"auto"` to measure the labels and size
316
+ * the band to fit them (never below the built-in 20px, and bounded above by a sanity ceiling so a
317
+ * pathological label cannot produce an absurd canvas). Under a non-zero
318
+ * `colLabelRotation` the measurement projects each label's width through the rotation, which is
319
+ * what makes a rotated axis usable without hand-tuning a magic number.
320
+ *
321
+ * Unset keeps the built-in 20px, for the same reason `rowLabelWidth` does: auto-sizing every
322
+ * existing heatmap would silently reflow charts whose labels already fit.
323
+ */
324
+ colLabelHeight?: number | 'auto';
325
+ /**
326
+ * Rotation, in degrees, applied to matrix column labels. Unset (or `0`) paints them horizontally
327
+ * exactly as before. In a dense matrix the per-column width is far narrower than a typical label,
328
+ * so horizontal labels collide with their neighbours; `45` or `90` is the standard remedy.
329
+ *
330
+ * Each label is rotated about an anchor at its own column's centre, with the label's *end* at the
331
+ * anchor, so it leans up and back over the columns to its left and the last column's label cannot
332
+ * overflow the canvas. Values outside `[0, 90]` clamp into it and non-finite values normalize to
333
+ * `0`; a rotation is not a coordinate a caller can usefully be surprised by.
334
+ *
335
+ * Pair with `colLabelHeight="auto"` to have the band size itself to the rotated extent.
336
+ *
337
+ * Not mirrored under `dir="rtl"`: both grid modes deliberately retain physical LTR geometry (see
338
+ * the class doc), and leaning one axis' labels the other way while the grid itself stays physical
339
+ * would be incoherent.
340
+ */
341
+ colLabelRotation?: number;
342
+ /** Column band resolved during the last draw, mirroring `resolvedRowLabelWidth`. */
343
+ private resolvedColLabelHeight;
344
+ /** Normalized rotation in degrees: finite, clamped to `[0, 90]`. */
345
+ private get effectiveColLabelRotation();
316
346
  /** Gutter resolved during the last draw, so hit-testing between draws agrees with what was
317
347
  * painted. Only ever differs from the default while `rowLabelWidth="auto"`. */
318
348
  private resolvedRowLabelWidth;
319
349
  private get matrixPadLeft();
320
350
  private get matrixPadTop();
351
+ /** Tallest rotated column label plus inset, floored at the built-in band and capped so labels can
352
+ * never crowd out the matrix. The column mirror of `measureRowLabelWidth()`. */
353
+ private measureColLabelHeight;
321
354
  /** Widest row label plus insets, floored at the built-in gutter and capped so labels can never
322
355
  * crowd out the matrix itself. Measured against the same font the labels are drawn with. */
323
356
  private measureRowLabelWidth;
@@ -1,4 +1,4 @@
1
- var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{getScratchCtx}from"../../../internal/canvas.js";import{resolveCssLength}from"../../../internal/css-length.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{activeElementIn}from"../../../internal/active-element.js";import{linearAlpha,linearBucket,midpointAlpha,midpointBucket,minMax,sqrtStep}from"./heatmap-scale.js";import{styles}from"./heatmap.styles.js";import{buildCalendarGrid,parseIsoDate,quartileBucket}from"./calendar-grid.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{acquireAnnouncementSink}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_heatmapValueLabel}from"../../../internal/default-strings.generated.js";const PAD_LEFT=60,PAD_TOP=20,ROW_LABEL_INSET=4,MAX_ROW_LABEL_FRACTION=.4,rowLabelWidthConverter={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)},FALLBACK_NO_DATA_FILL="rgba(128,128,128,0.25)",RAMP_STEPS=7,FALLBACK_SCALE_LO="#cde2fb",FALLBACK_SCALE_HI="#0969da",FALLBACK_LABEL_FONT="10px system-ui, sans-serif",CAL_PAD_LEFT=28,CAL_LABEL_H=16,CAL_CELL=11,CAL_GAP=2,DEFAULT_MATRIX_CELL_SIZE=22,DEFAULT_ACCESSIBLE_TARGET_SIZE_PX=40,DEFAULT_BUCKET_COUNT=5,FIT_MIN_CELL=4,MAX_BUCKET_COUNT=256,MAX_HEATMAP_CELLS=1e4,MAX_HEATMAP_DECORATIONS=256,MAX_ACCESSIBLE_HEATMAP_CELLS=400,RING_LINE_WIDTH=2,FALLBACK_FOCUS_RING_COLOR="#0969da",FALLBACK_ANNOTATION_COLOR="#cf222e",FALLBACK_SELECTED_COLOR="#1a7f37",ARROW_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]),MS_PER_DAY=864e5;function isoDateAtOffset(firstWeekStart,dayOffset){return new Date(firstWeekStart.getTime()+dayOffset*MS_PER_DAY).toISOString().slice(0,10)}const HEX_RE=/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i,RGB_RE=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/i;function hexToRgb(hex){const clean=hex.trim().replace("#","");if(!HEX_RE.test(clean))return null;const hasAlpha=clean.length===4||clean.length===8,full=clean.length<=4?clean.split("").map(c=>c+c).join(""):clean,num=Number.parseInt(full,16);return hasAlpha?[num>>>24&255,num>>>16&255,num>>>8&255,(num&255)/255]:[num>>16&255,num>>8&255,num&255,1]}function parseRgbString(value){const match=RGB_RE.exec(value);if(!match)return null;const a=match[4]===void 0?1:Number(match[4]);return[Number(match[1]),Number(match[2]),Number(match[3]),a]}function resolveViaPixelReadback(ctx){try{ctx.clearRect(0,0,1,1),ctx.fillRect(0,0,1,1);const[r=0,g=0,b=0,a=0]=ctx.getImageData(0,0,1,1).data;return[r,g,b,a/255]}catch{return null}}function formatRgb([r,g,b,a]){const alpha=Math.min(1,Math.max(0,a));return alpha>=1?`rgb(${r}, ${g}, ${b})`:`rgba(${r}, ${g}, ${b}, ${Math.round(alpha*1e3)/1e3})`}const warnedInvalidColors=new Set;function warnInvalidColor(color){warnedInvalidColors.has(color)||(warnedInvalidColors.add(color),console.warn(`<lr-heatmap> could not parse "${color}" (set via --lr-heatmap-scale-lo/-hi) as a CSS color; falling back to the default ramp endpoint.`))}let warnedNoCanvasContext=!1;function warnNoCanvasContext(){warnedNoCanvasContext||(warnedNoCanvasContext=!0,console.warn("<lr-heatmap>: no 2D canvas context is available in this environment; color resolution for non-hex/non-rgb values (e.g. oklch(), color(srgb ...), named colors) will fall back to the given default instead of resolving the requested color."))}function normalizeBucketCount(bucketCount){return finiteInteger(bucketCount,DEFAULT_BUCKET_COUNT,2,MAX_BUCKET_COUNT)}const optionalCellSizeConverter={fromAttribute(value){if(value===null||value.trim()==="")return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0},toAttribute(value){return value==null?null:String(value)}},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))},toAttribute(value){return String(normalizeBucketCount(value))}};function resolveRgb(color,fallbackHex,ownerDocument){const fallback=hexToRgb(fallbackHex)??[0,0,0,1],direct=hexToRgb(color);if(direct)return direct;const ctx=getScratchCtx(ownerDocument);if(!ctx)return warnNoCanvasContext(),fallback;const sentinel="rgb(1, 2, 3)";ctx.fillStyle=sentinel;const sentinelNormalized=ctx.fillStyle;if(ctx.fillStyle=color,ctx.fillStyle===sentinelNormalized&&color.trim()!==sentinel)return warnInvalidColor(color),fallback;const normalized=ctx.fillStyle;return hexToRgb(normalized)??parseRgbString(normalized)??resolveViaPixelReadback(ctx)??fallback}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])}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,heatmapValueLabel:LYRA_DEFAULT_heatmapValueLabel}}static{this.ownedCollectionProperties=Object.freeze(["data","annotations","legendStops","colorSteps"])}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 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 matrixPadTop(){if(typeof this.colLabelHeight!="number")return PAD_TOP;const resolved=finiteNumber(this.colLabelHeight,PAD_TOP);return resolved>=0?resolved:PAD_TOP}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,ctx.measureText(label).width);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)}ellipsize(ctx,label,maxWidth){if(maxWidth<=0)return"";if(ctx.measureText(label).width<=maxWidth)return label;const characters=[...label];let kept=characters.length-1;for(;kept>0;){const candidate=`${characters.slice(0,kept).join("")}\u2026`;if(ctx.measureText(candidate).width<=maxWidth)return candidate;kept-=1}return ctx.measureText("\u2026").width<=maxWidth?"\u2026":""}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 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)}get calendarWeekdayLabelText(){return this.calendarData?.weekdayLabelText}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.resolvedRowLabelWidth=PAD_LEFT,this.scale="linear",this.fitToWidth=!1,this._bucketCount=DEFAULT_BUCKET_COUNT,this.annotations=[],this.selectedCell=null,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.hoverCell=null,this.focusedCell=null,this.liveText="",this.accessibleTargetSizePx=DEFAULT_ACCESSIBLE_TARGET_SIZE_PX,this.restoringAccessibleFocus=!1,this.accessibleFocusGeneration=0,this.authorRole=null,this.authorAriaLabel=null,this.generatedAriaLabel="",this.syncingGeneratedSemantics=!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.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=>{const pos=this.hitTest(e.offsetX,e.offsetY);pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onKeyDown=e=>{this.effectiveMode==="calendar"?this.onCalendarKeyDown(e):this.onMatrixKeyDown(e)},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.focusedCell=pos,this.announce(pos))},this.onAccessibleCellClick=e=>{const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onAccessibleCellKeyDown=e=>{if(!ARROW_KEYS.has(e.key))return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(e.preventDefault(),this.focusedCell=pos,this.onKeyDown(e),this.focusAccessibleCell(this.focusedCell))},new ThemeWatcher(this,()=>this.refreshTheme())}warnOnLegendRampMismatch(){const rampColors=this.cachedColorSteps.map(color=>sanitizeCssColor(color)??color);if(rampColors.length===0)return;const legendColors=this.cachedLegendStops.filter(stop=>!!stop.color).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.syncAnnouncementSink(),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.canvasColorCache.clear(),this.watchDpr()}disconnectedCallback(){super.disconnectedCallback(),this.accessibleFocusGeneration++,this.pendingAccessibleFocus=void 0,this.pendingAccessibleFocusOrigin=void 0,this.restoringAccessibleFocus=!1,this.releaseAnnouncementSink(),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()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}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.has("data")||!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?activeElementIn(this.shadowRoot):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")||!this.hasUpdated){const colorSteps=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")||!this.hasUpdated)&&(this.cachedValueRange=this.computeValueRange()),(collectionChanged||!this.hasUpdated)&&this.rebuildAccessiblePositions(),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])}\u2013${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.setAttribute("role","group"),this.authorAriaLabel===null&&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.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)}updated(changed){if(super.updated(changed),["data","cellSize","maxCellSize","minCellSize","valueLabel","scale","fitToWidth","bucketCount","annotations","focusedCell","colorSteps","cellColor","selectedCell","legendStops","accessibleCells","accessibleTargetSizePx","locale"].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=activeElementIn(this.shadowRoot),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()}refreshAccessibleTargetSize(){const raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-icon-button-size").trim()??"",resolved=resolveCssLength(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}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){const inset=Math.min(state2==="annotation"?.5:state2==="selected"?3.5:6.5,Math.max(.5,(size-RING_LINE_WIDTH-1)/2)),extent=Math.max(1,size-inset*2);ctx.lineWidth=RING_LINE_WIDTH,ctx.strokeStyle=color,ctx.setLineDash?.(state2==="annotation"?[]:state2==="selected"?[4,2]:[1,2]),ctx.strokeRect(x+inset,y+inset,extent,extent),ctx.setLineDash?.([])}isSelectedPos(pos){return 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.drawDirty=!1,this.canvasHasContent=!1,this.effectiveMode==="calendar"?this.drawCalendar():this.drawMatrix()}requestDraw(){this.drawDirty=!0,this.canvasVisible&&this.draw()}repaintFocusRing(previous){if(!this.canvasHasContent||!this.canvas)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);if(!safe)return fallback;const scope=this.ownerDocument.createElement("span"),probe=this.ownerDocument.createElement("span");scope.hidden=!0,scope.style.color=fallback,probe.style.color=safe,scope.append(probe),this.renderRoot.append(scope);try{return this.ownerDocument.defaultView?.getComputedStyle(probe).color.trim()||fallback}finally{scope.remove()}}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(){const{weekCount}=this.cachedCalendarGrid;let size;if(this.fitToWidth&&weekCount>0){const hostWidth=this.clientWidth||CAL_PAD_LEFT+weekCount*(this.cellSize+CAL_GAP);size=this.clampFitCellSize((hostWidth-CAL_PAD_LEFT)/weekCount-CAL_GAP)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}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]??CAL_PAD_LEFT}rowYFor(weekday){return this.calendarRowPositions()[weekday]??CAL_LABEL_H}calendarColumnPositions(){const cellSize=this.calendarCellSize(),weekCount=this.cachedCalendarGrid.weekCount,callback=this.calendarColumnX,cached=this.cachedColumnGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize&&cached.weekCount===weekCount)return cached.positions;const positions=[];for(let index=0;index<=weekCount;index++){const fallback=index===0?CAL_PAD_LEFT:positions[index-1]+cellSize+CAL_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,cellSize,weekCount,positions},positions}calendarRowPositions(){const cellSize=this.calendarCellSize(),callback=this.calendarRowY,cached=this.cachedRowGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize)return cached.positions;const positions=[];for(let index=0;index<=7;index++){const fallback=index===0?CAL_LABEL_H:positions[index-1]+cellSize+CAL_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,positions},positions}weekAtX(x,weekCount){const positions=this.calendarColumnPositions(),cellSize=this.calendarCellSize();for(let week=0;week<weekCount;week++){const start=positions[week];if(x>=start&&x<start+cellSize)return week}return null}weekdayAtY(y){const positions=this.calendarRowPositions(),cellSize=this.calendarCellSize();for(let weekday=0;weekday<7;weekday++){const start=positions[weekday];if(y>=start&&y<start+cellSize)return weekday}return null}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}drawCalendar(){if(!this.canvas)return;const{weekCount,firstWeekStart,monthLabels}=this.cachedCalendarGrid,cellSize=this.calendarCellSize(),w=this.columnXFor(Math.max(1,weekCount)),h=this.rowYFor(7),dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;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.cachedCalendarCellsByPos.get(`${week}:${weekday}`)?.value??-1,x=this.columnXFor(week),y=this.rowYFor(weekday),override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(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)];ctx.fillRect(x,y,cellSize,cellSize)}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))}if(this.selectedCell?.date!=null){const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);if(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))}}ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const m of monthLabels)ctx.fillText(m.label,this.columnXFor(m.week),CAL_LABEL_H-4);this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{label&&ctx.fillText(label,2,this.rowYFor(weekday)+cellSize-1)}),this.canvasHasContent=!0}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;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}paintMatrixCell(ctx,row,col,cellSize,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.resolveCanvasColor(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));ctx.fillRect(this.matrixPadLeft+col*cellSize,this.matrixPadTop+row*cellSize,cellSize-1,cellSize-1)}paintMatrixFocusOverlays(ctx,row,col,cellSize,cs){const x=this.matrixPadLeft+col*cellSize,y=this.matrixPadTop+row*cellSize;this.cachedMatrixAnnotationPositions.has(`${row}:${col}`)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),this.selectedCell?.row===row&&this.selectedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),this.focusedCell&&"row"in this.focusedCell&&this.focusedCell.row===row&&this.focusedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintMatrixFocusCell(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),x=this.matrixPadLeft+pos.col*cellSize,y=this.matrixPadTop+pos.row*cellSize,ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);cs&&(this.paintMatrixCell(ctx,pos.row,pos.col,cellSize,cs,this.colorRamp(RAMP_STEPS,cs),this.noDataFill(cs)),this.paintMatrixFocusOverlays(ctx,pos.row,pos.col,cellSize,cs))}paintCalendarCell(ctx,week,weekday,cellSize,cs,ramp,noDataFill){const value=this.cachedCalendarCellsByPos.get(`${week}:${weekday}`)?.value??-1,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.resolveCanvasColor(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)];ctx.fillRect(this.columnXFor(week),this.rowYFor(weekday),cellSize,cellSize)}paintCalendarFocusOverlays(ctx,week,weekday,cellSize,cs){const date=this.calendarDateAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday),matches=candidate=>candidate?.date===date;this.cachedCalendarAnnotationDates.has(date)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),matches(this.selectedCell??void 0)&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),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){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;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const ramp=this.colorRamp(normalizeBucketCount(this.bucketCount),cs).colors;this.paintCalendarCell(ctx,pos.week,pos.weekday,cellSize,cs,ramp,this.noDataFill(cs)),this.paintCalendarFocusOverlays(ctx,pos.week,pos.weekday,cellSize,cs),ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const month of this.cachedCalendarGrid.monthLabels)ctx.fillText(month.label,this.columnXFor(month.week),CAL_LABEL_H-4);this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{label&&ctx.fillText(label,2,this.rowYFor(weekday)+cellSize-1)})}drawMatrix(){if(!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;this.rowLabelWidth==="auto"&&(this.resolvedRowLabelWidth=this.measureRowLabelWidth(getComputedStyle(this)));const padLeft=this.matrixPadLeft,padTop=this.matrixPadTop,cellSize=this.matrixCellSize(cols),w=padLeft+cols*cellSize,h=padTop+rows*cellSize,dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;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*cellSize,override=this.cellColor?.({row:r,col:c},v);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(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)}ctx.fillRect(x,y,cellSize-1,cellSize-1)}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*cellSize;this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.row!=null&&this.selectedCell.col!=null){const{row,col}=this.selectedCell;if(row>=0&&row<rows&&col>=0&&col<cols){const x=padLeft+col*cellSize,y=padTop+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}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*cellSize;this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);const rowLabelSpace=padLeft-ROW_LABEL_INSET*2;this.matrixRowLabels.forEach((label,r)=>{const shown=this.ellipsize(ctx,label,rowLabelSpace);shown&&ctx.fillText(shown,ROW_LABEL_INSET,padTop+r*cellSize+cellSize/2+3)}),this.matrixColLabels.forEach((label,c)=>{ctx.fillText(label,padLeft+c*cellSize+2,padTop-6)}),this.canvasHasContent=!0}hitTest(x,y){return this.effectiveMode==="calendar"?this.hitTestCalendar(x,y):this.hitTestMatrix(x,y)}hitTestMatrix(x,y){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return null;const cellSize=this.matrixCellSize(cols),col=Math.floor((x-this.matrixPadLeft)/cellSize),row=Math.floor((y-this.matrixPadTop)/cellSize);if(row<0||row>=rows||col<0||col>=cols)return null;const pos={row,col};return this.isCellInteractive(pos)?pos:null}firstInteractiveMatrixCell(rows,cols){for(let r=0;r<rows;r++)for(let c=0;c<cols;c++)if(this.isCellInteractive({row:r,col:c}))return{row:r,col:c};return null}nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols){let r=row,c=col;for(;;){const nr=Math.min(rows-1,Math.max(0,r+dRow)),nc=Math.min(cols-1,Math.max(0,c+dCol));if(nr===r&&nc===c)return{row,col};if(r=nr,c=nc,this.isCellInteractive({row:r,col:c}))return{row:r,col:c}}}firstInteractiveCalendarCell(weekCount){for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);if(this.isCellInteractive(pos))return pos}return null}nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount){let w=week,d=weekday;for(;;){const nw=Math.min(weekCount-1,Math.max(0,w+dWeek)),nd=Math.min(6,Math.max(0,d+dWeekday));if(nw===w&&nd===d)return this.calendarPos(week,weekday);w=nw,d=nd;const pos=this.calendarPos(w,d);if(this.isCellInteractive(pos))return pos}}hitTestCalendar(x,y){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return null;const week=this.weekAtX(x,weekCount),weekday=this.weekdayAtY(y);if(week===null||weekday===null)return null;const pos=this.calendarPos(week,weekday);return this.isCellInteractive(pos)?pos:null}calendarCellAt(pos){const match=this.cachedCalendarCellsByPos.get(`${pos.week}:${pos.weekday}`);return match?{date:match.date,value:match.value}:{date:this.calendarDateAt(pos.week,pos.weekday),value:-1}}calendarDateAt(week,weekday){const index=week*7+weekday;return this.cachedCalendarDateByPos[index]??isoDateAtOffset(this.cachedCalendarGrid.firstWeekStart,index)}calendarPos(week,weekday){return{week,weekday,date:this.calendarDateAt(week,weekday)}}cellRect(pos){if("week"in pos){const cellSize2=this.calendarCellSize();return{x:this.columnXFor(pos.week),y:this.rowYFor(pos.weekday),w:cellSize2,h:cellSize2}}const cellSize=this.matrixCellSize(this.matrixColLabels.length);return{x:this.matrixPadLeft+pos.col*cellSize,y:this.matrixPadTop+pos.row*cellSize,w:cellSize-1,h:cellSize-1}}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=parseIsoDate(date).toLocaleString(this.effectiveLocale||void 0,{month:"short",day:"numeric",timeZone:"UTC"}),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){const text=this.resolveCellText(pos),announcement=this.isSelectedPos(pos)?this.localize("heatmapSelectedCellLabel",void 0,{cell:text}):text;this.liveText=announcement,this.announcementSink?.announce(announcement)}emitCellClick(pos){if(this.isCellInteractive(pos))if("week"in pos){const{date,value}=this.calendarCellAt(pos);this.emit("lr-cell-click",{date,value})}else{const value=this.matrixValues[pos.row]?.[pos.col]??-1;this.emit("lr-cell-click",{row:pos.row,col:pos.col,value})}}tooltipStyle(pos){const rect=this.cellRect(pos);return{left:`${rect.x+rect.w/2}px`,top:`${rect.y}px`}}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}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);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.announce(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.announce(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);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,this.announce(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,this.announce(next)}resolveCanvasColor(value,cs){const cached=this.canvasColorCache.get(value);if(cached!==void 0)return cached;const fallback=this.noDataFill(cs);let candidate=value;if(value.includes("var(")){if(this.colorProbe||(this.colorProbe=this.ownerDocument.createElement("span"),this.colorProbe.style.cssText="position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;",this.shadowRoot.appendChild(this.colorProbe)),this.colorProbe.style.color="",this.colorProbe.style.color=value,!this.colorProbe.style.color)return this.canvasColorCache.set(value,fallback),fallback;candidate=this.ownerDocument.defaultView?.getComputedStyle(this.colorProbe).color||fallback}const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return fallback;ctx.fillStyle="rgb(1, 2, 3)";const firstSentinel=ctx.fillStyle;ctx.fillStyle=candidate;let resolved=ctx.fillStyle;if(resolved===firstSentinel){ctx.fillStyle="rgb(4, 5, 6)";const secondSentinel=ctx.fillStyle;ctx.fillStyle=candidate,resolved=ctx.fillStyle,resolved===secondSentinel&&(resolved=fallback)}return this.canvasColorCache.set(value,resolved),resolved}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;return html`
1
+ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3?target:desc===null?desc=Object.getOwnPropertyDescriptor(target,key):desc,d;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r};import{html,nothing}from"lit";import{property,query,state}from"lit/decorators.js";import{styleMap}from"lit/directives/style-map.js";import{LyraElement}from"../../../internal/lyra-element.js";import{srOnly}from"../../../internal/a11y.js";import{finiteInteger,finiteNumber,finiteRange}from"../../../internal/numbers.js";import{getScratchCtx}from"../../../internal/canvas.js";import{resolveCssLength}from"../../../internal/css-length.js";import{ThemeWatcher}from"../../../internal/theme-watcher.js";import{activeElementIn}from"../../../internal/active-element.js";import{linearAlpha,linearBucket,midpointAlpha,midpointBucket,minMax,sqrtStep}from"./heatmap-scale.js";import{styles}from"./heatmap.styles.js";import{buildCalendarGrid,parseIsoDate,quartileBucket}from"./calendar-grid.js";import{getDateTimeFormat,getNumberFormat}from"../../../internal/intl-cache.js";import{sanitizeCssColor}from"../../../internal/safe-css.js";import{devWarnOnce}from"../../../internal/dev-mode-attribute-warning.js";import{acquireAnnouncementSink}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_heatmapValueLabel}from"../../../internal/default-strings.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)},FALLBACK_NO_DATA_FILL="rgba(128,128,128,0.25)",RAMP_STEPS=7,FALLBACK_SCALE_LO="#cde2fb",FALLBACK_SCALE_HI="#0969da",FALLBACK_LABEL_FONT="10px system-ui, sans-serif",CAL_PAD_LEFT=28,CAL_LABEL_H=16,CAL_CELL=11,CAL_GAP=2,DEFAULT_MATRIX_CELL_SIZE=22,DEFAULT_ACCESSIBLE_TARGET_SIZE_PX=40,DEFAULT_BUCKET_COUNT=5,FIT_MIN_CELL=4,MAX_BUCKET_COUNT=256,MAX_HEATMAP_CELLS=1e4,MAX_HEATMAP_DECORATIONS=256,MAX_ACCESSIBLE_HEATMAP_CELLS=400,RING_LINE_WIDTH=2,FALLBACK_FOCUS_RING_COLOR="#0969da",FALLBACK_ANNOTATION_COLOR="#cf222e",FALLBACK_SELECTED_COLOR="#1a7f37",ARROW_KEYS=new Set(["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"]),MS_PER_DAY=864e5;function isoDateAtOffset(firstWeekStart,dayOffset){return new Date(firstWeekStart.getTime()+dayOffset*MS_PER_DAY).toISOString().slice(0,10)}const HEX_RE=/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i,RGB_RE=/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/i;function hexToRgb(hex){const clean=hex.trim().replace("#","");if(!HEX_RE.test(clean))return null;const hasAlpha=clean.length===4||clean.length===8,full=clean.length<=4?clean.split("").map(c=>c+c).join(""):clean,num=Number.parseInt(full,16);return hasAlpha?[num>>>24&255,num>>>16&255,num>>>8&255,(num&255)/255]:[num>>16&255,num>>8&255,num&255,1]}function parseRgbString(value){const match=RGB_RE.exec(value);if(!match)return null;const a=match[4]===void 0?1:Number(match[4]);return[Number(match[1]),Number(match[2]),Number(match[3]),a]}function resolveViaPixelReadback(ctx){try{ctx.clearRect(0,0,1,1),ctx.fillRect(0,0,1,1);const[r=0,g=0,b=0,a=0]=ctx.getImageData(0,0,1,1).data;return[r,g,b,a/255]}catch{return null}}function formatRgb([r,g,b,a]){const alpha=Math.min(1,Math.max(0,a));return alpha>=1?`rgb(${r}, ${g}, ${b})`:`rgba(${r}, ${g}, ${b}, ${Math.round(alpha*1e3)/1e3})`}const warnedInvalidColors=new Set;function warnInvalidColor(color){warnedInvalidColors.has(color)||(warnedInvalidColors.add(color),console.warn(`<lr-heatmap> could not parse "${color}" (set via --lr-heatmap-scale-lo/-hi) as a CSS color; falling back to the default ramp endpoint.`))}let warnedNoCanvasContext=!1;function warnNoCanvasContext(){warnedNoCanvasContext||(warnedNoCanvasContext=!0,console.warn("<lr-heatmap>: no 2D canvas context is available in this environment; color resolution for non-hex/non-rgb values (e.g. oklch(), color(srgb ...), named colors) will fall back to the given default instead of resolving the requested color."))}function normalizeBucketCount(bucketCount){return finiteInteger(bucketCount,DEFAULT_BUCKET_COUNT,2,MAX_BUCKET_COUNT)}const optionalCellSizeConverter={fromAttribute(value){if(value===null||value.trim()==="")return;const parsed=Number(value);return Number.isFinite(parsed)?parsed:void 0},toAttribute(value){return value==null?null:String(value)}},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))},toAttribute(value){return String(normalizeBucketCount(value))}};function resolveRgb(color,fallbackHex,ownerDocument){const fallback=hexToRgb(fallbackHex)??[0,0,0,1],direct=hexToRgb(color);if(direct)return direct;const ctx=getScratchCtx(ownerDocument);if(!ctx)return warnNoCanvasContext(),fallback;const sentinel="rgb(1, 2, 3)";ctx.fillStyle=sentinel;const sentinelNormalized=ctx.fillStyle;if(ctx.fillStyle=color,ctx.fillStyle===sentinelNormalized&&color.trim()!==sentinel)return warnInvalidColor(color),fallback;const normalized=ctx.fillStyle;return hexToRgb(normalized)??parseRgbString(normalized)??resolveViaPixelReadback(ctx)??fallback}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])}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,heatmapValueLabel:LYRA_DEFAULT_heatmapValueLabel}}static{this.ownedCollectionProperties=Object.freeze(["data","annotations","legendStops","colorSteps"])}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 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 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;for(const label of labels)widest=Math.max(widest,ctx.measureText(label).width);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,ctx.measureText(label).width);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)}ellipsize(ctx,label,maxWidth){if(maxWidth<=0)return"";if(ctx.measureText(label).width<=maxWidth)return label;const characters=[...label];let kept=characters.length-1;for(;kept>0;){const candidate=`${characters.slice(0,kept).join("")}\u2026`;if(ctx.measureText(candidate).width<=maxWidth)return candidate;kept-=1}return ctx.measureText("\u2026").width<=maxWidth?"\u2026":""}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 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)}get calendarWeekdayLabelText(){return this.calendarData?.weekdayLabelText}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.resolvedColLabelHeight=PAD_TOP,this.resolvedRowLabelWidth=PAD_LEFT,this.scale="linear",this.fitToWidth=!1,this._bucketCount=DEFAULT_BUCKET_COUNT,this.annotations=[],this.selectedCell=null,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.hoverCell=null,this.focusedCell=null,this.liveText="",this.accessibleTargetSizePx=DEFAULT_ACCESSIBLE_TARGET_SIZE_PX,this.restoringAccessibleFocus=!1,this.accessibleFocusGeneration=0,this.authorRole=null,this.authorAriaLabel=null,this.generatedAriaLabel="",this.syncingGeneratedSemantics=!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.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=>{const pos=this.hitTest(e.offsetX,e.offsetY);pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onKeyDown=e=>{this.effectiveMode==="calendar"?this.onCalendarKeyDown(e):this.onMatrixKeyDown(e)},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.focusedCell=pos,this.announce(pos))},this.onAccessibleCellClick=e=>{const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(this.focusedCell=pos,this.announce(pos),this.emitCellClick(pos))},this.onAccessibleCellKeyDown=e=>{if(!ARROW_KEYS.has(e.key))return;const key=e.currentTarget.dataset.cellKey,pos=key?this.accessibleCellAtKey(key):null;pos&&(e.preventDefault(),this.focusedCell=pos,this.onKeyDown(e),this.focusAccessibleCell(this.focusedCell))},new ThemeWatcher(this,()=>this.refreshTheme())}warnOnLegendRampMismatch(){const rampColors=this.cachedColorSteps.map(color=>sanitizeCssColor(color)??color);if(rampColors.length===0)return;const legendColors=this.cachedLegendStops.filter(stop=>!!stop.color).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.syncAnnouncementSink(),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.canvasColorCache.clear(),this.watchDpr()}disconnectedCallback(){super.disconnectedCallback(),this.accessibleFocusGeneration++,this.pendingAccessibleFocus=void 0,this.pendingAccessibleFocusOrigin=void 0,this.restoringAccessibleFocus=!1,this.releaseAnnouncementSink(),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()}releaseAnnouncementSink(){this.announcementSink?.release(),this.announcementSink=void 0}syncAnnouncementSink(){if(!this.isConnected){this.releaseAnnouncementSink();return}this.announcementSink?.element.ownerDocument!==this.ownerDocument&&(this.releaseAnnouncementSink(),this.announcementSink=acquireAnnouncementSink("polite",{document:this.ownerDocument,source:this}))}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.has("data")||!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?activeElementIn(this.shadowRoot):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")||!this.hasUpdated){const colorSteps=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")||!this.hasUpdated)&&(this.cachedValueRange=this.computeValueRange()),(collectionChanged||!this.hasUpdated)&&this.rebuildAccessiblePositions(),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])}\u2013${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.setAttribute("role","group"),this.authorAriaLabel===null&&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.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)}updated(changed){if(super.updated(changed),["data","cellSize","maxCellSize","minCellSize","valueLabel","scale","fitToWidth","bucketCount","annotations","focusedCell","colorSteps","cellColor","selectedCell","legendStops","accessibleCells","accessibleTargetSizePx","locale"].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=activeElementIn(this.shadowRoot),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()}refreshAccessibleTargetSize(){const raw=this.ownerDocument.defaultView?.getComputedStyle(this).getPropertyValue("--lr-icon-button-size").trim()??"",resolved=resolveCssLength(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}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){const inset=Math.min(state2==="annotation"?.5:state2==="selected"?3.5:6.5,Math.max(.5,(size-RING_LINE_WIDTH-1)/2)),extent=Math.max(1,size-inset*2);ctx.lineWidth=RING_LINE_WIDTH,ctx.strokeStyle=color,ctx.setLineDash?.(state2==="annotation"?[]:state2==="selected"?[4,2]:[1,2]),ctx.strokeRect(x+inset,y+inset,extent,extent),ctx.setLineDash?.([])}isSelectedPos(pos){return 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.drawDirty=!1,this.canvasHasContent=!1,this.effectiveMode==="calendar"?this.drawCalendar():this.drawMatrix()}requestDraw(){this.drawDirty=!0,this.canvasVisible&&this.draw()}repaintFocusRing(previous){if(!this.canvasHasContent||!this.canvas)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);if(!safe)return fallback;const scope=this.ownerDocument.createElement("span"),probe=this.ownerDocument.createElement("span");scope.hidden=!0,scope.style.color=fallback,probe.style.color=safe,scope.append(probe),this.renderRoot.append(scope);try{return this.ownerDocument.defaultView?.getComputedStyle(probe).color.trim()||fallback}finally{scope.remove()}}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(){const{weekCount}=this.cachedCalendarGrid;let size;if(this.fitToWidth&&weekCount>0){const hostWidth=this.clientWidth||CAL_PAD_LEFT+weekCount*(this.cellSize+CAL_GAP);size=this.clampFitCellSize((hostWidth-CAL_PAD_LEFT)/weekCount-CAL_GAP)}else size=this.cellSize;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}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]??CAL_PAD_LEFT}rowYFor(weekday){return this.calendarRowPositions()[weekday]??CAL_LABEL_H}calendarColumnPositions(){const cellSize=this.calendarCellSize(),weekCount=this.cachedCalendarGrid.weekCount,callback=this.calendarColumnX,cached=this.cachedColumnGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize&&cached.weekCount===weekCount)return cached.positions;const positions=[];for(let index=0;index<=weekCount;index++){const fallback=index===0?CAL_PAD_LEFT:positions[index-1]+cellSize+CAL_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,cellSize,weekCount,positions},positions}calendarRowPositions(){const cellSize=this.calendarCellSize(),callback=this.calendarRowY,cached=this.cachedRowGeometry;if(cached!==void 0&&cached.callback===callback&&cached.cellSize===cellSize)return cached.positions;const positions=[];for(let index=0;index<=7;index++){const fallback=index===0?CAL_LABEL_H:positions[index-1]+cellSize+CAL_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,positions},positions}weekAtX(x,weekCount){const positions=this.calendarColumnPositions(),cellSize=this.calendarCellSize();for(let week=0;week<weekCount;week++){const start=positions[week];if(x>=start&&x<start+cellSize)return week}return null}weekdayAtY(y){const positions=this.calendarRowPositions(),cellSize=this.calendarCellSize();for(let weekday=0;weekday<7;weekday++){const start=positions[weekday];if(y>=start&&y<start+cellSize)return weekday}return null}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}drawCalendar(){if(!this.canvas)return;const{weekCount,firstWeekStart,monthLabels}=this.cachedCalendarGrid,cellSize=this.calendarCellSize(),w=this.columnXFor(Math.max(1,weekCount)),h=this.rowYFor(7),dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;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.cachedCalendarCellsByPos.get(`${week}:${weekday}`)?.value??-1,x=this.columnXFor(week),y=this.rowYFor(weekday),override=this.cellColor?.(this.calendarPos(week,weekday),value);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(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)];ctx.fillRect(x,y,cellSize,cellSize)}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))}if(this.selectedCell?.date!=null){const match=this.cachedCalendarCellsByDate.get(this.selectedCell.date);if(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))}}ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const m of monthLabels)ctx.fillText(m.label,this.columnXFor(m.week),CAL_LABEL_H-4);this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{label&&ctx.fillText(label,2,this.rowYFor(weekday)+cellSize-1)}),this.canvasHasContent=!0}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;return this.accessibleCells?Math.max(size,this.accessibleTargetSizePx):size}paintMatrixCell(ctx,row,col,cellSize,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.resolveCanvasColor(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));ctx.fillRect(this.matrixPadLeft+col*cellSize,this.matrixPadTop+row*cellSize,cellSize-1,cellSize-1)}paintMatrixFocusOverlays(ctx,row,col,cellSize,cs){const x=this.matrixPadLeft+col*cellSize,y=this.matrixPadTop+row*cellSize;this.cachedMatrixAnnotationPositions.has(`${row}:${col}`)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),this.selectedCell?.row===row&&this.selectedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),this.focusedCell&&"row"in this.focusedCell&&this.focusedCell.row===row&&this.focusedCell.col===col&&this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}repaintMatrixFocusCell(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),x=this.matrixPadLeft+pos.col*cellSize,y=this.matrixPadTop+pos.row*cellSize,ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);cs&&(this.paintMatrixCell(ctx,pos.row,pos.col,cellSize,cs,this.colorRamp(RAMP_STEPS,cs),this.noDataFill(cs)),this.paintMatrixFocusOverlays(ctx,pos.row,pos.col,cellSize,cs))}paintCalendarCell(ctx,week,weekday,cellSize,cs,ramp,noDataFill){const value=this.cachedCalendarCellsByPos.get(`${week}:${weekday}`)?.value??-1,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.resolveCanvasColor(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)];ctx.fillRect(this.columnXFor(week),this.rowYFor(weekday),cellSize,cellSize)}paintCalendarFocusOverlays(ctx,week,weekday,cellSize,cs){const date=this.calendarDateAt(week,weekday),x=this.columnXFor(week),y=this.rowYFor(weekday),matches=candidate=>candidate?.date===date;this.cachedCalendarAnnotationDates.has(date)&&this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs)),matches(this.selectedCell??void 0)&&this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs)),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){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;ctx.clearRect(x-RING_LINE_WIDTH-1,y-RING_LINE_WIDTH-1,cellSize+2*(RING_LINE_WIDTH+1),cellSize+2*(RING_LINE_WIDTH+1));const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;const ramp=this.colorRamp(normalizeBucketCount(this.bucketCount),cs).colors;this.paintCalendarCell(ctx,pos.week,pos.weekday,cellSize,cs,ramp,this.noDataFill(cs)),this.paintCalendarFocusOverlays(ctx,pos.week,pos.weekday,cellSize,cs),ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);for(const month of this.cachedCalendarGrid.monthLabels)ctx.fillText(month.label,this.columnXFor(month.week),CAL_LABEL_H-4);this.weekdayLabels(firstWeekStart).forEach((label,weekday)=>{label&&ctx.fillText(label,2,this.rowYFor(weekday)+cellSize-1)})}drawMatrix(){if(!this.canvas)return;const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(this.rowLabelWidth==="auto"||this.colLabelHeight==="auto"){const measureStyle=getComputedStyle(this);this.rowLabelWidth==="auto"&&(this.resolvedRowLabelWidth=this.measureRowLabelWidth(measureStyle)),this.colLabelHeight==="auto"&&(this.resolvedColLabelHeight=this.measureColLabelHeight(measureStyle))}const padLeft=this.matrixPadLeft,padTop=this.matrixPadTop,cellSize=this.matrixCellSize(cols),w=padLeft+cols*cellSize,h=padTop+rows*cellSize,dpr=this.ownerDocument.defaultView?.devicePixelRatio||1;this.canvas.width=w*dpr,this.canvas.height=h*dpr,this.canvas.style.width=`${w}px`,this.canvas.style.height=`${h}px`;const ctx=this.canvas.getContext("2d");if(!ctx)return;ctx.scale(dpr,dpr),ctx.clearRect(0,0,w,h);const cs=this.ownerDocument.defaultView?.getComputedStyle(this);if(!cs)return;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*cellSize,override=this.cellColor?.({row:r,col:c},v);if(override!=null)ctx.fillStyle=this.resolveCanvasColor(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)}ctx.fillRect(x,y,cellSize-1,cellSize-1)}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*cellSize;this.strokeCellState(ctx,x,y,cellSize,"annotation",this.annotationColor(cs))}if(this.selectedCell?.row!=null&&this.selectedCell.col!=null){const{row,col}=this.selectedCell;if(row>=0&&row<rows&&col>=0&&col<cols){const x=padLeft+col*cellSize,y=padTop+row*cellSize;this.strokeCellState(ctx,x,y,cellSize,"selected",this.selectedColor(cs))}}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*cellSize;this.strokeCellState(ctx,x,y,cellSize,"focus",this.focusRingColor(cs))}}ctx.fillStyle=this.labelColor(cs),ctx.font=this.labelFont(cs);const rowLabelSpace=padLeft-ROW_LABEL_INSET*2;this.matrixRowLabels.forEach((label,r)=>{const shown=this.ellipsize(ctx,label,rowLabelSpace);shown&&ctx.fillText(shown,ROW_LABEL_INSET,padTop+r*cellSize+cellSize/2+3)});const colRotation=this.effectiveColLabelRotation;if(colRotation===0)this.matrixColLabels.forEach((label,c)=>{ctx.fillText(label,padLeft+c*cellSize+2,padTop-COL_LABEL_INSET)});else{const radians=colRotation*Math.PI/180,previousAlign=ctx.textAlign;ctx.textAlign="right",this.matrixColLabels.forEach((label,c)=>{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}this.canvasHasContent=!0}hitTest(x,y){return this.effectiveMode==="calendar"?this.hitTestCalendar(x,y):this.hitTestMatrix(x,y)}hitTestMatrix(x,y){const rows=this.matrixRowLabels.length,cols=this.matrixColLabels.length;if(rows===0||cols===0)return null;const cellSize=this.matrixCellSize(cols),col=Math.floor((x-this.matrixPadLeft)/cellSize),row=Math.floor((y-this.matrixPadTop)/cellSize);if(row<0||row>=rows||col<0||col>=cols)return null;const pos={row,col};return this.isCellInteractive(pos)?pos:null}firstInteractiveMatrixCell(rows,cols){for(let r=0;r<rows;r++)for(let c=0;c<cols;c++)if(this.isCellInteractive({row:r,col:c}))return{row:r,col:c};return null}nextInteractiveMatrixCell(row,col,dRow,dCol,rows,cols){let r=row,c=col;for(;;){const nr=Math.min(rows-1,Math.max(0,r+dRow)),nc=Math.min(cols-1,Math.max(0,c+dCol));if(nr===r&&nc===c)return{row,col};if(r=nr,c=nc,this.isCellInteractive({row:r,col:c}))return{row:r,col:c}}}firstInteractiveCalendarCell(weekCount){for(let week=0;week<weekCount;week++)for(let weekday=0;weekday<7;weekday++){const pos=this.calendarPos(week,weekday);if(this.isCellInteractive(pos))return pos}return null}nextInteractiveCalendarCell(week,weekday,dWeek,dWeekday,weekCount){let w=week,d=weekday;for(;;){const nw=Math.min(weekCount-1,Math.max(0,w+dWeek)),nd=Math.min(6,Math.max(0,d+dWeekday));if(nw===w&&nd===d)return this.calendarPos(week,weekday);w=nw,d=nd;const pos=this.calendarPos(w,d);if(this.isCellInteractive(pos))return pos}}hitTestCalendar(x,y){const{weekCount}=this.cachedCalendarGrid;if(weekCount===0)return null;const week=this.weekAtX(x,weekCount),weekday=this.weekdayAtY(y);if(week===null||weekday===null)return null;const pos=this.calendarPos(week,weekday);return this.isCellInteractive(pos)?pos:null}calendarCellAt(pos){const match=this.cachedCalendarCellsByPos.get(`${pos.week}:${pos.weekday}`);return match?{date:match.date,value:match.value}:{date:this.calendarDateAt(pos.week,pos.weekday),value:-1}}calendarDateAt(week,weekday){const index=week*7+weekday;return this.cachedCalendarDateByPos[index]??isoDateAtOffset(this.cachedCalendarGrid.firstWeekStart,index)}calendarPos(week,weekday){return{week,weekday,date:this.calendarDateAt(week,weekday)}}cellRect(pos){if("week"in pos){const cellSize2=this.calendarCellSize();return{x:this.columnXFor(pos.week),y:this.rowYFor(pos.weekday),w:cellSize2,h:cellSize2}}const cellSize=this.matrixCellSize(this.matrixColLabels.length);return{x:this.matrixPadLeft+pos.col*cellSize,y:this.matrixPadTop+pos.row*cellSize,w:cellSize-1,h:cellSize-1}}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=parseIsoDate(date).toLocaleString(this.effectiveLocale||void 0,{month:"short",day:"numeric",timeZone:"UTC"}),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){const text=this.resolveCellText(pos),announcement=this.isSelectedPos(pos)?this.localize("heatmapSelectedCellLabel",void 0,{cell:text}):text;this.liveText=announcement,this.announcementSink?.announce(announcement)}emitCellClick(pos){if(this.isCellInteractive(pos))if("week"in pos){const{date,value}=this.calendarCellAt(pos);this.emit("lr-cell-click",{date,value})}else{const value=this.matrixValues[pos.row]?.[pos.col]??-1;this.emit("lr-cell-click",{row:pos.row,col:pos.col,value})}}tooltipStyle(pos){const rect=this.cellRect(pos);return{left:`${rect.x+rect.w/2}px`,top:`${rect.y}px`}}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}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);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.announce(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.announce(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);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,this.announce(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,this.announce(next)}resolveCanvasColor(value,cs){const cached=this.canvasColorCache.get(value);if(cached!==void 0)return cached;const fallback=this.noDataFill(cs);let candidate=value;if(value.includes("var(")){if(this.colorProbe||(this.colorProbe=this.ownerDocument.createElement("span"),this.colorProbe.style.cssText="position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none;",this.shadowRoot.appendChild(this.colorProbe)),this.colorProbe.style.color="",this.colorProbe.style.color=value,!this.colorProbe.style.color)return this.canvasColorCache.set(value,fallback),fallback;candidate=this.ownerDocument.defaultView?.getComputedStyle(this.colorProbe).color||fallback}const ctx=getScratchCtx(this.ownerDocument);if(!ctx)return fallback;ctx.fillStyle="rgb(1, 2, 3)";const firstSentinel=ctx.fillStyle;ctx.fillStyle=candidate;let resolved=ctx.fillStyle;if(resolved===firstSentinel){ctx.fillStyle="rgb(4, 5, 6)";const secondSentinel=ctx.fillStyle;ctx.fillStyle=candidate,resolved=ctx.fillStyle,resolved===secondSentinel&&(resolved=fallback)}return this.canvasColorCache.set(value,resolved),resolved}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;return html`
2
2
  <div
3
3
  part="cells"
4
4
  role="grid"
@@ -92,4 +92,4 @@ var __decorate=function(decorators,target,key,desc){var c=arguments.length,r=c<3
92
92
  >`)}
93
93
  </div>
94
94
  </div>
95
- `}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}}__decorate([property({attribute:!1})],LyraHeatmap.prototype,"data",void 0),__decorate([property({converter:rowLabelWidthConverter,attribute:"row-label-width",reflect:!0})],LyraHeatmap.prototype,"rowLabelWidth",void 0),__decorate([property({type:Number,attribute:"col-label-height"})],LyraHeatmap.prototype,"colLabelHeight",void 0),__decorate([property({type:Number,attribute:"cell-size",converter:optionalCellSizeConverter})],LyraHeatmap.prototype,"cellSize",null),__decorate([property({attribute:"value-label"})],LyraHeatmap.prototype,"valueLabel",void 0),__decorate([property()],LyraHeatmap.prototype,"scale",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"domain",void 0),__decorate([property({type:Number})],LyraHeatmap.prototype,"midpoint",void 0),__decorate([property({type:Boolean,attribute:"fit-to-width"})],LyraHeatmap.prototype,"fitToWidth",void 0),__decorate([property({type:Number,attribute:"max-cell-size",converter:optionalCellSizeConverter})],LyraHeatmap.prototype,"maxCellSize",null),__decorate([property({type:Number,attribute:"min-cell-size",converter:optionalCellSizeConverter})],LyraHeatmap.prototype,"minCellSize",null),__decorate([property({attribute:"bucket-count",converter:bucketCountConverter})],LyraHeatmap.prototype,"bucketCount",null),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"annotations",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"legendStops",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"selectedCell",void 0),__decorate([property({type:Boolean,attribute:"accessible-cells"})],LyraHeatmap.prototype,"accessibleCells",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"cellText",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"cellInteractive",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"cellColor",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"colorSteps",void 0),__decorate([query("canvas")],LyraHeatmap.prototype,"canvas",void 0),__decorate([state()],LyraHeatmap.prototype,"hoverCell",void 0),__decorate([state()],LyraHeatmap.prototype,"focusedCell",void 0),__decorate([state()],LyraHeatmap.prototype,"liveText",void 0),__decorate([state()],LyraHeatmap.prototype,"accessibleTargetSizePx",void 0);export{LyraHeatmap,MAX_ACCESSIBLE_HEATMAP_CELLS,MAX_BUCKET_COUNT,MAX_HEATMAP_CELLS,MAX_HEATMAP_DECORATIONS,hexToRgb,normalizeBucketCount,resolveRgb};
95
+ `}formatCount(value){return getNumberFormat(this.effectiveLocale).format(value)}}__decorate([property({attribute:!1})],LyraHeatmap.prototype,"data",void 0),__decorate([property({converter:labelExtentConverter,attribute:"row-label-width",reflect:!0})],LyraHeatmap.prototype,"rowLabelWidth",void 0),__decorate([property({converter:labelExtentConverter,attribute:"col-label-height"})],LyraHeatmap.prototype,"colLabelHeight",void 0),__decorate([property({type:Number,attribute:"col-label-rotation"})],LyraHeatmap.prototype,"colLabelRotation",void 0),__decorate([property({type:Number,attribute:"cell-size",converter:optionalCellSizeConverter})],LyraHeatmap.prototype,"cellSize",null),__decorate([property({attribute:"value-label"})],LyraHeatmap.prototype,"valueLabel",void 0),__decorate([property()],LyraHeatmap.prototype,"scale",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"domain",void 0),__decorate([property({type:Number})],LyraHeatmap.prototype,"midpoint",void 0),__decorate([property({type:Boolean,attribute:"fit-to-width"})],LyraHeatmap.prototype,"fitToWidth",void 0),__decorate([property({type:Number,attribute:"max-cell-size",converter:optionalCellSizeConverter})],LyraHeatmap.prototype,"maxCellSize",null),__decorate([property({type:Number,attribute:"min-cell-size",converter:optionalCellSizeConverter})],LyraHeatmap.prototype,"minCellSize",null),__decorate([property({attribute:"bucket-count",converter:bucketCountConverter})],LyraHeatmap.prototype,"bucketCount",null),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"annotations",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"legendStops",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"selectedCell",void 0),__decorate([property({type:Boolean,attribute:"accessible-cells"})],LyraHeatmap.prototype,"accessibleCells",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"cellText",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"cellInteractive",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"cellColor",void 0),__decorate([property({attribute:!1})],LyraHeatmap.prototype,"colorSteps",void 0),__decorate([query("canvas")],LyraHeatmap.prototype,"canvas",void 0),__decorate([state()],LyraHeatmap.prototype,"hoverCell",void 0),__decorate([state()],LyraHeatmap.prototype,"focusedCell",void 0),__decorate([state()],LyraHeatmap.prototype,"liveText",void 0),__decorate([state()],LyraHeatmap.prototype,"accessibleTargetSizePx",void 0);export{LyraHeatmap,MAX_ACCESSIBLE_HEATMAP_CELLS,MAX_BUCKET_COUNT,MAX_HEATMAP_CELLS,MAX_HEATMAP_DECORATIONS,hexToRgb,normalizeBucketCount,resolveRgb};
@@ -973,6 +973,25 @@ export declare class LyraTable<T = unknown> extends LyraElement<LyraTableEventMa
973
973
  *
974
974
  * No `tabindex` on either: a persistent editor is a plain tab stop, exactly like the row-expand
975
975
  * toggle rendered a few lines above, and stays outside the header/row roving model. */
976
+ /** Column keys already reported by `renderCellValue()`, so a 400-row table logs once, not 400
977
+ * times, for the same authoring mistake. */
978
+ private readonly reportedMissingCellColumns;
979
+ /**
980
+ * Renders one cell, tolerating a column that omits its required `cell` renderer.
981
+ *
982
+ * `TableColumn.cell` is typed and documented required, but columns arrive through a lit
983
+ * `.columns=${[...]}` property binding, and lit-html property bindings are not type-checked by
984
+ * `tsc` -- only by lit-analyzer, which many projects do not run. So required-ness is unenforced
985
+ * where it is actually written. Calling it unguarded meant a single malformed column threw out of
986
+ * lit's `repeat` directive and took the WHOLE table down, with a stack carrying only lyra and
987
+ * lit-html frames: no application frame, no column key, no table identity. One report described
988
+ * carrying it undiagnosed across two releases as 16 unattributed unhandled rejections, while the
989
+ * suite still passed because its assertions were on surrounding markup.
990
+ *
991
+ * So: degrade to an empty cell -- the rest of the table stays usable -- and report once per
992
+ * column, naming the key and the tag, because attribution was the harder half of that bug.
993
+ */
994
+ private renderCellValue;
976
995
  private renderCellEditor;
977
996
  /** One rectangular placeholder, using `<lr-skeleton>`'s canonical `shape` axis. `announce` is
978
997
  * switched off on every one of them: `<lr-skeleton>` defaults it