@lostgradient/cinder 0.22.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/components.json +1 -1
  3. package/dist/_internal/chart/chart-bar-model.d.ts +24 -0
  4. package/dist/_internal/chart/chart-cartesian-model.d.ts +16 -0
  5. package/dist/_internal/chart/chart-layout.d.ts +23 -0
  6. package/dist/_internal/chart/chart-model-utilities.d.ts +157 -0
  7. package/dist/_internal/chart/chart-scale.d.ts +37 -0
  8. package/dist/_internal/chart/chart-utilities.d.ts +7 -164
  9. package/dist/_internal/chart/heatmap-utilities.d.ts +5 -4
  10. package/dist/components/_internal/chart-tooltip.css +21 -0
  11. package/dist/components/_internal/chart-tooltip.svelte.d.ts +11 -0
  12. package/dist/components/approval-card/index.js +5 -5
  13. package/dist/components/area-chart/area-chart.css +27 -23
  14. package/dist/components/area-chart/area-chart.schema.js +38 -1
  15. package/dist/components/area-chart/area-chart.types.d.ts +6 -2
  16. package/dist/components/area-chart/index.js +1589 -768
  17. package/dist/components/badge/badge.css +2 -2
  18. package/dist/components/badge/badge.schema.js +2 -2
  19. package/dist/components/badge/badge.types.d.ts +3 -3
  20. package/dist/components/badge/index.js +4 -4
  21. package/dist/components/bar-chart/bar-chart.css +27 -21
  22. package/dist/components/bar-chart/bar-chart.schema.js +38 -1
  23. package/dist/components/bar-chart/bar-chart.types.d.ts +7 -3
  24. package/dist/components/bar-chart/index.js +1544 -740
  25. package/dist/components/chart.types.d.ts +98 -2
  26. package/dist/components/json-schema-editor/index.js +4 -4
  27. package/dist/components/line-chart/index.js +1587 -785
  28. package/dist/components/line-chart/line-chart.css +25 -24
  29. package/dist/components/line-chart/line-chart.schema.js +38 -1
  30. package/dist/components/line-chart/line-chart.types.d.ts +6 -2
  31. package/dist/components/matrix-chart/index.js +1038 -429
  32. package/dist/components/matrix-chart/matrix-chart.css +12 -6
  33. package/dist/components/matrix-chart/matrix-chart.schema.js +26 -1
  34. package/dist/components/matrix-chart/matrix-chart.types.d.ts +5 -1
  35. package/dist/components/payload-inspector/index.js +4 -4
  36. package/dist/components/run-step-timeline/index.js +6 -6
  37. package/dist/components/sparkbar/index.js +1291 -4
  38. package/dist/components/sparkbar/sparkbar.css +5 -4
  39. package/dist/components/sparkbar/sparkbar.schema.js +26 -1
  40. package/dist/components/sparkbar/sparkbar.types.d.ts +5 -0
  41. package/dist/components/spectrogram/index.js +1076 -437
  42. package/dist/components/spectrogram/spectrogram.css +7 -6
  43. package/dist/components/spectrogram/spectrogram.schema.js +26 -1
  44. package/dist/components/spectrogram/spectrogram.types.d.ts +5 -1
  45. package/dist/components/spectrum-chart/index.js +1037 -423
  46. package/dist/components/spectrum-chart/spectrum-chart.css +8 -7
  47. package/dist/components/spectrum-chart/spectrum-chart.schema.js +26 -1
  48. package/dist/components/spectrum-chart/spectrum-chart.types.d.ts +5 -1
  49. package/dist/components/statistic/index.js +1284 -2
  50. package/dist/components/statistic/statistic.css +6 -5
  51. package/dist/components/statistic/statistic.schema.js +26 -1
  52. package/dist/components/statistic/statistic.types.d.ts +5 -0
  53. package/dist/components/statistic-group/index.js +1284 -2
  54. package/dist/components/waveform/index.js +1004 -404
  55. package/dist/components/waveform/waveform.css +8 -7
  56. package/dist/components/waveform/waveform.schema.js +26 -1
  57. package/dist/components/waveform/waveform.types.d.ts +5 -1
  58. package/dist/index.d.ts +1 -1
  59. package/dist/index.js +17730 -16540
  60. package/dist/server/components/approval-card/index.js +3 -3
  61. package/dist/server/components/area-chart/index.js +3 -3
  62. package/dist/server/components/badge/index.js +2 -2
  63. package/dist/server/components/bar-chart/index.js +3 -3
  64. package/dist/server/components/json-schema-editor/index.js +2 -2
  65. package/dist/server/components/line-chart/index.js +3 -3
  66. package/dist/server/components/matrix-chart/index.js +3 -3
  67. package/dist/server/components/payload-inspector/index.js +3 -3
  68. package/dist/server/components/run-step-timeline/index.js +2 -2
  69. package/dist/server/components/sparkbar/index.js +3 -2
  70. package/dist/server/components/spectrogram/index.js +3 -3
  71. package/dist/server/components/spectrum-chart/index.js +2 -2
  72. package/dist/server/components/statistic/index.js +4 -3
  73. package/dist/server/components/statistic-group/index.js +4 -3
  74. package/dist/server/components/waveform/index.js +2 -2
  75. package/dist/server/index.js +21 -21
  76. package/dist/server/{index.server-3dkwzkd3.js → index.server-10r7yf13.js} +110 -27
  77. package/dist/server/{index.server-93943z3e.js → index.server-151dt1tx.js} +1 -1
  78. package/dist/server/{index.server-pp2n6def.js → index.server-2y0xz53g.js} +37 -14
  79. package/dist/server/{index.server-bd8rcgf0.js → index.server-4hvjet4z.js} +1 -1
  80. package/dist/server/{index.server-bsm39gpy.js → index.server-5d83fkyg.js} +75 -21
  81. package/dist/server/{index.server-4wweyb2e.js → index.server-8dh2rtnc.js} +1 -1
  82. package/dist/server/{index.server-abqbstkt.js → index.server-9gj583qs.js} +41 -14
  83. package/dist/server/{index.server-2nmwsacy.js → index.server-9scm7zf9.js} +4 -4
  84. package/dist/server/{index.server-5j6jv7rm.js → index.server-9vwxyy06.js} +108 -29
  85. package/dist/server/{index.server-abjsjsw8.js → index.server-afpjvfz1.js} +111 -35
  86. package/dist/server/{index.server-86sw5ea6.js → index.server-dw9bz17h.js} +4 -4
  87. package/dist/server/{index.server-d26jzn2m.js → index.server-en31rprd.js} +3 -3
  88. package/dist/server/{index.server-dx58qant.js → index.server-f3a0ecqg.js} +72 -9
  89. package/dist/server/{index.server-d63pwytk.js → index.server-kz8aeeq5.js} +18 -10
  90. package/dist/server/index.server-mmmrgvyd.js +1274 -0
  91. package/dist/server/{index.server-1221p7e4.js → index.server-scahngwv.js} +13 -1
  92. package/dist/server/{index.server-nj8kk5bv.js → index.server-t73q59c1.js} +1 -1
  93. package/dist/server/{index.server-5schb2vt.js → index.server-tdrncj5e.js} +16 -6
  94. package/dist/server/{index.server-wm8957be.js → index.server-veqke4sq.js} +10 -1
  95. package/dist/server/{index.server-fphvzcfb.js → index.server-wqajghn9.js} +1 -1
  96. package/dist/server/{index.server-yd9shwqq.js → index.server-zjcjzcv6.js} +1 -1
  97. package/package.json +1 -1
  98. package/src/_internal/chart/chart-bar-model.ts +330 -0
  99. package/src/_internal/chart/chart-cartesian-model.ts +450 -0
  100. package/src/_internal/chart/chart-interaction.svelte.ts +25 -6
  101. package/src/_internal/chart/chart-layout.ts +348 -0
  102. package/src/_internal/chart/chart-model-utilities.ts +357 -0
  103. package/src/_internal/chart/chart-scale.ts +487 -0
  104. package/src/_internal/chart/chart-utilities.ts +22 -1078
  105. package/src/_internal/chart/heatmap-utilities.ts +21 -17
  106. package/src/components/_internal/chart-tooltip.css +21 -0
  107. package/src/components/_internal/chart-tooltip.svelte +44 -0
  108. package/src/components/approval-card/approval-card.svelte +1 -1
  109. package/src/components/area-chart/area-chart.css +27 -23
  110. package/src/components/area-chart/area-chart.examples.json +1 -1
  111. package/src/components/area-chart/area-chart.schema.json +37 -0
  112. package/src/components/area-chart/area-chart.schema.ts +40 -0
  113. package/src/components/area-chart/area-chart.svelte +103 -35
  114. package/src/components/area-chart/area-chart.types.ts +7 -1
  115. package/src/components/badge/badge.css +2 -2
  116. package/src/components/badge/badge.schema.json +1 -1
  117. package/src/components/badge/badge.schema.ts +1 -1
  118. package/src/components/badge/badge.svelte +2 -2
  119. package/src/components/badge/badge.types.ts +3 -3
  120. package/src/components/bar-chart/bar-chart.css +27 -21
  121. package/src/components/bar-chart/bar-chart.schema.json +37 -0
  122. package/src/components/bar-chart/bar-chart.schema.ts +40 -0
  123. package/src/components/bar-chart/bar-chart.svelte +94 -33
  124. package/src/components/bar-chart/bar-chart.types.ts +9 -2
  125. package/src/components/chart.types.ts +112 -2
  126. package/src/components/line-chart/line-chart.css +25 -24
  127. package/src/components/line-chart/line-chart.examples.json +1 -1
  128. package/src/components/line-chart/line-chart.schema.json +37 -0
  129. package/src/components/line-chart/line-chart.schema.ts +40 -0
  130. package/src/components/line-chart/line-chart.svelte +95 -40
  131. package/src/components/line-chart/line-chart.types.ts +7 -1
  132. package/src/components/matrix-chart/matrix-chart.css +12 -6
  133. package/src/components/matrix-chart/matrix-chart.schema.json +25 -0
  134. package/src/components/matrix-chart/matrix-chart.schema.ts +25 -0
  135. package/src/components/matrix-chart/matrix-chart.svelte +30 -12
  136. package/src/components/matrix-chart/matrix-chart.types.ts +5 -1
  137. package/src/components/run-step-timeline/run-step-timeline.svelte +2 -2
  138. package/src/components/sparkbar/sparkbar.css +5 -4
  139. package/src/components/sparkbar/sparkbar.schema.json +25 -0
  140. package/src/components/sparkbar/sparkbar.schema.ts +26 -0
  141. package/src/components/sparkbar/sparkbar.svelte +8 -1
  142. package/src/components/sparkbar/sparkbar.types.ts +5 -0
  143. package/src/components/spectrogram/spectrogram.css +7 -6
  144. package/src/components/spectrogram/spectrogram.schema.json +25 -0
  145. package/src/components/spectrogram/spectrogram.schema.ts +25 -0
  146. package/src/components/spectrogram/spectrogram.svelte +73 -28
  147. package/src/components/spectrogram/spectrogram.types.ts +5 -1
  148. package/src/components/spectrum-chart/spectrum-chart.css +8 -7
  149. package/src/components/spectrum-chart/spectrum-chart.schema.json +25 -0
  150. package/src/components/spectrum-chart/spectrum-chart.schema.ts +26 -0
  151. package/src/components/spectrum-chart/spectrum-chart.svelte +38 -12
  152. package/src/components/spectrum-chart/spectrum-chart.types.ts +5 -1
  153. package/src/components/statistic/statistic.css +6 -5
  154. package/src/components/statistic/statistic.schema.json +25 -0
  155. package/src/components/statistic/statistic.schema.ts +26 -0
  156. package/src/components/statistic/statistic.svelte +6 -1
  157. package/src/components/statistic/statistic.types.ts +5 -0
  158. package/src/components/waveform/waveform.css +8 -7
  159. package/src/components/waveform/waveform.schema.json +25 -0
  160. package/src/components/waveform/waveform.schema.ts +26 -0
  161. package/src/components/waveform/waveform.svelte +16 -3
  162. package/src/components/waveform/waveform.types.ts +5 -1
  163. package/src/index.ts +8 -0
  164. package/dist/server/index.server-6vbpz6dd.js +0 -690
@@ -58,7 +58,205 @@ import"@lostgradient/cinder/waveform/styles";
58
58
  import"svelte/internal/disclose-version";
59
59
  import * as $2 from "svelte/internal/client";
60
60
 
61
- // src/_internal/chart/chart-utilities.ts
61
+ // src/_internal/chart/chart-layout.ts
62
+ var CHART_OUTER_PADDING = 16;
63
+ var CHART_GUIDE_GAP = 8;
64
+ var CHART_AXIS_TITLE_GAP = 12;
65
+ var HORIZONTAL_CATEGORY_LABEL_GAP = 8;
66
+ var HORIZONTAL_CATEGORY_LABEL_OUTER_PADDING = 8;
67
+ var MAXIMUM_HORIZONTAL_CATEGORY_LABEL_FRACTION = 0.4;
68
+ var MAXIMUM_CHART_TEXT_MEASUREMENTS = 1024;
69
+ function createChartGeometry(width, height, options = {}) {
70
+ const xTickRotation = options.xAxis?.tickLabelRotation ?? 0;
71
+ if (!Number.isFinite(xTickRotation)) {
72
+ throw new Error(`[cinder/chart] rule=invalid-tick-label-rotation tickLabelRotation="${xTickRotation}": expected a finite number.`);
73
+ }
74
+ const xTickLabels = options.xTickLabels ?? [];
75
+ const yTickLabels = options.yTickLabels ?? [];
76
+ const measurementContext = createChartTextMeasurementContext(options.measureText ?? false, options.measurementElement, options.measurementVersion ?? 0);
77
+ const textMeasurements = measureChartTexts([
78
+ ...xTickLabels.map((label) => ({ label, rotation: xTickRotation })),
79
+ ...yTickLabels.map((label) => ({ label, rotation: 0 })),
80
+ ...options.xAxis?.label ? [{ label: options.xAxis.label, rotation: 0 }] : [],
81
+ ...options.yAxis?.label ? [{ label: options.yAxis.label, rotation: -90 }] : []
82
+ ], measurementContext);
83
+ const measurementFor = (label, rotation) => textMeasurements.get(chartTextMeasurementKey(label, rotation, measurementContext.cacheKey)) ?? fallbackChartTextMeasurement(label, rotation);
84
+ const xTickHeight = maximumMeasurement(xTickLabels, (label) => measurementFor(label, xTickRotation).height);
85
+ const firstXTickWidth = xTickLabels[0] ? measurementFor(xTickLabels[0], xTickRotation).width : 0;
86
+ const lastXTickLabel = xTickLabels.at(-1);
87
+ const lastXTickWidth = lastXTickLabel ? measurementFor(lastXTickLabel, xTickRotation).width : 0;
88
+ const yTickWidth = maximumMeasurement(yTickLabels, (label) => measurementFor(label, 0).width);
89
+ const xAxisTitleHeight = options.xAxis?.label ? measurementFor(options.xAxis.label, 0).height + CHART_AXIS_TITLE_GAP : 0;
90
+ const yAxisTitleWidth = options.yAxis?.label ? measurementFor(options.yAxis.label, -90).width + CHART_AXIS_TITLE_GAP : 0;
91
+ const derivedMarginLeft = CHART_OUTER_PADDING + yTickWidth + CHART_GUIDE_GAP + yAxisTitleWidth;
92
+ const maximumMarginLeft = Math.max(CHART_OUTER_PADDING, Math.floor(width * 0.4));
93
+ const endpointLeftMargin = Math.max(CHART_OUTER_PADDING, Math.ceil(firstXTickWidth / 2) + CHART_GUIDE_GAP);
94
+ const endpointRightMargin = Math.max(CHART_OUTER_PADDING, Math.ceil(lastXTickWidth / 2) + CHART_GUIDE_GAP);
95
+ const marginLeft = Math.min(maximumMarginLeft, Math.max(derivedMarginLeft, options.marginLeft ?? 0, endpointLeftMargin));
96
+ const marginTop = options.xTickPosition === "top" ? Math.min(Math.max(CHART_OUTER_PADDING, Math.floor(height * 0.45)), CHART_OUTER_PADDING + xTickHeight + CHART_GUIDE_GAP + xAxisTitleHeight) : CHART_OUTER_PADDING;
97
+ const marginRight = endpointRightMargin;
98
+ const marginBottom = options.xTickPosition === "top" ? CHART_OUTER_PADDING : Math.min(Math.max(CHART_OUTER_PADDING, Math.floor(height * 0.45)), CHART_OUTER_PADDING + xTickHeight + CHART_GUIDE_GAP + xAxisTitleHeight);
99
+ return {
100
+ plotWidth: Math.max(1, width - marginLeft - marginRight),
101
+ plotHeight: Math.max(1, height - marginTop - marginBottom),
102
+ marginTop,
103
+ marginRight,
104
+ marginBottom,
105
+ marginLeft
106
+ };
107
+ }
108
+ function createHorizontalCategoryLabelLayout(labels, chartWidth, options = {}) {
109
+ const measurementContext = createChartTextMeasurementContext(options.measureText ?? false, options.measurementElement, options.measurementVersion ?? 0);
110
+ const textMeasurements = measureChartTexts([...labels.map((label) => ({ label, rotation: 0 })), { label: "…", rotation: 0 }], measurementContext);
111
+ const measurementFor = (label) => textMeasurements.get(chartTextMeasurementKey(label, 0, measurementContext.cacheKey)) ?? fallbackChartTextMeasurement(label, 0);
112
+ const maximumMarginLeft = Math.max(CHART_OUTER_PADDING, Math.floor(chartWidth * MAXIMUM_HORIZONTAL_CATEGORY_LABEL_FRACTION));
113
+ let longestLabelWidth = 0;
114
+ for (const label of labels) {
115
+ longestLabelWidth = Math.max(longestLabelWidth, measurementFor(label).width);
116
+ }
117
+ const requestedMarginLeft = longestLabelWidth + HORIZONTAL_CATEGORY_LABEL_GAP + HORIZONTAL_CATEGORY_LABEL_OUTER_PADDING;
118
+ const marginLeft = Math.min(maximumMarginLeft, Math.max(CHART_OUTER_PADDING, requestedMarginLeft));
119
+ const availableLabelWidth = Math.max(0, marginLeft - HORIZONTAL_CATEGORY_LABEL_GAP - HORIZONTAL_CATEGORY_LABEL_OUTER_PADDING);
120
+ return {
121
+ marginLeft,
122
+ labels: labels.map((label) => truncateHorizontalCategoryLabel(label, availableLabelWidth, measurementFor))
123
+ };
124
+ }
125
+ function observeChartFontLoading(onFontsChanged) {
126
+ if (typeof document === "undefined" || !document.fonts)
127
+ return () => {};
128
+ let active = true;
129
+ const handleFontsChanged = () => {
130
+ if (active)
131
+ onFontsChanged();
132
+ };
133
+ document.fonts.addEventListener("loadingdone", handleFontsChanged);
134
+ document.fonts.ready.then(handleFontsChanged);
135
+ return () => {
136
+ active = false;
137
+ document.fonts.removeEventListener("loadingdone", handleFontsChanged);
138
+ };
139
+ }
140
+ function truncateHorizontalCategoryLabel(label, availableWidth, measurementFor) {
141
+ const measuredWidth = measurementFor(label).width;
142
+ if (measuredWidth <= availableWidth)
143
+ return label;
144
+ const fallbackWidth = fallbackChartTextMeasurement(label, 0).width;
145
+ const measurementScale = fallbackWidth > 0 ? measuredWidth / fallbackWidth : 1;
146
+ const estimatedWidth = (candidate) => candidate === "…" ? measurementFor("…").width : fallbackChartTextMeasurement(candidate, 0).width * measurementScale;
147
+ const characters = Array.from(label);
148
+ while (characters.length > 0) {
149
+ const truncated = `${characters.join("")}…`;
150
+ if (estimatedWidth(truncated) <= availableWidth)
151
+ return truncated;
152
+ characters.pop();
153
+ }
154
+ return availableWidth >= estimatedWidth("…") ? "…" : "";
155
+ }
156
+ function maximumMeasurement(labels, select) {
157
+ let maximum = 0;
158
+ for (const label of labels)
159
+ maximum = Math.max(maximum, select(label));
160
+ return maximum;
161
+ }
162
+ var chartTextMeasurementCache = new Map;
163
+ function measureChartTexts(entries, context) {
164
+ if (!context.container || typeof document === "undefined") {
165
+ return new Map(entries.map(({ label, rotation }) => [
166
+ chartTextMeasurementKey(label, rotation, context.cacheKey),
167
+ fallbackChartTextMeasurement(label, rotation)
168
+ ]));
169
+ }
170
+ const uniqueEntries = [
171
+ ...new Map(entries.map((entry) => [
172
+ chartTextMeasurementKey(entry.label, entry.rotation, context.cacheKey),
173
+ entry
174
+ ])).values()
175
+ ];
176
+ const missing = uniqueEntries.filter(({ label, rotation }) => !chartTextMeasurementCache.has(chartTextMeasurementKey(label, rotation, context.cacheKey)));
177
+ if (missing.length > 0) {
178
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
179
+ svg.setAttribute("style", "position:absolute;visibility:hidden;pointer-events:none;inline-size:0;block-size:0");
180
+ const texts = missing.map((entry) => {
181
+ const text = document.createElementNS("http://www.w3.org/2000/svg", "text");
182
+ if (context.textStyle)
183
+ text.setAttribute("style", context.textStyle);
184
+ text.textContent = entry.label;
185
+ svg.append(text);
186
+ return { ...entry, text };
187
+ });
188
+ context.container.append(svg);
189
+ for (const { label, rotation, text } of texts) {
190
+ let measurement;
191
+ try {
192
+ const bounds = text.getBBox();
193
+ if (bounds.width > 0 && bounds.height > 0) {
194
+ measurement = { width: bounds.width, height: bounds.height };
195
+ }
196
+ } catch {}
197
+ if (measurement) {
198
+ cacheChartTextMeasurement(chartTextMeasurementKey(label, rotation, context.cacheKey), rotateChartTextMeasurement(measurement, rotation));
199
+ }
200
+ }
201
+ svg.remove();
202
+ }
203
+ return new Map(entries.map(({ label, rotation }) => [
204
+ chartTextMeasurementKey(label, rotation, context.cacheKey),
205
+ chartTextMeasurementCache.get(chartTextMeasurementKey(label, rotation, context.cacheKey)) ?? fallbackChartTextMeasurement(label, rotation)
206
+ ]));
207
+ }
208
+ function cacheChartTextMeasurement(key, measurement) {
209
+ if (!chartTextMeasurementCache.has(key)) {
210
+ while (chartTextMeasurementCache.size >= MAXIMUM_CHART_TEXT_MEASUREMENTS) {
211
+ const oldestKey = chartTextMeasurementCache.keys().next().value;
212
+ if (oldestKey === undefined)
213
+ break;
214
+ chartTextMeasurementCache.delete(oldestKey);
215
+ }
216
+ }
217
+ chartTextMeasurementCache.set(key, measurement);
218
+ }
219
+ function chartTextMeasurementKey(label, rotation, measurementContext) {
220
+ return `${label}\x00${rotation}\x00${measurementContext}`;
221
+ }
222
+ function createChartTextMeasurementContext(allowBrowserMeasurement, measurementElement, measurementVersion) {
223
+ if (!allowBrowserMeasurement || !measurementElement || typeof window === "undefined" || !measurementElement.isConnected) {
224
+ return { cacheKey: "fallback" };
225
+ }
226
+ const style = window.getComputedStyle(measurementElement);
227
+ const fontSize = style.getPropertyValue("--cinder-text-xs").trim() || style.fontSize;
228
+ const textStyle = [
229
+ `font-family:${style.fontFamily}`,
230
+ `font-size:${fontSize}`,
231
+ `font-style:${style.fontStyle}`,
232
+ `font-weight:${style.fontWeight}`,
233
+ `font-stretch:${style.fontStretch}`,
234
+ `font-variant:${style.fontVariant}`,
235
+ `font-feature-settings:${style.fontFeatureSettings}`,
236
+ `font-kerning:${style.fontKerning}`,
237
+ `letter-spacing:${style.letterSpacing}`,
238
+ `text-transform:${style.textTransform}`
239
+ ].join(";");
240
+ return {
241
+ cacheKey: `browser\x00${measurementVersion}\x00${textStyle}`,
242
+ container: measurementElement,
243
+ textStyle
244
+ };
245
+ }
246
+ function fallbackChartTextMeasurement(label, rotation) {
247
+ return rotateChartTextMeasurement({ width: Array.from(label).length * 7, height: 12 }, rotation);
248
+ }
249
+ function rotateChartTextMeasurement(measurement, rotation) {
250
+ if (rotation === 0)
251
+ return measurement;
252
+ const radians = Math.abs(rotation) * Math.PI / 180;
253
+ return {
254
+ width: Math.abs(measurement.width * Math.cos(radians)) + Math.abs(measurement.height * Math.sin(radians)),
255
+ height: Math.abs(measurement.width * Math.sin(radians)) + Math.abs(measurement.height * Math.cos(radians))
256
+ };
257
+ }
258
+
259
+ // src/_internal/chart/chart-model-utilities.ts
62
260
  var chartPalette = [
63
261
  "var(--cinder-chart-series-1)",
64
262
  "var(--cinder-chart-series-2)",
@@ -69,8 +267,26 @@ var chartPalette = [
69
267
  "var(--cinder-chart-series-7)",
70
268
  "var(--cinder-chart-series-8)"
71
269
  ];
72
- function chartPaletteColor(index) {
73
- return chartPalette[index % chartPalette.length] ?? "var(--cinder-chart-series-1)";
270
+ function chartPaletteColor(index, palette = chartPalette) {
271
+ const resolvedPalette = palette.length > 0 ? palette : chartPalette;
272
+ if (index < 0)
273
+ return resolvedPalette[0] ?? chartPalette[0];
274
+ return resolvedPalette[index % resolvedPalette.length] ?? chartPalette[0];
275
+ }
276
+ function resolveChartTheme(theme = undefined) {
277
+ return {
278
+ foreground: theme?.foreground ?? "currentColor",
279
+ muted: theme?.muted ?? "currentColor",
280
+ grid: theme?.grid ?? "currentColor",
281
+ background: theme?.background ?? "transparent",
282
+ palette: theme?.palette?.length ? [...theme.palette] : [...chartPalette]
283
+ };
284
+ }
285
+ function chartResourceSegment(segment) {
286
+ return encodeURIComponent(segment).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replaceAll("_", "_u").replaceAll("-", "_d").replaceAll("%", "_x");
287
+ }
288
+ function chartResourceId(idPrefix, resource, seriesId) {
289
+ return [idPrefix, resource, seriesId].map(chartResourceSegment).join("-");
74
290
  }
75
291
  function assertValidChartNumber(componentId, rule, value, label) {
76
292
  if (!Number.isFinite(value) || value <= 0) {
@@ -92,6 +308,9 @@ function assertValidTickCount(componentId, axis) {
92
308
  function dataTableClass(visibility) {
93
309
  return visibility === "screen-reader-only" ? "cinder-sr-only" : undefined;
94
310
  }
311
+ function formatDataTableCaption(caption, displayedRowCount, totalRowCount) {
312
+ return totalRowCount > displayedRowCount ? `${caption} (showing ${displayedRowCount} of ${totalRowCount} data points)` : caption;
313
+ }
95
314
  function formatXValue(value, axis, context) {
96
315
  return axis?.format ? axis.format(value.raw, context) : value.label;
97
316
  }
@@ -136,194 +355,462 @@ function assertUniqueSeriesIds(componentId, series) {
136
355
  function toggleSeriesId(hiddenSeriesIds, seriesId) {
137
356
  return hiddenSeriesIds.includes(seriesId) ? hiddenSeriesIds.filter((id) => id !== seriesId) : [...hiddenSeriesIds, seriesId];
138
357
  }
139
- function createCartesianModel(options) {
140
- const {
141
- componentId,
142
- series,
143
- hiddenSeriesIds,
144
- width,
145
- height,
146
- xAxis,
147
- yAxis,
148
- stackedArea = false
149
- } = options;
150
- assertUniqueSeriesIds(componentId, series);
151
- assertValidChartNumber(componentId, "invalid-height", height, "height");
152
- assertValidTickCount(componentId, xAxis);
153
- assertValidTickCount(componentId, yAxis);
154
- const geometry = createGeometry(width, height);
155
- const allKinds = new Set;
156
- const xValuesByKey = new Map;
157
- const normalizedSeries = series.map((item, seriesIndex) => {
158
- const seenX = new Set;
159
- const color = item.color ?? chartPaletteColor(seriesIndex);
160
- const points = item.data.map((point, pointIndex) => {
161
- const x = normalizeXValue(point.x);
162
- allKinds.add(x.kind);
163
- if (seenX.has(x.key)) {
164
- throw new Error(`[cinder/${componentId}] rule=duplicate-x series="${item.id}" x="${x.label}": duplicate x values are not supported.`);
165
- }
166
- seenX.add(x.key);
167
- xValuesByKey.set(x.key, x);
168
- const y = normalizeNumericValue(componentId, item.id, x.label, point.y);
169
- return {
170
- seriesId: item.id,
171
- seriesLabel: item.label,
172
- color,
173
- x,
174
- y,
175
- originalY: point.y,
176
- index: pointIndex
177
- };
178
- });
179
- return { id: item.id, label: item.label, color, points };
180
- });
181
- if (allKinds.size > 1) {
182
- throw new Error(`[cinder/${componentId}] rule=mixed-x-domain-kind: all x values must share one domain kind.`);
358
+ function nearestTarget(targets, x, y, axis = "x") {
359
+ if (targets.length === 0)
360
+ return;
361
+ if (targets.length === 1)
362
+ return targets[0];
363
+ const pointerKey = axis === "x" ? x : y;
364
+ let low = 0;
365
+ let high = targets.length - 1;
366
+ while (low < high) {
367
+ const mid = low + high >> 1;
368
+ const midKey = axis === "x" ? targets[mid]?.x ?? 0 : targets[mid]?.y ?? 0;
369
+ if (midKey < pointerKey)
370
+ low = mid + 1;
371
+ else
372
+ high = mid;
183
373
  }
184
- if (stackedArea) {
185
- for (const item of normalizedSeries) {
186
- for (const point of item.points) {
187
- if ((point.y ?? 0) < 0) {
188
- throw new Error(`[cinder/${componentId}] rule=negative-stacked-area series="${item.id}" x="${point.x.label}": stacked areas do not support negative values.`);
189
- }
190
- }
374
+ const candidates = [];
375
+ function addBucket(start) {
376
+ const target = targets[start];
377
+ if (!target)
378
+ return;
379
+ const bucketKey = axis === "x" ? target.x : target.y;
380
+ for (let index = start;index >= 0; index--) {
381
+ const candidate = targets[index];
382
+ if (!candidate)
383
+ continue;
384
+ const candidateKey = axis === "x" ? candidate.x : candidate.y;
385
+ if (candidateKey !== bucketKey)
386
+ break;
387
+ candidates.push(candidate);
388
+ }
389
+ for (let index = start + 1;index < targets.length; index++) {
390
+ const candidate = targets[index];
391
+ if (!candidate)
392
+ continue;
393
+ const candidateKey = axis === "x" ? candidate.x : candidate.y;
394
+ if (candidateKey !== bucketKey)
395
+ break;
396
+ candidates.push(candidate);
191
397
  }
192
398
  }
193
- const sortedXValues = sortXValues([...xValuesByKey.values()]);
194
- const orderByKey = new Map(sortedXValues.map((value, index) => [value.key, index]));
195
- const visibleNumericValues = [];
196
- for (const item of normalizedSeries) {
197
- if (hiddenSeriesIds.includes(item.id))
399
+ addBucket(low);
400
+ if (low > 0) {
401
+ addBucket(low - 1);
402
+ }
403
+ let nearest;
404
+ let nearestDistance = Number.POSITIVE_INFINITY;
405
+ for (const target of candidates) {
406
+ const targetDistance = Math.hypot(target.x - x, target.y - y);
407
+ if (targetDistance >= nearestDistance)
198
408
  continue;
199
- for (const point of item.points) {
200
- if (point.y !== null)
201
- visibleNumericValues.push(point.y);
409
+ nearest = target;
410
+ nearestDistance = targetDistance;
411
+ }
412
+ return nearest;
413
+ }
414
+ function legendVisible(legendPosition, seriesCount) {
415
+ return legendPosition !== "none" && seriesCount > 0;
416
+ }
417
+
418
+ // src/_internal/chart/chart-scale.ts
419
+ var MAXIMUM_RENDERED_SERIES_POINTS = 2000;
420
+ function evenlySample(values, count) {
421
+ if (values.length <= count)
422
+ return [...values];
423
+ if (count <= 1)
424
+ return values[0] === undefined ? [] : [values[0]];
425
+ return Array.from({ length: count }, (_, index) => {
426
+ const sourceIndex = Math.round(index * (values.length - 1) / (count - 1));
427
+ return values[sourceIndex];
428
+ });
429
+ }
430
+ function boundedGapHeavyIndices(points, limit) {
431
+ const finiteRuns = [];
432
+ let index = 0;
433
+ while (index < points.length) {
434
+ while (index < points.length && points[index]?.y === null)
435
+ index += 1;
436
+ if (index >= points.length)
437
+ break;
438
+ let representative = index;
439
+ let maximumMagnitude = Math.abs(points[index]?.y ?? 0);
440
+ while (index + 1 < points.length && points[index + 1]?.y !== null) {
441
+ index += 1;
442
+ const magnitude = Math.abs(points[index]?.y ?? 0);
443
+ if (magnitude > maximumMagnitude) {
444
+ maximumMagnitude = magnitude;
445
+ representative = index;
446
+ }
202
447
  }
448
+ finiteRuns.push({ end: index, representative });
449
+ index += 1;
203
450
  }
204
- const stackedTotalsByKey = new Map(sortedXValues.map((value) => [value.key, 0]));
205
- if (stackedArea) {
206
- for (const item of normalizedSeries) {
207
- if (hiddenSeriesIds.includes(item.id))
451
+ const maximumFiniteRuns = Math.max(1, Math.floor((limit + 1) / 2));
452
+ const sampledRuns = evenlySample(finiteRuns, maximumFiniteRuns);
453
+ const selected = [];
454
+ sampledRuns.forEach((run, runIndex) => {
455
+ const previousRun = sampledRuns[runIndex - 1];
456
+ if (previousRun)
457
+ selected.push(previousRun.end + 1);
458
+ selected.push(run.representative);
459
+ });
460
+ return selected.sort((a, b) => a - b);
461
+ }
462
+ function layerExtremaIndices(layers, startIndex, endIndex) {
463
+ const extrema = new Set;
464
+ for (const layer of layers) {
465
+ let minimumIndex;
466
+ let maximumIndex;
467
+ let minimumValue = Number.POSITIVE_INFINITY;
468
+ let maximumValue = Number.NEGATIVE_INFINITY;
469
+ for (let index = startIndex;index < endIndex; index++) {
470
+ const value = layer[index];
471
+ if (value == null)
208
472
  continue;
209
- for (const point of item.points) {
210
- if (point.y === null)
211
- continue;
212
- stackedTotalsByKey.set(point.x.key, (stackedTotalsByKey.get(point.x.key) ?? 0) + point.y);
473
+ if (value < minimumValue) {
474
+ minimumValue = value;
475
+ minimumIndex = index;
476
+ }
477
+ if (value > maximumValue) {
478
+ maximumValue = value;
479
+ maximumIndex = index;
213
480
  }
214
481
  }
482
+ if (minimumIndex !== undefined)
483
+ extrema.add(minimumIndex);
484
+ if (maximumIndex !== undefined)
485
+ extrema.add(maximumIndex);
215
486
  }
216
- const domainValues = stackedArea ? [0, ...stackedTotalsByKey.values()] : visibleNumericValues;
217
- const [yMinimum, yMaximum] = createPaddedDomain(domainValues);
218
- const xStringScale = sortedXValues[0]?.kind === "string" ? createPointScale(sortedXValues.map((value) => value.key), [0, geometry.plotWidth], 0.5) : undefined;
219
- const xNumericScale = sortedXValues[0] && sortedXValues[0].kind !== "string" ? createLinearScale(createNumericDomain(sortedXValues), [0, geometry.plotWidth]) : undefined;
220
- const yScale = createLinearScale([yMinimum, yMaximum], [geometry.plotHeight, 0]);
221
- function scaleX(value) {
222
- if (value.kind === "string")
223
- return xStringScale?.(value.key) ?? 0;
224
- return xNumericScale?.(Number(value.comparable)) ?? 0;
487
+ return [...extrema];
488
+ }
489
+ function boundedGapHeavyLayerSelections(layers, pointCount, limit) {
490
+ const finiteIndices = [];
491
+ for (let index = 0;index < pointCount; index++) {
492
+ if (layers.some((layer) => layer[index] != null))
493
+ finiteIndices.push(index);
225
494
  }
226
- const tickCount = xAxis?.tickCount ?? sortedXValues.length;
227
- const xTicks = buildXAxisTicks(sortedXValues, tickCount, xAxis, scaleX);
228
- const targets = [];
229
- const tableRows = [];
230
- const stackedOffsetsByKey = new Map(sortedXValues.map((value) => [value.key, 0]));
231
- const renderedSeries = normalizedSeries.map((item) => {
232
- const hidden = hiddenSeriesIds.includes(item.id);
233
- const points = item.points.filter((point) => point.y !== null).toSorted((a, b) => (orderByKey.get(a.x.key) ?? 0) - (orderByKey.get(b.x.key) ?? 0));
234
- const placedPoints = points.map((point) => {
235
- const lowerValue = stackedArea ? stackedOffsetsByKey.get(point.x.key) ?? 0 : 0;
236
- const upperValue = lowerValue + (point.y ?? 0);
237
- return {
238
- ...point,
239
- pixelX: scaleX(point.x),
240
- pixelY: yScale(stackedArea ? upperValue : point.y ?? 0)
241
- };
242
- });
243
- const coordinates = placedPoints.map((placed) => ({
244
- x: placed.pixelX,
245
- y: placed.pixelY,
246
- y0: yScale(stackedArea ? stackedOffsetsByKey.get(placed.x.key) ?? 0 : 0)
247
- }));
248
- if (!hidden) {
249
- for (const placed of placedPoints) {
250
- const xLabel = formatXValue(placed.x, xAxis, {
251
- seriesId: item.id,
252
- seriesLabel: item.label,
253
- index: placed.index
254
- });
255
- const valueLabel = formatNumericValue(placed.y ?? 0, yAxis, series.find((entry) => entry.id === item.id)?.valueFormatter, { seriesId: item.id, seriesLabel: item.label, index: placed.index });
256
- targets.push({
257
- id: `${item.id}-${placed.x.key}`,
258
- seriesId: item.id,
259
- seriesLabel: item.label,
260
- xLabel,
261
- valueLabel,
262
- x: placed.pixelX,
263
- y: placed.pixelY,
264
- color: item.color
265
- });
266
- tableRows.push({
267
- id: `${item.id}-${placed.x.key}`,
268
- seriesLabel: item.label,
269
- xLabel,
270
- valueLabel
271
- });
495
+ const maximumFiniteSamples = Math.max(1, Math.floor((limit + 1) / 2));
496
+ const retainedIndices = new Set;
497
+ const priorityIndices = [
498
+ finiteIndices[0],
499
+ finiteIndices.at(-1),
500
+ ...layerExtremaIndices(layers, 0, pointCount)
501
+ ];
502
+ for (const index of priorityIndices) {
503
+ if (index !== undefined && retainedIndices.size < maximumFiniteSamples) {
504
+ retainedIndices.add(index);
505
+ }
506
+ }
507
+ const extremaPerBucket = Math.max(1, layers.length * 2);
508
+ const bucketCount = Math.floor((maximumFiniteSamples - retainedIndices.size) / extremaPerBucket);
509
+ for (let bucketIndex = 0;bucketIndex < bucketCount; bucketIndex++) {
510
+ const startIndex = Math.floor(bucketIndex * pointCount / bucketCount);
511
+ const endIndex = Math.floor((bucketIndex + 1) * pointCount / bucketCount);
512
+ for (const index of layerExtremaIndices(layers, startIndex, endIndex)) {
513
+ if (retainedIndices.size < maximumFiniteSamples)
514
+ retainedIndices.add(index);
515
+ }
516
+ }
517
+ const remainingCapacity = maximumFiniteSamples - retainedIndices.size;
518
+ if (remainingCapacity > 0) {
519
+ const coverageCandidates = finiteIndices.filter((index) => !retainedIndices.has(index));
520
+ for (const index of evenlySample(coverageCandidates, remainingCapacity)) {
521
+ retainedIndices.add(index);
522
+ }
523
+ }
524
+ const sampledIndices = [...retainedIndices].sort((a, b) => a - b);
525
+ const selectedSourceIndices = [];
526
+ sampledIndices.forEach((sourceIndex, selectionIndex) => {
527
+ const previousSourceIndex = sampledIndices[selectionIndex - 1];
528
+ if (previousSourceIndex !== undefined && sourceIndex > previousSourceIndex + 1) {
529
+ if (layers.some((layer) => layerHasOmittedGap(layer, previousSourceIndex, sourceIndex))) {
530
+ selectedSourceIndices.push(previousSourceIndex + Math.floor((sourceIndex - previousSourceIndex) / 2));
272
531
  }
273
- if (stackedArea) {
274
- for (const placed of placedPoints) {
275
- stackedOffsetsByKey.set(placed.x.key, (stackedOffsetsByKey.get(placed.x.key) ?? 0) + (placed.y ?? 0));
532
+ }
533
+ selectedSourceIndices.push(sourceIndex);
534
+ });
535
+ return selectedSourceIndices.map((sourceIndex, selectionIndex) => {
536
+ const previousSourceIndex = selectedSourceIndices[selectionIndex - 1];
537
+ const forceGapLayerIndices = [];
538
+ if (previousSourceIndex !== undefined && sourceIndex > previousSourceIndex + 1) {
539
+ layers.forEach((layer, layerIndex) => {
540
+ if (layerHasOmittedGap(layer, previousSourceIndex, sourceIndex)) {
541
+ forceGapLayerIndices.push(layerIndex);
276
542
  }
277
- }
543
+ });
278
544
  }
279
- return {
280
- ...item,
281
- hidden,
282
- points: hidden ? [] : placedPoints,
283
- path: hidden ? "" : createLinePath(coordinates),
284
- areaPath: hidden ? "" : createAreaPath(coordinates, stackedArea ? undefined : geometry.plotHeight)
285
- };
545
+ return { sourceIndex, forceGapLayerIndices };
286
546
  });
287
- targets.sort((a, b) => a.x - b.x);
288
- return {
289
- geometry,
290
- xTicks,
291
- yTicks: yScale.ticks(yAxis?.tickCount ?? 5),
292
- normalizedSeries: renderedSeries,
293
- tableRows,
294
- targets,
295
- empty: targets.length === 0,
296
- yDomain: [yMinimum, yMaximum]
297
- };
298
547
  }
299
- function buildXAxisTicks(sortedXValues, tickCount, xAxis, scaleX) {
300
- if (sortedXValues.length === 0)
301
- return [];
302
- const safeTickCount = Math.max(1, Math.min(tickCount, sortedXValues.length));
303
- if (safeTickCount >= sortedXValues.length) {
304
- return sortedXValues.map((value, index) => ({
305
- label: formatXValue(value, xAxis, { index }),
306
- x: scaleX(value)
548
+ function layerHasOmittedGap(layer, startIndex, endIndex) {
549
+ if (layer[startIndex] == null || layer[endIndex] == null)
550
+ return false;
551
+ for (let gapIndex = startIndex + 1;gapIndex < endIndex; gapIndex++) {
552
+ if (layer[gapIndex] == null)
553
+ return true;
554
+ }
555
+ return false;
556
+ }
557
+ function addGapBoundaryIndices(selected, pointCount, valueAt) {
558
+ for (let index = 1;index < pointCount; index++) {
559
+ const previousIsNull = valueAt(index - 1) == null;
560
+ const currentIsNull = valueAt(index) == null;
561
+ if (previousIsNull === currentIsNull)
562
+ continue;
563
+ selected.add(index - 1);
564
+ selected.add(index);
565
+ }
566
+ }
567
+ function decimationIndices(points, maximumPoints = MAXIMUM_RENDERED_SERIES_POINTS) {
568
+ if (points.length <= maximumPoints || maximumPoints < 2) {
569
+ return points.map((_, index) => index);
570
+ }
571
+ const limit = Math.max(2, Math.floor(maximumPoints));
572
+ const interiorLength = points.length - 2;
573
+ const selected = new Set([0, points.length - 1]);
574
+ addGapBoundaryIndices(selected, points.length, (index) => points[index]?.y);
575
+ const remainingExtremaBudget = limit - selected.size;
576
+ const bucketCount = Math.floor(remainingExtremaBudget / 2);
577
+ if (bucketCount < 1)
578
+ return boundedGapHeavyIndices(points, limit);
579
+ for (let bucketIndex = 0;bucketIndex < bucketCount; bucketIndex++) {
580
+ const start = 1 + Math.floor(bucketIndex * interiorLength / bucketCount);
581
+ const end = 1 + Math.floor((bucketIndex + 1) * interiorLength / bucketCount);
582
+ if (end <= start)
583
+ continue;
584
+ let minimumIndex;
585
+ let maximumIndex;
586
+ let minimumValue = Number.POSITIVE_INFINITY;
587
+ let maximumValue = Number.NEGATIVE_INFINITY;
588
+ for (let index = start;index < end; index++) {
589
+ const point = points[index];
590
+ if (!point)
591
+ continue;
592
+ if (point.y === null)
593
+ continue;
594
+ if (point.y < minimumValue) {
595
+ minimumValue = point.y;
596
+ minimumIndex = index;
597
+ }
598
+ if (point.y > maximumValue) {
599
+ maximumValue = point.y;
600
+ maximumIndex = index;
601
+ }
602
+ }
603
+ if (minimumIndex !== undefined)
604
+ selected.add(minimumIndex);
605
+ if (maximumIndex !== undefined)
606
+ selected.add(maximumIndex);
607
+ }
608
+ return [...selected].sort((a, b) => a - b);
609
+ }
610
+ function decimationIndicesForLayers(layers, maximumPoints = MAXIMUM_RENDERED_SERIES_POINTS) {
611
+ const pointCount = layers[0]?.length ?? 0;
612
+ if (pointCount <= maximumPoints || maximumPoints < 2) {
613
+ return Array.from({ length: pointCount }, (_, sourceIndex) => ({
614
+ sourceIndex,
615
+ forceGapLayerIndices: []
307
616
  }));
308
617
  }
309
- if (safeTickCount === 1) {
310
- const value = sortedXValues[0];
311
- return value ? [{ label: formatXValue(value, xAxis, { index: 0 }), x: scaleX(value) }] : [];
618
+ const limit = Math.max(2, Math.floor(maximumPoints));
619
+ const interiorLength = pointCount - 2;
620
+ const selected = new Set([0, pointCount - 1]);
621
+ for (const layer of layers) {
622
+ addGapBoundaryIndices(selected, pointCount, (index) => layer[index]);
312
623
  }
313
- const step = (sortedXValues.length - 1) / (safeTickCount - 1);
314
- const ticks = [];
315
- for (let i = 0;i < safeTickCount; i++) {
316
- const sourceIndex = Math.round(i * step);
317
- const value = sortedXValues[sourceIndex];
318
- if (!value)
624
+ const candidatesPerBucket = Math.max(1, layers.length * 2);
625
+ const bucketCount = Math.floor((limit - selected.size) / candidatesPerBucket);
626
+ if (bucketCount < 1)
627
+ return boundedGapHeavyLayerSelections(layers, pointCount, limit);
628
+ for (let bucketIndex = 0;bucketIndex < bucketCount; bucketIndex++) {
629
+ const start = 1 + Math.floor(bucketIndex * interiorLength / bucketCount);
630
+ const end = 1 + Math.floor((bucketIndex + 1) * interiorLength / bucketCount);
631
+ if (end <= start)
319
632
  continue;
320
- ticks.push({
321
- label: formatXValue(value, xAxis, { index: i }),
322
- x: scaleX(value)
323
- });
633
+ for (const layer of layers) {
634
+ let minimumIndex;
635
+ let maximumIndex;
636
+ let minimumValue = Number.POSITIVE_INFINITY;
637
+ let maximumValue = Number.NEGATIVE_INFINITY;
638
+ for (let index = start;index < end; index++) {
639
+ const value = layer[index];
640
+ if (value === null || value === undefined)
641
+ continue;
642
+ if (value < minimumValue) {
643
+ minimumValue = value;
644
+ minimumIndex = index;
645
+ }
646
+ if (value > maximumValue) {
647
+ maximumValue = value;
648
+ maximumIndex = index;
649
+ }
650
+ }
651
+ if (minimumIndex !== undefined)
652
+ selected.add(minimumIndex);
653
+ if (maximumIndex !== undefined)
654
+ selected.add(maximumIndex);
655
+ }
324
656
  }
325
- return ticks;
657
+ return [...selected].sort((a, b) => a - b).map((sourceIndex) => ({ sourceIndex, forceGapLayerIndices: [] }));
658
+ }
659
+ function decimatePlacedPoints(points, maximumPoints = MAXIMUM_RENDERED_SERIES_POINTS) {
660
+ return decimationIndices(points, maximumPoints).map((index) => points[index]);
661
+ }
662
+ function normalizeNumericValue(componentId, seriesId, xLabel, value) {
663
+ if (value === null || value === undefined)
664
+ return null;
665
+ if (!Number.isFinite(value)) {
666
+ throw new Error(`[cinder/${componentId}] rule=non-finite-y series="${seriesId}" x="${xLabel}": y values must be finite numbers.`);
667
+ }
668
+ return value;
669
+ }
670
+ function sortXValues(values) {
671
+ if (values[0]?.kind === "string")
672
+ return values;
673
+ return values.slice().sort((a, b) => Number(a.comparable) - Number(b.comparable));
674
+ }
675
+ function createPaddedDomain(values) {
676
+ if (values.length === 0)
677
+ return [-1, 1];
678
+ let minimum = values[0];
679
+ let maximum = values[0];
680
+ for (let index = 1;index < values.length; index++) {
681
+ const value = values[index];
682
+ if (value < minimum)
683
+ minimum = value;
684
+ if (value > maximum)
685
+ maximum = value;
686
+ }
687
+ if (minimum === maximum)
688
+ return [minimum - 1, maximum + 1];
689
+ return [Math.min(0, minimum), Math.max(0, maximum)];
690
+ }
691
+ function createLinearScale(domain, range) {
692
+ const [domainMinimum, domainMaximum] = domain[0] === domain[1] ? [domain[0] - 1, domain[1] + 1] : domain;
693
+ const [rangeMinimum, rangeMaximum] = range;
694
+ const domainSpan = domainMaximum - domainMinimum;
695
+ const rangeSpan = rangeMaximum - rangeMinimum;
696
+ const scale = Object.assign((value) => rangeMinimum + (value - domainMinimum) / domainSpan * rangeSpan, {
697
+ ticks: (count) => createTicks([domainMinimum, domainMaximum], count)
698
+ });
699
+ return scale;
700
+ }
701
+ function createPointScale(domain, range, padding) {
702
+ const positions = new Map;
703
+ const [rangeMinimum, rangeMaximum] = range;
704
+ if (domain.length === 1) {
705
+ positions.set(domain[0] ?? "", rangeMinimum + (rangeMaximum - rangeMinimum) / 2);
706
+ } else {
707
+ const step = (rangeMaximum - rangeMinimum) / Math.max(1, domain.length - 1 + padding * 2);
708
+ const start = rangeMinimum + step * padding;
709
+ domain.forEach((value, index) => positions.set(value, start + step * index));
710
+ }
711
+ return (value) => positions.get(value);
712
+ }
713
+ function createBandScale(domain, range, padding) {
714
+ const positions = new Map;
715
+ const [rangeMinimum, rangeMaximum] = range;
716
+ const availableSize = Math.max(0, rangeMaximum - rangeMinimum);
717
+ const step = domain.length === 0 ? 0 : availableSize / Math.max(1, domain.length + padding * (domain.length - 1));
718
+ const bandWidth = Math.max(0, step * (1 - padding));
719
+ domain.forEach((value, index) => positions.set(value, rangeMinimum + step * index));
720
+ const scale = Object.assign((value) => positions.get(value), {
721
+ bandwidth: () => bandWidth
722
+ });
723
+ return scale;
724
+ }
725
+ function createNumericDomain(values) {
726
+ if (values.length === 0)
727
+ return [0, 1];
728
+ let minimum = Number(values[0].comparable);
729
+ let maximum = minimum;
730
+ for (let index = 1;index < values.length; index++) {
731
+ const numeric = Number(values[index].comparable);
732
+ if (numeric < minimum)
733
+ minimum = numeric;
734
+ if (numeric > maximum)
735
+ maximum = numeric;
736
+ }
737
+ return minimum === maximum ? [minimum - 1, maximum + 1] : [minimum, maximum];
738
+ }
739
+ function createTicks(domain, count) {
740
+ const safeCount = Math.max(1, Math.floor(count));
741
+ if (safeCount === 1)
742
+ return [domain[0]];
743
+ const step = (domain[1] - domain[0]) / (safeCount - 1);
744
+ return Array.from({ length: safeCount }, (_, index) => domain[0] + step * index);
745
+ }
746
+ function createLinePath(points) {
747
+ if (points.length === 0)
748
+ return "";
749
+ const commands = [];
750
+ for (const [index, point] of points.entries()) {
751
+ if (point.y === null)
752
+ continue;
753
+ const previous = points[index - 1];
754
+ commands.push(previous?.y === null || commands.length === 0 ? `M${formatPathNumber(point.x)},${formatPathNumber(point.y)}` : `L${formatPathNumber(point.x)},${formatPathNumber(point.y)}`);
755
+ }
756
+ return commands.join("");
757
+ }
758
+ function createAreaPath(points, baseline) {
759
+ const segments = [];
760
+ let segment = [];
761
+ for (const point of points) {
762
+ if (point.y === null) {
763
+ if (segment.length > 0)
764
+ segments.push(segment);
765
+ segment = [];
766
+ continue;
767
+ }
768
+ segment.push({ ...point, y: point.y });
769
+ }
770
+ if (segment.length > 0)
771
+ segments.push(segment);
772
+ return segments.map((visiblePoints) => {
773
+ const firstPoint = visiblePoints[0];
774
+ const lowerPoints = [];
775
+ for (let index = visiblePoints.length - 1;index >= 0; index--) {
776
+ const point = visiblePoints[index];
777
+ lowerPoints.push(`L${formatPathNumber(point.x)},${formatPathNumber(point.y0 ?? baseline ?? 0)}`);
778
+ }
779
+ return [
780
+ `M${formatPathNumber(firstPoint.x)},${formatPathNumber(firstPoint.y0 ?? baseline ?? 0)}`,
781
+ `L${formatPathNumber(firstPoint.x)},${formatPathNumber(firstPoint.y)}`,
782
+ ...visiblePoints.slice(1).map((point) => `L${formatPathNumber(point.x)},${formatPathNumber(point.y)}`),
783
+ ...lowerPoints,
784
+ "Z"
785
+ ].join("");
786
+ }).join("");
787
+ }
788
+ function createStackedBarDomainValues(datumByKey, categories, series) {
789
+ const values = [0];
790
+ for (const category of categories) {
791
+ const datum = datumByKey.get(category.key);
792
+ if (!datum)
793
+ continue;
794
+ let positiveTotal = 0;
795
+ let negativeTotal = 0;
796
+ for (const item of series) {
797
+ const value = datum[item.valueKey];
798
+ if (typeof value !== "number")
799
+ continue;
800
+ if (value >= 0)
801
+ positiveTotal += value;
802
+ else
803
+ negativeTotal += value;
804
+ }
805
+ values.push(positiveTotal, negativeTotal);
806
+ }
807
+ return values;
326
808
  }
809
+ function formatPathNumber(value) {
810
+ return Number(value.toFixed(3)).toString();
811
+ }
812
+
813
+ // src/_internal/chart/chart-bar-model.ts
327
814
  function createBarModel(options) {
328
815
  const {
329
816
  data,
@@ -335,12 +822,17 @@ function createBarModel(options) {
335
822
  orientation,
336
823
  mode,
337
824
  xAxis,
338
- yAxis
825
+ yAxis,
826
+ theme,
827
+ measureText = false,
828
+ measurementElement,
829
+ measurementVersion = 0
339
830
  } = options;
340
831
  assertUniqueSeriesIds("bar-chart", series);
341
832
  assertValidChartNumber("bar-chart", "invalid-height", height, "height");
342
833
  assertValidTickCount("bar-chart", xAxis);
343
834
  assertValidTickCount("bar-chart", yAxis);
835
+ const resolvedTheme = resolveChartTheme(theme);
344
836
  const categories = [];
345
837
  const seenCategories = new Set;
346
838
  const categoryKinds = new Set;
@@ -381,21 +873,37 @@ function createBarModel(options) {
381
873
  }
382
874
  const sortedCategories = sortXValues(categories);
383
875
  const categoryLabels = sortedCategories.map((category, index) => formatXValue(category, orientation === "vertical" ? xAxis : yAxis, { index }));
384
- const horizontalCategoryLabelLayout = orientation === "horizontal" ? createHorizontalCategoryLabelLayout(categoryLabels, width) : undefined;
385
- const geometry = createGeometry(width, height, horizontalCategoryLabelLayout?.marginLeft);
876
+ const horizontalCategoryLabelLayout = orientation === "horizontal" ? createHorizontalCategoryLabelLayout(categoryLabels, width, {
877
+ measureText,
878
+ measurementElement,
879
+ measurementVersion
880
+ }) : undefined;
386
881
  const valueDomain = createPaddedDomain(mode === "stacked" ? createStackedBarDomainValues(datumByKey, sortedCategories, visibleSeries) : visibleValues);
882
+ const valueTickAxis = orientation === "vertical" ? yAxis : xAxis;
883
+ const valueTicks = createTicks(valueDomain, valueTickAxis?.tickCount ?? 5);
884
+ const valueTickLabels = valueTicks.map((tick, index) => formatNumericValue(tick, valueTickAxis, undefined, { index }));
885
+ const geometry = createChartGeometry(width, height, {
886
+ xTickLabels: orientation === "vertical" ? categoryLabels : valueTickLabels,
887
+ yTickLabels: orientation === "vertical" ? valueTickLabels : categoryLabels,
888
+ xAxis,
889
+ yAxis,
890
+ measureText,
891
+ measurementElement,
892
+ measurementVersion,
893
+ marginLeft: horizontalCategoryLabelLayout?.marginLeft
894
+ });
387
895
  if (sortedCategories.length === 0) {
388
- const tickAxis = orientation === "vertical" ? yAxis : xAxis;
389
896
  return {
390
897
  geometry,
391
898
  categories: [],
392
- yTicks: createTicks(valueDomain, tickAxis?.tickCount ?? 5),
899
+ yTicks: valueTicks,
393
900
  categoryTicks: [],
394
901
  bars: [],
395
902
  tableRows: [],
396
903
  targets: [],
397
904
  empty: true,
398
- valueDomain
905
+ valueDomain,
906
+ theme: resolvedTheme
399
907
  };
400
908
  }
401
909
  const valueScale = createLinearScale(valueDomain, orientation === "vertical" ? [geometry.plotHeight, 0] : [0, geometry.plotWidth]);
@@ -427,7 +935,7 @@ function createBarModel(options) {
427
935
  return;
428
936
  const value = rawValue;
429
937
  const seriesColorIndex = Math.max(0, series.findIndex((entry) => entry.id === item.id));
430
- const color = item.color ?? chartPaletteColor(seriesColorIndex);
938
+ const color = item.color ?? chartPaletteColor(seriesColorIndex, resolvedTheme.palette);
431
939
  const categoryPosition = categoryScale(category.key) ?? 0;
432
940
  let x = 0;
433
941
  let y = 0;
@@ -503,253 +1011,328 @@ function createBarModel(options) {
503
1011
  return {
504
1012
  geometry,
505
1013
  categories: sortedCategories,
506
- yTicks: valueScale.ticks((orientation === "vertical" ? yAxis : xAxis)?.tickCount ?? 5),
1014
+ yTicks: valueTicks,
507
1015
  categoryTicks,
508
1016
  bars,
509
1017
  tableRows,
510
1018
  targets,
511
1019
  empty: targets.length === 0,
512
- valueDomain
1020
+ valueDomain,
1021
+ theme: resolvedTheme
513
1022
  };
514
1023
  }
515
- function nearestTarget(targets, x, y, axis = "x") {
516
- if (targets.length === 0)
517
- return;
518
- if (targets.length === 1)
519
- return targets[0];
520
- const pointerKey = axis === "x" ? x : y;
521
- let low = 0;
522
- let high = targets.length - 1;
523
- while (low < high) {
524
- const mid = low + high >> 1;
525
- const midKey = axis === "x" ? targets[mid]?.x ?? 0 : targets[mid]?.y ?? 0;
526
- if (midKey < pointerKey)
527
- low = mid + 1;
528
- else
529
- high = mid;
1024
+ // src/_internal/chart/chart-cartesian-model.ts
1025
+ var DEFAULT_MAXIMUM_X_TICK_COUNT = 8;
1026
+ function createCartesianModel(options) {
1027
+ const {
1028
+ componentId,
1029
+ series,
1030
+ hiddenSeriesIds,
1031
+ width,
1032
+ height,
1033
+ xAxis,
1034
+ yAxis,
1035
+ stackedArea = false,
1036
+ theme,
1037
+ measureText = false,
1038
+ measurementElement,
1039
+ measurementVersion = 0
1040
+ } = options;
1041
+ assertUniqueSeriesIds(componentId, series);
1042
+ assertValidChartNumber(componentId, "invalid-height", height, "height");
1043
+ assertValidTickCount(componentId, xAxis);
1044
+ assertValidTickCount(componentId, yAxis);
1045
+ const resolvedTheme = resolveChartTheme(theme);
1046
+ let geometry = createChartGeometry(width, height, {
1047
+ measureText,
1048
+ measurementElement,
1049
+ measurementVersion
1050
+ });
1051
+ const allKinds = new Set;
1052
+ const xValuesByKey = new Map;
1053
+ const normalizedSeries = series.map((item, seriesIndex) => {
1054
+ const seenX = new Set;
1055
+ const color = item.color ?? chartPaletteColor(seriesIndex, resolvedTheme.palette);
1056
+ const points = item.data.map((point, pointIndex) => {
1057
+ const x = normalizeXValue(point.x);
1058
+ allKinds.add(x.kind);
1059
+ if (seenX.has(x.key)) {
1060
+ throw new Error(`[cinder/${componentId}] rule=duplicate-x series="${item.id}" x="${x.label}": duplicate x values are not supported.`);
1061
+ }
1062
+ seenX.add(x.key);
1063
+ xValuesByKey.set(x.key, x);
1064
+ const y = normalizeNumericValue(componentId, item.id, x.label, point.y);
1065
+ return {
1066
+ seriesId: item.id,
1067
+ seriesLabel: item.label,
1068
+ color,
1069
+ x,
1070
+ y,
1071
+ originalY: point.y,
1072
+ index: pointIndex
1073
+ };
1074
+ });
1075
+ return { id: item.id, label: item.label, color, points };
1076
+ });
1077
+ if (allKinds.size > 1) {
1078
+ throw new Error(`[cinder/${componentId}] rule=mixed-x-domain-kind: all x values must share one domain kind.`);
530
1079
  }
531
- const candidates = [];
532
- function addBucket(start) {
533
- const target = targets[start];
534
- if (!target)
535
- return;
536
- const bucketKey = axis === "x" ? target.x : target.y;
537
- for (let index = start;index >= 0; index--) {
538
- const candidate = targets[index];
539
- if (!candidate)
540
- continue;
541
- const candidateKey = axis === "x" ? candidate.x : candidate.y;
542
- if (candidateKey !== bucketKey)
543
- break;
544
- candidates.push(candidate);
545
- }
546
- for (let index = start + 1;index < targets.length; index++) {
547
- const candidate = targets[index];
548
- if (!candidate)
549
- continue;
550
- const candidateKey = axis === "x" ? candidate.x : candidate.y;
551
- if (candidateKey !== bucketKey)
552
- break;
553
- candidates.push(candidate);
1080
+ if (stackedArea) {
1081
+ for (const item of normalizedSeries) {
1082
+ for (const point of item.points) {
1083
+ if ((point.y ?? 0) < 0) {
1084
+ throw new Error(`[cinder/${componentId}] rule=negative-stacked-area series="${item.id}" x="${point.x.label}": stacked areas do not support negative values.`);
1085
+ }
1086
+ }
554
1087
  }
555
1088
  }
556
- addBucket(low);
557
- if (low > 0) {
558
- addBucket(low - 1);
559
- }
560
- let nearest;
561
- let nearestDistance = Number.POSITIVE_INFINITY;
562
- for (const target of candidates) {
563
- const targetDistance = Math.hypot(target.x - x, target.y - y);
564
- if (targetDistance >= nearestDistance)
1089
+ const sortedXValues = sortXValues([...xValuesByKey.values()]);
1090
+ const orderByKey = new Map(sortedXValues.map((value, index) => [value.key, index]));
1091
+ const visibleNumericValues = [];
1092
+ for (const item of normalizedSeries) {
1093
+ if (hiddenSeriesIds.includes(item.id))
565
1094
  continue;
566
- nearest = target;
567
- nearestDistance = targetDistance;
1095
+ for (const point of item.points) {
1096
+ if (point.y !== null)
1097
+ visibleNumericValues.push(point.y);
1098
+ }
568
1099
  }
569
- return nearest;
570
- }
571
- function legendVisible(legendPosition, seriesCount) {
572
- return legendPosition !== "none" && seriesCount > 0;
573
- }
574
- var DEFAULT_CHART_MARGIN_LEFT = 48;
575
- var HORIZONTAL_CATEGORY_LABEL_CHARACTER_WIDTH = 12;
576
- var HORIZONTAL_CATEGORY_LABEL_GAP = 8;
577
- var HORIZONTAL_CATEGORY_LABEL_OUTER_PADDING = 8;
578
- var MAXIMUM_HORIZONTAL_CATEGORY_LABEL_FRACTION = 0.4;
579
- function createGeometry(width, height, marginLeft = DEFAULT_CHART_MARGIN_LEFT) {
580
- const marginTop = 16;
581
- const marginRight = 16;
582
- const marginBottom = 36;
583
- return {
584
- plotWidth: Math.max(1, width - marginLeft - marginRight),
585
- plotHeight: Math.max(1, height - marginTop - marginBottom),
586
- marginTop,
587
- marginRight,
588
- marginBottom,
589
- marginLeft
590
- };
591
- }
592
- function createHorizontalCategoryLabelLayout(labels, chartWidth) {
593
- const maximumMarginLeft = Math.max(DEFAULT_CHART_MARGIN_LEFT, Math.floor(chartWidth * MAXIMUM_HORIZONTAL_CATEGORY_LABEL_FRACTION));
594
- let longestLabelWidth = 0;
595
- for (const label of labels) {
596
- longestLabelWidth = Math.max(longestLabelWidth, estimateHorizontalCategoryLabelWidth(label));
1100
+ const stackedTotalsByKey = new Map(sortedXValues.map((value) => [value.key, 0]));
1101
+ if (stackedArea) {
1102
+ for (const item of normalizedSeries) {
1103
+ if (hiddenSeriesIds.includes(item.id))
1104
+ continue;
1105
+ for (const point of item.points) {
1106
+ if (point.y === null)
1107
+ continue;
1108
+ stackedTotalsByKey.set(point.x.key, (stackedTotalsByKey.get(point.x.key) ?? 0) + point.y);
1109
+ }
1110
+ }
597
1111
  }
598
- const requestedMarginLeft = longestLabelWidth + HORIZONTAL_CATEGORY_LABEL_GAP + HORIZONTAL_CATEGORY_LABEL_OUTER_PADDING;
599
- const marginLeft = Math.min(maximumMarginLeft, Math.max(DEFAULT_CHART_MARGIN_LEFT, requestedMarginLeft));
600
- const availableLabelWidth = Math.max(0, marginLeft - HORIZONTAL_CATEGORY_LABEL_GAP - HORIZONTAL_CATEGORY_LABEL_OUTER_PADDING);
1112
+ const domainValues = stackedArea || componentId === "area-chart" ? [0, ...stackedArea ? stackedTotalsByKey.values() : visibleNumericValues] : visibleNumericValues;
1113
+ const [yMinimum, yMaximum] = createPaddedDomain(domainValues);
1114
+ const tickCount = xAxis?.tickCount ?? Math.min(sortedXValues.length, DEFAULT_MAXIMUM_X_TICK_COUNT);
1115
+ const preliminaryXTicks = buildXAxisTicks(sortedXValues, tickCount, xAxis, () => 0);
1116
+ const yTicks = createTicks([yMinimum, yMaximum], yAxis?.tickCount ?? 5);
1117
+ geometry = createChartGeometry(width, height, {
1118
+ xTickLabels: preliminaryXTicks.map((tick) => tick.label),
1119
+ yTickLabels: yTicks.map((tick, index) => formatNumericValue(tick, yAxis, undefined, { index })),
1120
+ xAxis,
1121
+ yAxis,
1122
+ measureText,
1123
+ measurementElement,
1124
+ measurementVersion
1125
+ });
1126
+ const xStringScale = sortedXValues[0]?.kind === "string" ? createPointScale(sortedXValues.map((value) => value.key), [0, geometry.plotWidth], 0.5) : undefined;
1127
+ const xNumericScale = sortedXValues[0] && sortedXValues[0].kind !== "string" ? createLinearScale(createNumericDomain(sortedXValues), [0, geometry.plotWidth]) : undefined;
1128
+ const yScale = createLinearScale([yMinimum, yMaximum], [geometry.plotHeight, 0]);
1129
+ function scaleX(value) {
1130
+ if (value.kind === "string")
1131
+ return xStringScale?.(value.key) ?? 0;
1132
+ return xNumericScale?.(Number(value.comparable)) ?? 0;
1133
+ }
1134
+ const xTicks = buildXAxisTicks(sortedXValues, tickCount, xAxis, scaleX);
1135
+ const targets = [];
1136
+ const tableRows = [];
1137
+ const stackedOffsetsByKey = new Map(sortedXValues.map((value) => [value.key, 0]));
1138
+ const normalizedPointsBySeriesId = stackedArea ? new Map(normalizedSeries.map((item) => [
1139
+ item.id,
1140
+ new Map(item.points.map((point) => [point.x.key, point]))
1141
+ ])) : undefined;
1142
+ const stackedRenderXValues = stackedArea ? sortedXValues.filter((value) => normalizedSeries.some((item) => !hiddenSeriesIds.includes(item.id) && normalizedPointsBySeriesId?.get(item.id)?.has(value.key))) : undefined;
1143
+ const stackedRenderDomain = stackedRenderXValues ?? [];
1144
+ const stackedVisibleSeries = stackedArea ? normalizedSeries.filter((item) => !hiddenSeriesIds.includes(item.id)) : [];
1145
+ const stackedLayerIndexBySeriesId = new Map(stackedVisibleSeries.map((item, layerIndex) => [item.id, layerIndex]));
1146
+ const stackedBoundaryLayers = stackedArea ? (() => {
1147
+ const cumulativeValuesByKey = new Map(stackedRenderDomain.map((value) => [value.key, 0]));
1148
+ return stackedVisibleSeries.map((item) => stackedRenderDomain.map((value) => {
1149
+ const point = normalizedPointsBySeriesId?.get(item.id)?.get(value.key);
1150
+ if (point?.y === null || point?.y === undefined)
1151
+ return null;
1152
+ const cumulativeValue = (cumulativeValuesByKey.get(value.key) ?? 0) + point.y;
1153
+ cumulativeValuesByKey.set(value.key, cumulativeValue);
1154
+ return cumulativeValue;
1155
+ }));
1156
+ })() : undefined;
1157
+ const stackedRenderSelections = stackedBoundaryLayers ? decimationIndicesForLayers(stackedBoundaryLayers) : undefined;
1158
+ const renderedSeries = normalizedSeries.map((item) => {
1159
+ const hidden = hiddenSeriesIds.includes(item.id);
1160
+ const points = item.points.slice().sort((a, b) => (orderByKey.get(a.x.key) ?? 0) - (orderByKey.get(b.x.key) ?? 0));
1161
+ const placedPoints = points.map((point) => {
1162
+ const lowerValue = stackedArea ? stackedOffsetsByKey.get(point.x.key) ?? 0 : 0;
1163
+ const upperValue = lowerValue + (point.y ?? 0);
1164
+ return {
1165
+ ...point,
1166
+ pixelX: scaleX(point.x),
1167
+ pixelY: yScale(stackedArea ? upperValue : point.y ?? 0),
1168
+ pixelY0: yScale(stackedArea ? lowerValue : 0)
1169
+ };
1170
+ });
1171
+ const placedPointsByKey = stackedRenderSelections ? new Map(placedPoints.map((point) => [point.x.key, point])) : undefined;
1172
+ const renderPoints = stackedRenderSelections ? stackedRenderSelections.map(({ sourceIndex, forceGapLayerIndices }) => {
1173
+ const x = stackedRenderDomain[sourceIndex];
1174
+ const layerIndex = stackedLayerIndexBySeriesId.get(item.id);
1175
+ const forceGap = layerIndex !== undefined && forceGapLayerIndices.includes(layerIndex);
1176
+ if (!forceGap) {
1177
+ const placedPoint = placedPointsByKey?.get(x.key);
1178
+ if (placedPoint)
1179
+ return placedPoint;
1180
+ }
1181
+ return {
1182
+ seriesId: item.id,
1183
+ seriesLabel: item.label,
1184
+ color: item.color,
1185
+ x,
1186
+ y: null,
1187
+ originalY: null,
1188
+ index: -1,
1189
+ pixelX: scaleX(x),
1190
+ pixelY: 0,
1191
+ pixelY0: stackedArea ? yScale(stackedOffsetsByKey.get(x.key) ?? 0) : yScale(0)
1192
+ };
1193
+ }) : decimatePlacedPoints(placedPoints);
1194
+ const coordinates = renderPoints.map((placed) => ({
1195
+ x: placed.pixelX,
1196
+ y: placed.y === null ? null : placed.pixelY,
1197
+ y0: placed.pixelY0
1198
+ }));
1199
+ if (!hidden) {
1200
+ for (const placed of placedPoints) {
1201
+ if (placed.y === null)
1202
+ continue;
1203
+ const xLabel = formatXValue(placed.x, xAxis, {
1204
+ seriesId: item.id,
1205
+ seriesLabel: item.label,
1206
+ index: placed.index
1207
+ });
1208
+ const valueLabel = formatNumericValue(placed.y ?? 0, yAxis, series.find((entry) => entry.id === item.id)?.valueFormatter, { seriesId: item.id, seriesLabel: item.label, index: placed.index });
1209
+ targets.push({
1210
+ id: `${item.id}-${placed.x.key}`,
1211
+ seriesId: item.id,
1212
+ seriesLabel: item.label,
1213
+ xLabel,
1214
+ valueLabel,
1215
+ x: placed.pixelX,
1216
+ y: placed.pixelY,
1217
+ color: item.color
1218
+ });
1219
+ tableRows.push({
1220
+ id: `${item.id}-${placed.x.key}`,
1221
+ seriesId: item.id,
1222
+ seriesLabel: item.label,
1223
+ xLabel,
1224
+ valueLabel
1225
+ });
1226
+ }
1227
+ if (stackedArea) {
1228
+ for (const placed of placedPoints) {
1229
+ stackedOffsetsByKey.set(placed.x.key, (stackedOffsetsByKey.get(placed.x.key) ?? 0) + (placed.y ?? 0));
1230
+ }
1231
+ }
1232
+ }
1233
+ return {
1234
+ ...item,
1235
+ hidden,
1236
+ points: hidden ? [] : renderPoints,
1237
+ path: hidden ? "" : createLinePath(coordinates),
1238
+ areaPath: hidden ? "" : createAreaPath(coordinates, stackedArea ? undefined : geometry.plotHeight)
1239
+ };
1240
+ });
1241
+ targets.sort((a, b) => a.x - b.x);
601
1242
  return {
602
- marginLeft,
603
- labels: labels.map((label) => truncateHorizontalCategoryLabel(label, availableLabelWidth))
1243
+ geometry,
1244
+ xTicks,
1245
+ yTicks,
1246
+ normalizedSeries: renderedSeries,
1247
+ tableRows: evenlySampleTableRows(tableRows, MAXIMUM_RENDERED_SERIES_POINTS),
1248
+ targets,
1249
+ empty: targets.length === 0,
1250
+ yDomain: [yMinimum, yMaximum],
1251
+ theme: resolvedTheme,
1252
+ marks: series.map((item) => ({
1253
+ seriesId: item.id,
1254
+ descriptors: componentId === "line-chart" ? [
1255
+ { type: "line", data: item.data },
1256
+ { type: "point", data: item.data }
1257
+ ] : [
1258
+ { type: "area", data: item.data },
1259
+ { type: "line", data: item.data }
1260
+ ]
1261
+ }))
604
1262
  };
605
1263
  }
606
- function estimateHorizontalCategoryLabelWidth(label) {
607
- return Array.from(label).length * HORIZONTAL_CATEGORY_LABEL_CHARACTER_WIDTH;
608
- }
609
- function truncateHorizontalCategoryLabel(label, availableWidth) {
610
- if (estimateHorizontalCategoryLabelWidth(label) <= availableWidth)
611
- return label;
612
- const availableCharacterCount = Math.floor(availableWidth / HORIZONTAL_CATEGORY_LABEL_CHARACTER_WIDTH);
613
- if (availableCharacterCount <= 0)
614
- return "";
615
- if (availableCharacterCount === 1)
616
- return "…";
617
- return `${Array.from(label).slice(0, availableCharacterCount - 1).join("")}…`;
618
- }
619
- function normalizeNumericValue(componentId, seriesId, xLabel, value) {
620
- if (value === null || value === undefined)
621
- return null;
622
- if (!Number.isFinite(value)) {
623
- throw new Error(`[cinder/${componentId}] rule=non-finite-y series="${seriesId}" x="${xLabel}": y values must be finite numbers.`);
1264
+ function evenlySampleTableRows(rows, maximumRows) {
1265
+ if (rows.length <= maximumRows)
1266
+ return rows;
1267
+ if (maximumRows <= 0)
1268
+ return [];
1269
+ const rowsBySeriesId = new Map;
1270
+ for (const row of rows) {
1271
+ const seriesRows = rowsBySeriesId.get(row.seriesId);
1272
+ if (seriesRows)
1273
+ seriesRows.push(row);
1274
+ else
1275
+ rowsBySeriesId.set(row.seriesId, [row]);
624
1276
  }
625
- return value;
626
- }
627
- function sortXValues(values) {
628
- if (values[0]?.kind === "string")
629
- return values;
630
- return [...values].toSorted((a, b) => Number(a.comparable) - Number(b.comparable));
631
- }
632
- function createPaddedDomain(values) {
633
- if (values.length === 0)
634
- return [-1, 1];
635
- let minimum = values[0];
636
- let maximum = values[0];
637
- for (let index = 1;index < values.length; index++) {
638
- const value = values[index];
639
- if (value < minimum)
640
- minimum = value;
641
- if (value > maximum)
642
- maximum = value;
1277
+ const seriesGroups = [...rowsBySeriesId.values()];
1278
+ if (seriesGroups.length >= maximumRows) {
1279
+ return seriesGroups.slice(0, maximumRows).map((group) => group[0]);
643
1280
  }
644
- if (minimum === maximum)
645
- return [minimum - 1, maximum + 1];
646
- return [Math.min(0, minimum), Math.max(0, maximum)];
647
- }
648
- function createLinearScale(domain, range) {
649
- const [domainMinimum, domainMaximum] = domain[0] === domain[1] ? [domain[0] - 1, domain[1] + 1] : domain;
650
- const [rangeMinimum, rangeMaximum] = range;
651
- const domainSpan = domainMaximum - domainMinimum;
652
- const rangeSpan = rangeMaximum - rangeMinimum;
653
- const scale = Object.assign((value) => rangeMinimum + (value - domainMinimum) / domainSpan * rangeSpan, {
654
- ticks: (count) => createTicks([domainMinimum, domainMaximum], count)
655
- });
656
- return scale;
657
- }
658
- function createPointScale(domain, range, padding) {
659
- const positions = new Map;
660
- const [rangeMinimum, rangeMaximum] = range;
661
- if (domain.length === 1) {
662
- positions.set(domain[0] ?? "", rangeMinimum + (rangeMaximum - rangeMinimum) / 2);
663
- } else {
664
- const step = (rangeMaximum - rangeMinimum) / Math.max(1, domain.length - 1 + padding * 2);
665
- const start = rangeMinimum + step * padding;
666
- domain.forEach((value, index) => positions.set(value, start + step * index));
1281
+ const remainingRows = maximumRows - seriesGroups.length;
1282
+ const capacities = seriesGroups.map((group) => group.length - 1);
1283
+ const totalCapacity = capacities.reduce((total, capacity) => total + capacity, 0);
1284
+ const exactShares = capacities.map((capacity) => remainingRows * capacity / totalCapacity);
1285
+ const allocations = exactShares.map((share) => 1 + Math.floor(share));
1286
+ let undistributedRows = maximumRows - allocations.reduce((total, count) => total + count, 0);
1287
+ const allocationOrder = exactShares.map((share, index) => ({ index, remainder: share - Math.floor(share) })).sort((a, b) => b.remainder - a.remainder || a.index - b.index);
1288
+ for (const { index } of allocationOrder) {
1289
+ if (undistributedRows === 0)
1290
+ break;
1291
+ if (allocations[index] >= seriesGroups[index].length)
1292
+ continue;
1293
+ allocations[index] += 1;
1294
+ undistributedRows -= 1;
667
1295
  }
668
- return (value) => positions.get(value);
1296
+ return seriesGroups.flatMap((group, index) => evenlySampleRows(group, allocations[index]));
669
1297
  }
670
- function createBandScale(domain, range, padding) {
671
- const positions = new Map;
672
- const [rangeMinimum, rangeMaximum] = range;
673
- const availableSize = Math.max(0, rangeMaximum - rangeMinimum);
674
- const step = domain.length === 0 ? 0 : availableSize / Math.max(1, domain.length + padding * (domain.length - 1));
675
- const bandWidth = Math.max(0, step * (1 - padding));
676
- domain.forEach((value, index) => positions.set(value, rangeMinimum + step * index));
677
- const scale = Object.assign((value) => positions.get(value), {
678
- bandwidth: () => bandWidth
1298
+ function evenlySampleRows(rows, requestedRows) {
1299
+ if (rows.length <= requestedRows)
1300
+ return rows;
1301
+ if (requestedRows <= 1)
1302
+ return rows[0] === undefined ? [] : [rows[0]];
1303
+ return Array.from({ length: requestedRows }, (_, index) => {
1304
+ const sourceIndex = Math.round(index * (rows.length - 1) / (requestedRows - 1));
1305
+ return rows[sourceIndex];
679
1306
  });
680
- return scale;
681
1307
  }
682
- function createNumericDomain(values) {
683
- if (values.length === 0)
684
- return [0, 1];
685
- let minimum = Number(values[0].comparable);
686
- let maximum = minimum;
687
- for (let index = 1;index < values.length; index++) {
688
- const numeric = Number(values[index].comparable);
689
- if (numeric < minimum)
690
- minimum = numeric;
691
- if (numeric > maximum)
692
- maximum = numeric;
1308
+ function buildXAxisTicks(sortedXValues, tickCount, xAxis, scaleX) {
1309
+ if (sortedXValues.length === 0)
1310
+ return [];
1311
+ const safeTickCount = Math.max(1, Math.min(tickCount, sortedXValues.length));
1312
+ if (safeTickCount >= sortedXValues.length) {
1313
+ return sortedXValues.map((value, index) => ({
1314
+ label: formatXValue(value, xAxis, { index }),
1315
+ x: scaleX(value)
1316
+ }));
693
1317
  }
694
- return minimum === maximum ? [minimum - 1, maximum + 1] : [minimum, maximum];
695
- }
696
- function createTicks(domain, count) {
697
- const safeCount = Math.max(1, Math.floor(count));
698
- if (safeCount === 1)
699
- return [domain[0]];
700
- const step = (domain[1] - domain[0]) / (safeCount - 1);
701
- return Array.from({ length: safeCount }, (_, index) => domain[0] + step * index);
702
- }
703
- function createLinePath(points) {
704
- if (points.length === 0)
705
- return "";
706
- const [firstPoint, ...remainingPoints] = points;
707
- return [
708
- `M${formatPathNumber(firstPoint?.x ?? 0)},${formatPathNumber(firstPoint?.y ?? 0)}`,
709
- ...remainingPoints.map((point) => `L${formatPathNumber(point.x)},${formatPathNumber(point.y)}`)
710
- ].join("");
711
- }
712
- function createAreaPath(points, baseline) {
713
- if (points.length === 0)
714
- return "";
715
- const firstPoint = points[0];
716
- const lastPoint = points.at(-1);
717
- if (!firstPoint || !lastPoint)
718
- return "";
719
- const lowerPoints = points.toReversed().map((point) => `L${formatPathNumber(point.x)},${formatPathNumber(point.y0 ?? baseline ?? 0)}`);
720
- return [
721
- `M${formatPathNumber(firstPoint.x)},${formatPathNumber(firstPoint.y0 ?? baseline ?? 0)}`,
722
- `L${formatPathNumber(firstPoint.x)},${formatPathNumber(firstPoint.y)}`,
723
- ...points.slice(1).map((point) => `L${formatPathNumber(point.x)},${formatPathNumber(point.y)}`),
724
- ...lowerPoints,
725
- "Z"
726
- ].join("");
727
- }
728
- function createStackedBarDomainValues(datumByKey, categories, series) {
729
- const values = [0];
730
- for (const category of categories) {
731
- const datum = datumByKey.get(category.key);
732
- if (!datum)
1318
+ if (safeTickCount === 1) {
1319
+ const value = sortedXValues[0];
1320
+ return value ? [{ label: formatXValue(value, xAxis, { index: 0 }), x: scaleX(value) }] : [];
1321
+ }
1322
+ const step = (sortedXValues.length - 1) / (safeTickCount - 1);
1323
+ const ticks = [];
1324
+ for (let i = 0;i < safeTickCount; i++) {
1325
+ const sourceIndex = Math.round(i * step);
1326
+ const value = sortedXValues[sourceIndex];
1327
+ if (!value)
733
1328
  continue;
734
- let positiveTotal = 0;
735
- let negativeTotal = 0;
736
- for (const item of series) {
737
- const value = datum[item.valueKey];
738
- if (typeof value !== "number")
739
- continue;
740
- if (value >= 0)
741
- positiveTotal += value;
742
- else
743
- negativeTotal += value;
744
- }
745
- values.push(positiveTotal, negativeTotal);
1329
+ ticks.push({
1330
+ label: formatXValue(value, xAxis, { index: sourceIndex }),
1331
+ x: scaleX(value)
1332
+ });
746
1333
  }
747
- return values;
748
- }
749
- function formatPathNumber(value) {
750
- return Number(value.toFixed(3)).toString();
1334
+ return ticks;
751
1335
  }
752
-
753
1336
  // src/utilities/class-names.ts
754
1337
  function classNames(...parts) {
755
1338
  return parts.filter((part) => typeof part === "string" && part.length > 0).join(" ");
@@ -805,6 +1388,7 @@ var rest_excludes = new Set([
805
1388
  "loading",
806
1389
  "dataTableVisibility",
807
1390
  "dataTableCaption",
1391
+ "theme",
808
1392
  "class",
809
1393
  "empty",
810
1394
  "loadingContent",
@@ -825,6 +1409,7 @@ function Waveform($$anchor, $$props) {
825
1409
  let renderMode = $2.prop($$props, "renderMode", 3, "path"), height = $2.prop($$props, "height", 3, 80), loading = $2.prop($$props, "loading", 3, false), dataTableVisibility = $2.prop($$props, "dataTableVisibility", 3, "screen-reader-only"), rest = $2.rest_props($$props, rest_excludes);
826
1410
  const rootId = $2.derived(() => $$props.id ?? generatedId);
827
1411
  const descriptionId = $2.derived(() => $$props.description ? `${$2.get(rootId)}-description` : undefined);
1412
+ const resolvedTheme = $2.derived(() => resolveChartTheme($$props.theme));
828
1413
  let measuredWidth = $2.state(400);
829
1414
  const observeResize = useResizeObserver((entries) => {
830
1415
  const entry = entries[0];
@@ -924,14 +1509,24 @@ function Waveform($$anchor, $$props) {
924
1509
  return `${base} (${$2.get(tableSamples).length} of ${$$props.data.length} samples shown)`;
925
1510
  });
926
1511
  var figure = root_8();
927
- $2.attribute_effect(figure, ($0) => ({
1512
+ $2.attribute_effect(figure, ($0, $1) => ({
928
1513
  ...rest,
929
1514
  id: $2.get(rootId),
930
1515
  class: $0,
931
1516
  "aria-label": $$props.label,
932
1517
  "aria-describedby": $2.get(descriptionId),
933
- "data-cinder-render-mode": renderMode()
934
- }), [() => classNames("cinder-waveform", $$props.class)]);
1518
+ "data-cinder-render-mode": renderMode(),
1519
+ [$2.STYLE]: $1
1520
+ }), [
1521
+ () => classNames("cinder-waveform", $$props.class),
1522
+ () => ({
1523
+ "--_cinder-chart-foreground": $2.get(resolvedTheme).foreground,
1524
+ "--_cinder-chart-muted": $2.get(resolvedTheme).muted,
1525
+ "--_cinder-chart-grid": $2.get(resolvedTheme).grid,
1526
+ "--_cinder-chart-background": $2.get(resolvedTheme).background,
1527
+ "--_cinder-chart-series-color": chartPaletteColor(0, $2.get(resolvedTheme).palette)
1528
+ })
1529
+ ]);
935
1530
  var node = $2.child(figure);
936
1531
  {
937
1532
  var consequent = ($$anchor2) => {
@@ -1038,19 +1633,23 @@ function Waveform($$anchor, $$props) {
1038
1633
  var node_9 = $2.first_child(fragment_3);
1039
1634
  $2.each(node_9, 17, () => $2.get(waveformBars), $2.index, ($$anchor4, bar) => {
1040
1635
  var rect = root_3();
1041
- $2.template_effect(() => {
1636
+ $2.template_effect(($0) => {
1042
1637
  $2.set_attribute(rect, "x", $2.get(bar).x);
1043
1638
  $2.set_attribute(rect, "y", $2.get(bar).y);
1044
1639
  $2.set_attribute(rect, "width", $2.get(bar).width);
1045
1640
  $2.set_attribute(rect, "height", $2.get(bar).height);
1046
- });
1641
+ $2.set_attribute(rect, "fill", $0);
1642
+ }, [() => chartPaletteColor(0, $2.get(resolvedTheme).palette)]);
1047
1643
  $2.append($$anchor4, rect);
1048
1644
  });
1049
1645
  $2.append($$anchor3, fragment_3);
1050
1646
  };
1051
1647
  var alternate_2 = ($$anchor3) => {
1052
1648
  var path = root_4();
1053
- $2.template_effect(() => $2.set_attribute(path, "d", $2.get(waveformPath)));
1649
+ $2.template_effect(($0) => {
1650
+ $2.set_attribute(path, "d", $2.get(waveformPath));
1651
+ $2.set_attribute(path, "stroke", $0);
1652
+ }, [() => chartPaletteColor(0, $2.get(resolvedTheme).palette)]);
1054
1653
  $2.append($$anchor3, path);
1055
1654
  };
1056
1655
  $2.if(node_8, ($$render) => {
@@ -1064,6 +1663,7 @@ function Waveform($$anchor, $$props) {
1064
1663
  $2.set_attribute(line, "x2", $2.get(measuredWidth));
1065
1664
  $2.set_attribute(line, "y1", $2.get(midY));
1066
1665
  $2.set_attribute(line, "y2", $2.get(midY));
1666
+ $2.set_attribute(line, "stroke", $2.get(resolvedTheme).grid);
1067
1667
  });
1068
1668
  $2.append($$anchor2, fragment_2);
1069
1669
  };
@@ -1130,4 +1730,4 @@ export {
1130
1730
  Waveform
1131
1731
  };
1132
1732
 
1133
- //# debugId=455821F1039F824964756E2164756E21
1733
+ //# debugId=C5519EF9672F43FD64756E2164756E21