@oicl/openbridge-webcomponents-full-bundle 2.1.0 → 2.1.1

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 (31) hide show
  1. package/bundle/openbridge-webcomponents.bundle.js +46 -37
  2. package/bundle/openbridge-webcomponents.bundle.js.map +1 -1
  3. package/custom-elements.json +5 -5
  4. package/dist/bars-graphs/donut-chart/donut-chart.d.ts.map +1 -1
  5. package/dist/bars-graphs/donut-chart/donut-chart.js +3 -4
  6. package/dist/bars-graphs/donut-chart/donut-chart.js.map +1 -1
  7. package/dist/bars-graphs/pie-chart/pie-chart.d.ts.map +1 -1
  8. package/dist/bars-graphs/pie-chart/pie-chart.js +3 -4
  9. package/dist/bars-graphs/pie-chart/pie-chart.js.map +1 -1
  10. package/dist/bars-graphs/polar-chart/polar-chart.d.ts.map +1 -1
  11. package/dist/bars-graphs/polar-chart/polar-chart.js +3 -4
  12. package/dist/bars-graphs/polar-chart/polar-chart.js.map +1 -1
  13. package/dist/bars-graphs/radial-bar-chart/radial-bar-chart.d.ts.map +1 -1
  14. package/dist/bars-graphs/radial-bar-chart/radial-bar-chart.js +3 -4
  15. package/dist/bars-graphs/radial-bar-chart/radial-bar-chart.js.map +1 -1
  16. package/dist/building-blocks/chart-line/chart-line-base.d.ts.map +1 -1
  17. package/dist/building-blocks/chart-line/chart-line-base.js +3 -6
  18. package/dist/building-blocks/chart-line/chart-line-base.js.map +1 -1
  19. package/dist/charthelpers/index.js +2 -2
  20. package/dist/charthelpers/legend.d.ts +24 -7
  21. package/dist/charthelpers/legend.d.ts.map +1 -1
  22. package/dist/charthelpers/legend.js +40 -16
  23. package/dist/charthelpers/legend.js.map +1 -1
  24. package/package.json +1 -1
  25. package/src/bars-graphs/donut-chart/donut-chart.ts +3 -4
  26. package/src/bars-graphs/pie-chart/pie-chart.ts +3 -4
  27. package/src/bars-graphs/polar-chart/polar-chart.ts +3 -4
  28. package/src/bars-graphs/radial-bar-chart/radial-bar-chart.ts +3 -4
  29. package/src/building-blocks/chart-line/chart-line-base.ts +3 -4
  30. package/src/charthelpers/legend.spec.ts +261 -0
  31. package/src/charthelpers/legend.ts +63 -27
@@ -3015,7 +3015,7 @@
3015
3015
  {
3016
3016
  "kind": "variable",
3017
3017
  "name": "ObcDonutChart",
3018
- "default": "class ObcDonutChart extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.colors = []; this.priority = Priority.regular; this.half = false; this.showOuterLabels = false; this.showUnit = false; this.outerLabelUnit = \"%\"; this.outerLabelMaxLength = 0; this.outerLabelDecimalPlaces = 0; this.centerReadoutLabel = \"Total\"; this.centerReadoutUnit = \"%\"; this.max = 100; this.thickness = 24; this.legend = false; this.showDebugOverlay = false; this.fixedHeight = 320; this.total = 0; this.formattedLabels = []; } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Get layout configuration for canvas calculation */ getLayoutConfig() { const denominator = this.max > 0 ? this.max : this.total > 0 ? this.total : 1; return { unit: this.outerLabelUnit, showUnit: this.showUnit, outerLabelMaxLength: this.outerLabelMaxLength, decimalPlaces: this.outerLabelDecimalPlaces, data: this.data, denominator }; } willUpdate(changed) { if (changed.has(\"data\")) this.total = calculateSumTotal(this.data); } updated(changed) { super.updated(changed); if (this.hasAnyChanged(changed, DONUT_WATCHED_PROP_NAMES)) { if (this.hasAnyChanged(changed, DONUT_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } } firstUpdated() { this.createChart(); this.themeObserver = observeThemeChanges(() => this.updateChartColors()); this.setupResizeObserver(); } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); } /** * The layout's isTooSmall decides which side the chart is on (one * threshold serves half and full circles); a flip changes the plugin * set, so the chart is rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => !this.lastDimensions?.isTooSmall, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } prepareChartData() { const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label); const remaining = Math.max(0, this.max - this.total); const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const segmentColors = values.map((_, index) => chartColors[index % chartColors.length] ?? getCssVariableValue(this, DONUT_DIMENSIONS.REMAINING_COLOR)); return { values: [...values, remaining], labels: [...labels, \"Remaining\"], colors: [...segmentColors, getCssVariableValue(this, DONUT_DIMENSIONS.REMAINING_COLOR)] }; } /** * Build a dataset configuration object shared by both createChart and updateChart */ createDatasetConfig(values, colors) { return { data: values, backgroundColor: colors, borderWidth: 1, borderColor: getCssVariableValue(this, DONUT_DIMENSIONS.GAP_AND_BORDER_COLOR), borderRadius: this.getBorderRadius(values), spacing: DONUT_DIMENSIONS.GAP_WIDTH }; } /** * Get Chart.js options using centralized fixed height layout calculation */ getChartOptions() { const dimensions = calculateFixedHeightChartLayout({ fixedHeight: this.fixedHeight, isHalfMode: this.half, showOuterLabels: this.showOuterLabels, canvasEl: this.canvasEl, layoutConfig: this.getLayoutConfig(), host: this }); this.lastDimensions = dimensions; this.formattedLabels = dimensions.formattedLabels; this.style.setProperty(\"--chart-width\", `${dimensions.calculatedWidth}px`); this.style.setProperty(\"--chart-height\", `${dimensions.actualHeight}px`); const dynamicPadding = dimensions.isTooSmall ? { top: 0, right: 0, bottom: 0, left: 0 } : { top: dimensions.topPadding, right: dimensions.rightPadding, bottom: dimensions.bottomPadding, left: dimensions.leftPadding }; return { responsive: false, maintainAspectRatio: false, devicePixelRatio: window.devicePixelRatio, rotation: this.half ? -90 : 0, circumference: this.half ? 180 : 360, cutout: `${(DONUT_DIMENSIONS.CHART_WIDTH - this.thickness * 2) / DONUT_DIMENSIONS.CHART_WIDTH * 100}%`, layout: { padding: dynamicPadding ?? DONUT_DIMENSIONS.CANVAS_PADDING }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !dimensions.isTooSmall, filter: (tooltipItem) => tooltipItem.label !== \"Remaining\", callbacks: { title: () => \"\", label: (context) => { const label = context.label ?? \"\"; const value = context.parsed; const denominator = this.max > 0 ? this.max : this.total > 0 ? this.total : 1; const isPercentage = this.outerLabelUnit === \"%\"; const numericValue = formatChartNumber(value, denominator, isPercentage, this.outerLabelDecimalPlaces); return this.showUnit && this.outerLabelUnit ? `${label} ${numericValue}${this.outerLabelUnit}` : `${label} ${numericValue}`; } } } }, animation: { animateRotate: false, animateScale: false } }; } createOuterLabelDonutPlugin() { const basePlugin = createArcOuterLabelPlugin(this, { formattedLabels: this.formattedLabels }); const originalAfterDatasetsDraw = basePlugin.afterDatasetsDraw; if (originalAfterDatasetsDraw) basePlugin.afterDatasetsDraw = (chart, args, pluginOptions, options) => { if (this.lastDimensions?.isTooSmall) return; originalAfterDatasetsDraw(chart, args, pluginOptions, options); }; return basePlugin; } createCenterReadoutDonutPlugin() { return { id: \"centerText\", beforeDraw: (chart) => { const { ctx, chartArea } = chart; const { width, height, left, top } = chartArea; if (this.lastDimensions?.isTooSmall) return; ctx.save(); ctx.textAlign = \"center\"; ctx.textBaseline = \"middle\"; const centerX = left + width / 2; const fontFamily = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontFamily); const lineGap = 4; const valueFontWeight = getCssVariableValue(this, CENTER_READOUT_CONFIG.value.fontWeightVar); const valueFontSize = getCssVariableValue(this, CENTER_READOUT_CONFIG.value.fontSizeVar); const valueColor = getCssVariableValue(this, CENTER_READOUT_CONFIG.value.fontColorVar); ctx.font = `${valueFontWeight} ${valueFontSize} ${fontFamily}`; const centerValueText = this.total.toFixed(0); const valueMetrics = ctx.measureText(centerValueText); const valueHeight = valueMetrics.actualBoundingBoxAscent + valueMetrics.actualBoundingBoxDescent; const labelFontWeight = getCssVariableValue(this, CENTER_READOUT_CONFIG.label.fontWeightVar); const labelFontSize = getCssVariableValue(this, CENTER_READOUT_CONFIG.label.fontSizeVar); const labelColor = getCssVariableValue(this, CENTER_READOUT_CONFIG.label.fontColorVar); const unitFontWeight = getCssVariableValue(this, CENTER_READOUT_CONFIG.unit.fontWeightVar); const unitFontSize = getCssVariableValue(this, CENTER_READOUT_CONFIG.unit.fontSizeVar); const unitColor = getCssVariableValue(this, CENTER_READOUT_CONFIG.unit.fontColorVar); const centerReadoutLabelText = this.centerReadoutLabel; const centerReadoutUnitText = this.centerReadoutUnit; const space = centerReadoutUnitText ? \" \" : \"\"; ctx.font = `${labelFontWeight} ${labelFontSize} ${fontFamily}`; const labelMetrics = ctx.measureText(centerReadoutLabelText); const spaceMetrics = ctx.measureText(space); ctx.font = `${unitFontWeight} ${unitFontSize} ${fontFamily}`; const unitMetrics = ctx.measureText(centerReadoutUnitText); const labelHeight = Math.max(labelMetrics.actualBoundingBoxAscent + labelMetrics.actualBoundingBoxDescent, unitMetrics.actualBoundingBoxAscent + unitMetrics.actualBoundingBoxDescent); let valueY; let labelY; if (this.half) { const meta = chart.getDatasetMeta(0); labelY = (meta.data[0] ? meta.data[0].y : top + height) - Math.max(labelMetrics.actualBoundingBoxDescent, unitMetrics.actualBoundingBoxDescent); valueY = labelY - labelHeight - lineGap - valueHeight + valueMetrics.actualBoundingBoxAscent; } else { const totalTextHeight = valueHeight + lineGap + labelHeight; valueY = top + height / 2 - totalTextHeight / 2 + valueMetrics.actualBoundingBoxAscent; labelY = valueY + valueMetrics.actualBoundingBoxDescent + lineGap + Math.max(labelMetrics.actualBoundingBoxAscent, unitMetrics.actualBoundingBoxAscent); } ctx.font = `${valueFontWeight} ${valueFontSize} ${fontFamily}`; ctx.fillStyle = valueColor; ctx.fillText(centerValueText, centerX, valueY); ctx.font = `${labelFontWeight} ${labelFontSize} ${fontFamily}`; const labelWidth = labelMetrics.width; const spaceWidth = spaceMetrics.width; ctx.font = `${unitFontWeight} ${unitFontSize} ${fontFamily}`; const unitWidth = unitMetrics.width; const totalWidth = labelWidth + (centerReadoutUnitText ? spaceWidth + unitWidth : 0); ctx.font = `${labelFontWeight} ${labelFontSize} ${fontFamily}`; ctx.fillStyle = labelColor; ctx.fillText(centerReadoutLabelText, centerX - totalWidth / 2 + labelWidth / 2, labelY); if (centerReadoutUnitText) { ctx.font = `${labelFontWeight} ${labelFontSize} ${fontFamily}`; ctx.fillStyle = labelColor; ctx.fillText(space, centerX - totalWidth / 2 + labelWidth + spaceWidth / 2, labelY); ctx.font = `${unitFontWeight} ${unitFontSize} ${fontFamily}`; ctx.fillStyle = unitColor; ctx.fillText(centerReadoutUnitText, centerX + totalWidth / 2 - unitWidth / 2, labelY); } ctx.restore(); } }; } getBorderRadius(values) { if (!this.half) return; const hasRemainingSegment = Math.max(0, this.max - this.total) > 0; return values.map((_value, index) => { if (index === 0) return { outerStart: DONUT_DIMENSIONS.BORDER_RADIUS, outerEnd: 0, innerStart: DONUT_DIMENSIONS.BORDER_RADIUS, innerEnd: 0 }; if (hasRemainingSegment ? index === values.length - 1 : index === values.length - 2) return { outerStart: 0, outerEnd: DONUT_DIMENSIONS.BORDER_RADIUS, innerStart: 0, innerEnd: DONUT_DIMENSIONS.BORDER_RADIUS }; return 0; }); } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; const { values, labels, colors } = this.prepareChartData(); const options = this.getChartOptions(); if (this.lastDimensions) { this.canvasEl.width = this.lastDimensions.calculatedWidth; this.canvasEl.height = this.lastDimensions.actualHeight; } this.chart = new Chart(ctx, { type: \"doughnut\", data: { labels, datasets: [this.createDatasetConfig(values, colors)] }, options, plugins: [...this.showOuterLabels ? [this.createOuterLabelDonutPlugin()] : [], this.createCenterReadoutDonutPlugin()] }); requestAnimationFrame(() => this.updateLegend()); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { values, labels, colors } = this.prepareChartData(); this.chart.data.labels = labels; this.chart.data.datasets = [this.createDatasetConfig(values, colors)]; const latestOptions = this.getChartOptions(); if (this.chart.options) Object.assign(this.chart.options, latestOptions); if (this.lastDimensions) this.chart.resize(this.lastDimensions.calculatedWidth, this.lastDimensions.actualHeight); this.chart.update(); requestAnimationFrame(() => this.updateLegend()); } /** * Update only chart colors without recalculating layout * Used by theme observer for efficient theme changes */ updateChartColors() { if (!this.chart) return; const { colors } = this.prepareChartData(); if (this.chart.data.datasets[0]) { this.chart.data.datasets[0].backgroundColor = colors; this.chart.data.datasets[0].borderColor = getCssVariableValue(this, DONUT_DIMENSIONS.GAP_AND_BORDER_COLOR); } this.chart.update(\"none\"); this.updateLegend(); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; const meta = this.chart.getDatasetMeta(0); if (!meta || !meta.controller) return; if (!this.data || this.data.length === 0) { this.legendDiv.innerHTML = \"\"; return; } const denominator = this.max > 0 ? this.max : this.total > 0 ? this.total : 1; const isPercentage = this.outerLabelUnit === \"%\"; try { const legendItems = this.data.map((item, i) => { const style = meta.controller.getStyle(i, false); const numericValue = formatChartNumber(item.value, denominator, isPercentage, this.outerLabelDecimalPlaces); const showUnit = this.showUnit && this.outerLabelUnit; const value = `${numericValue}`; const unit = showUnit ? `${this.outerLabelUnit}` : \"\"; return { fillStyle: style.backgroundColor, label: item.label, value, unit }; }); const legendHTML = generateLegendHTML(legendItems); this.legendDiv.innerHTML = legendHTML; } catch (error) { console.debug(\"[obc-donut-chart] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <canvas></canvas> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(donut_chart_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }"
3018
+ "default": "class ObcDonutChart extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.colors = []; this.priority = Priority.regular; this.half = false; this.showOuterLabels = false; this.showUnit = false; this.outerLabelUnit = \"%\"; this.outerLabelMaxLength = 0; this.outerLabelDecimalPlaces = 0; this.centerReadoutLabel = \"Total\"; this.centerReadoutUnit = \"%\"; this.max = 100; this.thickness = 24; this.legend = false; this.showDebugOverlay = false; this.fixedHeight = 320; this.total = 0; this.formattedLabels = []; } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Get layout configuration for canvas calculation */ getLayoutConfig() { const denominator = this.max > 0 ? this.max : this.total > 0 ? this.total : 1; return { unit: this.outerLabelUnit, showUnit: this.showUnit, outerLabelMaxLength: this.outerLabelMaxLength, decimalPlaces: this.outerLabelDecimalPlaces, data: this.data, denominator }; } willUpdate(changed) { if (changed.has(\"data\")) this.total = calculateSumTotal(this.data); } updated(changed) { super.updated(changed); if (this.hasAnyChanged(changed, DONUT_WATCHED_PROP_NAMES)) { if (this.hasAnyChanged(changed, DONUT_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } } firstUpdated() { this.createChart(); this.themeObserver = observeThemeChanges(() => this.updateChartColors()); this.setupResizeObserver(); } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); } /** * The layout's isTooSmall decides which side the chart is on (one * threshold serves half and full circles); a flip changes the plugin * set, so the chart is rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => !this.lastDimensions?.isTooSmall, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } prepareChartData() { const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label); const remaining = Math.max(0, this.max - this.total); const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const segmentColors = values.map((_, index) => chartColors[index % chartColors.length] ?? getCssVariableValue(this, DONUT_DIMENSIONS.REMAINING_COLOR)); return { values: [...values, remaining], labels: [...labels, \"Remaining\"], colors: [...segmentColors, getCssVariableValue(this, DONUT_DIMENSIONS.REMAINING_COLOR)] }; } /** * Build a dataset configuration object shared by both createChart and updateChart */ createDatasetConfig(values, colors) { return { data: values, backgroundColor: colors, borderWidth: 1, borderColor: getCssVariableValue(this, DONUT_DIMENSIONS.GAP_AND_BORDER_COLOR), borderRadius: this.getBorderRadius(values), spacing: DONUT_DIMENSIONS.GAP_WIDTH }; } /** * Get Chart.js options using centralized fixed height layout calculation */ getChartOptions() { const dimensions = calculateFixedHeightChartLayout({ fixedHeight: this.fixedHeight, isHalfMode: this.half, showOuterLabels: this.showOuterLabels, canvasEl: this.canvasEl, layoutConfig: this.getLayoutConfig(), host: this }); this.lastDimensions = dimensions; this.formattedLabels = dimensions.formattedLabels; this.style.setProperty(\"--chart-width\", `${dimensions.calculatedWidth}px`); this.style.setProperty(\"--chart-height\", `${dimensions.actualHeight}px`); const dynamicPadding = dimensions.isTooSmall ? { top: 0, right: 0, bottom: 0, left: 0 } : { top: dimensions.topPadding, right: dimensions.rightPadding, bottom: dimensions.bottomPadding, left: dimensions.leftPadding }; return { responsive: false, maintainAspectRatio: false, devicePixelRatio: window.devicePixelRatio, rotation: this.half ? -90 : 0, circumference: this.half ? 180 : 360, cutout: `${(DONUT_DIMENSIONS.CHART_WIDTH - this.thickness * 2) / DONUT_DIMENSIONS.CHART_WIDTH * 100}%`, layout: { padding: dynamicPadding ?? DONUT_DIMENSIONS.CANVAS_PADDING }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !dimensions.isTooSmall, filter: (tooltipItem) => tooltipItem.label !== \"Remaining\", callbacks: { title: () => \"\", label: (context) => { const label = context.label ?? \"\"; const value = context.parsed; const denominator = this.max > 0 ? this.max : this.total > 0 ? this.total : 1; const isPercentage = this.outerLabelUnit === \"%\"; const numericValue = formatChartNumber(value, denominator, isPercentage, this.outerLabelDecimalPlaces); return this.showUnit && this.outerLabelUnit ? `${label} ${numericValue}${this.outerLabelUnit}` : `${label} ${numericValue}`; } } } }, animation: { animateRotate: false, animateScale: false } }; } createOuterLabelDonutPlugin() { const basePlugin = createArcOuterLabelPlugin(this, { formattedLabels: this.formattedLabels }); const originalAfterDatasetsDraw = basePlugin.afterDatasetsDraw; if (originalAfterDatasetsDraw) basePlugin.afterDatasetsDraw = (chart, args, pluginOptions, options) => { if (this.lastDimensions?.isTooSmall) return; originalAfterDatasetsDraw(chart, args, pluginOptions, options); }; return basePlugin; } createCenterReadoutDonutPlugin() { return { id: \"centerText\", beforeDraw: (chart) => { const { ctx, chartArea } = chart; const { width, height, left, top } = chartArea; if (this.lastDimensions?.isTooSmall) return; ctx.save(); ctx.textAlign = \"center\"; ctx.textBaseline = \"middle\"; const centerX = left + width / 2; const fontFamily = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontFamily); const lineGap = 4; const valueFontWeight = getCssVariableValue(this, CENTER_READOUT_CONFIG.value.fontWeightVar); const valueFontSize = getCssVariableValue(this, CENTER_READOUT_CONFIG.value.fontSizeVar); const valueColor = getCssVariableValue(this, CENTER_READOUT_CONFIG.value.fontColorVar); ctx.font = `${valueFontWeight} ${valueFontSize} ${fontFamily}`; const centerValueText = this.total.toFixed(0); const valueMetrics = ctx.measureText(centerValueText); const valueHeight = valueMetrics.actualBoundingBoxAscent + valueMetrics.actualBoundingBoxDescent; const labelFontWeight = getCssVariableValue(this, CENTER_READOUT_CONFIG.label.fontWeightVar); const labelFontSize = getCssVariableValue(this, CENTER_READOUT_CONFIG.label.fontSizeVar); const labelColor = getCssVariableValue(this, CENTER_READOUT_CONFIG.label.fontColorVar); const unitFontWeight = getCssVariableValue(this, CENTER_READOUT_CONFIG.unit.fontWeightVar); const unitFontSize = getCssVariableValue(this, CENTER_READOUT_CONFIG.unit.fontSizeVar); const unitColor = getCssVariableValue(this, CENTER_READOUT_CONFIG.unit.fontColorVar); const centerReadoutLabelText = this.centerReadoutLabel; const centerReadoutUnitText = this.centerReadoutUnit; const space = centerReadoutUnitText ? \" \" : \"\"; ctx.font = `${labelFontWeight} ${labelFontSize} ${fontFamily}`; const labelMetrics = ctx.measureText(centerReadoutLabelText); const spaceMetrics = ctx.measureText(space); ctx.font = `${unitFontWeight} ${unitFontSize} ${fontFamily}`; const unitMetrics = ctx.measureText(centerReadoutUnitText); const labelHeight = Math.max(labelMetrics.actualBoundingBoxAscent + labelMetrics.actualBoundingBoxDescent, unitMetrics.actualBoundingBoxAscent + unitMetrics.actualBoundingBoxDescent); let valueY; let labelY; if (this.half) { const meta = chart.getDatasetMeta(0); labelY = (meta.data[0] ? meta.data[0].y : top + height) - Math.max(labelMetrics.actualBoundingBoxDescent, unitMetrics.actualBoundingBoxDescent); valueY = labelY - labelHeight - lineGap - valueHeight + valueMetrics.actualBoundingBoxAscent; } else { const totalTextHeight = valueHeight + lineGap + labelHeight; valueY = top + height / 2 - totalTextHeight / 2 + valueMetrics.actualBoundingBoxAscent; labelY = valueY + valueMetrics.actualBoundingBoxDescent + lineGap + Math.max(labelMetrics.actualBoundingBoxAscent, unitMetrics.actualBoundingBoxAscent); } ctx.font = `${valueFontWeight} ${valueFontSize} ${fontFamily}`; ctx.fillStyle = valueColor; ctx.fillText(centerValueText, centerX, valueY); ctx.font = `${labelFontWeight} ${labelFontSize} ${fontFamily}`; const labelWidth = labelMetrics.width; const spaceWidth = spaceMetrics.width; ctx.font = `${unitFontWeight} ${unitFontSize} ${fontFamily}`; const unitWidth = unitMetrics.width; const totalWidth = labelWidth + (centerReadoutUnitText ? spaceWidth + unitWidth : 0); ctx.font = `${labelFontWeight} ${labelFontSize} ${fontFamily}`; ctx.fillStyle = labelColor; ctx.fillText(centerReadoutLabelText, centerX - totalWidth / 2 + labelWidth / 2, labelY); if (centerReadoutUnitText) { ctx.font = `${labelFontWeight} ${labelFontSize} ${fontFamily}`; ctx.fillStyle = labelColor; ctx.fillText(space, centerX - totalWidth / 2 + labelWidth + spaceWidth / 2, labelY); ctx.font = `${unitFontWeight} ${unitFontSize} ${fontFamily}`; ctx.fillStyle = unitColor; ctx.fillText(centerReadoutUnitText, centerX + totalWidth / 2 - unitWidth / 2, labelY); } ctx.restore(); } }; } getBorderRadius(values) { if (!this.half) return; const hasRemainingSegment = Math.max(0, this.max - this.total) > 0; return values.map((_value, index) => { if (index === 0) return { outerStart: DONUT_DIMENSIONS.BORDER_RADIUS, outerEnd: 0, innerStart: DONUT_DIMENSIONS.BORDER_RADIUS, innerEnd: 0 }; if (hasRemainingSegment ? index === values.length - 1 : index === values.length - 2) return { outerStart: 0, outerEnd: DONUT_DIMENSIONS.BORDER_RADIUS, innerStart: 0, innerEnd: DONUT_DIMENSIONS.BORDER_RADIUS }; return 0; }); } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; const { values, labels, colors } = this.prepareChartData(); const options = this.getChartOptions(); if (this.lastDimensions) { this.canvasEl.width = this.lastDimensions.calculatedWidth; this.canvasEl.height = this.lastDimensions.actualHeight; } this.chart = new Chart(ctx, { type: \"doughnut\", data: { labels, datasets: [this.createDatasetConfig(values, colors)] }, options, plugins: [...this.showOuterLabels ? [this.createOuterLabelDonutPlugin()] : [], this.createCenterReadoutDonutPlugin()] }); requestAnimationFrame(() => this.updateLegend()); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { values, labels, colors } = this.prepareChartData(); this.chart.data.labels = labels; this.chart.data.datasets = [this.createDatasetConfig(values, colors)]; const latestOptions = this.getChartOptions(); if (this.chart.options) Object.assign(this.chart.options, latestOptions); if (this.lastDimensions) this.chart.resize(this.lastDimensions.calculatedWidth, this.lastDimensions.actualHeight); this.chart.update(); requestAnimationFrame(() => this.updateLegend()); } /** * Update only chart colors without recalculating layout * Used by theme observer for efficient theme changes */ updateChartColors() { if (!this.chart) return; const { colors } = this.prepareChartData(); if (this.chart.data.datasets[0]) { this.chart.data.datasets[0].backgroundColor = colors; this.chart.data.datasets[0].borderColor = getCssVariableValue(this, DONUT_DIMENSIONS.GAP_AND_BORDER_COLOR); } this.chart.update(\"none\"); this.updateLegend(); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; const meta = this.chart.getDatasetMeta(0); if (!meta || !meta.controller) return; if (!this.data || this.data.length === 0) { renderLegend(this.legendDiv, []); return; } const denominator = this.max > 0 ? this.max : this.total > 0 ? this.total : 1; const isPercentage = this.outerLabelUnit === \"%\"; try { const legendItems = this.data.map((item, i) => { const style = meta.controller.getStyle(i, false); const numericValue = formatChartNumber(item.value, denominator, isPercentage, this.outerLabelDecimalPlaces); const showUnit = this.showUnit && this.outerLabelUnit; const value = `${numericValue}`; const unit = showUnit ? `${this.outerLabelUnit}` : \"\"; return { fillStyle: style.backgroundColor, label: item.label, value, unit }; }); renderLegend(this.legendDiv, legendItems); } catch (error) { console.debug(\"[obc-donut-chart] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <canvas></canvas> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(donut_chart_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }"
3019
3019
  }
3020
3020
  ],
3021
3021
  "exports": [
@@ -3057,7 +3057,7 @@
3057
3057
  {
3058
3058
  "kind": "variable",
3059
3059
  "name": "ObcPieChart",
3060
- "default": "class ObcPieChart extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.colors = []; this.priority = Priority.regular; this.showOuterLabels = false; this.showUnit = false; this.sunburst = false; this.outerLabelUnit = \"%\"; this.outerLabelMaxLength = 0; this.outerLabelDecimalPlaces = 0; this.legend = false; this.showDebugOverlay = false; this.fixedHeight = 320; this.total = 0; this.formattedLabels = []; this.activeSegmentIndex = null; this.handleCanvasClick = (event) => { if (!this.chart || !this.sunburst) return; const elements = this.chart.getElementsAtEventForMode(event, \"nearest\", { intersect: true }, false); if (elements.length > 0) { const clickedIndex = elements[0].index; const newIndex = this.activeSegmentIndex === clickedIndex ? null : clickedIndex; this.activeSegmentIndex = newIndex; this.chart.destroy(); this.createChart(); } }; } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Get layout configuration for canvas calculation */ getLayoutConfig() { return { unit: this.outerLabelUnit, showUnit: this.showUnit, outerLabelMaxLength: this.outerLabelMaxLength, decimalPlaces: this.outerLabelDecimalPlaces, data: this.data, denominator: this.total > 0 ? this.total : 1 }; } willUpdate(changed) { if (changed.has(\"data\")) this.total = calculateSumTotal(this.data); } updated(changed) { super.updated(changed); if (this.hasAnyChanged(changed, PIE_WATCHED_PROP_NAMES)) { if (this.hasAnyChanged(changed, PIE_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.removeSunburstInteraction(); this.createChart(); if (this.sunburst) this.setupSunburstInteraction(); } else this.updateChart(); } } firstUpdated() { this.createChart(); this.themeObserver = observeThemeChanges(() => this.updateChartColors()); this.setupResizeObserver(); if (this.sunburst) this.setupSunburstInteraction(); } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); this.removeSunburstInteraction(); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } setupSunburstInteraction() { if (!this.canvasEl) return; this.canvasEl.addEventListener(\"click\", this.handleCanvasClick); this.canvasEl.style.cursor = \"pointer\"; } removeSunburstInteraction() { if (!this.canvasEl) return; this.canvasEl.removeEventListener(\"click\", this.handleCanvasClick); this.canvasEl.style.cursor = \"\"; } prepareChartData() { const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label); const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const segmentColors = values.map((_, index) => chartColors[index % chartColors.length]); if (!this.sunburst) return { values, labels, colors: segmentColors, sunburstValues: [], sunburstColors: [], sunburstLabels: [] }; const sunburstValues = []; const sunburstColors = []; const sunburstLabels = []; this.data.forEach((segment, parentIndex) => { const children = segment.children || []; if (children.length > 0) children.forEach((child, childIndex) => { sunburstValues.push(child.value); sunburstLabels.push(child.label); const colorIndex = (parentIndex + childIndex + 1) % chartColors.length; sunburstColors.push(chartColors[colorIndex]); }); else { sunburstValues.push(segment.value); sunburstLabels.push(\"\"); sunburstColors.push(\"transparent\"); } }); return { values, labels, colors: segmentColors, sunburstValues, sunburstColors, sunburstLabels }; } /** * Get Chart.js options using centralized fixed height layout calculation */ getChartOptions() { const radiusPercentage = this.sunburst && this.activeSegmentIndex !== null ? 75 : 100; const dimensions = calculateFixedHeightChartLayout({ fixedHeight: this.fixedHeight, isHalfMode: false, showOuterLabels: this.showOuterLabels, canvasEl: this.canvasEl, layoutConfig: this.getLayoutConfig(), host: this }); this.lastDimensions = dimensions; this.formattedLabels = dimensions.formattedLabels; this.style.setProperty(\"--chart-width\", `${dimensions.calculatedWidth}px`); this.style.setProperty(\"--chart-height\", `${dimensions.actualHeight}px`); const dynamicPadding = dimensions.isTooSmall ? { top: 0, right: 0, bottom: 0, left: 0 } : { top: dimensions.topPadding, right: dimensions.rightPadding, bottom: dimensions.bottomPadding, left: dimensions.leftPadding }; return { responsive: false, maintainAspectRatio: false, devicePixelRatio: window.devicePixelRatio, radius: `${radiusPercentage}%`, layout: { padding: dynamicPadding ?? PIE_DIMENSIONS.CANVAS_PADDING }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !dimensions.isTooSmall, filter: (tooltipItem) => { const dataset = tooltipItem.dataset; return (Array.isArray(dataset.backgroundColor) ? dataset.backgroundColor[tooltipItem.dataIndex] : dataset.backgroundColor) !== \"transparent\"; }, callbacks: { title: () => \"\", label: (context) => { const label = context.label ?? \"\"; const value = context.parsed; const denominator = this.total > 0 ? this.total : 1; const isPercentage = this.outerLabelUnit === \"%\"; const numericValue = formatChartNumber(value, denominator, isPercentage, this.outerLabelDecimalPlaces); return this.showUnit && this.outerLabelUnit ? `${label} ${numericValue}${this.outerLabelUnit}` : `${label} ${numericValue}`; } } } }, animation: { animateRotate: false, animateScale: false } }; } createOuterLabelPiePlugin() { return createArcOuterLabelPlugin(this, { formattedLabels: this.formattedLabels, hideIndex: this.sunburst ? this.activeSegmentIndex : null }); } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; const { values, labels, colors, sunburstValues, sunburstColors, sunburstLabels } = this.prepareChartData(); const datasets = [{ data: values, backgroundColor: colors, borderWidth: 1, borderColor: getCssVariableValue(this, PIE_DIMENSIONS.GAP_AND_BORDER_COLOR) }]; const options = this.getChartOptions(); if (this.lastDimensions) { this.canvasEl.width = this.lastDimensions.calculatedWidth; this.canvasEl.height = this.lastDimensions.actualHeight; } const isTooSmall = this.lastDimensions?.isTooSmall ?? false; this.chart = new Chart(ctx, { type: \"pie\", data: { labels, datasets }, options, plugins: [...this.showOuterLabels && !isTooSmall ? [this.createOuterLabelPiePlugin()] : [], this.sunburst && sunburstValues.length > 0 ? this.createSunburstPlugin(sunburstValues, sunburstColors, sunburstLabels) : { id: \"sunburst\" }].filter((p) => p !== void 0) }); requestAnimationFrame(() => this.updateLegend()); } createSunburstPlugin(_outerValues, sunburstColors, sunburstLabels) { return { id: \"sunburst\", afterDatasetsDraw: (chart) => { const meta = chart.getDatasetMeta(0); if (!meta?.data.length) return; if (this.activeSegmentIndex === null) return; const { ctx } = chart; const centerX = chart.chartArea.left + chart.chartArea.width / 2; const centerY = chart.chartArea.top + chart.chartArea.height / 2; ctx.save(); const innerPieRadius = meta.data[0].outerRadius; const originalFullRadius = innerPieRadius / .75; const isTooSmall = (this.canvasEl?.clientHeight ?? 0) < PIE_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const outerRingInnerRadius = innerPieRadius + (isTooSmall ? 2 : 8); const outerRingOuterRadius = isTooSmall ? originalFullRadius : originalFullRadius; const fontFamily = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontFamily); const fontWeight = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontWeightVar); const fontSize = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontSizeVar); const fontColor = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontColorVar); ctx.font = `${fontWeight} ${fontSize} ${fontFamily}`; ctx.fillStyle = fontColor; ctx.textBaseline = \"middle\"; let sunburstDataIndex = 0; this.data.forEach((segment, segmentIndex) => { const children = segment.children || []; if (children.length > 0) { if (segmentIndex === this.activeSegmentIndex) { const childrenTotal = children.reduce((sum, child) => sum + child.value, 0); let startAngle = 0; const parentArc = meta.data[segmentIndex]; const parentStart = parentArc.startAngle; const parentAngleRange = parentArc.endAngle - parentStart; children.forEach((child) => { const childValue = child.value; const childRatio = childValue / childrenTotal; const childAngleRange = parentAngleRange * childRatio; const childStartAngle = parentStart + startAngle; const childEndAngle = childStartAngle + childAngleRange; ctx.fillStyle = sunburstColors[sunburstDataIndex] || \"transparent\"; ctx.beginPath(); ctx.arc(centerX, centerY, outerRingOuterRadius, childStartAngle, childEndAngle); ctx.arc(centerX, centerY, outerRingInnerRadius, childEndAngle, childStartAngle, true); ctx.closePath(); ctx.fill(); if (this.showOuterLabels && sunburstLabels[sunburstDataIndex]) { const middleAngle = (childStartAngle + childEndAngle) / 2; const labelRadius = outerRingOuterRadius + OUTER_LABEL_CONFIG.labelGap; const x = centerX + Math.cos(middleAngle) * labelRadius; const y = centerY + Math.sin(middleAngle) * labelRadius; const alignLeft = Math.cos(middleAngle) >= 0; ctx.fillStyle = fontColor; ctx.textAlign = alignLeft ? \"left\" : \"right\"; const textX = alignLeft ? x + OUTER_LABEL_CONFIG.labelGap : x - OUTER_LABEL_CONFIG.labelGap; const total = this.total > 0 ? this.total : 1; const valueText = formatSingleLabel(childValue, total, { unit: this.outerLabelUnit, showUnit: this.showUnit, decimalPlaces: this.outerLabelDecimalPlaces, maxLength: this.outerLabelMaxLength }); ctx.fillText(valueText, textX, y); } startAngle += childAngleRange; sunburstDataIndex++; }); } else sunburstDataIndex += children.length; } else sunburstDataIndex++; }); ctx.restore(); } }; } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; if (this.lastDimensions) this.chart.resize(this.lastDimensions.calculatedWidth, this.lastDimensions.actualHeight); this.chart.update(); requestAnimationFrame(() => this.updateLegend()); } /** * Update only chart colors without recreating the entire chart * Used by theme observer for efficient theme changes */ updateChartColors() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { colors, sunburstColors } = this.prepareChartData(); if (this.chart.data.datasets[0]) this.chart.data.datasets[0].backgroundColor = colors; if (this.sunburst && this.chart.data.datasets[1]) this.chart.data.datasets[1].backgroundColor = sunburstColors; this.chart.update(\"none\"); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; const meta = this.chart.getDatasetMeta(0); if (!meta || !meta.controller) return; if (!this.data || this.data.length === 0) { this.legendDiv.innerHTML = \"\"; return; } const denominator = this.total > 0 ? this.total : 1; const isPercentage = this.outerLabelUnit === \"%\"; try { const legendItems = this.data.map((item, i) => { const style = meta.controller.getStyle(i, false); const numericValue = formatChartNumber(item.value, denominator, isPercentage, this.outerLabelDecimalPlaces); const showUnit = this.showUnit && this.outerLabelUnit; const value = `${numericValue}`; const unit = showUnit ? `${this.outerLabelUnit}` : \"\"; return { fillStyle: style.backgroundColor, label: item.label, value, unit }; }); const legendHTML = generateLegendHTML(legendItems); this.legendDiv.innerHTML = legendHTML; } catch (error) { console.debug(\"[obc-pie-chart] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <canvas></canvas> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(pie_chart_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }"
3060
+ "default": "class ObcPieChart extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.colors = []; this.priority = Priority.regular; this.showOuterLabels = false; this.showUnit = false; this.sunburst = false; this.outerLabelUnit = \"%\"; this.outerLabelMaxLength = 0; this.outerLabelDecimalPlaces = 0; this.legend = false; this.showDebugOverlay = false; this.fixedHeight = 320; this.total = 0; this.formattedLabels = []; this.activeSegmentIndex = null; this.handleCanvasClick = (event) => { if (!this.chart || !this.sunburst) return; const elements = this.chart.getElementsAtEventForMode(event, \"nearest\", { intersect: true }, false); if (elements.length > 0) { const clickedIndex = elements[0].index; const newIndex = this.activeSegmentIndex === clickedIndex ? null : clickedIndex; this.activeSegmentIndex = newIndex; this.chart.destroy(); this.createChart(); } }; } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Get layout configuration for canvas calculation */ getLayoutConfig() { return { unit: this.outerLabelUnit, showUnit: this.showUnit, outerLabelMaxLength: this.outerLabelMaxLength, decimalPlaces: this.outerLabelDecimalPlaces, data: this.data, denominator: this.total > 0 ? this.total : 1 }; } willUpdate(changed) { if (changed.has(\"data\")) this.total = calculateSumTotal(this.data); } updated(changed) { super.updated(changed); if (this.hasAnyChanged(changed, PIE_WATCHED_PROP_NAMES)) { if (this.hasAnyChanged(changed, PIE_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.removeSunburstInteraction(); this.createChart(); if (this.sunburst) this.setupSunburstInteraction(); } else this.updateChart(); } } firstUpdated() { this.createChart(); this.themeObserver = observeThemeChanges(() => this.updateChartColors()); this.setupResizeObserver(); if (this.sunburst) this.setupSunburstInteraction(); } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); this.removeSunburstInteraction(); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } setupSunburstInteraction() { if (!this.canvasEl) return; this.canvasEl.addEventListener(\"click\", this.handleCanvasClick); this.canvasEl.style.cursor = \"pointer\"; } removeSunburstInteraction() { if (!this.canvasEl) return; this.canvasEl.removeEventListener(\"click\", this.handleCanvasClick); this.canvasEl.style.cursor = \"\"; } prepareChartData() { const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label); const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const segmentColors = values.map((_, index) => chartColors[index % chartColors.length]); if (!this.sunburst) return { values, labels, colors: segmentColors, sunburstValues: [], sunburstColors: [], sunburstLabels: [] }; const sunburstValues = []; const sunburstColors = []; const sunburstLabels = []; this.data.forEach((segment, parentIndex) => { const children = segment.children || []; if (children.length > 0) children.forEach((child, childIndex) => { sunburstValues.push(child.value); sunburstLabels.push(child.label); const colorIndex = (parentIndex + childIndex + 1) % chartColors.length; sunburstColors.push(chartColors[colorIndex]); }); else { sunburstValues.push(segment.value); sunburstLabels.push(\"\"); sunburstColors.push(\"transparent\"); } }); return { values, labels, colors: segmentColors, sunburstValues, sunburstColors, sunburstLabels }; } /** * Get Chart.js options using centralized fixed height layout calculation */ getChartOptions() { const radiusPercentage = this.sunburst && this.activeSegmentIndex !== null ? 75 : 100; const dimensions = calculateFixedHeightChartLayout({ fixedHeight: this.fixedHeight, isHalfMode: false, showOuterLabels: this.showOuterLabels, canvasEl: this.canvasEl, layoutConfig: this.getLayoutConfig(), host: this }); this.lastDimensions = dimensions; this.formattedLabels = dimensions.formattedLabels; this.style.setProperty(\"--chart-width\", `${dimensions.calculatedWidth}px`); this.style.setProperty(\"--chart-height\", `${dimensions.actualHeight}px`); const dynamicPadding = dimensions.isTooSmall ? { top: 0, right: 0, bottom: 0, left: 0 } : { top: dimensions.topPadding, right: dimensions.rightPadding, bottom: dimensions.bottomPadding, left: dimensions.leftPadding }; return { responsive: false, maintainAspectRatio: false, devicePixelRatio: window.devicePixelRatio, radius: `${radiusPercentage}%`, layout: { padding: dynamicPadding ?? PIE_DIMENSIONS.CANVAS_PADDING }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !dimensions.isTooSmall, filter: (tooltipItem) => { const dataset = tooltipItem.dataset; return (Array.isArray(dataset.backgroundColor) ? dataset.backgroundColor[tooltipItem.dataIndex] : dataset.backgroundColor) !== \"transparent\"; }, callbacks: { title: () => \"\", label: (context) => { const label = context.label ?? \"\"; const value = context.parsed; const denominator = this.total > 0 ? this.total : 1; const isPercentage = this.outerLabelUnit === \"%\"; const numericValue = formatChartNumber(value, denominator, isPercentage, this.outerLabelDecimalPlaces); return this.showUnit && this.outerLabelUnit ? `${label} ${numericValue}${this.outerLabelUnit}` : `${label} ${numericValue}`; } } } }, animation: { animateRotate: false, animateScale: false } }; } createOuterLabelPiePlugin() { return createArcOuterLabelPlugin(this, { formattedLabels: this.formattedLabels, hideIndex: this.sunburst ? this.activeSegmentIndex : null }); } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; const { values, labels, colors, sunburstValues, sunburstColors, sunburstLabels } = this.prepareChartData(); const datasets = [{ data: values, backgroundColor: colors, borderWidth: 1, borderColor: getCssVariableValue(this, PIE_DIMENSIONS.GAP_AND_BORDER_COLOR) }]; const options = this.getChartOptions(); if (this.lastDimensions) { this.canvasEl.width = this.lastDimensions.calculatedWidth; this.canvasEl.height = this.lastDimensions.actualHeight; } const isTooSmall = this.lastDimensions?.isTooSmall ?? false; this.chart = new Chart(ctx, { type: \"pie\", data: { labels, datasets }, options, plugins: [...this.showOuterLabels && !isTooSmall ? [this.createOuterLabelPiePlugin()] : [], this.sunburst && sunburstValues.length > 0 ? this.createSunburstPlugin(sunburstValues, sunburstColors, sunburstLabels) : { id: \"sunburst\" }].filter((p) => p !== void 0) }); requestAnimationFrame(() => this.updateLegend()); } createSunburstPlugin(_outerValues, sunburstColors, sunburstLabels) { return { id: \"sunburst\", afterDatasetsDraw: (chart) => { const meta = chart.getDatasetMeta(0); if (!meta?.data.length) return; if (this.activeSegmentIndex === null) return; const { ctx } = chart; const centerX = chart.chartArea.left + chart.chartArea.width / 2; const centerY = chart.chartArea.top + chart.chartArea.height / 2; ctx.save(); const innerPieRadius = meta.data[0].outerRadius; const originalFullRadius = innerPieRadius / .75; const isTooSmall = (this.canvasEl?.clientHeight ?? 0) < PIE_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const outerRingInnerRadius = innerPieRadius + (isTooSmall ? 2 : 8); const outerRingOuterRadius = isTooSmall ? originalFullRadius : originalFullRadius; const fontFamily = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontFamily); const fontWeight = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontWeightVar); const fontSize = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontSizeVar); const fontColor = getCssVariableValue(this, OUTER_LABEL_CONFIG.fontColorVar); ctx.font = `${fontWeight} ${fontSize} ${fontFamily}`; ctx.fillStyle = fontColor; ctx.textBaseline = \"middle\"; let sunburstDataIndex = 0; this.data.forEach((segment, segmentIndex) => { const children = segment.children || []; if (children.length > 0) { if (segmentIndex === this.activeSegmentIndex) { const childrenTotal = children.reduce((sum, child) => sum + child.value, 0); let startAngle = 0; const parentArc = meta.data[segmentIndex]; const parentStart = parentArc.startAngle; const parentAngleRange = parentArc.endAngle - parentStart; children.forEach((child) => { const childValue = child.value; const childRatio = childValue / childrenTotal; const childAngleRange = parentAngleRange * childRatio; const childStartAngle = parentStart + startAngle; const childEndAngle = childStartAngle + childAngleRange; ctx.fillStyle = sunburstColors[sunburstDataIndex] || \"transparent\"; ctx.beginPath(); ctx.arc(centerX, centerY, outerRingOuterRadius, childStartAngle, childEndAngle); ctx.arc(centerX, centerY, outerRingInnerRadius, childEndAngle, childStartAngle, true); ctx.closePath(); ctx.fill(); if (this.showOuterLabels && sunburstLabels[sunburstDataIndex]) { const middleAngle = (childStartAngle + childEndAngle) / 2; const labelRadius = outerRingOuterRadius + OUTER_LABEL_CONFIG.labelGap; const x = centerX + Math.cos(middleAngle) * labelRadius; const y = centerY + Math.sin(middleAngle) * labelRadius; const alignLeft = Math.cos(middleAngle) >= 0; ctx.fillStyle = fontColor; ctx.textAlign = alignLeft ? \"left\" : \"right\"; const textX = alignLeft ? x + OUTER_LABEL_CONFIG.labelGap : x - OUTER_LABEL_CONFIG.labelGap; const total = this.total > 0 ? this.total : 1; const valueText = formatSingleLabel(childValue, total, { unit: this.outerLabelUnit, showUnit: this.showUnit, decimalPlaces: this.outerLabelDecimalPlaces, maxLength: this.outerLabelMaxLength }); ctx.fillText(valueText, textX, y); } startAngle += childAngleRange; sunburstDataIndex++; }); } else sunburstDataIndex += children.length; } else sunburstDataIndex++; }); ctx.restore(); } }; } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; if (this.lastDimensions) this.chart.resize(this.lastDimensions.calculatedWidth, this.lastDimensions.actualHeight); this.chart.update(); requestAnimationFrame(() => this.updateLegend()); } /** * Update only chart colors without recreating the entire chart * Used by theme observer for efficient theme changes */ updateChartColors() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { colors, sunburstColors } = this.prepareChartData(); if (this.chart.data.datasets[0]) this.chart.data.datasets[0].backgroundColor = colors; if (this.sunburst && this.chart.data.datasets[1]) this.chart.data.datasets[1].backgroundColor = sunburstColors; this.chart.update(\"none\"); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; const meta = this.chart.getDatasetMeta(0); if (!meta || !meta.controller) return; if (!this.data || this.data.length === 0) { renderLegend(this.legendDiv, []); return; } const denominator = this.total > 0 ? this.total : 1; const isPercentage = this.outerLabelUnit === \"%\"; try { const legendItems = this.data.map((item, i) => { const style = meta.controller.getStyle(i, false); const numericValue = formatChartNumber(item.value, denominator, isPercentage, this.outerLabelDecimalPlaces); const showUnit = this.showUnit && this.outerLabelUnit; const value = `${numericValue}`; const unit = showUnit ? `${this.outerLabelUnit}` : \"\"; return { fillStyle: style.backgroundColor, label: item.label, value, unit }; }); renderLegend(this.legendDiv, legendItems); } catch (error) { console.debug(\"[obc-pie-chart] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <canvas></canvas> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(pie_chart_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }"
3061
3061
  }
3062
3062
  ],
3063
3063
  "exports": [
@@ -3078,7 +3078,7 @@
3078
3078
  {
3079
3079
  "kind": "variable",
3080
3080
  "name": "ObcPolarChart",
3081
- "default": "class ObcPolarChart extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.colors = []; this.centerFirstSector = false; this.priority = Priority.regular; this.monochrome = false; this.discreteColorStops = false; this.showSectorLabels = false; this.showUnit = false; this.showOuterLabels = false; this.outerLabelUnit = \"°\"; this.outerLabelMaxLength = 0; this.outerLabelDecimalPlaces = 0; this.fixedHeight = 320; this.legend = false; this.showDebugOverlay = false; this.formattedLabels = []; this.calculatedChartDiameter = CHART_DIMENSIONS.CHART_WIDTH; } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } updated(changed) { super.updated(changed); if (this.hasAnyChanged(changed, POLAR_WATCHED_PROP_NAMES)) { if (this.hasAnyChanged(changed, POLAR_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } } firstUpdated() { this.createChart(); this.themeObserver = observeThemeChanges(() => this.updateChart()); this.setupResizeObserver(); } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } prepareChartData() { const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label); const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const segmentColors = this.discreteColorStops ? values.map(() => \"transparent\") : values.map((_, index) => this.monochrome ? chartColors[0] : chartColors[index % chartColors.length]); const numSectors = this.data.length; return { values, labels, colors: segmentColors, chartColors, displayLabels: this.showSectorLabels ? labels : Array.from({ length: numSectors }, (_, i) => { return `${i * 360 / numSectors}`; }) }; } getLayoutConfig() { return { unit: this.outerLabelUnit, showUnit: this.showUnit, outerLabelMaxLength: this.outerLabelMaxLength, decimalPlaces: this.outerLabelDecimalPlaces, data: this.showSectorLabels ? this.data : Array.from({ length: this.data.length }, (_, i) => ({ label: \"\", value: i * 360 / this.data.length })), denominator: this.showSectorLabels ? 1 : 360 }; } getChartOptions() { const dimensions = calculateFixedHeightChartLayout({ fixedHeight: this.fixedHeight, isHalfMode: false, showOuterLabels: this.showOuterLabels, canvasEl: this.canvasEl, layoutConfig: this.getLayoutConfig(), host: this }); this.lastDimensions = dimensions; this.calculatedChartDiameter = dimensions.chartDiameter; this.formattedLabels = dimensions.formattedLabels; this.style.setProperty(\"--chart-width\", `${dimensions.calculatedWidth}px`); this.style.setProperty(\"--chart-height\", `${dimensions.actualHeight}px`); const dynamicPadding = dimensions.isTooSmall ? { top: 0, right: 0, bottom: 0, left: 0 } : { top: dimensions.topPadding, right: dimensions.rightPadding, bottom: dimensions.bottomPadding, left: dimensions.leftPadding }; const chartColors = getChartColorsOrDefault(this, this.colors, CHART_SECTOR_DEFAULT_COLORS); const numTicks = this.discreteColorStops ? chartColors.length + 1 : 6; const maxValue = Math.max(...this.data.map((d) => d.value), 100); const anglePerSector = 360 / this.data.length; const startAngle = this.centerFirstSector ? 0 : -anglePerSector / 2; return { responsive: false, maintainAspectRatio: false, devicePixelRatio: window.devicePixelRatio, layout: { padding: dynamicPadding ?? POLAR_BAR_DIMENSIONS.CANVAS_PADDING }, scales: { r: { startAngle, angleLines: { display: true, color: getCssVariableValue(this, POLAR_BAR_DIMENSIONS.GAP_AND_BORDER_COLOR), lineWidth: 1 }, grid: { display: true, color: getCssVariableValue(this, POLAR_BAR_DIMENSIONS.GAP_AND_BORDER_COLOR), lineWidth: 1 }, pointLabels: { display: false }, ticks: { display: false, stepSize: maxValue / (numTicks - 1), count: numTicks }, max: maxValue } }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !dimensions.isTooSmall, callbacks: { title: () => \"\", label: (context) => { const dataIndex = context.dataIndex; const data = this.data?.[dataIndex]; return `${data?.label ?? \"\"} ${typeof data?.value === \"number\" ? data.value : Number(data?.value)}`; } } } }, animation: false }; } createDiscreteColorPlugin() { return { id: \"discreteColors\", beforeDatasetsDraw: (chart) => { if (!this.discreteColorStops) return; const { ctx, scales } = chart; const scale = scales.r; if (!scale) return; const centerX = scale.xCenter; const centerY = scale.yCenter; const maxRadius = this.calculatedChartDiameter / 2; const numSectors = this.data.length; const anglePerSector = Math.PI * 2 / numSectors; const rotationOffset = this.centerFirstSector ? 0 : -anglePerSector / 2; const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const numBands = chartColors.length; const maxValue = Math.max(...this.data.map((d) => d.value), 100); const colorStops = chartColors.reverse().map((color, index) => ({ threshold: (index + 1) / numBands * maxValue, color })); ctx.save(); this.data.forEach((dataPoint, sectorIndex) => { const sectorValue = dataPoint.value; const startAngle = sectorIndex * anglePerSector + rotationOffset - Math.PI / 2; const endAngle = startAngle + anglePerSector; let previousRadius = 0; colorStops.forEach((stop) => { const thresholdRadius = stop.threshold / maxValue * maxRadius; const sectorRadiusLimit = sectorValue / maxValue * maxRadius; let drawRadius; if (sectorRadiusLimit <= thresholdRadius) drawRadius = sectorRadiusLimit; else drawRadius = thresholdRadius; if (drawRadius > previousRadius) { ctx.fillStyle = stop.color; ctx.beginPath(); ctx.arc(centerX, centerY, drawRadius, startAngle, endAngle); if (previousRadius > 0) ctx.arc(centerX, centerY, previousRadius, endAngle, startAngle, true); else ctx.lineTo(centerX, centerY); ctx.closePath(); ctx.fill(); } previousRadius = drawRadius; if (sectorRadiusLimit <= thresholdRadius) return; }); }); ctx.restore(); } }; } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; const { values, colors, displayLabels } = this.prepareChartData(); const plugins = []; if (this.discreteColorStops) plugins.push(this.createDiscreteColorPlugin()); const chartOptions = this.getChartOptions(); if (this.lastDimensions) { this.canvasEl.width = this.lastDimensions.calculatedWidth; this.canvasEl.height = this.lastDimensions.actualHeight; } if (this.showOuterLabels && this.formattedLabels.length > 0) { const numSectors = values.length; const anglePerSector = Math.PI * 2 / (numSectors || 1); const rotationOffset = this.centerFirstSector ? 0 : -anglePerSector / 2; plugins.push(createArcOuterLabelPlugin(this, { formattedLabels: this.formattedLabels.slice(0, numSectors), rotationOffset, chartDiameter: this.calculatedChartDiameter, type: \"polar\" })); } this.chart = new Chart(ctx, { type: \"polarArea\", data: { labels: displayLabels, datasets: [{ data: values, backgroundColor: colors, borderWidth: 1, borderColor: getCssVariableValue(this, POLAR_BAR_DIMENSIONS.GAP_AND_BORDER_COLOR) }] }, options: chartOptions, plugins }); requestAnimationFrame(() => this.updateLegend()); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { values, colors, displayLabels } = this.prepareChartData(); this.chart.data.labels = displayLabels; if (this.chart.data.datasets[0]) { this.chart.data.datasets[0].data = values; this.chart.data.datasets[0].backgroundColor = colors; } const latestOptions = this.getChartOptions(); if (this.chart.options) Object.assign(this.chart.options, latestOptions); if (this.lastDimensions) this.chart.resize(this.lastDimensions.calculatedWidth, this.lastDimensions.actualHeight); this.chart.update(); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; const meta = this.chart.getDatasetMeta(0); if (!meta || !meta.controller) return; if (!this.data || this.data.length === 0) { this.legendDiv.innerHTML = \"\"; return; } const denominator = this.showSectorLabels ? 1 : 360; const isPercentage = this.outerLabelUnit === \"%\"; try { const legendItems = this.data.map((item, i) => { const style = meta.controller.getStyle(i, false); let label; let valueToFormat; if (this.showSectorLabels) { label = item.label; valueToFormat = item.value; } else { label = `${i * 360 / this.data.length}${this.outerLabelUnit}`; valueToFormat = item.value; } const numericValue = formatChartNumber(valueToFormat, denominator, isPercentage, this.outerLabelDecimalPlaces); const showUnit = this.showUnit && this.outerLabelUnit; const value = `${numericValue}`; const unit = showUnit && this.showSectorLabels ? `${this.outerLabelUnit}` : \"\"; return { fillStyle: style.backgroundColor, label, value, unit }; }); const legendHTML = generateLegendHTML(legendItems); this.legendDiv.innerHTML = legendHTML; } catch (error) { console.debug(\"[obc-polar-chart] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <canvas></canvas> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(polar_chart_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }"
3081
+ "default": "class ObcPolarChart extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.colors = []; this.centerFirstSector = false; this.priority = Priority.regular; this.monochrome = false; this.discreteColorStops = false; this.showSectorLabels = false; this.showUnit = false; this.showOuterLabels = false; this.outerLabelUnit = \"°\"; this.outerLabelMaxLength = 0; this.outerLabelDecimalPlaces = 0; this.fixedHeight = 320; this.legend = false; this.showDebugOverlay = false; this.formattedLabels = []; this.calculatedChartDiameter = CHART_DIMENSIONS.CHART_WIDTH; } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } updated(changed) { super.updated(changed); if (this.hasAnyChanged(changed, POLAR_WATCHED_PROP_NAMES)) { if (this.hasAnyChanged(changed, POLAR_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } } firstUpdated() { this.createChart(); this.themeObserver = observeThemeChanges(() => this.updateChart()); this.setupResizeObserver(); } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } prepareChartData() { const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label); const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const segmentColors = this.discreteColorStops ? values.map(() => \"transparent\") : values.map((_, index) => this.monochrome ? chartColors[0] : chartColors[index % chartColors.length]); const numSectors = this.data.length; return { values, labels, colors: segmentColors, chartColors, displayLabels: this.showSectorLabels ? labels : Array.from({ length: numSectors }, (_, i) => { return `${i * 360 / numSectors}`; }) }; } getLayoutConfig() { return { unit: this.outerLabelUnit, showUnit: this.showUnit, outerLabelMaxLength: this.outerLabelMaxLength, decimalPlaces: this.outerLabelDecimalPlaces, data: this.showSectorLabels ? this.data : Array.from({ length: this.data.length }, (_, i) => ({ label: \"\", value: i * 360 / this.data.length })), denominator: this.showSectorLabels ? 1 : 360 }; } getChartOptions() { const dimensions = calculateFixedHeightChartLayout({ fixedHeight: this.fixedHeight, isHalfMode: false, showOuterLabels: this.showOuterLabels, canvasEl: this.canvasEl, layoutConfig: this.getLayoutConfig(), host: this }); this.lastDimensions = dimensions; this.calculatedChartDiameter = dimensions.chartDiameter; this.formattedLabels = dimensions.formattedLabels; this.style.setProperty(\"--chart-width\", `${dimensions.calculatedWidth}px`); this.style.setProperty(\"--chart-height\", `${dimensions.actualHeight}px`); const dynamicPadding = dimensions.isTooSmall ? { top: 0, right: 0, bottom: 0, left: 0 } : { top: dimensions.topPadding, right: dimensions.rightPadding, bottom: dimensions.bottomPadding, left: dimensions.leftPadding }; const chartColors = getChartColorsOrDefault(this, this.colors, CHART_SECTOR_DEFAULT_COLORS); const numTicks = this.discreteColorStops ? chartColors.length + 1 : 6; const maxValue = Math.max(...this.data.map((d) => d.value), 100); const anglePerSector = 360 / this.data.length; const startAngle = this.centerFirstSector ? 0 : -anglePerSector / 2; return { responsive: false, maintainAspectRatio: false, devicePixelRatio: window.devicePixelRatio, layout: { padding: dynamicPadding ?? POLAR_BAR_DIMENSIONS.CANVAS_PADDING }, scales: { r: { startAngle, angleLines: { display: true, color: getCssVariableValue(this, POLAR_BAR_DIMENSIONS.GAP_AND_BORDER_COLOR), lineWidth: 1 }, grid: { display: true, color: getCssVariableValue(this, POLAR_BAR_DIMENSIONS.GAP_AND_BORDER_COLOR), lineWidth: 1 }, pointLabels: { display: false }, ticks: { display: false, stepSize: maxValue / (numTicks - 1), count: numTicks }, max: maxValue } }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !dimensions.isTooSmall, callbacks: { title: () => \"\", label: (context) => { const dataIndex = context.dataIndex; const data = this.data?.[dataIndex]; return `${data?.label ?? \"\"} ${typeof data?.value === \"number\" ? data.value : Number(data?.value)}`; } } } }, animation: false }; } createDiscreteColorPlugin() { return { id: \"discreteColors\", beforeDatasetsDraw: (chart) => { if (!this.discreteColorStops) return; const { ctx, scales } = chart; const scale = scales.r; if (!scale) return; const centerX = scale.xCenter; const centerY = scale.yCenter; const maxRadius = this.calculatedChartDiameter / 2; const numSectors = this.data.length; const anglePerSector = Math.PI * 2 / numSectors; const rotationOffset = this.centerFirstSector ? 0 : -anglePerSector / 2; const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const numBands = chartColors.length; const maxValue = Math.max(...this.data.map((d) => d.value), 100); const colorStops = chartColors.reverse().map((color, index) => ({ threshold: (index + 1) / numBands * maxValue, color })); ctx.save(); this.data.forEach((dataPoint, sectorIndex) => { const sectorValue = dataPoint.value; const startAngle = sectorIndex * anglePerSector + rotationOffset - Math.PI / 2; const endAngle = startAngle + anglePerSector; let previousRadius = 0; colorStops.forEach((stop) => { const thresholdRadius = stop.threshold / maxValue * maxRadius; const sectorRadiusLimit = sectorValue / maxValue * maxRadius; let drawRadius; if (sectorRadiusLimit <= thresholdRadius) drawRadius = sectorRadiusLimit; else drawRadius = thresholdRadius; if (drawRadius > previousRadius) { ctx.fillStyle = stop.color; ctx.beginPath(); ctx.arc(centerX, centerY, drawRadius, startAngle, endAngle); if (previousRadius > 0) ctx.arc(centerX, centerY, previousRadius, endAngle, startAngle, true); else ctx.lineTo(centerX, centerY); ctx.closePath(); ctx.fill(); } previousRadius = drawRadius; if (sectorRadiusLimit <= thresholdRadius) return; }); }); ctx.restore(); } }; } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; const { values, colors, displayLabels } = this.prepareChartData(); const plugins = []; if (this.discreteColorStops) plugins.push(this.createDiscreteColorPlugin()); const chartOptions = this.getChartOptions(); if (this.lastDimensions) { this.canvasEl.width = this.lastDimensions.calculatedWidth; this.canvasEl.height = this.lastDimensions.actualHeight; } if (this.showOuterLabels && this.formattedLabels.length > 0) { const numSectors = values.length; const anglePerSector = Math.PI * 2 / (numSectors || 1); const rotationOffset = this.centerFirstSector ? 0 : -anglePerSector / 2; plugins.push(createArcOuterLabelPlugin(this, { formattedLabels: this.formattedLabels.slice(0, numSectors), rotationOffset, chartDiameter: this.calculatedChartDiameter, type: \"polar\" })); } this.chart = new Chart(ctx, { type: \"polarArea\", data: { labels: displayLabels, datasets: [{ data: values, backgroundColor: colors, borderWidth: 1, borderColor: getCssVariableValue(this, POLAR_BAR_DIMENSIONS.GAP_AND_BORDER_COLOR) }] }, options: chartOptions, plugins }); requestAnimationFrame(() => this.updateLegend()); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { values, colors, displayLabels } = this.prepareChartData(); this.chart.data.labels = displayLabels; if (this.chart.data.datasets[0]) { this.chart.data.datasets[0].data = values; this.chart.data.datasets[0].backgroundColor = colors; } const latestOptions = this.getChartOptions(); if (this.chart.options) Object.assign(this.chart.options, latestOptions); if (this.lastDimensions) this.chart.resize(this.lastDimensions.calculatedWidth, this.lastDimensions.actualHeight); this.chart.update(); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; const meta = this.chart.getDatasetMeta(0); if (!meta || !meta.controller) return; if (!this.data || this.data.length === 0) { renderLegend(this.legendDiv, []); return; } const denominator = this.showSectorLabels ? 1 : 360; const isPercentage = this.outerLabelUnit === \"%\"; try { const legendItems = this.data.map((item, i) => { const style = meta.controller.getStyle(i, false); let label; let valueToFormat; if (this.showSectorLabels) { label = item.label; valueToFormat = item.value; } else { label = `${i * 360 / this.data.length}${this.outerLabelUnit}`; valueToFormat = item.value; } const numericValue = formatChartNumber(valueToFormat, denominator, isPercentage, this.outerLabelDecimalPlaces); const showUnit = this.showUnit && this.outerLabelUnit; const value = `${numericValue}`; const unit = showUnit && this.showSectorLabels ? `${this.outerLabelUnit}` : \"\"; return { fillStyle: style.backgroundColor, label, value, unit }; }); renderLegend(this.legendDiv, legendItems); } catch (error) { console.debug(\"[obc-polar-chart] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <canvas></canvas> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(polar_chart_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }"
3082
3082
  }
3083
3083
  ],
3084
3084
  "exports": [
@@ -3099,7 +3099,7 @@
3099
3099
  {
3100
3100
  "kind": "variable",
3101
3101
  "name": "ObcRadialBarChart",
3102
- "default": "class ObcRadialBarChart extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.colors = []; this.priority = Priority.regular; this.max = 100; this.circumference = 270; this.legend = false; this.showDebugOverlay = false; this.fixedHeight = 320; this.minRingThickness = 16; } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Calculate optimal cutout percentage and whether rings should use minimum thickness * based on available chart space and number of rings. * * Algorithm: * 1. Calculate total space needed for all rings at minRingThickness * 2. If enough space: use equal thickness and adjust cutout * 3. If not enough space with minCutout: reduce cutout to minimum * 4. If still not enough: rings must be thinner than minimum * * @param chartDiameter - Available chart diameter in pixels * @param isTooSmall - Whether chart is below MIN_HEIGHT_WITH_LABELS (affects border width) * @returns Object with calculated cutout percentage and flag for using minimum thickness */ calculateOptimalLayout(chartDiameter, isTooSmall) { const numRings = this.data.length; if (numRings === 0) return { cutout: RADIAL_BAR_DIMENSIONS.DEFAULT_MAX_CUTOUT_PERCENT, useMinThickness: false }; const effectiveSpacing = isTooSmall ? RADIAL_BAR_DIMENSIONS.SPACING / 2 : RADIAL_BAR_DIMENSIONS.SPACING; const totalSpacePerRing = this.minRingThickness + effectiveSpacing; const radius = chartDiameter / 2; const calculatedCutoutPercent = (radius - numRings * totalSpacePerRing) / radius * 100; if (calculatedCutoutPercent >= RADIAL_BAR_DIMENSIONS.MIN_CUTOUT_PERCENT) return { cutout: Math.min(calculatedCutoutPercent, RADIAL_BAR_DIMENSIONS.DEFAULT_MAX_CUTOUT_PERCENT), useMinThickness: true }; else if ((radius - radius * RADIAL_BAR_DIMENSIONS.MIN_CUTOUT_PERCENT / 100) / numRings >= totalSpacePerRing) return { cutout: RADIAL_BAR_DIMENSIONS.MIN_CUTOUT_PERCENT, useMinThickness: true }; else return { cutout: RADIAL_BAR_DIMENSIONS.MIN_CUTOUT_PERCENT, useMinThickness: false }; } updated(changed) { super.updated(changed); if (this.hasAnyChanged(changed, RADIAL_BAR_WATCHED_PROP_NAMES)) { if (this.hasAnyChanged(changed, RADIAL_BAR_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } } firstUpdated() { this.createChart(); this.themeObserver = observeThemeChanges(() => this.updateChart()); this.setupResizeObserver(); } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= RADIAL_BAR_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } prepareChartData() { const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const remainingColor = getCssVariableValue(this, RADIAL_BAR_DIMENSIONS.REMAINING_COLOR); const borderColor = getCssVariableValue(this, RADIAL_BAR_DIMENSIONS.GAP_AND_BORDER_COLOR); const effectiveSpacing = (this.canvasEl?.clientHeight ?? 0) < RADIAL_BAR_DIMENSIONS.MIN_HEIGHT_WITH_LABELS ? RADIAL_BAR_DIMENSIONS.SPACING / 2 : RADIAL_BAR_DIMENSIONS.SPACING; return { datasets: this.data.map((value, index) => { const remaining = Math.max(0, this.max - value); const color = chartColors[index % chartColors.length] ?? CHART_SECTOR_DEFAULT_COLORS[0]; return { data: [value, remaining], backgroundColor: [color, remainingColor], borderWidth: effectiveSpacing, borderColor, borderRadius: RADIAL_BAR_DIMENSIONS.BORDER_RADIUS, spacing: 0, weight: 1 }; }) }; } getChartOptions() { const rotation = 0; const dimensions = calculateFixedHeightChartLayout({ fixedHeight: this.fixedHeight, isHalfMode: false, showOuterLabels: false, canvasEl: this.canvasEl, layoutConfig: { data: [], denominator: 100 }, host: this }); this.lastDimensions = dimensions; this.style.setProperty(\"--chart-width\", `${dimensions.calculatedWidth}px`); this.style.setProperty(\"--chart-height\", `${dimensions.actualHeight}px`); const dynamicPadding = dimensions.isTooSmall ? 0 : RADIAL_BAR_DIMENSIONS.CANVAS_PADDING; const chartDiameter = dimensions.isTooSmall ? dimensions.actualHeight - dynamicPadding * 2 : RADIAL_BAR_DIMENSIONS.CHART_WIDTH; const { cutout: optimalCutout } = this.calculateOptimalLayout(chartDiameter, dimensions.isTooSmall); return { responsive: false, maintainAspectRatio: false, devicePixelRatio: window.devicePixelRatio, rotation, circumference: this.circumference, cutout: `${optimalCutout}%`, layout: { padding: { top: dynamicPadding, right: dynamicPadding, bottom: dynamicPadding, left: dynamicPadding } }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !dimensions.isTooSmall, filter: (tooltipItem) => tooltipItem.label !== \"Remaining\", callbacks: { title: () => \"\", label: (context) => { const datasetIndex = context.datasetIndex; if (context.dataIndex !== 0) return \"\"; return `${`Ring ${datasetIndex + 1}`} ${context.parsed}`; } } } }, animation: { animateRotate: false, animateScale: false } }; } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; const { datasets } = this.prepareChartData(); const options = this.getChartOptions(); if (this.lastDimensions) { this.canvasEl.width = this.lastDimensions.calculatedWidth; this.canvasEl.height = this.lastDimensions.actualHeight; } this.chart = new Chart(ctx, { type: \"doughnut\", data: { labels: this.data.map((_, i) => `Ring ${i + 1}`), datasets }, options }); requestAnimationFrame(() => this.updateLegend()); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { datasets } = this.prepareChartData(); this.chart.data.labels = this.data.map((_, i) => `Ring ${i + 1}`); this.chart.data.datasets = datasets; const newOptions = this.getChartOptions(); if (this.chart.options) Object.assign(this.chart.options, newOptions); if (this.lastDimensions) this.chart.resize(this.lastDimensions.calculatedWidth, this.lastDimensions.actualHeight); this.chart.update(); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; if (!this.data || this.data.length === 0) { this.legendDiv.innerHTML = \"\"; return; } try { const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const legendItems = this.data.map((value, i) => { return { fillStyle: chartColors[i % chartColors.length] ?? (this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS[0] : CHART_SECTOR_DEFAULT_COLORS[0]), label: `Ring ${i + 1}`, value: value.toString(), unit: \"\" }; }); const legendHTML = generateLegendHTML(legendItems); this.legendDiv.innerHTML = legendHTML; } catch (error) { console.debug(\"[obc-radial-bar-chart] updateLegend: error generating legend HTML\", error); } } render() { const wrapperClasses = { wrapper: true, debug: this.showDebugOverlay }; return html` <div class=${classMap(wrapperClasses)}> <canvas></canvas> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(radial_bar_chart_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }"
3102
+ "default": "class ObcRadialBarChart extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.colors = []; this.priority = Priority.regular; this.max = 100; this.circumference = 270; this.legend = false; this.showDebugOverlay = false; this.fixedHeight = 320; this.minRingThickness = 16; } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Calculate optimal cutout percentage and whether rings should use minimum thickness * based on available chart space and number of rings. * * Algorithm: * 1. Calculate total space needed for all rings at minRingThickness * 2. If enough space: use equal thickness and adjust cutout * 3. If not enough space with minCutout: reduce cutout to minimum * 4. If still not enough: rings must be thinner than minimum * * @param chartDiameter - Available chart diameter in pixels * @param isTooSmall - Whether chart is below MIN_HEIGHT_WITH_LABELS (affects border width) * @returns Object with calculated cutout percentage and flag for using minimum thickness */ calculateOptimalLayout(chartDiameter, isTooSmall) { const numRings = this.data.length; if (numRings === 0) return { cutout: RADIAL_BAR_DIMENSIONS.DEFAULT_MAX_CUTOUT_PERCENT, useMinThickness: false }; const effectiveSpacing = isTooSmall ? RADIAL_BAR_DIMENSIONS.SPACING / 2 : RADIAL_BAR_DIMENSIONS.SPACING; const totalSpacePerRing = this.minRingThickness + effectiveSpacing; const radius = chartDiameter / 2; const calculatedCutoutPercent = (radius - numRings * totalSpacePerRing) / radius * 100; if (calculatedCutoutPercent >= RADIAL_BAR_DIMENSIONS.MIN_CUTOUT_PERCENT) return { cutout: Math.min(calculatedCutoutPercent, RADIAL_BAR_DIMENSIONS.DEFAULT_MAX_CUTOUT_PERCENT), useMinThickness: true }; else if ((radius - radius * RADIAL_BAR_DIMENSIONS.MIN_CUTOUT_PERCENT / 100) / numRings >= totalSpacePerRing) return { cutout: RADIAL_BAR_DIMENSIONS.MIN_CUTOUT_PERCENT, useMinThickness: true }; else return { cutout: RADIAL_BAR_DIMENSIONS.MIN_CUTOUT_PERCENT, useMinThickness: false }; } updated(changed) { super.updated(changed); if (this.hasAnyChanged(changed, RADIAL_BAR_WATCHED_PROP_NAMES)) { if (this.hasAnyChanged(changed, RADIAL_BAR_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } } firstUpdated() { this.createChart(); this.themeObserver = observeThemeChanges(() => this.updateChart()); this.setupResizeObserver(); } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= RADIAL_BAR_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } prepareChartData() { const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const remainingColor = getCssVariableValue(this, RADIAL_BAR_DIMENSIONS.REMAINING_COLOR); const borderColor = getCssVariableValue(this, RADIAL_BAR_DIMENSIONS.GAP_AND_BORDER_COLOR); const effectiveSpacing = (this.canvasEl?.clientHeight ?? 0) < RADIAL_BAR_DIMENSIONS.MIN_HEIGHT_WITH_LABELS ? RADIAL_BAR_DIMENSIONS.SPACING / 2 : RADIAL_BAR_DIMENSIONS.SPACING; return { datasets: this.data.map((value, index) => { const remaining = Math.max(0, this.max - value); const color = chartColors[index % chartColors.length] ?? CHART_SECTOR_DEFAULT_COLORS[0]; return { data: [value, remaining], backgroundColor: [color, remainingColor], borderWidth: effectiveSpacing, borderColor, borderRadius: RADIAL_BAR_DIMENSIONS.BORDER_RADIUS, spacing: 0, weight: 1 }; }) }; } getChartOptions() { const rotation = 0; const dimensions = calculateFixedHeightChartLayout({ fixedHeight: this.fixedHeight, isHalfMode: false, showOuterLabels: false, canvasEl: this.canvasEl, layoutConfig: { data: [], denominator: 100 }, host: this }); this.lastDimensions = dimensions; this.style.setProperty(\"--chart-width\", `${dimensions.calculatedWidth}px`); this.style.setProperty(\"--chart-height\", `${dimensions.actualHeight}px`); const dynamicPadding = dimensions.isTooSmall ? 0 : RADIAL_BAR_DIMENSIONS.CANVAS_PADDING; const chartDiameter = dimensions.isTooSmall ? dimensions.actualHeight - dynamicPadding * 2 : RADIAL_BAR_DIMENSIONS.CHART_WIDTH; const { cutout: optimalCutout } = this.calculateOptimalLayout(chartDiameter, dimensions.isTooSmall); return { responsive: false, maintainAspectRatio: false, devicePixelRatio: window.devicePixelRatio, rotation, circumference: this.circumference, cutout: `${optimalCutout}%`, layout: { padding: { top: dynamicPadding, right: dynamicPadding, bottom: dynamicPadding, left: dynamicPadding } }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !dimensions.isTooSmall, filter: (tooltipItem) => tooltipItem.label !== \"Remaining\", callbacks: { title: () => \"\", label: (context) => { const datasetIndex = context.datasetIndex; if (context.dataIndex !== 0) return \"\"; return `${`Ring ${datasetIndex + 1}`} ${context.parsed}`; } } } }, animation: { animateRotate: false, animateScale: false } }; } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; const { datasets } = this.prepareChartData(); const options = this.getChartOptions(); if (this.lastDimensions) { this.canvasEl.width = this.lastDimensions.calculatedWidth; this.canvasEl.height = this.lastDimensions.actualHeight; } this.chart = new Chart(ctx, { type: \"doughnut\", data: { labels: this.data.map((_, i) => `Ring ${i + 1}`), datasets }, options }); requestAnimationFrame(() => this.updateLegend()); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { datasets } = this.prepareChartData(); this.chart.data.labels = this.data.map((_, i) => `Ring ${i + 1}`); this.chart.data.datasets = datasets; const newOptions = this.getChartOptions(); if (this.chart.options) Object.assign(this.chart.options, newOptions); if (this.lastDimensions) this.chart.resize(this.lastDimensions.calculatedWidth, this.lastDimensions.actualHeight); this.chart.update(); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; if (!this.data || this.data.length === 0) { renderLegend(this.legendDiv, []); return; } try { const chartColors = getChartColorsOrDefault(this, this.colors, this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS); const legendItems = this.data.map((value, i) => { return { fillStyle: chartColors[i % chartColors.length] ?? (this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS[0] : CHART_SECTOR_DEFAULT_COLORS[0]), label: `Ring ${i + 1}`, value: value.toString(), unit: \"\" }; }); renderLegend(this.legendDiv, legendItems); } catch (error) { console.debug(\"[obc-radial-bar-chart] updateLegend: error generating legend HTML\", error); } } render() { const wrapperClasses = { wrapper: true, debug: this.showDebugOverlay }; return html` <div class=${classMap(wrapperClasses)}> <canvas></canvas> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(radial_bar_chart_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }"
3103
3103
  }
3104
3104
  ],
3105
3105
  "exports": [
@@ -3349,7 +3349,7 @@
3349
3349
  {
3350
3350
  "kind": "variable",
3351
3351
  "name": "ObcChartLineBase",
3352
- "default": "class extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.datasets = void 0; this.labels = void 0; this.colors = []; this.legend = false; this.showDebugOverlay = false; this.width = 480; this.height = 320; this.fixedAspectRatioScaling = false; this.scaleReferenceSize = 384; this.xAxisType = \"category\"; this.yAxisPosition = \"left\"; this.yAxes = void 0; this.xAxis = void 0; this.xMarker = void 0; this.yMarker = void 0; this.showGrid = false; this.showGridX = false; this.showGridY = false; this.showTickMarks = false; this.hasLabelPadding = true; this.rangeLabels = \"none\"; this.warnedDateDisplayScale = false; this.DEFAULT_TENSION = .4; this.POINT_RADIUS = 3; this.showPoints = false; this.lineMode = \"smooth\"; this.unit = \"\"; this.timeDisplay = \"date\"; this.xTicksLimit = void 0; this.xStepSize = void 0; this.yTicksLimit = void 0; this.yStepSize = void 0; this.state = InstrumentState.active; this.priority = Priority.regular; this.frameStyle = FrameStyle.regular; this.borderRadiusPosition = void 0; this.borderRadiusPositionExternalScales = void 0; this.instrumentMode = false; this.borderRadius = void 0; this.externalScaleDimensions = /* @__PURE__ */ new Map(); this.isUpdatingScales = false; this.currentBorderRadiusPx = 8; this.computedWidth = 480; this.computedHeight = 320; this.savedLabelThickness = /* @__PURE__ */ new WeakMap(); this.savedMainTickmarkLabels = /* @__PURE__ */ new WeakMap(); this.lastRangeLabels = []; this.lastMarkers = {}; this.rangeLabelCache = { y: [], x: [] }; this.updateBorderRadius = () => { if (!this.canvasEl) return; let next; if (this.instrumentMode) next = this.borderRadius ?? 8; else next = readExternalScaleBorderRadiusPx(this.canvasEl, ScaleType.regular, EXTERNAL_SCALE_BORDER_RADIUS_CSS_VAR); if (this.currentBorderRadiusPx !== next) { this.currentBorderRadiusPx = next; if (this.chart) { this.chart.destroy(); this.createChart(); } } }; this.handleSlotChange = () => { this.externalScaleDimensions.clear(); this.waitForScaleDimensions(); }; this.handleScaleDimensionsChanged = (e) => { if (this.isUpdatingScales) return; const { side, thickness } = e.detail; if (this.externalScaleDimensions.get(side) === thickness) return; this.externalScaleDimensions.set(side, thickness); if (this.dimensionUpdateTimer) clearTimeout(this.dimensionUpdateTimer); this.dimensionUpdateTimer = setTimeout(() => { this.syncScalesAndChart(); }, 16); }; } /** @internal - The y side wants range labels; an edge-to-edge chart never does. */ get rangeLabelsY() { return this.hasLabelPadding && (this.rangeLabels === \"y\" || this.rangeLabels === \"xy\"); } /** @internal - The x side wants range labels; an edge-to-edge chart never does. */ get rangeLabelsX() { return this.hasLabelPadding && (this.rangeLabels === \"x\" || this.rangeLabels === \"xy\"); } /** @internal - True when the x-axis positions points by numeric value. */ get isNumericXAxis() { return this.xAxisType === \"time\" || this.xAxisType === \"number\"; } /** * Id of the y scale a dataset lands on when it names none. Chart.js would * otherwise add a default `y` scale next to the configured ones and draw it. */ get primaryYAxisId() { return this.yAxes?.length ? this.yAxes[0].id ?? \"y0\" : \"y\"; } /** @internal - Normalization mode for the current x-axis type. */ get xValueMode() { return this.xAxisType === \"number\" ? XValueMode.number : XValueMode.time; } /** * `reverse` of the axis a side follows: the first axis positioned on that * side, else the first entry — the selection `resolveAxisRange()` makes. */ isYAxisReversed(side = \"left\") { if (!this.yAxes?.length) return false; return (this.yAxes.find((a) => (a.position ?? \"left\") === side) ?? this.yAxes[0]).reverse ?? false; } /** @internal - Warn once per data assignment about unparseable x-values. */ warnOnInvalidX(xValues, sourceRef) { const invalid = xValues.filter((x) => !Number.isFinite(x)).length; if (invalid === 0 || this.lastWarnedXSource === sourceRef) return; this.lastWarnedXSource = sourceRef; console.warn(`[obc-chart] ${invalid} x value(s) could not be parsed for xAxisType='${this.xAxisType}'; the points render as gaps.`); } /** * Should fill be applied to this chart? * Line graph returns false, area graph returns true. * Must be implemented in subclass. */ shouldApplyFill() { throw new Error(\"shouldApplyFill() must be implemented in subclass\"); } /** * Get fill mode for area rendering. * Line graph returns undefined, area graph returns 'semitransparent' | 'solid' | 'threshold'. * Must be implemented in subclass. */ getFillMode() { throw new Error(\"getFillMode() must be implemented in subclass\"); } /** * Should multi-series datasets be stacked? * Line graph returns false, area graph returns stacked property value. * Must be implemented in subclass. */ shouldStack() { throw new Error(\"shouldStack() must be implemented in subclass\"); } /** * Label band a slotted scale needs for its compact labels, in the scale's * own viewBox units. The scale prints the raw values, so those are what is * measured; the x band is one text line. */ compactLabelThickness(axis) { const context = this.canvasEl?.getContext(\"2d\"); if (!context) return void 0; const font = this.rangeLabelFont(); let visual; if (axis === \"y\") { const bounds = this.rangeLabelCache.bounds; if (!bounds) return void 0; const texts = yRangeLabelValues(bounds.min, bounds.max).map(String); visual = measureRangeLabelGutters(context, font, texts, []).side + 4; } else visual = measureRangeLabelGutters(context, font, [], [\"x\"]).bottom + 8; if (!this.fixedAspectRatioScaling) return Math.ceil(visual); const effectiveLength = axis === \"y\" ? this.getEffectiveHeight() : this.getEffectiveWidth(); return Math.ceil(visual * this.scaleReferenceSize / effectiveLength); } /** @internal - Ellipse clips applied last, in pixels by dataset index, for tests. */ get lastClips() { return (this.chart && datasetClipRecords.get(this.chart)) ?? {}; } slotFor(side) { return { left: this.leftScaleSlot, right: this.rightScaleSlot, top: this.topScaleSlot, bottom: this.bottomScaleSlot }[side]; } hasSlottedScale(side) { return (this.slotFor(side)?.assignedElements().length ?? 0) > 0; } /** @internal - Below the label threshold on either dimension. */ isBelowThreshold() { return this.getEffectiveWidth() < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS || this.getEffectiveHeight() < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; } get ySide() { return (this.yAxes?.[0]?.position ?? this.yAxisPosition) === \"right\" ? \"right\" : \"left\"; } rangeLabelFont() { const sizePx = Number.parseFloat(getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontSizeVar)); return { family: getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontFamily), sizePx: Number.isFinite(sizePx) ? sizePx : 12, weight: getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontWeightVar) }; } /** * Extent of the prepared data: one for x, one per y scale id. Each y axis * ranges from its own datasets, so a merged extent would label one axis * with another's values. */ dataExtents(prepared) { const x = { min: Infinity, max: -Infinity }; const y = /* @__PURE__ */ new Map(); const take = (extent, v) => { if (!Number.isFinite(v)) return; extent.min = Math.min(extent.min, v); extent.max = Math.max(extent.max, v); }; prepared.datasets.forEach((dataset) => { const id = dataset.yAxisID ?? this.primaryYAxisId; const extent = y.get(id) ?? { min: Infinity, max: -Infinity }; y.set(id, extent); dataset.data.forEach((point) => { if (typeof point === \"number\") take(extent, point); else if (point) { take(x, point.x); take(extent, point.y); } }); }); y.forEach((extent, id) => { if (!(extent.min <= extent.max)) y.delete(id); }); return { x: x.min <= x.max ? x : void 0, y }; } /** * Range the y labels describe. Below the threshold the axis runs on data * bounds, so its datasets' extent is exact and needs no chart to read from. */ yRangeBounds(extents) { let axis; let id = \"y\"; if (this.yAxes?.length) { const match = this.yAxes.findIndex((a) => (a.position ?? \"left\") === this.ySide); const index = match === -1 ? 0 : match; axis = this.yAxes[index]; id = axis.id ?? `y${index}`; } const extent = extents.get(id); const stackedScale = this.shouldStack() ? this.chart?.scales[id] : void 0; const min = axis?.min ?? stackedScale?.min ?? extent?.min; const max = axis?.max ?? stackedScale?.max ?? extent?.max; return min !== void 0 && max !== void 0 ? { min, max } : void 0; } /** First and last x label, or nothing when there is no span to label. */ xEdgeLabelTexts(prepared, extent) { if (!this.isNumericXAxis) { const labels = prepared.labels.map(String); const first = labels[0]; const last = labels[labels.length - 1]; return labels.length > 1 && first !== last ? [first, last] : []; } const min = this.xAxis?.min ?? extent?.min; const max = this.xAxis?.max ?? extent?.max; if (min === void 0 || max === void 0 || min === max) return []; const reference = this.timeDisplay === \"minutes\" ? this.computeTimeReference() : void 0; return [formatXValue(min, this.xValueMode, reference), formatXValue(max, this.xValueMode, reference)]; } /** * Recompute the range labels. A side with a slotted scale is labelled by * the scale, so it gets no text here; the y bounds are kept regardless, * since the scale's compact band is measured from them. */ refreshRangeLabels() { const cache = { y: [], x: [] }; if (this.isBelowThreshold() && (this.rangeLabelsY || this.rangeLabelsX)) { const prepared = this.prepareChartDataAndLabels(); const extents = this.dataExtents(prepared); if (this.rangeLabelsY) { cache.bounds = this.yRangeBounds(extents.y); if (cache.bounds && !this.hasSlottedScale(\"left\") && !this.hasSlottedScale(\"right\")) { const { min, max } = cache.bounds; cache.y = yRangeLabelValues(min, max).map((v) => formatRangeValue(v, min, max)); } } if (this.rangeLabelsX && !this.hasSlottedScale(\"top\") && !this.hasSlottedScale(\"bottom\")) cache.x = this.xEdgeLabelTexts(prepared, extents.x); } this.rangeLabelCache = cache; return cache; } /** * Value cursors drawn after the datasets, in the dataset's own colour, so no * annotation dependency is needed. A no-op while both markers are unset. */ createMarkersPlugin() { return { id: \"markers\", afterDatasetsDraw: (chart) => { this.lastMarkers = {}; if (!this.xMarker && !this.yMarker) return; const area = chart.chartArea; const ctx = chart.ctx; const datasetOf = (index = 0) => chart.data.datasets[index]; const yScaleOf = (ds) => chart.scales[ds?.yAxisID ?? this.primaryYAxisId]; const colorOf = (ds) => typeof ds?.borderColor === \"string\" ? ds.borderColor : getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); ctx.save(); ctx.beginPath(); ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); ctx.clip(); let dot; const xScale = chart.scales[\"x\"]; if (this.xMarker && xScale) { const ds = datasetOf(this.xMarker.datasetIndex); const xValue = this.isNumericXAxis ? normalizeXValue(this.xMarker.x, this.xValueMode) : typeof this.xMarker.x === \"number\" ? this.xMarker.x : (chart.data.labels ?? []).indexOf(this.xMarker.x); if (Number.isFinite(xValue) && (this.isNumericXAxis || xValue >= 0)) { const xPixel = xScale.getPixelForValue(xValue); const x = Math.round(xPixel) + .5; const hit = chart.getDatasetMeta(this.xMarker.datasetIndex ?? 0).dataset?.interpolate({ x: xPixel, y: 0 }, \"x\"); const hitY = (Array.isArray(hit) ? hit[0] : hit)?.y; const y = typeof hitY === \"number\" ? hitY : void 0; const color = colorOf(ds); ctx.strokeStyle = color; ctx.lineWidth = MARKER.lineWidth; ctx.setLineDash([]); ctx.beginPath(); ctx.moveTo(x, area.top); ctx.lineTo(x, y ?? area.top); ctx.stroke(); ctx.setLineDash([...MARKER.dash]); ctx.beginPath(); ctx.moveTo(x, y ?? area.top); ctx.lineTo(x, area.bottom); ctx.stroke(); ctx.setLineDash([]); if (y !== void 0 && xPixel >= area.left && xPixel <= area.right && y >= area.top && y <= area.bottom && (this.xMarker.showDot ?? true)) dot = { x, y, color }; this.lastMarkers.x = { x, y, dot: dot !== void 0 }; } } if (this.yMarker) { const ds = datasetOf(this.yMarker.datasetIndex); const yScale = yScaleOf(ds); if (yScale) { const y = yScale.getPixelForValue(this.yMarker.y); ctx.lineWidth = MARKER.lineWidth; ctx.strokeStyle = getCssVariableValue(this, MARKER.ringColorVar); ctx.beginPath(); ctx.moveTo(area.left, y + MARKER.valueLineWidth / 2 + .5); ctx.lineTo(area.right, y + MARKER.valueLineWidth / 2 + .5); ctx.stroke(); ctx.lineWidth = MARKER.valueLineWidth; ctx.strokeStyle = colorOf(ds); ctx.beginPath(); ctx.moveTo(area.left, y); ctx.lineTo(area.right, y); ctx.stroke(); this.lastMarkers.y = { y }; } } ctx.restore(); if (dot) { ctx.save(); ctx.beginPath(); ctx.arc(dot.x, dot.y, MARKER.dotRadius, 0, Math.PI * 2); ctx.fillStyle = dot.color; ctx.fill(); ctx.lineWidth = MARKER.dotRingWidth; ctx.strokeStyle = getCssVariableValue(this, MARKER.ringColorVar); ctx.stroke(); ctx.restore(); } } }; } /** * Paints min / 0 / max and first / last once Chart.js has drawn, inside the * gutters `getChartOptions()` reserved. The end labels sit flush with the * plot edges so no vertical padding is needed for them. */ createRangeLabelsPlugin() { return { id: \"rangeLabels\", afterDraw: (chart) => { this.lastRangeLabels = []; const { y: yTexts, x: xTexts, bounds } = this.rangeLabelCache; if (!yTexts.length && !xTexts.length) return; const area = chart.chartArea; const ctx = chart.ctx; const font = this.rangeLabelFont(); const lineHeight = rangeLabelLineHeight(font); ctx.save(); ctx.font = rangeLabelFontString(font); ctx.fillStyle = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); const scale = chart.scales[this.primaryYAxisId]; if (yTexts.length && bounds && scale) { const onRight = this.ySide === \"right\"; const x = onRight ? area.right + 8 : area.left - 8; ctx.textAlign = onRight ? \"left\" : \"right\"; const values = yRangeLabelValues(bounds.min, bounds.max); const reversed = this.isYAxisReversed(this.ySide); for (let i = values.length - 1; i >= 0; i--) { const isMax = i === values.length - 1; const isMin = i === 0; const isEnd = isMax || isMin; const atTop = isMax !== reversed; const y = isEnd ? atTop ? area.top : area.bottom : scale.getPixelForValue(values[i]); if (!isMax && !isMin && (y - area.top < lineHeight || area.bottom - y < lineHeight)) continue; ctx.textBaseline = isEnd ? atTop ? \"top\" : \"bottom\" : \"middle\"; ctx.fillText(yTexts[i], x, y); this.lastRangeLabels.push({ axis: \"y\", text: yTexts[i], x, y }); } } if (xTexts.length === 2) { const y = area.bottom + 4; ctx.textBaseline = \"top\"; ctx.textAlign = \"left\"; ctx.fillText(xTexts[0], area.left, y); this.lastRangeLabels.push({ axis: \"x\", text: xTexts[0], x: area.left, y }); ctx.textAlign = \"right\"; ctx.fillText(xTexts[1], area.right, y); this.lastRangeLabels.push({ axis: \"x\", text: xTexts[1], x: area.right, y }); } ctx.restore(); } }; } /** * Check if a slotted scale element is actually visible (renders content). * For bar-vertical/bar-horizontal elements, checks hasBar and hasScale properties. */ hasVisibleScale(side) { return (this.slotFor(side)?.assignedElements() ?? []).some((el) => { const barEl = el; if (\"hasBar\" in barEl && \"hasScale\" in barEl) return barEl.hasBar === true || barEl.hasScale === true; return true; }); } computeRoundedCorners() { if (!this.borderRadiusPosition) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; if (this.borderRadiusPosition === BorderRadiusPosition.middleChild) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; if (this.borderRadiusPosition === BorderRadiusPosition.middleRoundedChild) return { topLeft: true, topRight: true, bottomLeft: true, bottomRight: true }; const hasLeft = this.hasVisibleScale(\"left\"); const hasRight = this.hasVisibleScale(\"right\"); const hasTop = this.hasVisibleScale(\"top\"); const hasBottom = this.hasVisibleScale(\"bottom\"); if (hasLeft && hasRight || hasTop && hasBottom) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; const result = { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; const isInner = this.borderRadiusPosition === BorderRadiusPosition.innerFirstChild; const isOuter = this.borderRadiusPosition === BorderRadiusPosition.outerLastChild; if (hasRight && hasBottom) { if (isInner) result.bottomRight = true; else if (isOuter) result.topLeft = true; } else if (hasRight && hasTop) { if (isInner) result.topRight = true; else if (isOuter) result.bottomLeft = true; } else if (hasLeft && hasBottom) { if (isInner) result.bottomLeft = true; else if (isOuter) result.topRight = true; } else if (hasLeft && hasTop) { if (isInner) result.topLeft = true; else if (isOuter) result.bottomRight = true; } else if (hasRight && !hasLeft) { if (isInner) { result.topLeft = true; result.bottomLeft = true; } else if (isOuter) { result.topRight = true; result.bottomRight = true; } } else if (hasLeft && !hasRight) { if (isInner) { result.topRight = true; result.bottomRight = true; } else if (isOuter) { result.topLeft = true; result.bottomLeft = true; } } else if (hasBottom && !hasTop) { if (isInner) { result.topLeft = true; result.topRight = true; } else if (isOuter) { result.bottomLeft = true; result.bottomRight = true; } } else if (hasTop && !hasBottom) { if (isInner) { result.bottomLeft = true; result.bottomRight = true; } else if (isOuter) { result.topLeft = true; result.topRight = true; } } return result; } /** * Create a Chart.js plugin that draws a border around the chart area with selective corner rounding * and clips content to that border. */ createBorderPlugin() { const corners = this.computeRoundedCorners(); const radius = this.currentBorderRadiusPx; let didApplyClip = false; const buildRoundedRectPath = (ctx, rect, cornerRadius) => { const { x, y, width, height } = rect; if (width <= 0 || height <= 0) return; const r = clamp(cornerRadius, 0, Math.max(0, Math.min(width, height) / 2)); ctx.moveTo(x + (corners.topLeft ? r : 0), y); ctx.lineTo(x + width - (corners.topRight ? r : 0), y); if (corners.topRight) ctx.arcTo(x + width, y, x + width, y + r, r); ctx.lineTo(x + width, y + height - (corners.bottomRight ? r : 0)); if (corners.bottomRight) ctx.arcTo(x + width, y + height, x + width - r, y + height, r); ctx.lineTo(x + (corners.bottomLeft ? r : 0), y + height); if (corners.bottomLeft) ctx.arcTo(x, y + height, x, y + height - r, r); ctx.lineTo(x, y + (corners.topLeft ? r : 0)); if (corners.topLeft) ctx.arcTo(x, y, x + r, y, r); }; return { id: \"chartAreaBorder\", beforeDatasetsDraw: (chart) => { const ctx = chart.ctx; const chartArea = chart.chartArea; if (!chartArea) return; const clipInset = 1; const { top, right, bottom, left } = chartArea; const rect = { x: left + clipInset, y: top + clipInset, width: right - left - 2, height: bottom - top - 2 }; const clipRadius = Math.max(0, radius - clipInset); ctx.save(); didApplyClip = true; ctx.beginPath(); buildRoundedRectPath(ctx, rect, clipRadius); ctx.closePath(); if (this.instrumentMode) { ctx.fillStyle = getCssVariableValue(this, CHART_AREA_BACKGROUND_COLOR_VAR); ctx.fill(); } ctx.clip(); }, afterDraw: (chart) => { const ctx = chart.ctx; const chartArea = chart.chartArea; if (!chartArea) return; const borderWidthPx = 1; const strokeInset = borderWidthPx / 2; const { top, right, bottom, left } = chartArea; const rect = { x: left + strokeInset, y: top + strokeInset, width: right - left - strokeInset * 2, height: bottom - top - strokeInset * 2 }; const strokeRadius = Math.max(0, radius - strokeInset); const skipTop = this.hasVisibleScale(\"top\"); const skipRight = this.hasVisibleScale(\"right\"); const skipBottom = this.hasVisibleScale(\"bottom\"); const skipLeft = this.hasVisibleScale(\"left\"); const borderColor = getCssVariableValue(this, \"--instrument-frame-tertiary-color\"); ctx.save(); ctx.strokeStyle = borderColor; ctx.lineWidth = borderWidthPx; const { x, y, width, height } = rect; const r = clamp(strokeRadius, 0, Math.max(0, Math.min(width, height) / 2)); if (!skipTop && !skipRight && !skipBottom && !skipLeft) { ctx.beginPath(); buildRoundedRectPath(ctx, rect, strokeRadius); ctx.closePath(); ctx.stroke(); } else { if (!skipTop) { ctx.beginPath(); if (!skipLeft && corners.topLeft) ctx.moveTo(x + r, y); else ctx.moveTo(x, y); if (!skipRight && corners.topRight) ctx.lineTo(x + width - r, y); else ctx.lineTo(x + width, y); ctx.stroke(); } if (!skipRight) { ctx.beginPath(); if (!skipTop && corners.topRight) ctx.moveTo(x + width, y + r); else ctx.moveTo(x + width, y); if (!skipBottom && corners.bottomRight) ctx.lineTo(x + width, y + height - r); else ctx.lineTo(x + width, y + height); ctx.stroke(); } if (!skipBottom) { ctx.beginPath(); if (!skipRight && corners.bottomRight) ctx.moveTo(x + width - r, y + height); else ctx.moveTo(x + width, y + height); if (!skipLeft && corners.bottomLeft) ctx.lineTo(x + r, y + height); else ctx.lineTo(x, y + height); ctx.stroke(); } if (!skipLeft) { ctx.beginPath(); if (!skipBottom && corners.bottomLeft) ctx.moveTo(x, y + height - r); else ctx.moveTo(x, y + height); if (!skipTop && corners.topLeft) ctx.lineTo(x, y + r); else ctx.lineTo(x, y); ctx.stroke(); } if (!skipTop && !skipLeft && corners.topLeft) { ctx.beginPath(); ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); ctx.stroke(); } if (!skipTop && !skipRight && corners.topRight) { ctx.beginPath(); ctx.arc(x + width - r, y + r, r, Math.PI * 1.5, Math.PI * 2); ctx.stroke(); } if (!skipRight && !skipBottom && corners.bottomRight) { ctx.beginPath(); ctx.arc(x + width - r, y + height - r, r, 0, Math.PI * .5); ctx.stroke(); } if (!skipBottom && !skipLeft && corners.bottomLeft) { ctx.beginPath(); ctx.arc(x + r, y + height - r, r, Math.PI * .5, Math.PI); ctx.stroke(); } } ctx.restore(); if (this.showPoints) { ctx.save(); chart.data.datasets.forEach((_ds, datasetIndex) => { const meta = chart.getDatasetMeta(datasetIndex); if (!meta || meta.hidden) return; (meta.data ?? []).forEach((el) => { const point = el; if (point.skip) return; const r = point.options?.radius; if (typeof r === \"number\" && r <= 0) return; point.draw(ctx); }); }); ctx.restore(); } }, afterDatasetsDraw: (chart) => { if (didApplyClip) { chart.ctx.restore(); didApplyClip = false; } } }; } /** * Check if any external scales are slotted */ hasExternalScales() { const top = this.topScaleSlot?.assignedElements() ?? []; const bottom = this.bottomScaleSlot?.assignedElements() ?? []; const left = this.leftScaleSlot?.assignedElements() ?? []; const right = this.rightScaleSlot?.assignedElements() ?? []; return top.length > 0 || bottom.length > 0 || left.length > 0 || right.length > 0; } /** * Wait for all slotted scales to report their dimensions */ async waitForScaleDimensions() { if (!this.hasExternalScales()) { this.requestUpdate(); return; } const scaleElements = []; [ this.topScaleSlot, this.bottomScaleSlot, this.leftScaleSlot, this.rightScaleSlot ].forEach((slot) => { if (slot) { const assigned = slot.assignedElements(); scaleElements.push(...assigned); } }); const setScaleProps = (slot) => { if (!slot) return; slot.assignedElements().forEach((scale) => { scale.fixedAspectRatio = this.fixedAspectRatioScaling; scale.scaleReferenceSize = this.scaleReferenceSize; }); }; setScaleProps(this.leftScaleSlot); setScaleProps(this.rightScaleSlot); setScaleProps(this.topScaleSlot); setScaleProps(this.bottomScaleSlot); await Promise.all(scaleElements.map((el) => \"updateComplete\" in el && typeof el.updateComplete === \"object\" ? el.updateComplete : Promise.resolve())); if (this.externalScaleDimensions.size === 0 && scaleElements.length > 0) await new Promise((resolve) => setTimeout(resolve, 50)); this.syncScalesAndChart(); } /** * Synchronize scale and chart dimensions/data * This is the main coordination function */ syncScalesAndChart() { if (this.isUpdatingScales) return false; this.isUpdatingScales = true; try { const padding = this.computeChartPadding(); const effectiveWidth = this.getEffectiveWidth() - padding.left - padding.right; const effectiveHeight = this.getEffectiveHeight() - padding.top - padding.bottom; if (effectiveWidth <= 0 || effectiveHeight <= 0) { console.warn(\"[chart-line-base] Invalid effective dimensions\", { width: this.getEffectiveWidth(), height: this.getEffectiveHeight(), padding, effectiveWidth, effectiveHeight }); return false; } this.updateScaleProperties(padding); if (this.chart) this.chart.destroy(); this.createChart(); return true; } finally { this.isUpdatingScales = false; } } /** * Calculate chart padding from external scale dimensions. * * For sides without an external scale, falls back to `CHART_DIMENSIONS.CANVAS_PADDING` * (the chart's own padding to reserve room for axis tick labels). When * `hasLabelPadding=false` that fallback is 0 so the chart renders edge-to-edge, * and this same value is cascaded to slotted scales via `updateScaleProperties()` * — so the bar's main-axis padding (`paddingTop`/`paddingBottom` for vertical bars) * collapses with the chart's perpendicular padding and they stay visually aligned. */ calculatePaddingFromScales() { const defaultPadding = this.hasLabelPadding ? CHART_DIMENSIONS.CANVAS_PADDING : 0; return { top: this.externalScaleDimensions.get(\"top\") ?? defaultPadding, right: this.externalScaleDimensions.get(\"right\") ?? defaultPadding, bottom: this.externalScaleDimensions.get(\"bottom\") ?? defaultPadding, left: this.externalScaleDimensions.get(\"left\") ?? defaultPadding }; } /** * Range a slotted scale on the given side has to cover. * * A range pinned in the axis configuration is used as is: it is the source * of truth, and on the first sync there is no chart to read yet. Otherwise * the live Chart.js scale is read under the id `buildScalesConfig()` gives * it. A side with no axis of its own follows the first configured one. */ resolveAxisRange(side) { let id = side === \"x\" ? \"x\" : \"y\"; let configured; if (side === \"x\") configured = this.isNumericXAxis ? this.xAxis : void 0; else if (this.yAxes?.length) { const match = this.yAxes.findIndex((axis) => (axis.position ?? \"left\") === side); const index = match === -1 ? 0 : match; const axis = this.yAxes[index]; id = axis.id ?? `y${index}`; configured = axis; } if (configured?.min !== void 0 && configured.max !== void 0) return { min: configured.min, max: configured.max }; const scale = this.chart?.scales[id]; return { min: scale?.min ?? configured?.min ?? 0, max: scale?.max ?? configured?.max ?? 100 }; } /** * Range pushed to the top and bottom scales, or `undefined` to leave them * alone. A scale prints its values verbatim, and on a `time` axis the raw * range is epoch milliseconds. In `minutes` display the range is converted * to the minutes the chart's own labels show; `date` display has no numeric * equivalent, so the scale keeps its own range. */ resolveSlottedXRange() { const range = this.resolveAxisRange(\"x\"); if (this.xAxisType !== \"time\") return range; if (this.timeDisplay !== \"minutes\") { if (!this.warnedDateDisplayScale) { this.warnedDateDisplayScale = true; console.warn(\"[obc-chart] a slotted horizontal scale cannot label a time axis in 'date' display and keeps its own range; use timeDisplay='minutes' or a number axis.\"); } return; } const pinned = this.xAxis?.min !== void 0 && this.xAxis?.max !== void 0; const reference = this.computeTimeReference(); if (reference === void 0 || !this.chart && !pinned) return void 0; const minute = 6e4; return { min: (range.min - reference) / minute, max: (range.max - reference) / minute }; } /** * Update properties on slotted scale elements */ updateScaleProperties(padding) { const leftRange = this.resolveAxisRange(\"left\"); const rightRange = this.resolveAxisRange(\"right\"); const xRange = this.resolveSlottedXRange(); const effectiveWidth = this.getEffectiveWidth(); const effectiveHeight = this.getEffectiveHeight(); const aboveThreshold = effectiveWidth >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS && effectiveHeight >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const showLabels = this.hasLabelPadding && aboveThreshold; const compactY = !aboveThreshold && this.rangeLabelsY; const compactX = !aboveThreshold && this.rangeLabelsX; const compactYThickness = compactY ? this.compactLabelThickness(\"y\") : void 0; const compactXThickness = compactX ? this.compactLabelThickness(\"x\") : void 0; const mainLabelsFor = (scale, compact) => { if (compact) { if (!this.savedMainTickmarkLabels.has(scale)) this.savedMainTickmarkLabels.set(scale, scale.showMainTickmarkLabels ?? false); return true; } if (!this.savedMainTickmarkLabels.has(scale)) return void 0; const saved = this.savedMainTickmarkLabels.get(scale); this.savedMainTickmarkLabels.delete(scale); return saved; }; const bandFor = (scale, compact, thickness) => { if (compact) { if (thickness === void 0 || typeof scale.labelThickness !== \"number\") return; if (!this.savedLabelThickness.has(scale)) this.savedLabelThickness.set(scale, scale.labelThickness); return thickness; } const saved = this.savedLabelThickness.get(scale); this.savedLabelThickness.delete(scale); return saved; }; const verticalViewBoxPadding = this.fixedAspectRatioScaling ? { top: Math.round(padding.top * this.scaleReferenceSize / effectiveHeight), bottom: Math.round(padding.bottom * this.scaleReferenceSize / effectiveHeight) } : { top: padding.top, bottom: padding.bottom }; const horizontalViewBoxPadding = this.fixedAspectRatioScaling ? { left: Math.round(padding.left * this.scaleReferenceSize / effectiveWidth), right: Math.round(padding.right * this.scaleReferenceSize / effectiveWidth) } : { left: padding.left, right: padding.right }; const updates = []; /** Empty on a side whose slotted scale carries a range of its own. */ const rangeProps = (side, range) => this.ownsSlottedScaleRange(side) ? { minValue: range.min, maxValue: range.max, ...side === \"left\" || side === \"right\" ? { reverse: this.isYAxisReversed(side) } : {} } : {}; if (this.leftScaleSlot) this.leftScaleSlot.assignedElements().forEach((scale) => { const props = { ...rangeProps(\"left\", leftRange), height: effectiveHeight, paddingTop: verticalViewBoxPadding.top, paddingBottom: verticalViewBoxPadding.bottom, paddingStart: verticalViewBoxPadding.top, paddingEnd: verticalViewBoxPadding.bottom, showLabels: showLabels || compactY, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.yStepSize !== void 0) props.primaryTickmarkInterval = this.yStepSize; const band = bandFor(scale, compactY, compactYThickness); const mainLabels = mainLabelsFor(scale, compactY); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.leftScaleSlot, scale, props ]); }); if (this.rightScaleSlot) this.rightScaleSlot.assignedElements().forEach((scale) => { const props = { ...rangeProps(\"right\", rightRange), height: effectiveHeight, paddingTop: verticalViewBoxPadding.top, paddingBottom: verticalViewBoxPadding.bottom, paddingStart: verticalViewBoxPadding.top, paddingEnd: verticalViewBoxPadding.bottom, showLabels: showLabels || compactY, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.yStepSize !== void 0) props.primaryTickmarkInterval = this.yStepSize; const band = bandFor(scale, compactY, compactYThickness); const mainLabels = mainLabelsFor(scale, compactY); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.rightScaleSlot, scale, props ]); }); if (this.topScaleSlot) this.topScaleSlot.assignedElements().forEach((scale) => { const props = { ...xRange, width: effectiveWidth, paddingLeft: horizontalViewBoxPadding.left, paddingRight: horizontalViewBoxPadding.right, paddingStart: horizontalViewBoxPadding.left, paddingEnd: horizontalViewBoxPadding.right, showLabels: showLabels || compactX, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.xStepSize !== void 0) props.primaryTickmarkInterval = this.xStepSize; const band = bandFor(scale, compactX, compactXThickness); const mainLabels = mainLabelsFor(scale, compactX); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.topScaleSlot, scale, props ]); }); if (this.bottomScaleSlot) this.bottomScaleSlot.assignedElements().forEach((scale) => { const props = { ...xRange, width: effectiveWidth, paddingLeft: horizontalViewBoxPadding.left, paddingRight: horizontalViewBoxPadding.right, paddingStart: horizontalViewBoxPadding.left, paddingEnd: horizontalViewBoxPadding.right, showLabels: showLabels || compactX, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.xStepSize !== void 0) props.primaryTickmarkInterval = this.xStepSize; const band = bandFor(scale, compactX, compactXThickness); const mainLabels = mainLabelsFor(scale, compactX); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.bottomScaleSlot, scale, props ]); }); updates.forEach(([_slot, scale, props]) => { Object.assign(scale, props); }); } /** * Whether the chart's axis range is what a slotted scale on this side should * describe. A subclass that slots a scale of its own and gives it a separate * range returns false for that side, otherwise the sync below overwrites it. */ ownsSlottedScaleRange(_side) { return true; } /** * Push the current axis ranges to the slotted scales. The full * `updateScaleProperties()` cascade runs before the chart is (re)built and * so reads the previous chart's ranges; this closes that gap once the new * chart exists, and keeps auto-ranged scales in step with the data. */ syncSlottedScaleRanges() { const apply = (side, slot, range) => { if (!slot || !range || !this.ownsSlottedScaleRange(side)) return; slot.assignedElements().forEach((scale) => { scale.minValue = range.min; scale.maxValue = range.max; if (side === \"left\" || side === \"right\") scale.reverse = this.isYAxisReversed(side); }); }; apply(\"left\", this.leftScaleSlot, this.resolveAxisRange(\"left\")); apply(\"right\", this.rightScaleSlot, this.resolveAxisRange(\"right\")); const xRange = this.resolveSlottedXRange(); apply(\"top\", this.topScaleSlot, xRange); apply(\"bottom\", this.bottomScaleSlot, xRange); } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Apply fillMode rules to datasets. Must be called after the chart is created * so scales and pixel coordinates are available for gradient construction. * * NOTE: For non-threshold modes (solid, semitransparent), backgroundColor is already * set correctly in buildDataset(). This method now only handles threshold gradients * which require Chart.js scales to be available. * * @returns Whether it set gradients; they reach the drawn chart on its next update. */ applyFillModes() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return false; const chart = this.chart; const ctx = chart.ctx; if (!ctx) return false; const fill = this.shouldApplyFill(); if (this.getFillMode() !== \"threshold\" || !fill) return false; let applied = false; chart.data.datasets.forEach((ds, _idx) => { const dataset = ds; if (dataset.fill === false || !fill) return; const yScaleId = dataset.yAxisID ?? \"y\"; const yScale = chart.scales[yScaleId]; if (!yScale) return; const dataValues = dataset.data.map((d) => typeof d === \"number\" ? d : d.y).filter((v) => Number.isFinite(v)); if (dataValues.length === 0) return; const thresholdVal = (Math.min(...dataValues) + Math.max(...dataValues)) / 2; const thresholdPixel = yScale.getPixelForValue(thresholdVal); const range = yScale.bottom - yScale.top; let stop = (thresholdPixel - yScale.top) / range; if (!Number.isFinite(stop) || range === 0) stop = .5; else stop = clamp(stop, 0, 1); const lowRaw = LINE_GRAPH_GRID_CONFIG.thresholdLowColorVar; const highRaw = LINE_GRAPH_GRID_CONFIG.thresholdHighColorVar; const createGradient = (lowAlpha, highAlpha) => { const low = applyAlphaToColor(this, lowRaw, lowAlpha); const high = applyAlphaToColor(this, highRaw, highAlpha); const grad = ctx.createLinearGradient(0, yScale.top, 0, yScale.bottom); grad.addColorStop(0, high); grad.addColorStop(stop, high); grad.addColorStop(stop, low); grad.addColorStop(1, low); return grad; }; const fillGradient = createGradient(.35, .35); const borderGradient = createGradient(.8, .8); dataset.backgroundColor = fillGradient; dataset.borderColor = borderGradient; applied = true; }); return applied; } updated(changed) { super.updated(changed); if (!this.hasAnyChanged(changed, LINE_GRAPH_WATCHED_PROP_NAMES)) return; if (this.hasAnyChanged(changed, LINE_GRAPH_DIMENSION_PROP_NAMES)) { if (this.updateComputedDimensions()) return; } const belowThreshold = this.isBelowThreshold(); const crossedThreshold = this.wasBelowThreshold !== void 0 && this.wasBelowThreshold !== belowThreshold; this.wasBelowThreshold = belowThreshold; if ((changed.has(\"hasLabelPadding\") || changed.has(\"rangeLabels\") || crossedThreshold) && this.hasExternalScales()) { this.syncScalesAndChart(); return; } if (this.hasAnyChanged(changed, LINE_GRAPH_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } async firstUpdated() { await this.waitForScaleDimensions(); if (!this.hasExternalScales()) this.createChart(); this.themeObserver = observeThemeChanges(() => { this.updateChartColors(); this.updateBorderRadius(); }); this.setupResizeObserver(); this.setupAspectRatioResizeObserver(); if (this.canvasEl) { if (!this.instrumentMode) this.borderRadiusObserver = startExternalScaleBorderRadiusObserver(this.canvasEl, this.updateBorderRadius); this.updateBorderRadius(); } } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); this.aspectRatioResizeObserver?.disconnect(); this.borderRadiusObserver?.disconnect(); if (this.dimensionUpdateTimer) clearTimeout(this.dimensionUpdateTimer); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS && (this.canvasEl?.clientWidth ?? 0) >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } /** * Setup resize observer for fixed aspect ratio scaling. * Observes the wrapper element and recalculates dimensions when parent size changes. */ setupAspectRatioResizeObserver() { const wrapper = this.renderRoot.querySelector(\".wrapper\"); if (!wrapper) return; this.updateComputedDimensions(); this.aspectRatioResizeObserver = new ResizeObserver(() => { if (!this.fixedAspectRatioScaling) return; this.updateComputedDimensions(); }); this.aspectRatioResizeObserver.observe(wrapper); } /** * Refresh `computedWidth` / `computedHeight`, the derived pixel size the * chart and its slotted scales are laid out from. * * In pixel mode they mirror `width` / `height`. Only in * `fixedAspectRatioScaling` mode are they derived — from the wrapper's * measured width and the aspect ratio the `width` / `height` pair defines — * and only then can this rebuild the chart. * * @returns `true` when the change was significant enough that the chart was * rebuilt here, so the caller must not rebuild it a second time. */ updateComputedDimensions() { if (!this.fixedAspectRatioScaling) { this.computedWidth = this.width; this.computedHeight = this.height; return false; } const wrapper = this.renderRoot.querySelector(\".wrapper\"); if (!wrapper) return false; const parentWidth = wrapper.clientWidth; if (parentWidth <= 0) return false; const aspectRatio = this.width / this.height; const newWidth = parentWidth; const newHeight = Math.round(parentWidth / aspectRatio); if (this.computedWidth !== newWidth || this.computedHeight !== newHeight) { this.computedWidth = newWidth; this.computedHeight = newHeight; if (this.hasExternalScales()) return this.syncScalesAndChart(); else if (this.chart) { this.chart.destroy(); this.createChart(); return true; } } return false; } /** * Get the effective width for chart rendering. * Returns computed width when fixedAspectRatioScaling is true, otherwise the width property. */ getEffectiveWidth() { return this.fixedAspectRatioScaling ? this.computedWidth : this.width; } /** * Get the effective height for chart rendering. * Returns computed height when fixedAspectRatioScaling is true, otherwise the height property. */ getEffectiveHeight() { return this.fixedAspectRatioScaling ? this.computedHeight : this.height; } /** * Get the scale factor for proportional scaling when fixedAspectRatioScaling is true. * Returns 1.0 when not in fixed aspect ratio mode. * The scale factor is based on computed width vs reference width (the width property). */ getScaleFactor() { if (!this.fixedAspectRatioScaling) return 1; return this.computedWidth / this.width; } /** * Build a complete dataset configuration with all styling properties. * Handles both new datasets (from values array) and existing datasets (normalization). * * @param data - Either numeric values array or existing dataset to normalize * @param index - Dataset index for color cycling * @param chartColors - Color palette array * @param totalCount - Total number of datasets (used for stacked divider logic) * @returns Fully configured Chart.js dataset */ buildDataset(data, index, chartColors, totalCount = 1) { const currentColor = chartColors[index % chartColors.length]; const existingDataset = Array.isArray(data) ? null : data; const values = Array.isArray(data) ? data : null; const borderColor = existingDataset?.borderColor ?? currentColor; const explicitFill = existingDataset?.fill; const fillFlag = explicitFill !== void 0 ? explicitFill !== false : this.shouldApplyFill(); const tension = this.lineMode === \"smooth\" ? this.DEFAULT_TENSION : 0; const needsDivider = this.shouldStack() && this.getFillMode() !== \"threshold\" && index < totalCount - 1; let backgroundColor = \"transparent\"; const fillMode = this.getFillMode(); if (fillFlag && fillMode) { const nextColor = chartColors[(index + 1) % chartColors.length]; if (fillMode === \"solid\") backgroundColor = String(borderColor); else if (fillMode === \"semitransparent\") backgroundColor = applyAlphaToColor(this, nextColor, .5); else if (fillMode === \"threshold\") backgroundColor = applyAlphaToColor(this, nextColor, .5); } return { ...existingDataset || {}, data: existingDataset?.data ?? values, yAxisID: existingDataset?.yAxisID ?? this.primaryYAxisId, borderColor, backgroundColor: existingDataset?.backgroundColor ?? backgroundColor, borderWidth: existingDataset?.borderWidth ?? 2, showLine: existingDataset?.showLine ?? true, tension: existingDataset?.tension ?? tension, pointRadius: existingDataset?.pointRadius ?? (this.showPoints ? this.POINT_RADIUS : 0), pointBackgroundColor: existingDataset?.pointBackgroundColor ?? \"#fff\", pointBorderColor: existingDataset?.pointBorderColor ?? borderColor, pointBorderWidth: existingDataset?.pointBorderWidth ?? 2, stepped: existingDataset?.stepped ?? this.lineMode === \"stepped\", fill: explicitFill === void 0 || explicitFill === true ? fillFlag ? \"start\" : false : explicitFill, spanGaps: existingDataset?.spanGaps ?? true, ...needsDivider && { segment: { borderColor: getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.stackedDividerColorVar), borderWidth: 1 } } }; } /** * Create threshold mode datasets: invisible baseline + main dataset with * above/below fills. Accepts plain values (category mode) or {x, y} points * (time/number mode); the baseline mirrors the input x-positions. */ createThresholdDatasets(values, chartColors) { const yValues = values.map((v) => typeof v === \"number\" ? v : v.y).filter((n) => Number.isFinite(n)); const threshold = ((yValues.length ? Math.min(...yValues) : 0) + (yValues.length ? Math.max(...yValues) : 100)) / 2; const baselineData = values.map((v) => typeof v === \"number\" ? threshold : { x: v.x, y: threshold }); const lowRaw = LINE_GRAPH_GRID_CONFIG.thresholdLowColorVar; const highRaw = LINE_GRAPH_GRID_CONFIG.thresholdHighColorVar; const highFill = applyAlphaToColor(this, highRaw, .35); const lowFill = applyAlphaToColor(this, lowRaw, .35); const baselineDataset = { label: \"threshold-baseline\", data: baselineData, yAxisID: this.primaryYAxisId, borderColor: \"transparent\", backgroundColor: \"transparent\", borderWidth: 0, pointRadius: 0, showLine: false, fill: false, spanGaps: true }; const main = this.buildDataset(values, 0, chartColors); main.fill = { target: 0, above: highFill, below: lowFill }; main.borderWidth = 2; return [baselineDataset, main]; } /** * Prepare normalized datasets for multi-series charts. * In time/number mode every point's x is normalized (epoch ms / number) * so strings, Dates and Temporal objects position correctly. */ prepareMultiSeriesDatasets() { const defaultPalette = this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS; const chartColors = getChartColorsOrDefault(this, this.colors, defaultPalette); const normalized = this.datasets.map((ds) => this.normalizeDatasetX(ds)); if (this.isNumericXAxis) this.warnOnInvalidX(normalized.flatMap((ds) => (ds.data ?? []).map((pt) => pt && typeof pt === \"object\" ? pt.x : 0)), this.datasets); const totalCount = this.datasets.length; return normalized.map((ds, i) => this.buildDataset(ds, i, chartColors, totalCount)); } /** @internal - Return a copy of the dataset with normalized point x-values. */ normalizeDatasetX(ds) { if (!this.isNumericXAxis || !ds.data) return ds; const data = ds.data.map((pt) => pt && typeof pt === \"object\" && \"x\" in pt ? { ...pt, x: normalizeXValue(pt.x, this.xValueMode) } : pt); return { ...ds, data }; } /** * Prepare datasets for single-series charts. * Category mode: labels + numeric values (unchanged legacy path). * Time/number mode: normalized {x, y} points on a linear scale. * Handles both regular and threshold fill modes. */ prepareSingleSeriesDatasets() { const defaultPalette = this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS; const chartColors = getChartColorsOrDefault(this, this.colors, defaultPalette); const fill = this.shouldApplyFill(); const fillMode = this.getFillMode(); if (this.isNumericXAxis) { const points = this.data.map((d) => ({ x: normalizeXValue(d.x ?? d.label ?? NaN, this.xValueMode), y: d.value })); this.warnOnInvalidX(points.map((p) => p.x), this.data); return { datasets: fill && fillMode === \"threshold\" ? this.createThresholdDatasets(points, chartColors) : [this.buildDataset(points, 0, chartColors)], labels: [] }; } const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label ?? String(d.x ?? \"\")); return { datasets: fill && fillMode === \"threshold\" ? this.createThresholdDatasets(values, chartColors) : [this.buildDataset(values, 0, chartColors)], labels }; } /** * One padding source for the Chart.js layout and the slotted scales: two * sources painted the canvas over a scale and inset a scale inside a chart. */ computeChartPadding() { const isTooSmall = this.isBelowThreshold(); const scaleFactor = this.getScaleFactor(); const defaultPaddingScaled = !this.hasLabelPadding ? 0 : this.fixedAspectRatioScaling ? Math.round(CHART_DIMENSIONS.CANVAS_PADDING * scaleFactor) : CHART_DIMENSIONS.CANVAS_PADDING; const { y: yTexts, x: xTexts } = this.refreshRangeLabels(); const context = this.canvasEl?.getContext(\"2d\"); const gutters = (yTexts.length || xTexts.length) && context ? measureRangeLabelGutters(context, this.rangeLabelFont(), yTexts, xTexts) : { side: 0, bottom: 0 }; const scalePadding = this.calculatePaddingFromScales(); const freeSide = (side) => { if (!isTooSmall) return defaultPaddingScaled; if (side === \"bottom\") return gutters.bottom; return side === this.ySide ? gutters.side : 0; }; return { top: this.externalScaleDimensions.has(\"top\") ? scalePadding.top : freeSide(\"top\"), right: this.externalScaleDimensions.has(\"right\") ? scalePadding.right : freeSide(\"right\"), bottom: this.externalScaleDimensions.has(\"bottom\") ? scalePadding.bottom : freeSide(\"bottom\"), left: this.externalScaleDimensions.has(\"left\") ? scalePadding.left : freeSide(\"left\") }; } /** * Get Chart.js options with dynamic sizing and padding */ getChartOptions() { const effectiveWidth = this.getEffectiveWidth(); const effectiveHeight = this.getEffectiveHeight(); const isTooSmall = effectiveWidth < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS || effectiveHeight < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const padding = this.computeChartPadding(); if (this.fixedAspectRatioScaling) { this.style.setProperty(\"--chart-width\", \"100%\"); this.style.setProperty(\"--chart-height\", `${effectiveHeight}px`); } else { this.style.setProperty(\"--chart-width\", `${this.width}px`); this.style.setProperty(\"--chart-height\", `${this.height}px`); } const refTs = this.computeTimeReference(); const effectiveShowTickMarks = this.hasExternalScales() ? false : this.showTickMarks; return { responsive: true, maintainAspectRatio: false, layout: { padding }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !isTooSmall, callbacks: { title: () => \"\", label: (context) => { const value = typeof context.parsed === \"object\" && context.parsed !== null ? context.parsed.y : context.parsed; const numericValue = formatChartNumber(value, 1, false, 0); const unit = this.unit ? `${this.unit}` : \"\"; let label = context.label ?? \"\"; if (this.isNumericXAxis) { const x = typeof context.parsed === \"object\" && context.parsed !== null ? context.parsed.x : NaN; const relativeTo = this.timeDisplay === \"minutes\" ? refTs : void 0; label = formatXValue(x, this.xValueMode, relativeTo); } return `${label} ${numericValue}${unit}`; } } } }, animation: false, scales: this.buildScalesConfig(refTs, isTooSmall, effectiveShowTickMarks) }; } /** * Compute reference timestamp for time axis formatting. * Returns earliest timestamp for 'date' mode, latest for 'minutes' mode. * A pinned x range supplies the reference instead, so the axis edge stays * the reference while the data has not reached it yet. */ computeTimeReference() { if (this.xAxisType !== \"time\") return void 0; const pinned = this.timeDisplay === \"minutes\" ? this.xAxis?.max : this.xAxis?.min; if (pinned !== void 0 && Number.isFinite(pinned)) return pinned; const timestamps = []; if (this.datasets?.length) this.datasets.forEach((ds) => { if (!ds.data) return; ds.data.forEach((pt) => { if (pt && typeof pt === \"object\" && \"x\" in pt) { const ts = normalizeXValue(pt.x, XValueMode.time); if (Number.isFinite(ts)) timestamps.push(ts); } }); }); else if (this.data?.length) this.data.forEach((d) => { const ts = normalizeXValue(d.x ?? d.label ?? NaN, XValueMode.time); if (Number.isFinite(ts)) timestamps.push(ts); }); if (!timestamps.length && this.labels?.length) this.labels.forEach((l) => { if (typeof l === \"string\") { const ts = new Date(l).getTime(); if (Number.isFinite(ts)) timestamps.push(ts); } }); return timestamps.length ? this.timeDisplay === \"minutes\" ? Math.max(...timestamps) : Math.min(...timestamps) : void 0; } /** * Build Chart.js scale configuration with theme-aware styling. * Applies CSS variables for grid colors, tick colors, and label typography. * * @param minX - Reference timestamp for time-based x-axis (used for 'minutes' display) * @param isTooSmall - Whether chart is below 192px threshold (hides ticks when true) * @param showTickMarks - Whether to show tick marks (overridden to false when external scales present) * @returns Configured scales object for Chart.js options */ buildScalesConfig(minX, isTooSmall = false, showTickMarks = true) { const gridColor = getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.gridColorVar); const tickColor = getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.tickColorVar); const fontFamily = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontFamily); const fontSize = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontSizeVar); const fontWeight = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontWeightVar); const fontColor = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); const showLabels = showTickMarks && !isTooSmall && this.hasLabelPadding; const showTicks = showTickMarks && !isTooSmall && this.hasLabelPadding; const fontConfig = { family: fontFamily, size: fontSize, weight: fontWeight }; const x = { type: this.xAxisType === \"category\" ? \"category\" : \"linear\", offset: false, grace: 0, bounds: \"data\", min: this.isNumericXAxis ? this.xAxis?.min : void 0, max: this.isNumericXAxis ? this.xAxis?.max : void 0, grid: { display: this.showGrid && this.showGridX, color: gridColor, offset: false, drawTicks: showTicks }, ticks: { display: showLabels, color: fontColor, font: fontConfig, maxRotation: 0, minRotation: 0, maxTicksLimit: this.xTicksLimit, stepSize: this.xStepSize, callback: (value) => { if (!this.isNumericXAxis) return String(value); const n = Number(value); if (!Number.isFinite(n)) return String(value); const relativeTo = this.timeDisplay === \"minutes\" ? minX : void 0; return formatXValue(n, this.xValueMode, relativeTo); } }, border: { display: showLabels, color: tickColor } }; const yAxesConfig = this.yAxes?.length ? this.yAxes.map((axis, i) => ({ id: axis.id ?? `y${i}`, position: axis.position ?? \"left\", min: axis.min, max: axis.max, reverse: axis.reverse ?? false, gridDisplay: axis.grid ?? (this.showGrid && this.showGridY) })) : [{ id: \"y\", position: this.yAxisPosition, min: void 0, max: void 0, reverse: false, gridDisplay: this.showGrid && this.showGridY }]; const scalesRecord = { x }; yAxesConfig.forEach(({ id, position, min, max, reverse, gridDisplay }) => { scalesRecord[id] = { type: \"linear\", display: true, position, reverse, stacked: this.shouldStack() && this.getFillMode() !== \"threshold\", grace: isTooSmall ? 0 : void 0, bounds: isTooSmall ? \"data\" : \"ticks\", grid: { display: gridDisplay, color: gridColor, drawTicks: showTicks }, ticks: { display: showLabels, color: fontColor, font: fontConfig, maxTicksLimit: this.yTicksLimit, stepSize: this.yStepSize }, border: { display: showLabels, color: tickColor }, min, max }; }); return scalesRecord; } /** * Prepare chart data and labels for both single and multi-series modes */ prepareChartDataAndLabels() { if (this.datasets?.length) return { datasets: this.prepareMultiSeriesDatasets(), labels: this.labels ?? [] }; return this.prepareSingleSeriesDatasets(); } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; if (this.chart) { this.chart.destroy(); this.chart = void 0; } const { datasets, labels } = this.prepareChartDataAndLabels(); this.chart = new Chart(ctx, { type: \"line\", data: { labels, datasets }, options: this.getChartOptions(), plugins: [ ...this.borderRadiusPosition ? [this.createBorderPlugin()] : [], ...this.rangeLabels !== \"none\" ? [this.createRangeLabelsPlugin()] : [], this.createMarkersPlugin() ] }); requestAnimationFrame(() => this.updateLegend()); if (this.applyFillModes()) this.chart.update(\"none\"); this.syncSlottedScaleRanges(); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { datasets, labels } = this.prepareChartDataAndLabels(); this.chart.data.labels = labels; this.chart.data.datasets = datasets; Object.assign(this.chart.options, this.getChartOptions()); this.applyFillModes(); this.chart.update(); this.syncSlottedScaleRanges(); requestAnimationFrame(() => this.updateLegend()); } /** * Update only chart colors without recalculating layout * Used by theme observer for efficient theme changes */ updateChartColors() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; this.applyFillModes(); this.chart.update(\"none\"); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; if (!this.chart.data.datasets || this.chart.data.datasets.length === 0) { this.legendDiv.innerHTML = \"\"; return; } try { const legendItems = this.chart.data.datasets.map((ds, i) => { const meta = this.chart.getDatasetMeta(i); if (!meta || !meta.controller) return null; const style = meta.controller.getStyle(0, false); const dataset = ds; return { fillStyle: dataset.borderColor ?? style.borderColor ?? \"\", label: dataset.label || `Series ${i + 1}`, value: \"\", unit: \"\" }; }).filter((item) => item !== null); if (legendItems.length > 0) { const legendHTML = generateLegendHTML(legendItems); this.legendDiv.innerHTML = legendHTML; } } catch (error) { console.debug(\"[chart-line-base] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <div class=\"canvas-and-slots-container\"> <slot name=\"top-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"bottom-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"left-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"right-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <canvas></canvas> </div> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(chart_line_base_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }",
3352
+ "default": "class extends LitElement { constructor(..._args) { super(..._args); this.data = []; this.datasets = void 0; this.labels = void 0; this.colors = []; this.legend = false; this.showDebugOverlay = false; this.width = 480; this.height = 320; this.fixedAspectRatioScaling = false; this.scaleReferenceSize = 384; this.xAxisType = \"category\"; this.yAxisPosition = \"left\"; this.yAxes = void 0; this.xAxis = void 0; this.xMarker = void 0; this.yMarker = void 0; this.showGrid = false; this.showGridX = false; this.showGridY = false; this.showTickMarks = false; this.hasLabelPadding = true; this.rangeLabels = \"none\"; this.warnedDateDisplayScale = false; this.DEFAULT_TENSION = .4; this.POINT_RADIUS = 3; this.showPoints = false; this.lineMode = \"smooth\"; this.unit = \"\"; this.timeDisplay = \"date\"; this.xTicksLimit = void 0; this.xStepSize = void 0; this.yTicksLimit = void 0; this.yStepSize = void 0; this.state = InstrumentState.active; this.priority = Priority.regular; this.frameStyle = FrameStyle.regular; this.borderRadiusPosition = void 0; this.borderRadiusPositionExternalScales = void 0; this.instrumentMode = false; this.borderRadius = void 0; this.externalScaleDimensions = /* @__PURE__ */ new Map(); this.isUpdatingScales = false; this.currentBorderRadiusPx = 8; this.computedWidth = 480; this.computedHeight = 320; this.savedLabelThickness = /* @__PURE__ */ new WeakMap(); this.savedMainTickmarkLabels = /* @__PURE__ */ new WeakMap(); this.lastRangeLabels = []; this.lastMarkers = {}; this.rangeLabelCache = { y: [], x: [] }; this.updateBorderRadius = () => { if (!this.canvasEl) return; let next; if (this.instrumentMode) next = this.borderRadius ?? 8; else next = readExternalScaleBorderRadiusPx(this.canvasEl, ScaleType.regular, EXTERNAL_SCALE_BORDER_RADIUS_CSS_VAR); if (this.currentBorderRadiusPx !== next) { this.currentBorderRadiusPx = next; if (this.chart) { this.chart.destroy(); this.createChart(); } } }; this.handleSlotChange = () => { this.externalScaleDimensions.clear(); this.waitForScaleDimensions(); }; this.handleScaleDimensionsChanged = (e) => { if (this.isUpdatingScales) return; const { side, thickness } = e.detail; if (this.externalScaleDimensions.get(side) === thickness) return; this.externalScaleDimensions.set(side, thickness); if (this.dimensionUpdateTimer) clearTimeout(this.dimensionUpdateTimer); this.dimensionUpdateTimer = setTimeout(() => { this.syncScalesAndChart(); }, 16); }; } /** @internal - The y side wants range labels; an edge-to-edge chart never does. */ get rangeLabelsY() { return this.hasLabelPadding && (this.rangeLabels === \"y\" || this.rangeLabels === \"xy\"); } /** @internal - The x side wants range labels; an edge-to-edge chart never does. */ get rangeLabelsX() { return this.hasLabelPadding && (this.rangeLabels === \"x\" || this.rangeLabels === \"xy\"); } /** @internal - True when the x-axis positions points by numeric value. */ get isNumericXAxis() { return this.xAxisType === \"time\" || this.xAxisType === \"number\"; } /** * Id of the y scale a dataset lands on when it names none. Chart.js would * otherwise add a default `y` scale next to the configured ones and draw it. */ get primaryYAxisId() { return this.yAxes?.length ? this.yAxes[0].id ?? \"y0\" : \"y\"; } /** @internal - Normalization mode for the current x-axis type. */ get xValueMode() { return this.xAxisType === \"number\" ? XValueMode.number : XValueMode.time; } /** * `reverse` of the axis a side follows: the first axis positioned on that * side, else the first entry — the selection `resolveAxisRange()` makes. */ isYAxisReversed(side = \"left\") { if (!this.yAxes?.length) return false; return (this.yAxes.find((a) => (a.position ?? \"left\") === side) ?? this.yAxes[0]).reverse ?? false; } /** @internal - Warn once per data assignment about unparseable x-values. */ warnOnInvalidX(xValues, sourceRef) { const invalid = xValues.filter((x) => !Number.isFinite(x)).length; if (invalid === 0 || this.lastWarnedXSource === sourceRef) return; this.lastWarnedXSource = sourceRef; console.warn(`[obc-chart] ${invalid} x value(s) could not be parsed for xAxisType='${this.xAxisType}'; the points render as gaps.`); } /** * Should fill be applied to this chart? * Line graph returns false, area graph returns true. * Must be implemented in subclass. */ shouldApplyFill() { throw new Error(\"shouldApplyFill() must be implemented in subclass\"); } /** * Get fill mode for area rendering. * Line graph returns undefined, area graph returns 'semitransparent' | 'solid' | 'threshold'. * Must be implemented in subclass. */ getFillMode() { throw new Error(\"getFillMode() must be implemented in subclass\"); } /** * Should multi-series datasets be stacked? * Line graph returns false, area graph returns stacked property value. * Must be implemented in subclass. */ shouldStack() { throw new Error(\"shouldStack() must be implemented in subclass\"); } /** * Label band a slotted scale needs for its compact labels, in the scale's * own viewBox units. The scale prints the raw values, so those are what is * measured; the x band is one text line. */ compactLabelThickness(axis) { const context = this.canvasEl?.getContext(\"2d\"); if (!context) return void 0; const font = this.rangeLabelFont(); let visual; if (axis === \"y\") { const bounds = this.rangeLabelCache.bounds; if (!bounds) return void 0; const texts = yRangeLabelValues(bounds.min, bounds.max).map(String); visual = measureRangeLabelGutters(context, font, texts, []).side + 4; } else visual = measureRangeLabelGutters(context, font, [], [\"x\"]).bottom + 8; if (!this.fixedAspectRatioScaling) return Math.ceil(visual); const effectiveLength = axis === \"y\" ? this.getEffectiveHeight() : this.getEffectiveWidth(); return Math.ceil(visual * this.scaleReferenceSize / effectiveLength); } /** @internal - Ellipse clips applied last, in pixels by dataset index, for tests. */ get lastClips() { return (this.chart && datasetClipRecords.get(this.chart)) ?? {}; } slotFor(side) { return { left: this.leftScaleSlot, right: this.rightScaleSlot, top: this.topScaleSlot, bottom: this.bottomScaleSlot }[side]; } hasSlottedScale(side) { return (this.slotFor(side)?.assignedElements().length ?? 0) > 0; } /** @internal - Below the label threshold on either dimension. */ isBelowThreshold() { return this.getEffectiveWidth() < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS || this.getEffectiveHeight() < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; } get ySide() { return (this.yAxes?.[0]?.position ?? this.yAxisPosition) === \"right\" ? \"right\" : \"left\"; } rangeLabelFont() { const sizePx = Number.parseFloat(getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontSizeVar)); return { family: getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontFamily), sizePx: Number.isFinite(sizePx) ? sizePx : 12, weight: getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontWeightVar) }; } /** * Extent of the prepared data: one for x, one per y scale id. Each y axis * ranges from its own datasets, so a merged extent would label one axis * with another's values. */ dataExtents(prepared) { const x = { min: Infinity, max: -Infinity }; const y = /* @__PURE__ */ new Map(); const take = (extent, v) => { if (!Number.isFinite(v)) return; extent.min = Math.min(extent.min, v); extent.max = Math.max(extent.max, v); }; prepared.datasets.forEach((dataset) => { const id = dataset.yAxisID ?? this.primaryYAxisId; const extent = y.get(id) ?? { min: Infinity, max: -Infinity }; y.set(id, extent); dataset.data.forEach((point) => { if (typeof point === \"number\") take(extent, point); else if (point) { take(x, point.x); take(extent, point.y); } }); }); y.forEach((extent, id) => { if (!(extent.min <= extent.max)) y.delete(id); }); return { x: x.min <= x.max ? x : void 0, y }; } /** * Range the y labels describe. Below the threshold the axis runs on data * bounds, so its datasets' extent is exact and needs no chart to read from. */ yRangeBounds(extents) { let axis; let id = \"y\"; if (this.yAxes?.length) { const match = this.yAxes.findIndex((a) => (a.position ?? \"left\") === this.ySide); const index = match === -1 ? 0 : match; axis = this.yAxes[index]; id = axis.id ?? `y${index}`; } const extent = extents.get(id); const stackedScale = this.shouldStack() ? this.chart?.scales[id] : void 0; const min = axis?.min ?? stackedScale?.min ?? extent?.min; const max = axis?.max ?? stackedScale?.max ?? extent?.max; return min !== void 0 && max !== void 0 ? { min, max } : void 0; } /** First and last x label, or nothing when there is no span to label. */ xEdgeLabelTexts(prepared, extent) { if (!this.isNumericXAxis) { const labels = prepared.labels.map(String); const first = labels[0]; const last = labels[labels.length - 1]; return labels.length > 1 && first !== last ? [first, last] : []; } const min = this.xAxis?.min ?? extent?.min; const max = this.xAxis?.max ?? extent?.max; if (min === void 0 || max === void 0 || min === max) return []; const reference = this.timeDisplay === \"minutes\" ? this.computeTimeReference() : void 0; return [formatXValue(min, this.xValueMode, reference), formatXValue(max, this.xValueMode, reference)]; } /** * Recompute the range labels. A side with a slotted scale is labelled by * the scale, so it gets no text here; the y bounds are kept regardless, * since the scale's compact band is measured from them. */ refreshRangeLabels() { const cache = { y: [], x: [] }; if (this.isBelowThreshold() && (this.rangeLabelsY || this.rangeLabelsX)) { const prepared = this.prepareChartDataAndLabels(); const extents = this.dataExtents(prepared); if (this.rangeLabelsY) { cache.bounds = this.yRangeBounds(extents.y); if (cache.bounds && !this.hasSlottedScale(\"left\") && !this.hasSlottedScale(\"right\")) { const { min, max } = cache.bounds; cache.y = yRangeLabelValues(min, max).map((v) => formatRangeValue(v, min, max)); } } if (this.rangeLabelsX && !this.hasSlottedScale(\"top\") && !this.hasSlottedScale(\"bottom\")) cache.x = this.xEdgeLabelTexts(prepared, extents.x); } this.rangeLabelCache = cache; return cache; } /** * Value cursors drawn after the datasets, in the dataset's own colour, so no * annotation dependency is needed. A no-op while both markers are unset. */ createMarkersPlugin() { return { id: \"markers\", afterDatasetsDraw: (chart) => { this.lastMarkers = {}; if (!this.xMarker && !this.yMarker) return; const area = chart.chartArea; const ctx = chart.ctx; const datasetOf = (index = 0) => chart.data.datasets[index]; const yScaleOf = (ds) => chart.scales[ds?.yAxisID ?? this.primaryYAxisId]; const colorOf = (ds) => typeof ds?.borderColor === \"string\" ? ds.borderColor : getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); ctx.save(); ctx.beginPath(); ctx.rect(area.left, area.top, area.right - area.left, area.bottom - area.top); ctx.clip(); let dot; const xScale = chart.scales[\"x\"]; if (this.xMarker && xScale) { const ds = datasetOf(this.xMarker.datasetIndex); const xValue = this.isNumericXAxis ? normalizeXValue(this.xMarker.x, this.xValueMode) : typeof this.xMarker.x === \"number\" ? this.xMarker.x : (chart.data.labels ?? []).indexOf(this.xMarker.x); if (Number.isFinite(xValue) && (this.isNumericXAxis || xValue >= 0)) { const xPixel = xScale.getPixelForValue(xValue); const x = Math.round(xPixel) + .5; const hit = chart.getDatasetMeta(this.xMarker.datasetIndex ?? 0).dataset?.interpolate({ x: xPixel, y: 0 }, \"x\"); const hitY = (Array.isArray(hit) ? hit[0] : hit)?.y; const y = typeof hitY === \"number\" ? hitY : void 0; const color = colorOf(ds); ctx.strokeStyle = color; ctx.lineWidth = MARKER.lineWidth; ctx.setLineDash([]); ctx.beginPath(); ctx.moveTo(x, area.top); ctx.lineTo(x, y ?? area.top); ctx.stroke(); ctx.setLineDash([...MARKER.dash]); ctx.beginPath(); ctx.moveTo(x, y ?? area.top); ctx.lineTo(x, area.bottom); ctx.stroke(); ctx.setLineDash([]); if (y !== void 0 && xPixel >= area.left && xPixel <= area.right && y >= area.top && y <= area.bottom && (this.xMarker.showDot ?? true)) dot = { x, y, color }; this.lastMarkers.x = { x, y, dot: dot !== void 0 }; } } if (this.yMarker) { const ds = datasetOf(this.yMarker.datasetIndex); const yScale = yScaleOf(ds); if (yScale) { const y = yScale.getPixelForValue(this.yMarker.y); ctx.lineWidth = MARKER.lineWidth; ctx.strokeStyle = getCssVariableValue(this, MARKER.ringColorVar); ctx.beginPath(); ctx.moveTo(area.left, y + MARKER.valueLineWidth / 2 + .5); ctx.lineTo(area.right, y + MARKER.valueLineWidth / 2 + .5); ctx.stroke(); ctx.lineWidth = MARKER.valueLineWidth; ctx.strokeStyle = colorOf(ds); ctx.beginPath(); ctx.moveTo(area.left, y); ctx.lineTo(area.right, y); ctx.stroke(); this.lastMarkers.y = { y }; } } ctx.restore(); if (dot) { ctx.save(); ctx.beginPath(); ctx.arc(dot.x, dot.y, MARKER.dotRadius, 0, Math.PI * 2); ctx.fillStyle = dot.color; ctx.fill(); ctx.lineWidth = MARKER.dotRingWidth; ctx.strokeStyle = getCssVariableValue(this, MARKER.ringColorVar); ctx.stroke(); ctx.restore(); } } }; } /** * Paints min / 0 / max and first / last once Chart.js has drawn, inside the * gutters `getChartOptions()` reserved. The end labels sit flush with the * plot edges so no vertical padding is needed for them. */ createRangeLabelsPlugin() { return { id: \"rangeLabels\", afterDraw: (chart) => { this.lastRangeLabels = []; const { y: yTexts, x: xTexts, bounds } = this.rangeLabelCache; if (!yTexts.length && !xTexts.length) return; const area = chart.chartArea; const ctx = chart.ctx; const font = this.rangeLabelFont(); const lineHeight = rangeLabelLineHeight(font); ctx.save(); ctx.font = rangeLabelFontString(font); ctx.fillStyle = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); const scale = chart.scales[this.primaryYAxisId]; if (yTexts.length && bounds && scale) { const onRight = this.ySide === \"right\"; const x = onRight ? area.right + 8 : area.left - 8; ctx.textAlign = onRight ? \"left\" : \"right\"; const values = yRangeLabelValues(bounds.min, bounds.max); const reversed = this.isYAxisReversed(this.ySide); for (let i = values.length - 1; i >= 0; i--) { const isMax = i === values.length - 1; const isMin = i === 0; const isEnd = isMax || isMin; const atTop = isMax !== reversed; const y = isEnd ? atTop ? area.top : area.bottom : scale.getPixelForValue(values[i]); if (!isMax && !isMin && (y - area.top < lineHeight || area.bottom - y < lineHeight)) continue; ctx.textBaseline = isEnd ? atTop ? \"top\" : \"bottom\" : \"middle\"; ctx.fillText(yTexts[i], x, y); this.lastRangeLabels.push({ axis: \"y\", text: yTexts[i], x, y }); } } if (xTexts.length === 2) { const y = area.bottom + 4; ctx.textBaseline = \"top\"; ctx.textAlign = \"left\"; ctx.fillText(xTexts[0], area.left, y); this.lastRangeLabels.push({ axis: \"x\", text: xTexts[0], x: area.left, y }); ctx.textAlign = \"right\"; ctx.fillText(xTexts[1], area.right, y); this.lastRangeLabels.push({ axis: \"x\", text: xTexts[1], x: area.right, y }); } ctx.restore(); } }; } /** * Check if a slotted scale element is actually visible (renders content). * For bar-vertical/bar-horizontal elements, checks hasBar and hasScale properties. */ hasVisibleScale(side) { return (this.slotFor(side)?.assignedElements() ?? []).some((el) => { const barEl = el; if (\"hasBar\" in barEl && \"hasScale\" in barEl) return barEl.hasBar === true || barEl.hasScale === true; return true; }); } computeRoundedCorners() { if (!this.borderRadiusPosition) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; if (this.borderRadiusPosition === BorderRadiusPosition.middleChild) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; if (this.borderRadiusPosition === BorderRadiusPosition.middleRoundedChild) return { topLeft: true, topRight: true, bottomLeft: true, bottomRight: true }; const hasLeft = this.hasVisibleScale(\"left\"); const hasRight = this.hasVisibleScale(\"right\"); const hasTop = this.hasVisibleScale(\"top\"); const hasBottom = this.hasVisibleScale(\"bottom\"); if (hasLeft && hasRight || hasTop && hasBottom) return { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; const result = { topLeft: false, topRight: false, bottomLeft: false, bottomRight: false }; const isInner = this.borderRadiusPosition === BorderRadiusPosition.innerFirstChild; const isOuter = this.borderRadiusPosition === BorderRadiusPosition.outerLastChild; if (hasRight && hasBottom) { if (isInner) result.bottomRight = true; else if (isOuter) result.topLeft = true; } else if (hasRight && hasTop) { if (isInner) result.topRight = true; else if (isOuter) result.bottomLeft = true; } else if (hasLeft && hasBottom) { if (isInner) result.bottomLeft = true; else if (isOuter) result.topRight = true; } else if (hasLeft && hasTop) { if (isInner) result.topLeft = true; else if (isOuter) result.bottomRight = true; } else if (hasRight && !hasLeft) { if (isInner) { result.topLeft = true; result.bottomLeft = true; } else if (isOuter) { result.topRight = true; result.bottomRight = true; } } else if (hasLeft && !hasRight) { if (isInner) { result.topRight = true; result.bottomRight = true; } else if (isOuter) { result.topLeft = true; result.bottomLeft = true; } } else if (hasBottom && !hasTop) { if (isInner) { result.topLeft = true; result.topRight = true; } else if (isOuter) { result.bottomLeft = true; result.bottomRight = true; } } else if (hasTop && !hasBottom) { if (isInner) { result.bottomLeft = true; result.bottomRight = true; } else if (isOuter) { result.topLeft = true; result.topRight = true; } } return result; } /** * Create a Chart.js plugin that draws a border around the chart area with selective corner rounding * and clips content to that border. */ createBorderPlugin() { const corners = this.computeRoundedCorners(); const radius = this.currentBorderRadiusPx; let didApplyClip = false; const buildRoundedRectPath = (ctx, rect, cornerRadius) => { const { x, y, width, height } = rect; if (width <= 0 || height <= 0) return; const r = clamp(cornerRadius, 0, Math.max(0, Math.min(width, height) / 2)); ctx.moveTo(x + (corners.topLeft ? r : 0), y); ctx.lineTo(x + width - (corners.topRight ? r : 0), y); if (corners.topRight) ctx.arcTo(x + width, y, x + width, y + r, r); ctx.lineTo(x + width, y + height - (corners.bottomRight ? r : 0)); if (corners.bottomRight) ctx.arcTo(x + width, y + height, x + width - r, y + height, r); ctx.lineTo(x + (corners.bottomLeft ? r : 0), y + height); if (corners.bottomLeft) ctx.arcTo(x, y + height, x, y + height - r, r); ctx.lineTo(x, y + (corners.topLeft ? r : 0)); if (corners.topLeft) ctx.arcTo(x, y, x + r, y, r); }; return { id: \"chartAreaBorder\", beforeDatasetsDraw: (chart) => { const ctx = chart.ctx; const chartArea = chart.chartArea; if (!chartArea) return; const clipInset = 1; const { top, right, bottom, left } = chartArea; const rect = { x: left + clipInset, y: top + clipInset, width: right - left - 2, height: bottom - top - 2 }; const clipRadius = Math.max(0, radius - clipInset); ctx.save(); didApplyClip = true; ctx.beginPath(); buildRoundedRectPath(ctx, rect, clipRadius); ctx.closePath(); if (this.instrumentMode) { ctx.fillStyle = getCssVariableValue(this, CHART_AREA_BACKGROUND_COLOR_VAR); ctx.fill(); } ctx.clip(); }, afterDraw: (chart) => { const ctx = chart.ctx; const chartArea = chart.chartArea; if (!chartArea) return; const borderWidthPx = 1; const strokeInset = borderWidthPx / 2; const { top, right, bottom, left } = chartArea; const rect = { x: left + strokeInset, y: top + strokeInset, width: right - left - strokeInset * 2, height: bottom - top - strokeInset * 2 }; const strokeRadius = Math.max(0, radius - strokeInset); const skipTop = this.hasVisibleScale(\"top\"); const skipRight = this.hasVisibleScale(\"right\"); const skipBottom = this.hasVisibleScale(\"bottom\"); const skipLeft = this.hasVisibleScale(\"left\"); const borderColor = getCssVariableValue(this, \"--instrument-frame-tertiary-color\"); ctx.save(); ctx.strokeStyle = borderColor; ctx.lineWidth = borderWidthPx; const { x, y, width, height } = rect; const r = clamp(strokeRadius, 0, Math.max(0, Math.min(width, height) / 2)); if (!skipTop && !skipRight && !skipBottom && !skipLeft) { ctx.beginPath(); buildRoundedRectPath(ctx, rect, strokeRadius); ctx.closePath(); ctx.stroke(); } else { if (!skipTop) { ctx.beginPath(); if (!skipLeft && corners.topLeft) ctx.moveTo(x + r, y); else ctx.moveTo(x, y); if (!skipRight && corners.topRight) ctx.lineTo(x + width - r, y); else ctx.lineTo(x + width, y); ctx.stroke(); } if (!skipRight) { ctx.beginPath(); if (!skipTop && corners.topRight) ctx.moveTo(x + width, y + r); else ctx.moveTo(x + width, y); if (!skipBottom && corners.bottomRight) ctx.lineTo(x + width, y + height - r); else ctx.lineTo(x + width, y + height); ctx.stroke(); } if (!skipBottom) { ctx.beginPath(); if (!skipRight && corners.bottomRight) ctx.moveTo(x + width - r, y + height); else ctx.moveTo(x + width, y + height); if (!skipLeft && corners.bottomLeft) ctx.lineTo(x + r, y + height); else ctx.lineTo(x, y + height); ctx.stroke(); } if (!skipLeft) { ctx.beginPath(); if (!skipBottom && corners.bottomLeft) ctx.moveTo(x, y + height - r); else ctx.moveTo(x, y + height); if (!skipTop && corners.topLeft) ctx.lineTo(x, y + r); else ctx.lineTo(x, y); ctx.stroke(); } if (!skipTop && !skipLeft && corners.topLeft) { ctx.beginPath(); ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5); ctx.stroke(); } if (!skipTop && !skipRight && corners.topRight) { ctx.beginPath(); ctx.arc(x + width - r, y + r, r, Math.PI * 1.5, Math.PI * 2); ctx.stroke(); } if (!skipRight && !skipBottom && corners.bottomRight) { ctx.beginPath(); ctx.arc(x + width - r, y + height - r, r, 0, Math.PI * .5); ctx.stroke(); } if (!skipBottom && !skipLeft && corners.bottomLeft) { ctx.beginPath(); ctx.arc(x + r, y + height - r, r, Math.PI * .5, Math.PI); ctx.stroke(); } } ctx.restore(); if (this.showPoints) { ctx.save(); chart.data.datasets.forEach((_ds, datasetIndex) => { const meta = chart.getDatasetMeta(datasetIndex); if (!meta || meta.hidden) return; (meta.data ?? []).forEach((el) => { const point = el; if (point.skip) return; const r = point.options?.radius; if (typeof r === \"number\" && r <= 0) return; point.draw(ctx); }); }); ctx.restore(); } }, afterDatasetsDraw: (chart) => { if (didApplyClip) { chart.ctx.restore(); didApplyClip = false; } } }; } /** * Check if any external scales are slotted */ hasExternalScales() { const top = this.topScaleSlot?.assignedElements() ?? []; const bottom = this.bottomScaleSlot?.assignedElements() ?? []; const left = this.leftScaleSlot?.assignedElements() ?? []; const right = this.rightScaleSlot?.assignedElements() ?? []; return top.length > 0 || bottom.length > 0 || left.length > 0 || right.length > 0; } /** * Wait for all slotted scales to report their dimensions */ async waitForScaleDimensions() { if (!this.hasExternalScales()) { this.requestUpdate(); return; } const scaleElements = []; [ this.topScaleSlot, this.bottomScaleSlot, this.leftScaleSlot, this.rightScaleSlot ].forEach((slot) => { if (slot) { const assigned = slot.assignedElements(); scaleElements.push(...assigned); } }); const setScaleProps = (slot) => { if (!slot) return; slot.assignedElements().forEach((scale) => { scale.fixedAspectRatio = this.fixedAspectRatioScaling; scale.scaleReferenceSize = this.scaleReferenceSize; }); }; setScaleProps(this.leftScaleSlot); setScaleProps(this.rightScaleSlot); setScaleProps(this.topScaleSlot); setScaleProps(this.bottomScaleSlot); await Promise.all(scaleElements.map((el) => \"updateComplete\" in el && typeof el.updateComplete === \"object\" ? el.updateComplete : Promise.resolve())); if (this.externalScaleDimensions.size === 0 && scaleElements.length > 0) await new Promise((resolve) => setTimeout(resolve, 50)); this.syncScalesAndChart(); } /** * Synchronize scale and chart dimensions/data * This is the main coordination function */ syncScalesAndChart() { if (this.isUpdatingScales) return false; this.isUpdatingScales = true; try { const padding = this.computeChartPadding(); const effectiveWidth = this.getEffectiveWidth() - padding.left - padding.right; const effectiveHeight = this.getEffectiveHeight() - padding.top - padding.bottom; if (effectiveWidth <= 0 || effectiveHeight <= 0) { console.warn(\"[chart-line-base] Invalid effective dimensions\", { width: this.getEffectiveWidth(), height: this.getEffectiveHeight(), padding, effectiveWidth, effectiveHeight }); return false; } this.updateScaleProperties(padding); if (this.chart) this.chart.destroy(); this.createChart(); return true; } finally { this.isUpdatingScales = false; } } /** * Calculate chart padding from external scale dimensions. * * For sides without an external scale, falls back to `CHART_DIMENSIONS.CANVAS_PADDING` * (the chart's own padding to reserve room for axis tick labels). When * `hasLabelPadding=false` that fallback is 0 so the chart renders edge-to-edge, * and this same value is cascaded to slotted scales via `updateScaleProperties()` * — so the bar's main-axis padding (`paddingTop`/`paddingBottom` for vertical bars) * collapses with the chart's perpendicular padding and they stay visually aligned. */ calculatePaddingFromScales() { const defaultPadding = this.hasLabelPadding ? CHART_DIMENSIONS.CANVAS_PADDING : 0; return { top: this.externalScaleDimensions.get(\"top\") ?? defaultPadding, right: this.externalScaleDimensions.get(\"right\") ?? defaultPadding, bottom: this.externalScaleDimensions.get(\"bottom\") ?? defaultPadding, left: this.externalScaleDimensions.get(\"left\") ?? defaultPadding }; } /** * Range a slotted scale on the given side has to cover. * * A range pinned in the axis configuration is used as is: it is the source * of truth, and on the first sync there is no chart to read yet. Otherwise * the live Chart.js scale is read under the id `buildScalesConfig()` gives * it. A side with no axis of its own follows the first configured one. */ resolveAxisRange(side) { let id = side === \"x\" ? \"x\" : \"y\"; let configured; if (side === \"x\") configured = this.isNumericXAxis ? this.xAxis : void 0; else if (this.yAxes?.length) { const match = this.yAxes.findIndex((axis) => (axis.position ?? \"left\") === side); const index = match === -1 ? 0 : match; const axis = this.yAxes[index]; id = axis.id ?? `y${index}`; configured = axis; } if (configured?.min !== void 0 && configured.max !== void 0) return { min: configured.min, max: configured.max }; const scale = this.chart?.scales[id]; return { min: scale?.min ?? configured?.min ?? 0, max: scale?.max ?? configured?.max ?? 100 }; } /** * Range pushed to the top and bottom scales, or `undefined` to leave them * alone. A scale prints its values verbatim, and on a `time` axis the raw * range is epoch milliseconds. In `minutes` display the range is converted * to the minutes the chart's own labels show; `date` display has no numeric * equivalent, so the scale keeps its own range. */ resolveSlottedXRange() { const range = this.resolveAxisRange(\"x\"); if (this.xAxisType !== \"time\") return range; if (this.timeDisplay !== \"minutes\") { if (!this.warnedDateDisplayScale) { this.warnedDateDisplayScale = true; console.warn(\"[obc-chart] a slotted horizontal scale cannot label a time axis in 'date' display and keeps its own range; use timeDisplay='minutes' or a number axis.\"); } return; } const pinned = this.xAxis?.min !== void 0 && this.xAxis?.max !== void 0; const reference = this.computeTimeReference(); if (reference === void 0 || !this.chart && !pinned) return void 0; const minute = 6e4; return { min: (range.min - reference) / minute, max: (range.max - reference) / minute }; } /** * Update properties on slotted scale elements */ updateScaleProperties(padding) { const leftRange = this.resolveAxisRange(\"left\"); const rightRange = this.resolveAxisRange(\"right\"); const xRange = this.resolveSlottedXRange(); const effectiveWidth = this.getEffectiveWidth(); const effectiveHeight = this.getEffectiveHeight(); const aboveThreshold = effectiveWidth >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS && effectiveHeight >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const showLabels = this.hasLabelPadding && aboveThreshold; const compactY = !aboveThreshold && this.rangeLabelsY; const compactX = !aboveThreshold && this.rangeLabelsX; const compactYThickness = compactY ? this.compactLabelThickness(\"y\") : void 0; const compactXThickness = compactX ? this.compactLabelThickness(\"x\") : void 0; const mainLabelsFor = (scale, compact) => { if (compact) { if (!this.savedMainTickmarkLabels.has(scale)) this.savedMainTickmarkLabels.set(scale, scale.showMainTickmarkLabels ?? false); return true; } if (!this.savedMainTickmarkLabels.has(scale)) return void 0; const saved = this.savedMainTickmarkLabels.get(scale); this.savedMainTickmarkLabels.delete(scale); return saved; }; const bandFor = (scale, compact, thickness) => { if (compact) { if (thickness === void 0 || typeof scale.labelThickness !== \"number\") return; if (!this.savedLabelThickness.has(scale)) this.savedLabelThickness.set(scale, scale.labelThickness); return thickness; } const saved = this.savedLabelThickness.get(scale); this.savedLabelThickness.delete(scale); return saved; }; const verticalViewBoxPadding = this.fixedAspectRatioScaling ? { top: Math.round(padding.top * this.scaleReferenceSize / effectiveHeight), bottom: Math.round(padding.bottom * this.scaleReferenceSize / effectiveHeight) } : { top: padding.top, bottom: padding.bottom }; const horizontalViewBoxPadding = this.fixedAspectRatioScaling ? { left: Math.round(padding.left * this.scaleReferenceSize / effectiveWidth), right: Math.round(padding.right * this.scaleReferenceSize / effectiveWidth) } : { left: padding.left, right: padding.right }; const updates = []; /** Empty on a side whose slotted scale carries a range of its own. */ const rangeProps = (side, range) => this.ownsSlottedScaleRange(side) ? { minValue: range.min, maxValue: range.max, ...side === \"left\" || side === \"right\" ? { reverse: this.isYAxisReversed(side) } : {} } : {}; if (this.leftScaleSlot) this.leftScaleSlot.assignedElements().forEach((scale) => { const props = { ...rangeProps(\"left\", leftRange), height: effectiveHeight, paddingTop: verticalViewBoxPadding.top, paddingBottom: verticalViewBoxPadding.bottom, paddingStart: verticalViewBoxPadding.top, paddingEnd: verticalViewBoxPadding.bottom, showLabels: showLabels || compactY, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.yStepSize !== void 0) props.primaryTickmarkInterval = this.yStepSize; const band = bandFor(scale, compactY, compactYThickness); const mainLabels = mainLabelsFor(scale, compactY); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.leftScaleSlot, scale, props ]); }); if (this.rightScaleSlot) this.rightScaleSlot.assignedElements().forEach((scale) => { const props = { ...rangeProps(\"right\", rightRange), height: effectiveHeight, paddingTop: verticalViewBoxPadding.top, paddingBottom: verticalViewBoxPadding.bottom, paddingStart: verticalViewBoxPadding.top, paddingEnd: verticalViewBoxPadding.bottom, showLabels: showLabels || compactY, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.yStepSize !== void 0) props.primaryTickmarkInterval = this.yStepSize; const band = bandFor(scale, compactY, compactYThickness); const mainLabels = mainLabelsFor(scale, compactY); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.rightScaleSlot, scale, props ]); }); if (this.topScaleSlot) this.topScaleSlot.assignedElements().forEach((scale) => { const props = { ...xRange, width: effectiveWidth, paddingLeft: horizontalViewBoxPadding.left, paddingRight: horizontalViewBoxPadding.right, paddingStart: horizontalViewBoxPadding.left, paddingEnd: horizontalViewBoxPadding.right, showLabels: showLabels || compactX, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.xStepSize !== void 0) props.primaryTickmarkInterval = this.xStepSize; const band = bandFor(scale, compactX, compactXThickness); const mainLabels = mainLabelsFor(scale, compactX); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.topScaleSlot, scale, props ]); }); if (this.bottomScaleSlot) this.bottomScaleSlot.assignedElements().forEach((scale) => { const props = { ...xRange, width: effectiveWidth, paddingLeft: horizontalViewBoxPadding.left, paddingRight: horizontalViewBoxPadding.right, paddingStart: horizontalViewBoxPadding.left, paddingEnd: horizontalViewBoxPadding.right, showLabels: showLabels || compactX, fixedAspectRatio: this.fixedAspectRatioScaling, scaleReferenceSize: this.scaleReferenceSize, state: this.state, priority: this.priority, frameStyle: this.frameStyle, borderRadiusPosition: this.borderRadiusPositionExternalScales }; if (this.xStepSize !== void 0) props.primaryTickmarkInterval = this.xStepSize; const band = bandFor(scale, compactX, compactXThickness); const mainLabels = mainLabelsFor(scale, compactX); if (mainLabels !== void 0) props.showMainTickmarkLabels = mainLabels; if (band !== void 0) props.labelThickness = band; updates.push([ this.bottomScaleSlot, scale, props ]); }); updates.forEach(([_slot, scale, props]) => { Object.assign(scale, props); }); } /** * Whether the chart's axis range is what a slotted scale on this side should * describe. A subclass that slots a scale of its own and gives it a separate * range returns false for that side, otherwise the sync below overwrites it. */ ownsSlottedScaleRange(_side) { return true; } /** * Push the current axis ranges to the slotted scales. The full * `updateScaleProperties()` cascade runs before the chart is (re)built and * so reads the previous chart's ranges; this closes that gap once the new * chart exists, and keeps auto-ranged scales in step with the data. */ syncSlottedScaleRanges() { const apply = (side, slot, range) => { if (!slot || !range || !this.ownsSlottedScaleRange(side)) return; slot.assignedElements().forEach((scale) => { scale.minValue = range.min; scale.maxValue = range.max; if (side === \"left\" || side === \"right\") scale.reverse = this.isYAxisReversed(side); }); }; apply(\"left\", this.leftScaleSlot, this.resolveAxisRange(\"left\")); apply(\"right\", this.rightScaleSlot, this.resolveAxisRange(\"right\")); const xRange = this.resolveSlottedXRange(); apply(\"top\", this.topScaleSlot, xRange); apply(\"bottom\", this.bottomScaleSlot, xRange); } hasAnyChanged(changed, props) { return props.some((prop) => changed.has(prop)); } /** * Apply fillMode rules to datasets. Must be called after the chart is created * so scales and pixel coordinates are available for gradient construction. * * NOTE: For non-threshold modes (solid, semitransparent), backgroundColor is already * set correctly in buildDataset(). This method now only handles threshold gradients * which require Chart.js scales to be available. * * @returns Whether it set gradients; they reach the drawn chart on its next update. */ applyFillModes() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return false; const chart = this.chart; const ctx = chart.ctx; if (!ctx) return false; const fill = this.shouldApplyFill(); if (this.getFillMode() !== \"threshold\" || !fill) return false; let applied = false; chart.data.datasets.forEach((ds, _idx) => { const dataset = ds; if (dataset.fill === false || !fill) return; const yScaleId = dataset.yAxisID ?? \"y\"; const yScale = chart.scales[yScaleId]; if (!yScale) return; const dataValues = dataset.data.map((d) => typeof d === \"number\" ? d : d.y).filter((v) => Number.isFinite(v)); if (dataValues.length === 0) return; const thresholdVal = (Math.min(...dataValues) + Math.max(...dataValues)) / 2; const thresholdPixel = yScale.getPixelForValue(thresholdVal); const range = yScale.bottom - yScale.top; let stop = (thresholdPixel - yScale.top) / range; if (!Number.isFinite(stop) || range === 0) stop = .5; else stop = clamp(stop, 0, 1); const lowRaw = LINE_GRAPH_GRID_CONFIG.thresholdLowColorVar; const highRaw = LINE_GRAPH_GRID_CONFIG.thresholdHighColorVar; const createGradient = (lowAlpha, highAlpha) => { const low = applyAlphaToColor(this, lowRaw, lowAlpha); const high = applyAlphaToColor(this, highRaw, highAlpha); const grad = ctx.createLinearGradient(0, yScale.top, 0, yScale.bottom); grad.addColorStop(0, high); grad.addColorStop(stop, high); grad.addColorStop(stop, low); grad.addColorStop(1, low); return grad; }; const fillGradient = createGradient(.35, .35); const borderGradient = createGradient(.8, .8); dataset.backgroundColor = fillGradient; dataset.borderColor = borderGradient; applied = true; }); return applied; } updated(changed) { super.updated(changed); if (!this.hasAnyChanged(changed, LINE_GRAPH_WATCHED_PROP_NAMES)) return; if (this.hasAnyChanged(changed, LINE_GRAPH_DIMENSION_PROP_NAMES)) { if (this.updateComputedDimensions()) return; } const belowThreshold = this.isBelowThreshold(); const crossedThreshold = this.wasBelowThreshold !== void 0 && this.wasBelowThreshold !== belowThreshold; this.wasBelowThreshold = belowThreshold; if ((changed.has(\"hasLabelPadding\") || changed.has(\"rangeLabels\") || crossedThreshold) && this.hasExternalScales()) { this.syncScalesAndChart(); return; } if (this.hasAnyChanged(changed, LINE_GRAPH_RECREATE_PROP_NAMES)) { this.chart?.destroy(); this.createChart(); } else this.updateChart(); } async firstUpdated() { await this.waitForScaleDimensions(); if (!this.hasExternalScales()) this.createChart(); this.themeObserver = observeThemeChanges(() => { this.updateChartColors(); this.updateBorderRadius(); }); this.setupResizeObserver(); this.setupAspectRatioResizeObserver(); if (this.canvasEl) { if (!this.instrumentMode) this.borderRadiusObserver = startExternalScaleBorderRadiusObserver(this.canvasEl, this.updateBorderRadius); this.updateBorderRadius(); } } disconnectedCallback() { super.disconnectedCallback(); this.chart?.destroy(); this.themeObserver?.disconnect(); this.resizeObserver?.disconnect(); this.aspectRatioResizeObserver?.disconnect(); this.borderRadiusObserver?.disconnect(); if (this.dimensionUpdateTimer) clearTimeout(this.dimensionUpdateTimer); } /** * Crossing MIN_HEIGHT_WITH_LABELS changes the plugin set, so the chart is * rebuilt rather than updated. */ setupResizeObserver() { if (!this.canvasEl) return; this.resizeObserver = observeLabelThreshold(this.canvasEl, () => (this.canvasEl?.clientHeight ?? 0) >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS && (this.canvasEl?.clientWidth ?? 0) >= RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS, { rebuild: () => { this.chart?.destroy(); this.createChart(); }, update: () => this.updateChart() }); } /** * Setup resize observer for fixed aspect ratio scaling. * Observes the wrapper element and recalculates dimensions when parent size changes. */ setupAspectRatioResizeObserver() { const wrapper = this.renderRoot.querySelector(\".wrapper\"); if (!wrapper) return; this.updateComputedDimensions(); this.aspectRatioResizeObserver = new ResizeObserver(() => { if (!this.fixedAspectRatioScaling) return; this.updateComputedDimensions(); }); this.aspectRatioResizeObserver.observe(wrapper); } /** * Refresh `computedWidth` / `computedHeight`, the derived pixel size the * chart and its slotted scales are laid out from. * * In pixel mode they mirror `width` / `height`. Only in * `fixedAspectRatioScaling` mode are they derived — from the wrapper's * measured width and the aspect ratio the `width` / `height` pair defines — * and only then can this rebuild the chart. * * @returns `true` when the change was significant enough that the chart was * rebuilt here, so the caller must not rebuild it a second time. */ updateComputedDimensions() { if (!this.fixedAspectRatioScaling) { this.computedWidth = this.width; this.computedHeight = this.height; return false; } const wrapper = this.renderRoot.querySelector(\".wrapper\"); if (!wrapper) return false; const parentWidth = wrapper.clientWidth; if (parentWidth <= 0) return false; const aspectRatio = this.width / this.height; const newWidth = parentWidth; const newHeight = Math.round(parentWidth / aspectRatio); if (this.computedWidth !== newWidth || this.computedHeight !== newHeight) { this.computedWidth = newWidth; this.computedHeight = newHeight; if (this.hasExternalScales()) return this.syncScalesAndChart(); else if (this.chart) { this.chart.destroy(); this.createChart(); return true; } } return false; } /** * Get the effective width for chart rendering. * Returns computed width when fixedAspectRatioScaling is true, otherwise the width property. */ getEffectiveWidth() { return this.fixedAspectRatioScaling ? this.computedWidth : this.width; } /** * Get the effective height for chart rendering. * Returns computed height when fixedAspectRatioScaling is true, otherwise the height property. */ getEffectiveHeight() { return this.fixedAspectRatioScaling ? this.computedHeight : this.height; } /** * Get the scale factor for proportional scaling when fixedAspectRatioScaling is true. * Returns 1.0 when not in fixed aspect ratio mode. * The scale factor is based on computed width vs reference width (the width property). */ getScaleFactor() { if (!this.fixedAspectRatioScaling) return 1; return this.computedWidth / this.width; } /** * Build a complete dataset configuration with all styling properties. * Handles both new datasets (from values array) and existing datasets (normalization). * * @param data - Either numeric values array or existing dataset to normalize * @param index - Dataset index for color cycling * @param chartColors - Color palette array * @param totalCount - Total number of datasets (used for stacked divider logic) * @returns Fully configured Chart.js dataset */ buildDataset(data, index, chartColors, totalCount = 1) { const currentColor = chartColors[index % chartColors.length]; const existingDataset = Array.isArray(data) ? null : data; const values = Array.isArray(data) ? data : null; const borderColor = existingDataset?.borderColor ?? currentColor; const explicitFill = existingDataset?.fill; const fillFlag = explicitFill !== void 0 ? explicitFill !== false : this.shouldApplyFill(); const tension = this.lineMode === \"smooth\" ? this.DEFAULT_TENSION : 0; const needsDivider = this.shouldStack() && this.getFillMode() !== \"threshold\" && index < totalCount - 1; let backgroundColor = \"transparent\"; const fillMode = this.getFillMode(); if (fillFlag && fillMode) { const nextColor = chartColors[(index + 1) % chartColors.length]; if (fillMode === \"solid\") backgroundColor = String(borderColor); else if (fillMode === \"semitransparent\") backgroundColor = applyAlphaToColor(this, nextColor, .5); else if (fillMode === \"threshold\") backgroundColor = applyAlphaToColor(this, nextColor, .5); } return { ...existingDataset || {}, data: existingDataset?.data ?? values, yAxisID: existingDataset?.yAxisID ?? this.primaryYAxisId, borderColor, backgroundColor: existingDataset?.backgroundColor ?? backgroundColor, borderWidth: existingDataset?.borderWidth ?? 2, showLine: existingDataset?.showLine ?? true, tension: existingDataset?.tension ?? tension, pointRadius: existingDataset?.pointRadius ?? (this.showPoints ? this.POINT_RADIUS : 0), pointBackgroundColor: existingDataset?.pointBackgroundColor ?? \"#fff\", pointBorderColor: existingDataset?.pointBorderColor ?? borderColor, pointBorderWidth: existingDataset?.pointBorderWidth ?? 2, stepped: existingDataset?.stepped ?? this.lineMode === \"stepped\", fill: explicitFill === void 0 || explicitFill === true ? fillFlag ? \"start\" : false : explicitFill, spanGaps: existingDataset?.spanGaps ?? true, ...needsDivider && { segment: { borderColor: getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.stackedDividerColorVar), borderWidth: 1 } } }; } /** * Create threshold mode datasets: invisible baseline + main dataset with * above/below fills. Accepts plain values (category mode) or {x, y} points * (time/number mode); the baseline mirrors the input x-positions. */ createThresholdDatasets(values, chartColors) { const yValues = values.map((v) => typeof v === \"number\" ? v : v.y).filter((n) => Number.isFinite(n)); const threshold = ((yValues.length ? Math.min(...yValues) : 0) + (yValues.length ? Math.max(...yValues) : 100)) / 2; const baselineData = values.map((v) => typeof v === \"number\" ? threshold : { x: v.x, y: threshold }); const lowRaw = LINE_GRAPH_GRID_CONFIG.thresholdLowColorVar; const highRaw = LINE_GRAPH_GRID_CONFIG.thresholdHighColorVar; const highFill = applyAlphaToColor(this, highRaw, .35); const lowFill = applyAlphaToColor(this, lowRaw, .35); const baselineDataset = { label: \"threshold-baseline\", data: baselineData, yAxisID: this.primaryYAxisId, borderColor: \"transparent\", backgroundColor: \"transparent\", borderWidth: 0, pointRadius: 0, showLine: false, fill: false, spanGaps: true }; const main = this.buildDataset(values, 0, chartColors); main.fill = { target: 0, above: highFill, below: lowFill }; main.borderWidth = 2; return [baselineDataset, main]; } /** * Prepare normalized datasets for multi-series charts. * In time/number mode every point's x is normalized (epoch ms / number) * so strings, Dates and Temporal objects position correctly. */ prepareMultiSeriesDatasets() { const defaultPalette = this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS; const chartColors = getChartColorsOrDefault(this, this.colors, defaultPalette); const normalized = this.datasets.map((ds) => this.normalizeDatasetX(ds)); if (this.isNumericXAxis) this.warnOnInvalidX(normalized.flatMap((ds) => (ds.data ?? []).map((pt) => pt && typeof pt === \"object\" ? pt.x : 0)), this.datasets); const totalCount = this.datasets.length; return normalized.map((ds, i) => this.buildDataset(ds, i, chartColors, totalCount)); } /** @internal - Return a copy of the dataset with normalized point x-values. */ normalizeDatasetX(ds) { if (!this.isNumericXAxis || !ds.data) return ds; const data = ds.data.map((pt) => pt && typeof pt === \"object\" && \"x\" in pt ? { ...pt, x: normalizeXValue(pt.x, this.xValueMode) } : pt); return { ...ds, data }; } /** * Prepare datasets for single-series charts. * Category mode: labels + numeric values (unchanged legacy path). * Time/number mode: normalized {x, y} points on a linear scale. * Handles both regular and threshold fill modes. */ prepareSingleSeriesDatasets() { const defaultPalette = this.priority === Priority.enhanced ? CHART_SECTOR_ENHANCED_COLORS : CHART_SECTOR_DEFAULT_COLORS; const chartColors = getChartColorsOrDefault(this, this.colors, defaultPalette); const fill = this.shouldApplyFill(); const fillMode = this.getFillMode(); if (this.isNumericXAxis) { const points = this.data.map((d) => ({ x: normalizeXValue(d.x ?? d.label ?? NaN, this.xValueMode), y: d.value })); this.warnOnInvalidX(points.map((p) => p.x), this.data); return { datasets: fill && fillMode === \"threshold\" ? this.createThresholdDatasets(points, chartColors) : [this.buildDataset(points, 0, chartColors)], labels: [] }; } const values = this.data.map((d) => d.value); const labels = this.data.map((d) => d.label ?? String(d.x ?? \"\")); return { datasets: fill && fillMode === \"threshold\" ? this.createThresholdDatasets(values, chartColors) : [this.buildDataset(values, 0, chartColors)], labels }; } /** * One padding source for the Chart.js layout and the slotted scales: two * sources painted the canvas over a scale and inset a scale inside a chart. */ computeChartPadding() { const isTooSmall = this.isBelowThreshold(); const scaleFactor = this.getScaleFactor(); const defaultPaddingScaled = !this.hasLabelPadding ? 0 : this.fixedAspectRatioScaling ? Math.round(CHART_DIMENSIONS.CANVAS_PADDING * scaleFactor) : CHART_DIMENSIONS.CANVAS_PADDING; const { y: yTexts, x: xTexts } = this.refreshRangeLabels(); const context = this.canvasEl?.getContext(\"2d\"); const gutters = (yTexts.length || xTexts.length) && context ? measureRangeLabelGutters(context, this.rangeLabelFont(), yTexts, xTexts) : { side: 0, bottom: 0 }; const scalePadding = this.calculatePaddingFromScales(); const freeSide = (side) => { if (!isTooSmall) return defaultPaddingScaled; if (side === \"bottom\") return gutters.bottom; return side === this.ySide ? gutters.side : 0; }; return { top: this.externalScaleDimensions.has(\"top\") ? scalePadding.top : freeSide(\"top\"), right: this.externalScaleDimensions.has(\"right\") ? scalePadding.right : freeSide(\"right\"), bottom: this.externalScaleDimensions.has(\"bottom\") ? scalePadding.bottom : freeSide(\"bottom\"), left: this.externalScaleDimensions.has(\"left\") ? scalePadding.left : freeSide(\"left\") }; } /** * Get Chart.js options with dynamic sizing and padding */ getChartOptions() { const effectiveWidth = this.getEffectiveWidth(); const effectiveHeight = this.getEffectiveHeight(); const isTooSmall = effectiveWidth < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS || effectiveHeight < RECTANGULAR_CHART_DIMENSIONS.MIN_HEIGHT_WITH_LABELS; const padding = this.computeChartPadding(); if (this.fixedAspectRatioScaling) { this.style.setProperty(\"--chart-width\", \"100%\"); this.style.setProperty(\"--chart-height\", `${effectiveHeight}px`); } else { this.style.setProperty(\"--chart-width\", `${this.width}px`); this.style.setProperty(\"--chart-height\", `${this.height}px`); } const refTs = this.computeTimeReference(); const effectiveShowTickMarks = this.hasExternalScales() ? false : this.showTickMarks; return { responsive: true, maintainAspectRatio: false, layout: { padding }, plugins: { legend: { display: false, labels: { generateLabels: () => [] }, onClick: () => {} }, tooltip: { ...getChartTooltipOptions(this), enabled: !isTooSmall, callbacks: { title: () => \"\", label: (context) => { const value = typeof context.parsed === \"object\" && context.parsed !== null ? context.parsed.y : context.parsed; const numericValue = formatChartNumber(value, 1, false, 0); const unit = this.unit ? `${this.unit}` : \"\"; let label = context.label ?? \"\"; if (this.isNumericXAxis) { const x = typeof context.parsed === \"object\" && context.parsed !== null ? context.parsed.x : NaN; const relativeTo = this.timeDisplay === \"minutes\" ? refTs : void 0; label = formatXValue(x, this.xValueMode, relativeTo); } return `${label} ${numericValue}${unit}`; } } } }, animation: false, scales: this.buildScalesConfig(refTs, isTooSmall, effectiveShowTickMarks) }; } /** * Compute reference timestamp for time axis formatting. * Returns earliest timestamp for 'date' mode, latest for 'minutes' mode. * A pinned x range supplies the reference instead, so the axis edge stays * the reference while the data has not reached it yet. */ computeTimeReference() { if (this.xAxisType !== \"time\") return void 0; const pinned = this.timeDisplay === \"minutes\" ? this.xAxis?.max : this.xAxis?.min; if (pinned !== void 0 && Number.isFinite(pinned)) return pinned; const timestamps = []; if (this.datasets?.length) this.datasets.forEach((ds) => { if (!ds.data) return; ds.data.forEach((pt) => { if (pt && typeof pt === \"object\" && \"x\" in pt) { const ts = normalizeXValue(pt.x, XValueMode.time); if (Number.isFinite(ts)) timestamps.push(ts); } }); }); else if (this.data?.length) this.data.forEach((d) => { const ts = normalizeXValue(d.x ?? d.label ?? NaN, XValueMode.time); if (Number.isFinite(ts)) timestamps.push(ts); }); if (!timestamps.length && this.labels?.length) this.labels.forEach((l) => { if (typeof l === \"string\") { const ts = new Date(l).getTime(); if (Number.isFinite(ts)) timestamps.push(ts); } }); return timestamps.length ? this.timeDisplay === \"minutes\" ? Math.max(...timestamps) : Math.min(...timestamps) : void 0; } /** * Build Chart.js scale configuration with theme-aware styling. * Applies CSS variables for grid colors, tick colors, and label typography. * * @param minX - Reference timestamp for time-based x-axis (used for 'minutes' display) * @param isTooSmall - Whether chart is below 192px threshold (hides ticks when true) * @param showTickMarks - Whether to show tick marks (overridden to false when external scales present) * @returns Configured scales object for Chart.js options */ buildScalesConfig(minX, isTooSmall = false, showTickMarks = true) { const gridColor = getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.gridColorVar); const tickColor = getCssVariableValue(this, LINE_GRAPH_GRID_CONFIG.tickColorVar); const fontFamily = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontFamily); const fontSize = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontSizeVar); const fontWeight = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontWeightVar); const fontColor = getCssVariableValue(this, LINE_GRAPH_LABEL_CONFIG.fontColorVar); const showLabels = showTickMarks && !isTooSmall && this.hasLabelPadding; const showTicks = showTickMarks && !isTooSmall && this.hasLabelPadding; const fontConfig = { family: fontFamily, size: fontSize, weight: fontWeight }; const x = { type: this.xAxisType === \"category\" ? \"category\" : \"linear\", offset: false, grace: 0, bounds: \"data\", min: this.isNumericXAxis ? this.xAxis?.min : void 0, max: this.isNumericXAxis ? this.xAxis?.max : void 0, grid: { display: this.showGrid && this.showGridX, color: gridColor, offset: false, drawTicks: showTicks }, ticks: { display: showLabels, color: fontColor, font: fontConfig, maxRotation: 0, minRotation: 0, maxTicksLimit: this.xTicksLimit, stepSize: this.xStepSize, callback: (value) => { if (!this.isNumericXAxis) return String(value); const n = Number(value); if (!Number.isFinite(n)) return String(value); const relativeTo = this.timeDisplay === \"minutes\" ? minX : void 0; return formatXValue(n, this.xValueMode, relativeTo); } }, border: { display: showLabels, color: tickColor } }; const yAxesConfig = this.yAxes?.length ? this.yAxes.map((axis, i) => ({ id: axis.id ?? `y${i}`, position: axis.position ?? \"left\", min: axis.min, max: axis.max, reverse: axis.reverse ?? false, gridDisplay: axis.grid ?? (this.showGrid && this.showGridY) })) : [{ id: \"y\", position: this.yAxisPosition, min: void 0, max: void 0, reverse: false, gridDisplay: this.showGrid && this.showGridY }]; const scalesRecord = { x }; yAxesConfig.forEach(({ id, position, min, max, reverse, gridDisplay }) => { scalesRecord[id] = { type: \"linear\", display: true, position, reverse, stacked: this.shouldStack() && this.getFillMode() !== \"threshold\", grace: isTooSmall ? 0 : void 0, bounds: isTooSmall ? \"data\" : \"ticks\", grid: { display: gridDisplay, color: gridColor, drawTicks: showTicks }, ticks: { display: showLabels, color: fontColor, font: fontConfig, maxTicksLimit: this.yTicksLimit, stepSize: this.yStepSize }, border: { display: showLabels, color: tickColor }, min, max }; }); return scalesRecord; } /** * Prepare chart data and labels for both single and multi-series modes */ prepareChartDataAndLabels() { if (this.datasets?.length) return { datasets: this.prepareMultiSeriesDatasets(), labels: this.labels ?? [] }; return this.prepareSingleSeriesDatasets(); } createChart() { if (!this.canvasEl || !this.canvasEl.isConnected) return; const ctx = this.canvasEl.getContext(\"2d\"); if (!ctx) return; if (this.chart) { this.chart.destroy(); this.chart = void 0; } const { datasets, labels } = this.prepareChartDataAndLabels(); this.chart = new Chart(ctx, { type: \"line\", data: { labels, datasets }, options: this.getChartOptions(), plugins: [ ...this.borderRadiusPosition ? [this.createBorderPlugin()] : [], ...this.rangeLabels !== \"none\" ? [this.createRangeLabelsPlugin()] : [], this.createMarkersPlugin() ] }); requestAnimationFrame(() => this.updateLegend()); if (this.applyFillModes()) this.chart.update(\"none\"); this.syncSlottedScaleRanges(); } updateChart() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; const { datasets, labels } = this.prepareChartDataAndLabels(); this.chart.data.labels = labels; this.chart.data.datasets = datasets; Object.assign(this.chart.options, this.getChartOptions()); this.applyFillModes(); this.chart.update(); this.syncSlottedScaleRanges(); requestAnimationFrame(() => this.updateLegend()); } /** * Update only chart colors without recalculating layout * Used by theme observer for efficient theme changes */ updateChartColors() { if (!this.chart || !this.canvasEl || !this.canvasEl.isConnected) return; this.applyFillModes(); this.chart.update(\"none\"); requestAnimationFrame(() => this.updateLegend()); } /** * Update the legend HTML content */ updateLegend() { if (!this.legend || !this.legendDiv || !this.chart) return; if (!this.chart.data.datasets || this.chart.data.datasets.length === 0) { renderLegend(this.legendDiv, []); return; } try { const legendItems = this.chart.data.datasets.map((ds, i) => { const meta = this.chart.getDatasetMeta(i); if (!meta || !meta.controller) return null; const style = meta.controller.getStyle(0, false); const dataset = ds; return { fillStyle: dataset.borderColor ?? style.borderColor ?? \"\", label: dataset.label || `Series ${i + 1}`, value: \"\", unit: \"\" }; }).filter((item) => item !== null); if (legendItems.length > 0) renderLegend(this.legendDiv, legendItems); } catch (error) { console.debug(\"[chart-line-base] updateLegend: error generating legend HTML\", error); } } render() { return html` <div class=\"wrapper\"> <div class=\"canvas-and-slots-container\"> <slot name=\"top-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"bottom-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"left-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <slot name=\"right-scale\" @slotchange=${this.handleSlotChange} @scale-dimensions-changed=${this.handleScaleDimensionsChanged} ></slot> <canvas></canvas> </div> ${this.legend ? html`<div class=\"legend\"></div>` : \"\"} </div> `; } static { this.styles = [ unsafeCSS(chart_line_base_default), unsafeCSS(chart_common_default), unsafeCSS(chart_legend_default), unsafeCSS(chart_debug_default) ]; } }",
3353
3353
  "description": "Abstract base class for line and area chart components built on Chart.js.\n\n## Concrete implementations\n- `<obc-line-graph>`: Line chart (non-filled)\n- `<obc-area-graph>`: Area chart with fill modes (semitransparent, solid, threshold)\n\n## Features\n- **Single or multi-series**: Use `data` for simple single-series or `datasets` for multi-series charts\n- **Category, time and number axes**: `category` (labels, evenly spaced), `time` (epoch ms,\n ISO strings, `Date` or Temporal objects — positioned proportionally, so uneven intervals\n render unevenly) and `number` (plain numeric x-values on a linear scale)\n- **Line styles**: Choose `smooth` (curved), `straight`, or `stepped` line rendering\n- **Fill modes**: Area fills with `semitransparent`, `solid`, or `threshold` (red/blue above/below midpoint)\n- **Stacked charts**: Enable `stacked` for multi-series datasets to stack values on y-axis\n- **Flexible axes**: Single y-axis via `yAxisPosition` or multi-axis via `yAxes` for complex charts\n- **Theme-aware**: Automatically updates colors on theme changes using CSS variables\n- **Responsive sizing**: Fixed height with 1.5:1 aspect ratio (e.g., 320px height → 480px width)\n- **Grid & ticks**: Toggle grid lines (`showGrid`, `showGridX`, `showGridY`) and tick marks (`showTickMarks`)\n- **Legend support**: Optional HTML legend showing series labels with `legend` property\n- **External axis support**: via slots\n- **Color priority**: Set `priority` to `Priority.enhanced` to use the blue/enhanced\n color palette instead of the default gray/regular palette (default: `Priority.regular`)\n\n## Size Behavior\n- Above 192px: Shows labels, tick marks, and grid lines with standard padding\n- Below 192px: Hides labels/ticks and uses edge-to-edge rendering for compact display\n\n## Examples\n\nBasic single-series with category axis:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.data = [\n {label: 'Jan', value: 10},\n {label: 'Feb', value: 14},\n {label: 'Mar', value: 12}\n ];\n chart.unit = 'kW';\n chart.height = 256;\n<\\/script>\n```\n\nMulti-series with time axis and legend:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.xAxisType = 'time';\n chart.timeDisplay = 'date';\n chart.legend = true;\n chart.datasets = [\n {label: 'Temperature', data: [{x: '2025-01-01', y: 20}, {x: '2025-01-02', y: 22}]},\n {label: 'Humidity', data: [{x: '2025-01-01', y: 65}, {x: '2025-01-02', y: 68}]}\n ];\n<\\/script>\n```\n\nSingle-series with time axis (uneven intervals position proportionally;\nx accepts epoch ms, ISO strings, Date or Temporal objects):\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.xAxisType = 'time';\n chart.timeDisplay = 'minutes';\n chart.data = [\n {x: '2026-07-06T10:00:00Z', value: 10},\n {x: new Date('2026-07-06T10:03:00Z'), value: 14},\n {x: Temporal.Instant.from('2026-07-06T10:15:00Z'), value: 12}\n ];\n<\\/script>\n```\n\nSingle-series with numeric x-axis:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.xAxisType = 'number';\n chart.data = [\n {x: 0, value: 2},\n {x: 2.5, value: 3},\n {x: 10, value: 6}\n ];\n<\\/script>\n```\n\nStacked area chart with solid fill:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.datasets = [\n {label: 'Series A', data: [2, 3, 4, 3, 5]},\n {label: 'Series B', data: [1, 2, 3, 2, 4]},\n {label: 'Series C', data: [3, 2, 1, 2, 3]}\n ];\n chart.fillMode = 'solid';\n chart.stacked = true;\n chart.legend = true;\n<\\/script>\n```\n\nThreshold fill (single-series only):\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.data = [{label: '1', value: 20}, {label: '2', value: 45}, {label: '3', value: 35}];\n chart.fillMode = 'threshold';\n<\\/script>\n```\n\nMulti-axis chart with right-side y-axis:\n```html\n<obc-line-graph></obc-line-graph>\n<script>\n const chart = document.querySelector('obc-line-graph');\n chart.yAxes = [\n {id: 'y-temp', position: 'left', min: 0, max: 100},\n {id: 'y-pressure', position: 'right', min: 0, max: 10}\n ];\n chart.datasets = [\n {label: 'Temperature', data: [20, 25, 30], yAxisID: 'y-temp'},\n {label: 'Pressure', data: [2, 3, 2.5], yAxisID: 'y-pressure'}\n ];\n<\\/script>\n```"
3354
3354
  }
3355
3355
  ],
@@ -1 +1 @@
1
- {"version":3,"file":"donut-chart.d.ts","sourceRoot":"","sources":["../../../src/bars-graphs/donut-chart/donut-chart.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAE,cAAc,EAAkB,MAAM,KAAK,CAAC;AAOhE,OAAO,EAAC,QAAQ,EAAC,MAAM,uCAAuC,CAAC;AAgE/D,MAAM,MAAM,kBAAkB,GAAG;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoFG;AACH,qBACa,aAAc,SAAQ,UAAU;IAE3C,IAAI,EAAE,kBAAkB,EAAE,CAAM;IAGhC,MAAM,EAAE,MAAM,EAAE,CAAM;IAGtB,QAAQ,EAAE,QAAQ,CAAoB;IAGtC,IAAI,UAAS;IAGb,eAAe,UAAS;IAGxB,QAAQ,UAAS;IAGjB,cAAc,SAAO;IAKrB,mBAAmB,SAAK;IAKxB,uBAAuB,SAAK;IAG5B,kBAAkB,SAAW;IAG7B,iBAAiB,SAAO;IAGxB,GAAG,SAAO;IAGV,SAAS,SAAM;IAGf,MAAM,UAAS;IAGf,gBAAgB,UAAS;IAGzB,WAAW,SAAO;IAElB,gBAAgB;IACP,OAAO,CAAC,KAAK,CAAK;IAE3B,iEAAiE;IACxD,OAAO,CAAC,eAAe,CAAgB;IAEhD,gBAAgB;IACC,OAAO,CAAC,QAAQ,CAAC,CAAoB;IAEtD,gBAAgB;IACE,OAAO,CAAC,SAAS,CAAC,CAAiB;IAErD,gBAAgB;IAChB,OAAO,CAAC,KAAK,CAAC,CAAQ;IAEtB,yEAAyE;IACzE,OAAO,CAAC,cAAc,CAAC,CAA6B;IAEpD,gBAAgB;IAChB,OAAO,CAAC,aAAa,CAAC,CAAmB;IAEzC,+GAA+G;IAC/G,OAAO,CAAC,cAAc,CAAC,CAAiB;IAExC,OAAO,CAAC,aAAa;IAOrB;;OAEG;IACH,OAAO,CAAC,eAAe;IAgBd,UAAU,CAAC,OAAO,EAAE,cAAc;IAOlC,OAAO,CAAC,OAAO,EAAE,cAAc;IAoB/B,YAAY;IAMZ,oBAAoB;IAO7B;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IAgB3B,OAAO,CAAC,gBAAgB;IA2BxB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAiB3B;;OAEG;IACH,OAAO,CAAC,eAAe;IA0FvB,OAAO,CAAC,2BAA2B;IAsBnC,OAAO,CAAC,8BAA8B;IA6KtC,OAAO,CAAC,eAAe;IAyCvB,OAAO,CAAC,WAAW;IAmCnB,OAAO,CAAC,WAAW;IA6BnB;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAmBzB;;OAEG;IACH,OAAO,CAAC,YAAY;IAqDX,MAAM;IASf,OAAgB,MAAM,4BAKpB;CACH;AAED,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,qBAAqB;QAC7B,iBAAiB,EAAE,aAAa,CAAC;KAClC;CACF"}
1
+ {"version":3,"file":"donut-chart.d.ts","sourceRoot":"","sources":["../../../src/bars-graphs/donut-chart/donut-chart.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAE,cAAc,EAAkB,MAAM,KAAK,CAAC;AAOhE,OAAO,EAAC,QAAQ,EAAC,MAAM,uCAAuC,CAAC;AAgE/D,MAAM,MAAM,kBAAkB,GAAG;IAC/B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoFG;AACH,qBACa,aAAc,SAAQ,UAAU;IAE3C,IAAI,EAAE,kBAAkB,EAAE,CAAM;IAGhC,MAAM,EAAE,MAAM,EAAE,CAAM;IAGtB,QAAQ,EAAE,QAAQ,CAAoB;IAGtC,IAAI,UAAS;IAGb,eAAe,UAAS;IAGxB,QAAQ,UAAS;IAGjB,cAAc,SAAO;IAKrB,mBAAmB,SAAK;IAKxB,uBAAuB,SAAK;IAG5B,kBAAkB,SAAW;IAG7B,iBAAiB,SAAO;IAGxB,GAAG,SAAO;IAGV,SAAS,SAAM;IAGf,MAAM,UAAS;IAGf,gBAAgB,UAAS;IAGzB,WAAW,SAAO;IAElB,gBAAgB;IACP,OAAO,CAAC,KAAK,CAAK;IAE3B,iEAAiE;IACxD,OAAO,CAAC,eAAe,CAAgB;IAEhD,gBAAgB;IACC,OAAO,CAAC,QAAQ,CAAC,CAAoB;IAEtD,gBAAgB;IACE,OAAO,CAAC,SAAS,CAAC,CAAiB;IAErD,gBAAgB;IAChB,OAAO,CAAC,KAAK,CAAC,CAAQ;IAEtB,yEAAyE;IACzE,OAAO,CAAC,cAAc,CAAC,CAA6B;IAEpD,gBAAgB;IAChB,OAAO,CAAC,aAAa,CAAC,CAAmB;IAEzC,+GAA+G;IAC/G,OAAO,CAAC,cAAc,CAAC,CAAiB;IAExC,OAAO,CAAC,aAAa;IAOrB;;OAEG;IACH,OAAO,CAAC,eAAe;IAgBd,UAAU,CAAC,OAAO,EAAE,cAAc;IAOlC,OAAO,CAAC,OAAO,EAAE,cAAc;IAoB/B,YAAY;IAMZ,oBAAoB;IAO7B;;;;OAIG;IACH,OAAO,CAAC,mBAAmB;IAgB3B,OAAO,CAAC,gBAAgB;IA2BxB;;OAEG;IACH,OAAO,CAAC,mBAAmB;IAiB3B;;OAEG;IACH,OAAO,CAAC,eAAe;IA0FvB,OAAO,CAAC,2BAA2B;IAsBnC,OAAO,CAAC,8BAA8B;IA6KtC,OAAO,CAAC,eAAe;IAyCvB,OAAO,CAAC,WAAW;IAmCnB,OAAO,CAAC,WAAW;IA6BnB;;;OAGG;IACH,OAAO,CAAC,iBAAiB;IAmBzB;;OAEG;IACH,OAAO,CAAC,YAAY;IAoDX,MAAM;IASf,OAAgB,MAAM,4BAKpB;CACH;AAED,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,qBAAqB;QAC7B,iBAAiB,EAAE,aAAa,CAAC;KAClC;CACF"}
@@ -5,7 +5,7 @@ import { calculateFixedHeightChartLayout, formatChartNumber } from "../../charth
5
5
  import { observeThemeChanges } from "../../charthelpers/theme.js";
6
6
  import { calculateSumTotal, createArcOuterLabelPlugin } from "../../charthelpers/outer-labels.js";
7
7
  import { getChartTooltipOptions } from "../../charthelpers/tooltip.js";
8
- import { generateLegendHTML } from "../../charthelpers/legend.js";
8
+ import { renderLegend } from "../../charthelpers/legend.js";
9
9
  import { observeLabelThreshold } from "../../charthelpers/label-threshold.js";
10
10
  import "../../charthelpers/index.js";
11
11
  import __decorate from "../../_virtual/_@oxc-project_runtime@0.150.0/helpers/esm/decorate.js";
@@ -372,7 +372,7 @@ var ObcDonutChart = class ObcDonutChart extends LitElement {
372
372
  const meta = this.chart.getDatasetMeta(0);
373
373
  if (!meta || !meta.controller) return;
374
374
  if (!this.data || this.data.length === 0) {
375
- this.legendDiv.innerHTML = "";
375
+ renderLegend(this.legendDiv, []);
376
376
  return;
377
377
  }
378
378
  const denominator = this.max > 0 ? this.max : this.total > 0 ? this.total : 1;
@@ -391,8 +391,7 @@ var ObcDonutChart = class ObcDonutChart extends LitElement {
391
391
  unit
392
392
  };
393
393
  });
394
- const legendHTML = generateLegendHTML(legendItems);
395
- this.legendDiv.innerHTML = legendHTML;
394
+ renderLegend(this.legendDiv, legendItems);
396
395
  } catch (error) {
397
396
  console.debug("[obc-donut-chart] updateLegend: error generating legend HTML", error);
398
397
  }