@opendata-ai/openchart-engine 7.11.0 → 8.0.0-rc.10

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 (160) hide show
  1. package/dist/index.d.ts +124 -14
  2. package/dist/index.js +16254 -9417
  3. package/dist/index.js.map +1 -1
  4. package/package.json +11 -4
  5. package/src/__tests__/__snapshots__/compile-snapshot.test.ts.snap +232 -56
  6. package/src/__tests__/annotation-behavior.test.ts +852 -0
  7. package/src/__tests__/axes.test.ts +50 -3
  8. package/src/__tests__/compile-chart.test.ts +30 -0
  9. package/src/__tests__/compile-footnotes.test.ts +277 -0
  10. package/src/__tests__/compile-layer.test.ts +120 -1
  11. package/src/__tests__/facet.test.ts +144 -0
  12. package/src/__tests__/helpers/invariants.ts +54 -20
  13. package/src/__tests__/known-bugs.test.ts +455 -2
  14. package/src/__tests__/legend.test.ts +69 -4
  15. package/src/__tests__/ranking-recipes.test.ts +260 -0
  16. package/src/__tests__/scales.test.ts +9 -3
  17. package/src/__tests__/series-search.test.ts +92 -0
  18. package/src/__tests__/spec-sugar.test.ts +801 -0
  19. package/src/__tests__/you-draw-it.test.ts +160 -0
  20. package/src/annotations/__tests__/compute.test.ts +207 -92
  21. package/src/annotations/__tests__/geometry.test.ts +66 -0
  22. package/src/annotations/__tests__/resolve-text.test.ts +527 -27
  23. package/src/annotations/__tests__/rich-text.test.ts +91 -0
  24. package/src/annotations/__tests__/thinning.test.ts +148 -0
  25. package/src/annotations/collisions.ts +130 -84
  26. package/src/annotations/compute.ts +83 -85
  27. package/src/annotations/constants.ts +116 -6
  28. package/src/annotations/geometry.ts +228 -77
  29. package/src/annotations/move.ts +135 -0
  30. package/src/annotations/placement.ts +62 -14
  31. package/src/annotations/resolve-range.ts +2 -0
  32. package/src/annotations/resolve-refline.ts +2 -0
  33. package/src/annotations/resolve-text.ts +318 -111
  34. package/src/annotations/rich-text.ts +65 -0
  35. package/src/annotations/thinning.ts +84 -10
  36. package/src/barlist/compile-barlist.ts +16 -6
  37. package/src/charts/_shared/format-label-value.ts +9 -8
  38. package/src/charts/bar/__tests__/compute.test.ts +57 -10
  39. package/src/charts/bar/__tests__/labels.test.ts +5 -4
  40. package/src/charts/bar/compute.ts +2 -6
  41. package/src/charts/bar/index.ts +8 -1
  42. package/src/charts/bar/labels.ts +3 -3
  43. package/src/charts/beeswarm/__tests__/compute.test.ts +280 -0
  44. package/src/charts/beeswarm/__tests__/dodge.test.ts +148 -0
  45. package/src/charts/beeswarm/compute.ts +203 -0
  46. package/src/charts/beeswarm/dodge.ts +155 -0
  47. package/src/charts/beeswarm/index.ts +32 -0
  48. package/src/charts/builtin.ts +12 -1
  49. package/src/charts/calendar/__tests__/compute.test.ts +417 -0
  50. package/src/charts/calendar/compute.ts +319 -0
  51. package/src/charts/calendar/index.ts +32 -0
  52. package/src/charts/column/__tests__/compute.test.ts +21 -7
  53. package/src/charts/column/__tests__/labels.test.ts +76 -1
  54. package/src/charts/column/compute.ts +2 -6
  55. package/src/charts/column/index.ts +10 -2
  56. package/src/charts/column/labels.ts +95 -21
  57. package/src/charts/dot/index.ts +8 -1
  58. package/src/charts/dot/labels.ts +3 -3
  59. package/src/charts/line/__tests__/compute.test.ts +15 -19
  60. package/src/charts/line/area.ts +8 -23
  61. package/src/charts/line/compute.ts +32 -2
  62. package/src/charts/parliament/__tests__/compute.test.ts +411 -0
  63. package/src/charts/parliament/compute.ts +313 -0
  64. package/src/charts/parliament/index.ts +32 -0
  65. package/src/charts/pie/__tests__/compute.test.ts +103 -0
  66. package/src/charts/pie/compute.ts +63 -8
  67. package/src/charts/pie/labels.ts +1 -0
  68. package/src/charts/range/__tests__/compute.test.ts +486 -0
  69. package/src/charts/range/compute.ts +273 -0
  70. package/src/charts/range/index.ts +82 -0
  71. package/src/charts/range/labels.ts +169 -0
  72. package/src/charts/rect/__tests__/compute.test.ts +120 -0
  73. package/src/charts/rect/index.ts +127 -0
  74. package/src/charts/scatter/compute.ts +7 -21
  75. package/src/charts/text/__tests__/compute.test.ts +307 -0
  76. package/src/charts/text/index.ts +44 -7
  77. package/src/charts/tick/__tests__/compute.test.ts +75 -0
  78. package/src/charts/tick/index.ts +7 -4
  79. package/src/charts/utils.ts +5 -3
  80. package/src/charts/waffle/__tests__/compute.test.ts +305 -0
  81. package/src/charts/waffle/compute.ts +197 -0
  82. package/src/charts/waffle/index.ts +31 -0
  83. package/src/compile/__tests__/color-scale-reverse.test.ts +89 -0
  84. package/src/compile/__tests__/data-clip.test.ts +68 -0
  85. package/src/compile/__tests__/fill-patterns.test.ts +154 -0
  86. package/src/compile/__tests__/size-scale.test.ts +108 -0
  87. package/src/compile/color-scale-range.ts +54 -33
  88. package/src/compile/data-clip.ts +21 -6
  89. package/src/compile/fill-patterns.ts +74 -0
  90. package/src/compile/layer.ts +121 -21
  91. package/src/compile/size-scale.ts +141 -0
  92. package/src/compile/spec-sugar.ts +767 -0
  93. package/src/compile/you-draw-it.ts +123 -0
  94. package/src/compile.ts +415 -110
  95. package/src/compiler/__tests__/a11y-warnings.test.ts +148 -0
  96. package/src/compiler/__tests__/fixtures/vl-parity/axis-null.json +19 -0
  97. package/src/compiler/__tests__/fixtures/vl-parity/color-value.json +20 -0
  98. package/src/compiler/__tests__/fixtures/vl-parity/count-aggregate.json +22 -0
  99. package/src/compiler/__tests__/fixtures/vl-parity/data-values.json +19 -0
  100. package/src/compiler/__tests__/fixtures/vl-parity/layer-axis-null.json +14 -0
  101. package/src/compiler/__tests__/fixtures/vl-parity/layer-count.json +34 -0
  102. package/src/compiler/__tests__/fixtures/vl-parity/layer-data-values.json +22 -0
  103. package/src/compiler/__tests__/fixtures/vl-parity/layer-legend-null.json +41 -0
  104. package/src/compiler/__tests__/fixtures/vl-parity/layer-scheme.json +38 -0
  105. package/src/compiler/__tests__/fixtures/vl-parity/layer-sort.json +28 -0
  106. package/src/compiler/__tests__/fixtures/vl-parity/layer-theta.json +28 -0
  107. package/src/compiler/__tests__/fixtures/vl-parity/layer-title.json +30 -0
  108. package/src/compiler/__tests__/fixtures/vl-parity/layer-value-def.json +29 -0
  109. package/src/compiler/__tests__/fixtures/vl-parity/legend-null.json +32 -0
  110. package/src/compiler/__tests__/fixtures/vl-parity/scheme.json +25 -0
  111. package/src/compiler/__tests__/fixtures/vl-parity/sort-by-value.json +19 -0
  112. package/src/compiler/__tests__/fixtures/vl-parity/theta-arc.json +19 -0
  113. package/src/compiler/__tests__/fixtures/vl-parity/title-subtitle.json +21 -0
  114. package/src/compiler/__tests__/fixtures/vl-parity/width-height.json +23 -0
  115. package/src/compiler/__tests__/keys.test.ts +3 -9
  116. package/src/compiler/__tests__/normalize.test.ts +65 -1
  117. package/src/compiler/__tests__/validate-did-you-mean.test.ts +170 -0
  118. package/src/compiler/__tests__/validate-near-miss.test.ts +251 -0
  119. package/src/compiler/__tests__/validate.test.ts +258 -0
  120. package/src/compiler/__tests__/vl-parity.test.ts +68 -0
  121. package/src/compiler/a11y-warnings.ts +110 -0
  122. package/src/compiler/keys.ts +5 -4
  123. package/src/compiler/normalize.ts +151 -7
  124. package/src/compiler/types.ts +11 -0
  125. package/src/compiler/validate.ts +961 -32
  126. package/src/endpoint-labels/__tests__/compute.test.ts +88 -0
  127. package/src/endpoint-labels/compute.ts +40 -12
  128. package/src/endpoint-labels/format.ts +45 -15
  129. package/src/endpoint-labels/predict.ts +50 -36
  130. package/src/format/__tests__/field-format.test.ts +164 -0
  131. package/src/format/field-format.ts +27 -0
  132. package/src/geo/__tests__/compile-map.test.ts +1128 -0
  133. package/src/geo/compile-map.ts +1376 -0
  134. package/src/geo/join.ts +115 -0
  135. package/src/geo/projections.ts +65 -0
  136. package/src/geo/types.ts +26 -0
  137. package/src/graphs/__tests__/compile-graph.test.ts +25 -0
  138. package/src/graphs/compile-graph.ts +27 -18
  139. package/src/index.ts +20 -2
  140. package/src/layout/axes/ticks.ts +59 -10
  141. package/src/layout/axes.ts +35 -6
  142. package/src/layout/dimensions.ts +139 -83
  143. package/src/layout/facet.ts +14 -3
  144. package/src/layout/plan.ts +83 -33
  145. package/src/layout/scales.ts +132 -15
  146. package/src/legend/__tests__/continuous.test.ts +318 -0
  147. package/src/legend/__tests__/size.test.ts +348 -0
  148. package/src/legend/__tests__/suppression.test.ts +17 -1
  149. package/src/legend/compute.ts +123 -16
  150. package/src/legend/continuous.ts +327 -0
  151. package/src/legend/size.ts +407 -0
  152. package/src/legend/suppression.ts +8 -7
  153. package/src/sankey/compile-sankey.ts +31 -19
  154. package/src/tables/format-cells.ts +16 -7
  155. package/src/tilemap/__tests__/compile-tilemap.test.ts +39 -0
  156. package/src/tilemap/compile-tilemap.ts +24 -7
  157. package/src/tooltips/__tests__/compute.test.ts +2 -2
  158. package/src/tooltips/compute.ts +422 -41
  159. package/src/transforms/__tests__/conditional.test.ts +18 -0
  160. package/src/transforms/aggregate.ts +2 -1
@@ -153,15 +153,17 @@ export function getColor(
153
153
 
154
154
  /**
155
155
  * Get color from a sequential (quantitative) color scale.
156
- * Maps a numeric value to a color via linear interpolation.
156
+ * Maps a numeric value to a color via linear interpolation, or to a discrete
157
+ * class color for binned (quantile/quantize/threshold) color scales.
157
158
  */
158
159
  export function getSequentialColor(
159
160
  scales: ResolvedScales,
160
161
  value: number,
161
162
  fallback: string = DEFAULT_COLOR,
162
163
  ): string | GradientDef {
163
- if (scales.color?.type === 'sequential') {
164
- const colorScale = scales.color.scale as unknown as (v: number) => string;
164
+ const type = scales.color?.type;
165
+ if (type === 'sequential' || type === 'quantile' || type === 'quantize' || type === 'threshold') {
166
+ const colorScale = scales.color!.scale as unknown as (v: number) => string;
165
167
  return colorScale(value);
166
168
  }
167
169
  return scales.defaultColor ?? fallback;
@@ -0,0 +1,305 @@
1
+ import type { LayoutStrategy, Rect, RectMark } from '@opendata-ai/openchart-core';
2
+ import { describe, expect, it } from 'vitest';
3
+
4
+ import { compileChart } from '../../../compile';
5
+ import type { NormalizedChartSpec } from '../../../compiler/types';
6
+ import { computeScales } from '../../../layout/scales';
7
+ import { computeWaffleMarks, largestRemainderCells } from '../compute';
8
+
9
+ // ---------------------------------------------------------------------------
10
+ // Shared fixtures
11
+ // ---------------------------------------------------------------------------
12
+
13
+ const chartArea: Rect = { x: 40, y: 20, width: 400, height: 400 };
14
+
15
+ const fullStrategy: LayoutStrategy = {
16
+ labelMode: 'all',
17
+ legendPosition: 'right',
18
+ annotationPosition: 'inline',
19
+ axisLabelDensity: 'full',
20
+ };
21
+
22
+ const energyMix = [
23
+ { source: 'Fossil', share: 60 },
24
+ { source: 'Renewables', share: 30 },
25
+ { source: 'Nuclear', share: 10 },
26
+ ];
27
+
28
+ function makeWaffleSpec(overrides: Partial<NormalizedChartSpec> = {}): NormalizedChartSpec {
29
+ return {
30
+ markType: 'waffle',
31
+ markDef: { type: 'waffle' },
32
+ data: [...energyMix],
33
+ encoding: {
34
+ y: { field: 'share', type: 'quantitative' },
35
+ color: { field: 'source', type: 'nominal' },
36
+ },
37
+ chrome: {},
38
+ annotations: [],
39
+ responsive: true,
40
+ theme: {},
41
+ darkMode: 'off',
42
+ labels: { density: 'auto', format: '' },
43
+ ...overrides,
44
+ } as NormalizedChartSpec;
45
+ }
46
+
47
+ function marksFor(spec: NormalizedChartSpec): RectMark[] {
48
+ const scales = computeScales(spec, chartArea, spec.data);
49
+ return computeWaffleMarks(spec, scales, chartArea, fullStrategy);
50
+ }
51
+
52
+ /** Deterministic LCG so the property test carries no runtime randomness. */
53
+ function lcg(seed: number): () => number {
54
+ let s = seed >>> 0;
55
+ return () => {
56
+ s = (s * 1664525 + 1013904223) >>> 0;
57
+ return s / 2 ** 32;
58
+ };
59
+ }
60
+
61
+ // ---------------------------------------------------------------------------
62
+ // largestRemainderCells
63
+ // ---------------------------------------------------------------------------
64
+
65
+ describe('largestRemainderCells', () => {
66
+ it('sums exactly to units', () => {
67
+ expect(largestRemainderCells([60, 30, 10], 100).reduce((a, b) => a + b, 0)).toBe(100);
68
+ expect(largestRemainderCells([1, 1, 1], 100).reduce((a, b) => a + b, 0)).toBe(100);
69
+ expect(largestRemainderCells([7, 13, 3], 40).reduce((a, b) => a + b, 0)).toBe(40);
70
+ });
71
+
72
+ it('rounds a 0.4-cell category by largest remainder while the total stays exact', () => {
73
+ // Quotas 33.2 / 33.2 / 33.2 / 0.4: the 0.4 remainder is the largest, so
74
+ // the small category wins the single leftover cell.
75
+ expect(largestRemainderCells([33.2, 33.2, 33.2, 0.4], 100)).toEqual([33, 33, 33, 1]);
76
+
77
+ // Quotas 49.8 / 49.8 / 0.4: both 0.8 remainders beat 0.4, so the small
78
+ // category legitimately rounds to 0 cells (no minimum-1-cell rule).
79
+ expect(largestRemainderCells([49.8, 49.8, 0.4], 100)).toEqual([50, 50, 0]);
80
+ });
81
+
82
+ it('breaks equal remainders by larger raw value, then stable input index', () => {
83
+ // Quotas 1.5 / 2.5 / 3.5 / 2.5 (all remainders 0.5), two leftover cells:
84
+ // the largest raw value (35) wins first, then the 25s tie and the earlier
85
+ // input index (1) wins over index 3.
86
+ expect(largestRemainderCells([15, 25, 35, 25], 10)).toEqual([1, 3, 4, 2]);
87
+
88
+ // Fully symmetric tie: value tiebreak is moot, index order decides.
89
+ expect(largestRemainderCells([25, 25, 25, 25], 10)).toEqual([3, 3, 2, 2]);
90
+ });
91
+
92
+ it('allocates 0 cells to non-finite and negative values', () => {
93
+ expect(largestRemainderCells([Number.NaN, 50, -10, 50], 10)).toEqual([0, 5, 0, 5]);
94
+ });
95
+
96
+ it('returns all zeros when there is nothing to allocate', () => {
97
+ expect(largestRemainderCells([0, 0], 100)).toEqual([0, 0]);
98
+ expect(largestRemainderCells([], 100)).toEqual([]);
99
+ });
100
+ });
101
+
102
+ // ---------------------------------------------------------------------------
103
+ // computeWaffleMarks geometry
104
+ // ---------------------------------------------------------------------------
105
+
106
+ describe('computeWaffleMarks', () => {
107
+ it('emits square cells with a gap of cell/6', () => {
108
+ const marks = marksFor(makeWaffleSpec());
109
+ expect(marks).toHaveLength(100);
110
+
111
+ const first = marks[0];
112
+ expect(first.width).toBeCloseTo(first.height);
113
+
114
+ // Neighbor in the same row sits one cell + gap to the right.
115
+ const second = marks[1];
116
+ expect(second.y).toBe(first.y);
117
+ expect(second.x - (first.x + first.width)).toBeCloseTo(first.width / 6);
118
+ });
119
+
120
+ it('fills bottom-left to top-right by rows', () => {
121
+ const marks = marksFor(makeWaffleSpec());
122
+
123
+ // First cell is the leftmost column; the first 10 cells share the bottom row.
124
+ const xs = marks.map((m) => m.x);
125
+ const ys = marks.map((m) => m.y);
126
+ expect(marks[0].x).toBe(Math.min(...xs));
127
+ expect(marks[0].y).toBe(Math.max(...ys));
128
+ for (let i = 1; i < 10; i++) {
129
+ expect(marks[i].y).toBe(marks[0].y);
130
+ expect(marks[i].x).toBeGreaterThan(marks[i - 1].x);
131
+ }
132
+ // Cell 10 wraps to the next row up.
133
+ expect(marks[10].x).toBe(marks[0].x);
134
+ expect(marks[10].y).toBeLessThan(marks[0].y);
135
+ // Last cell tops out the grid.
136
+ expect(marks[99].y).toBe(Math.min(...ys));
137
+ });
138
+
139
+ it('centers the grid in the chart area', () => {
140
+ const marks = marksFor(makeWaffleSpec());
141
+ const minX = Math.min(...marks.map((m) => m.x));
142
+ const maxX = Math.max(...marks.map((m) => m.x + m.width));
143
+ const minY = Math.min(...marks.map((m) => m.y));
144
+ const maxY = Math.max(...marks.map((m) => m.y + m.height));
145
+
146
+ expect(minX - chartArea.x).toBeCloseTo(chartArea.x + chartArea.width - maxX);
147
+ expect(minY - chartArea.y).toBeCloseTo(chartArea.y + chartArea.height - maxY);
148
+ });
149
+
150
+ it('assigns category cells contiguously in data order with stable keys', () => {
151
+ const marks = marksFor(makeWaffleSpec());
152
+
153
+ const bySource = (s: string) =>
154
+ marks.filter((m) => (m.data as { source: string }).source === s);
155
+ expect(bySource('Fossil')).toHaveLength(60);
156
+ expect(bySource('Renewables')).toHaveLength(30);
157
+ expect(bySource('Nuclear')).toHaveLength(10);
158
+
159
+ expect(marks[0].key).toBe('Fossil|0');
160
+ expect(marks[59].key).toBe('Fossil|59');
161
+ expect(marks[60].key).toBe('Renewables|0');
162
+ expect(marks[99].key).toBe('Nuclear|9');
163
+ });
164
+
165
+ it('respects units and columns mark options', () => {
166
+ const spec = makeWaffleSpec({
167
+ markDef: { type: 'waffle', units: 40, columns: 8 },
168
+ });
169
+ const marks = marksFor(spec);
170
+ expect(marks).toHaveLength(40);
171
+
172
+ // 8 columns x 5 rows: cells 0-7 share the bottom row, cell 8 wraps.
173
+ expect(marks[7].y).toBe(marks[0].y);
174
+ expect(marks[8].x).toBe(marks[0].x);
175
+ expect(marks[8].y).toBeLessThan(marks[0].y);
176
+ });
177
+
178
+ it('labels the first cell of each category "x of N units" and marks the rest decorative', () => {
179
+ const marks = marksFor(makeWaffleSpec());
180
+
181
+ expect(marks[0].aria.label).toBe('Fossil: 60 of 100 units (60%)');
182
+ expect(marks[0].aria.decorative).toBeUndefined();
183
+ expect(marks[1].aria.label).toBe('Fossil: 60 of 100 units (60%)');
184
+ expect(marks[1].aria.decorative).toBe(true);
185
+ expect(marks[60].aria.label).toBe('Renewables: 30 of 100 units (30%)');
186
+ expect(marks[60].aria.decorative).toBeUndefined();
187
+ });
188
+
189
+ it('defaults cornerRadius to 1 and honors a mark-level override', () => {
190
+ expect(marksFor(makeWaffleSpec())[0].cornerRadius).toBe(1);
191
+
192
+ const spec = makeWaffleSpec({ markDef: { type: 'waffle', cornerRadius: 3 } });
193
+ expect(marksFor(spec)[0].cornerRadius).toBe(3);
194
+ });
195
+ });
196
+
197
+ // ---------------------------------------------------------------------------
198
+ // compileChart integration (spec in, layout out)
199
+ // ---------------------------------------------------------------------------
200
+
201
+ describe('compileChart with waffle marks', () => {
202
+ const baseSpec = {
203
+ mark: 'waffle' as const,
204
+ data: [...energyMix],
205
+ encoding: {
206
+ theta: { field: 'share', type: 'quantitative' as const },
207
+ color: { field: 'source', type: 'nominal' as const },
208
+ },
209
+ };
210
+
211
+ it('renders exactly units cells for random distributions summing to 100% (property test)', () => {
212
+ const rand = lcg(20260711);
213
+
214
+ for (let trial = 0; trial < 25; trial++) {
215
+ const categoryCount = 2 + Math.floor(rand() * 7);
216
+ const raw = Array.from({ length: categoryCount }, () => 0.01 + rand());
217
+ const total = raw.reduce((a, b) => a + b, 0);
218
+ const data = raw.map((v, i) => ({ category: `C${i}`, share: (v / total) * 100 }));
219
+
220
+ const layout = compileChart(
221
+ {
222
+ mark: 'waffle',
223
+ data,
224
+ encoding: {
225
+ theta: { field: 'share', type: 'quantitative' },
226
+ color: { field: 'category', type: 'nominal' },
227
+ },
228
+ },
229
+ { width: 600, height: 400 },
230
+ );
231
+
232
+ const cells = layout.marks.filter((m) => m.type === 'rect');
233
+ expect(cells).toHaveLength(100);
234
+ }
235
+ });
236
+
237
+ it('accepts theta as the value channel and compiles without axes or gridlines', () => {
238
+ const layout = compileChart(baseSpec, { width: 600, height: 400 });
239
+
240
+ expect(layout.marks.filter((m) => m.type === 'rect')).toHaveLength(100);
241
+ expect(layout.axes.x).toBeUndefined();
242
+ expect(layout.axes.y).toBeUndefined();
243
+ });
244
+
245
+ it('shares one tooltip object across every cell of a category', () => {
246
+ const layout = compileChart(baseSpec, { width: 600, height: 400 });
247
+
248
+ const rects = layout.marks
249
+ .map((m, i) => ({ mark: m as RectMark, id: `rect-${i}` }))
250
+ .filter(({ mark }) => mark.type === 'rect');
251
+
252
+ const fossilIds = rects
253
+ .filter(({ mark }) => (mark.data as { source: string }).source === 'Fossil')
254
+ .map(({ id }) => id);
255
+ const nuclearIds = rects
256
+ .filter(({ mark }) => (mark.data as { source: string }).source === 'Nuclear')
257
+ .map(({ id }) => id);
258
+ expect(fossilIds).toHaveLength(60);
259
+
260
+ const fossilTooltip = layout.tooltipDescriptors.get(fossilIds[0]);
261
+ expect(fossilTooltip).toBeDefined();
262
+ // Literally the same object for all cells: one hover target per category.
263
+ for (const id of fossilIds) {
264
+ expect(layout.tooltipDescriptors.get(id)).toBe(fossilTooltip);
265
+ }
266
+ expect(layout.tooltipDescriptors.get(nuclearIds[0])).not.toBe(fossilTooltip);
267
+
268
+ expect(fossilTooltip!.title).toBe('Fossil');
269
+ const share = fossilTooltip!.fields.find((f) => f.label === 'Share');
270
+ expect(share?.value).toBe('60 of 100 units');
271
+ });
272
+
273
+ it('lists a category in the legend even when it rounds to 0 cells', () => {
274
+ const layout = compileChart(
275
+ {
276
+ mark: 'waffle',
277
+ data: [
278
+ { source: 'A', share: 49.8 },
279
+ { source: 'B', share: 49.8 },
280
+ { source: 'C', share: 0.4 },
281
+ ],
282
+ encoding: {
283
+ theta: { field: 'share', type: 'quantitative' },
284
+ color: { field: 'source', type: 'nominal' },
285
+ },
286
+ },
287
+ { width: 600, height: 400 },
288
+ );
289
+
290
+ const cells = layout.marks.filter((m): m is RectMark => m.type === 'rect');
291
+ expect(cells).toHaveLength(100);
292
+ expect(cells.some((m) => (m.data as { source: string }).source === 'C')).toBe(false);
293
+
294
+ expect(layout.legend.type).toBe('categorical');
295
+ const labels =
296
+ layout.legend.type === 'categorical' ? layout.legend.entries.map((e) => e.label) : [];
297
+ expect(labels).toContain('C');
298
+ });
299
+
300
+ it('generates alt text with the unit framing', () => {
301
+ const layout = compileChart(baseSpec, { width: 600, height: 400 });
302
+ expect(layout.a11y.altText).toContain('Waffle chart');
303
+ expect(layout.a11y.altText).toContain('dividing 100 units');
304
+ });
305
+ });
@@ -0,0 +1,197 @@
1
+ /**
2
+ * Waffle chart mark computation.
3
+ *
4
+ * A unit grid ("3 in 100 people") for part-to-whole counts. Category values
5
+ * aggregate by the nominal color field, normalize to `markDef.units` cells
6
+ * via largest-remainder rounding (cells always sum exactly to units), and
7
+ * fill the grid bottom-left to top-right by rows, matching how readers count.
8
+ *
9
+ * Geometry: square cells with a gap of cell/6, grid centered in the chart
10
+ * area. No positional scales are consumed; the value comes straight from the
11
+ * data (the `theta` channel aliases to `y` in the sugar pass, same as arc).
12
+ *
13
+ * Zero-cell categories are legitimate: a nonzero share can round to 0 cells
14
+ * and there is deliberately no minimum-1-cell rule (a floor would distort the
15
+ * other categories). The legend still lists the category because legend
16
+ * entries derive from data, not marks.
17
+ */
18
+
19
+ import type {
20
+ DataRow,
21
+ Encoding,
22
+ LayoutStrategy,
23
+ MarkAria,
24
+ Rect,
25
+ RectMark,
26
+ } from '@opendata-ai/openchart-core';
27
+ import { formatPercent } from '@opendata-ai/openchart-core';
28
+
29
+ import { serializeKeyValue } from '../../compiler/keys';
30
+ import type { NormalizedChartSpec } from '../../compiler/types';
31
+ import type { ResolvedScales } from '../../layout/scales';
32
+ import { getColor } from '../utils';
33
+
34
+ // ---------------------------------------------------------------------------
35
+ // Constants
36
+ // ---------------------------------------------------------------------------
37
+
38
+ /** Default total cell count (the "out of 100" framing). */
39
+ const DEFAULT_UNITS = 100;
40
+
41
+ /** Default column count (10x10 grid at the default units). */
42
+ const DEFAULT_COLUMNS = 10;
43
+
44
+ /** Default cell corner radius (px). Subtle rounding; cells stay data-crisp. */
45
+ const DEFAULT_CORNER_RADIUS = 1;
46
+
47
+ /** Gap between cells as a fraction of the cell size. */
48
+ const GAP_FRACTION = 1 / 6;
49
+
50
+ // ---------------------------------------------------------------------------
51
+ // Largest-remainder rounding
52
+ // ---------------------------------------------------------------------------
53
+
54
+ /**
55
+ * Allocate `units` integer cells across `values` proportionally using the
56
+ * largest-remainder method, so the result always sums exactly to `units`.
57
+ *
58
+ * Tiebreak is deterministic and never depends on map iteration order:
59
+ * equal remainders break by larger raw value, then by stable input index.
60
+ * Non-finite and negative values allocate 0 cells.
61
+ */
62
+ export function largestRemainderCells(values: number[], units: number): number[] {
63
+ const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0));
64
+ const total = clean.reduce((sum, v) => sum + v, 0);
65
+ const cells = new Array<number>(values.length).fill(0);
66
+ if (total <= 0 || units <= 0) return cells;
67
+
68
+ const quotas = clean.map((v) => (v / total) * units);
69
+ let allocated = 0;
70
+ for (let i = 0; i < quotas.length; i++) {
71
+ cells[i] = Math.floor(quotas[i]);
72
+ allocated += cells[i];
73
+ }
74
+
75
+ // Distribute the leftover cells to the largest remainders. Ties break by
76
+ // larger raw value, then smaller input index (stable and deterministic).
77
+ const order = quotas
78
+ .map((q, i) => ({ remainder: q - Math.floor(q), value: clean[i], index: i }))
79
+ .sort((a, b) => b.remainder - a.remainder || b.value - a.value || a.index - b.index);
80
+ for (let k = 0; k < units - allocated; k++) {
81
+ cells[order[k].index] += 1;
82
+ }
83
+
84
+ return cells;
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // Public API
89
+ // ---------------------------------------------------------------------------
90
+
91
+ /**
92
+ * Compute waffle cell marks from a normalized chart spec.
93
+ *
94
+ * Categories come from the color field (aggregated in data order, matching
95
+ * pie), the share value from the quantitative y channel (theta pre-aliased
96
+ * to y). Emits one RectMark per cell in fill order (bottom-left to top-right
97
+ * by rows), which also drives the entrance-stagger sweep.
98
+ */
99
+ export function computeWaffleMarks(
100
+ spec: NormalizedChartSpec,
101
+ scales: ResolvedScales,
102
+ chartArea: Rect,
103
+ _strategy: LayoutStrategy,
104
+ ): RectMark[] {
105
+ const encoding = spec.encoding as Encoding;
106
+
107
+ const valueChannel = encoding.y ?? encoding.x;
108
+ const colorField = encoding.color && 'field' in encoding.color ? encoding.color.field : undefined;
109
+ if (!valueChannel || !colorField) return [];
110
+
111
+ // Aggregate values by category, preserving data order (drives cell order,
112
+ // color assignment, and the legend, which derives the same order from data).
113
+ const categoryTotals = new Map<string, number>();
114
+ const categoryRows = new Map<string, DataRow>();
115
+ for (const row of spec.data) {
116
+ const cat = String(row[colorField] ?? '');
117
+ const val = Number(row[valueChannel.field] ?? 0);
118
+ if (!Number.isFinite(val) || val < 0) continue;
119
+
120
+ categoryTotals.set(cat, (categoryTotals.get(cat) ?? 0) + val);
121
+ if (!categoryRows.has(cat)) {
122
+ categoryRows.set(cat, row);
123
+ }
124
+ }
125
+
126
+ const categories = [...categoryTotals.keys()];
127
+ const values = categories.map((cat) => categoryTotals.get(cat)!);
128
+ const total = values.reduce((sum, v) => sum + v, 0);
129
+ if (categories.length === 0 || total <= 0) return [];
130
+
131
+ const units = Math.max(1, Math.round(spec.markDef.units ?? DEFAULT_UNITS));
132
+ const columns = Math.max(1, Math.round(spec.markDef.columns ?? DEFAULT_COLUMNS));
133
+ const rows = Math.ceil(units / columns);
134
+
135
+ const cellCounts = largestRemainderCells(values, units);
136
+
137
+ // Square cells with gap = cell/6: grid width = columns*cell + (columns-1)*gap.
138
+ // Solve for the cell size on both axes and take the smaller so the grid
139
+ // stays square and inside the chart area, then center it.
140
+ const cell = Math.min(
141
+ chartArea.width / (columns + (columns - 1) * GAP_FRACTION),
142
+ chartArea.height / (rows + (rows - 1) * GAP_FRACTION),
143
+ );
144
+ if (!(cell > 0)) return [];
145
+
146
+ const gap = cell * GAP_FRACTION;
147
+ const step = cell + gap;
148
+ const gridWidth = columns * cell + (columns - 1) * gap;
149
+ const gridHeight = rows * cell + (rows - 1) * gap;
150
+ const originX = chartArea.x + (chartArea.width - gridWidth) / 2;
151
+ // Top edge of the bottom row; rows fill upward from here.
152
+ const bottomRowY = chartArea.y + (chartArea.height - gridHeight) / 2 + gridHeight - cell;
153
+
154
+ const cornerRadius =
155
+ spec.markDef.cornerRadius === 'pill'
156
+ ? cell / 2
157
+ : (spec.markDef.cornerRadius ?? DEFAULT_CORNER_RADIUS);
158
+
159
+ const marks: RectMark[] = [];
160
+ let cellIndex = 0;
161
+
162
+ for (let c = 0; c < categories.length; c++) {
163
+ const category = categories[c];
164
+ const count = cellCounts[c];
165
+ const value = categoryTotals.get(category)!;
166
+ const percentStr = total > 0 ? formatPercent(value / total) : '0%';
167
+ const row = categoryRows.get(category)!;
168
+ const catKey = serializeKeyValue(category);
169
+ const fill = getColor(scales, category);
170
+
171
+ // One SR stop per category: the first cell carries the label, the rest
172
+ // are decorative duplicates (100 cells would drown screen reader users).
173
+ const aria: MarkAria = {
174
+ label: `${category}: ${count} of ${units} units (${percentStr})`,
175
+ };
176
+
177
+ for (let k = 0; k < count; k++, cellIndex++) {
178
+ const col = cellIndex % columns;
179
+ const gridRow = Math.floor(cellIndex / columns); // 0 = bottom row
180
+
181
+ marks.push({
182
+ type: 'rect',
183
+ key: `${catKey}|${k}`,
184
+ x: originX + col * step,
185
+ y: bottomRowY - gridRow * step,
186
+ width: cell,
187
+ height: cell,
188
+ fill,
189
+ cornerRadius,
190
+ data: row as Record<string, unknown>,
191
+ aria: k === 0 ? aria : { ...aria, decorative: true },
192
+ });
193
+ }
194
+ }
195
+
196
+ return marks;
197
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Waffle chart module.
3
+ *
4
+ * Exports the waffle renderer and computation functions. Waffles emit plain
5
+ * RectMark[] (rendered by the existing rect mark path) with no per-cell value
6
+ * labels: the legend names the categories and the tooltip carries the counts,
7
+ * so cell labels would only add noise to the grid.
8
+ */
9
+
10
+ import type { Mark } from '@opendata-ai/openchart-core';
11
+ import type { ChartRenderer } from '../registry';
12
+ import { computeWaffleMarks } from './compute';
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Waffle chart renderer
16
+ // ---------------------------------------------------------------------------
17
+
18
+ /**
19
+ * Waffle chart renderer.
20
+ *
21
+ * Produces one square cell per unit, filled bottom-left to top-right by rows.
22
+ */
23
+ export const waffleRenderer: ChartRenderer = (spec, scales, chartArea, strategy, _theme) => {
24
+ return computeWaffleMarks(spec, scales, chartArea, strategy) as Mark[];
25
+ };
26
+
27
+ // ---------------------------------------------------------------------------
28
+ // Public exports
29
+ // ---------------------------------------------------------------------------
30
+
31
+ export { computeWaffleMarks, largestRemainderCells } from './compute';
@@ -0,0 +1,89 @@
1
+ import { DIVERGING_PALETTES } from '@opendata-ai/openchart-core';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { compileChart } from '../../compile';
4
+
5
+ const OPTIONS = { width: 800, height: 400 };
6
+
7
+ /** d3 hands interpolated colors back as `rgb(r, g, b)`; compare on a single form. */
8
+ function hex(value: string): string {
9
+ const rgb = /^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/.exec(value.trim());
10
+ if (!rgb) return value.trim().toLowerCase();
11
+ const channel = (n: string) => Number(n).toString(16).padStart(2, '0');
12
+ return `#${channel(rgb[1])}${channel(rgb[2])}${channel(rgb[3])}`;
13
+ }
14
+
15
+ const ROWS = [
16
+ { day: 'a', value: -2 },
17
+ { day: 'b', value: 0 },
18
+ { day: 'c', value: 2 },
19
+ ];
20
+
21
+ /** The compiled fill of the mark carrying `value`, as the reader would see it. */
22
+ function colorAt(layout: ReturnType<typeof compileChart>, value: number): string {
23
+ const mark = layout.marks.find(
24
+ (m) => (m as { data?: Record<string, unknown> }).data?.value === value,
25
+ );
26
+ const fill = (mark as { fill?: string } | undefined)?.fill;
27
+ return hex(String(fill));
28
+ }
29
+
30
+ const RED_BLUE = DIVERGING_PALETTES.redBlue;
31
+ const RED = hex(RED_BLUE[0]);
32
+ const BLUE = hex(RED_BLUE[RED_BLUE.length - 1]);
33
+
34
+ // A bar, not a rect: this suite is about the color ramp, and it needs a mark
35
+ // with a quantitative axis to carry the value. `rect` used to alias the column
36
+ // renderer, so it stood in for one here; now that `rect` is a real heatmap mark
37
+ // (two categorical axes, cells sized by bandwidth) it emits nothing for a
38
+ // quantitative y, and there is no fill to read back.
39
+ function spec(reverse?: boolean) {
40
+ return {
41
+ mark: 'bar' as const,
42
+ data: ROWS,
43
+ encoding: {
44
+ x: { field: 'day', type: 'nominal' as const },
45
+ y: { field: 'value', type: 'quantitative' as const },
46
+ color: {
47
+ field: 'value',
48
+ type: 'quantitative' as const,
49
+ scale: reverse ? { scheme: 'redBlue', reverse: true } : { scheme: 'redBlue' },
50
+ },
51
+ },
52
+ };
53
+ }
54
+
55
+ describe('scale.reverse on a color channel', () => {
56
+ it('ramps low -> red, high -> blue by default (ColorBrewer RdBu order)', () => {
57
+ const layout = compileChart(spec(), OPTIONS);
58
+ expect(colorAt(layout, -2)).toBe(RED);
59
+ expect(colorAt(layout, 2)).toBe(BLUE);
60
+ });
61
+
62
+ it('flips the ramp so low -> blue, high -> red', () => {
63
+ const layout = compileChart(spec(true), OPTIONS);
64
+ expect(colorAt(layout, -2)).toBe(BLUE);
65
+ expect(colorAt(layout, 2)).toBe(RED);
66
+ });
67
+
68
+ it('keeps the diverging midpoint label when the ramp is reversed', () => {
69
+ // A reversed diverging ramp is still diverging: flipping the stops must not
70
+ // cost it the center tick (min / mid / max, not just min / max).
71
+ const forward = compileChart(spec(), OPTIONS).legend;
72
+ const reversed = compileChart(spec(true), OPTIONS).legend;
73
+ const tickCount = (l: typeof forward) =>
74
+ (l as { ticks?: unknown[] } | undefined)?.ticks?.length ?? 0;
75
+ expect(tickCount(forward)).toBe(3);
76
+ expect(tickCount(reversed)).toBe(tickCount(forward));
77
+ });
78
+
79
+ it('keeps the legend ramp in step with the marks', () => {
80
+ const legend = compileChart(spec(true), OPTIONS).legend;
81
+ // The legend resolves its ramp from the same scale.range the marks use, so a
82
+ // reversed scale must not leave the legend pointing the original direction.
83
+ expect(legend?.type).toBe('continuous');
84
+ const stops = (legend as { colorStops: Array<{ color: string }> }).colorStops;
85
+ expect(stops.length).toBeGreaterThan(1);
86
+ expect(hex(stops[0].color)).toBe(BLUE);
87
+ expect(hex(stops[stops.length - 1].color)).toBe(RED);
88
+ });
89
+ });