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

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 (271) hide show
  1. package/dist/index.d.ts +7 -0
  2. package/dist/index.js +123 -54
  3. package/dist/index.js.map +1 -1
  4. package/package.json +3 -4
  5. package/src/__test-fixtures__/specs.ts +0 -182
  6. package/src/__tests__/__snapshots__/compile-snapshot.test.ts.snap +0 -2401
  7. package/src/__tests__/annotation-behavior.test.ts +0 -852
  8. package/src/__tests__/axes.test.ts +0 -1579
  9. package/src/__tests__/compile-animation.test.ts +0 -161
  10. package/src/__tests__/compile-chart.test.ts +0 -1303
  11. package/src/__tests__/compile-footnotes.test.ts +0 -277
  12. package/src/__tests__/compile-layer.test.ts +0 -969
  13. package/src/__tests__/compile-snapshot.test.ts +0 -156
  14. package/src/__tests__/compound-labels.test.ts +0 -147
  15. package/src/__tests__/dimensions.test.ts +0 -918
  16. package/src/__tests__/encoding-sugar.test.ts +0 -390
  17. package/src/__tests__/facet.test.ts +0 -359
  18. package/src/__tests__/helpers/invariants.ts +0 -299
  19. package/src/__tests__/known-bugs.test.ts +0 -566
  20. package/src/__tests__/layout-fuzz.test.ts +0 -358
  21. package/src/__tests__/layout-invariants.test.ts +0 -535
  22. package/src/__tests__/legend.test.ts +0 -721
  23. package/src/__tests__/mark-keys.test.ts +0 -294
  24. package/src/__tests__/ranking-recipes.test.ts +0 -260
  25. package/src/__tests__/rotation.test.ts +0 -83
  26. package/src/__tests__/scales.test.ts +0 -323
  27. package/src/__tests__/series-search.test.ts +0 -92
  28. package/src/__tests__/spec-sugar.test.ts +0 -801
  29. package/src/__tests__/you-draw-it.test.ts +0 -160
  30. package/src/annotations/__tests__/compute.test.ts +0 -1672
  31. package/src/annotations/__tests__/geometry.test.ts +0 -66
  32. package/src/annotations/__tests__/placement-fuzz.test.ts +0 -256
  33. package/src/annotations/__tests__/placement-invariants.test.ts +0 -345
  34. package/src/annotations/__tests__/placement.test.ts +0 -316
  35. package/src/annotations/__tests__/resolve-text.test.ts +0 -788
  36. package/src/annotations/__tests__/rich-text.test.ts +0 -91
  37. package/src/annotations/__tests__/thinning.test.ts +0 -285
  38. package/src/annotations/collisions.ts +0 -326
  39. package/src/annotations/compute.ts +0 -333
  40. package/src/annotations/constants.ts +0 -162
  41. package/src/annotations/geometry.ts +0 -376
  42. package/src/annotations/move.ts +0 -135
  43. package/src/annotations/placement.ts +0 -636
  44. package/src/annotations/position.ts +0 -131
  45. package/src/annotations/resolve-range.ts +0 -117
  46. package/src/annotations/resolve-refline.ts +0 -157
  47. package/src/annotations/resolve-text.ts +0 -545
  48. package/src/annotations/rich-text.ts +0 -65
  49. package/src/annotations/thinning.ts +0 -190
  50. package/src/barlist/__tests__/compile-barlist.test.ts +0 -200
  51. package/src/barlist/compile-barlist.ts +0 -391
  52. package/src/barlist/types.ts +0 -28
  53. package/src/charts/__tests__/post-process.test.ts +0 -237
  54. package/src/charts/__tests__/registry.test.ts +0 -116
  55. package/src/charts/__tests__/utils.test.ts +0 -195
  56. package/src/charts/_shared/__tests__/density-filter.test.ts +0 -32
  57. package/src/charts/_shared/density-filter.ts +0 -26
  58. package/src/charts/_shared/format-label-value.ts +0 -16
  59. package/src/charts/bar/__tests__/compute.test.ts +0 -934
  60. package/src/charts/bar/__tests__/gradient-orient.test.ts +0 -127
  61. package/src/charts/bar/__tests__/labels.test.ts +0 -292
  62. package/src/charts/bar/compute.ts +0 -539
  63. package/src/charts/bar/index.ts +0 -60
  64. package/src/charts/bar/labels.ts +0 -311
  65. package/src/charts/beeswarm/__tests__/compute.test.ts +0 -280
  66. package/src/charts/beeswarm/__tests__/dodge.test.ts +0 -148
  67. package/src/charts/beeswarm/compute.ts +0 -203
  68. package/src/charts/beeswarm/dodge.ts +0 -155
  69. package/src/charts/beeswarm/index.ts +0 -32
  70. package/src/charts/builtin.ts +0 -75
  71. package/src/charts/calendar/__tests__/compute.test.ts +0 -417
  72. package/src/charts/calendar/compute.ts +0 -319
  73. package/src/charts/calendar/index.ts +0 -32
  74. package/src/charts/column/__tests__/compute.test.ts +0 -540
  75. package/src/charts/column/__tests__/labels.test.ts +0 -179
  76. package/src/charts/column/compute.ts +0 -493
  77. package/src/charts/column/index.ts +0 -53
  78. package/src/charts/column/labels.ts +0 -229
  79. package/src/charts/dot/__tests__/compute.test.ts +0 -380
  80. package/src/charts/dot/__tests__/labels.test.ts +0 -98
  81. package/src/charts/dot/compute.ts +0 -285
  82. package/src/charts/dot/index.ts +0 -62
  83. package/src/charts/dot/labels.ts +0 -121
  84. package/src/charts/line/__tests__/compute.test.ts +0 -1194
  85. package/src/charts/line/__tests__/curves.test.ts +0 -51
  86. package/src/charts/line/__tests__/labels.test.ts +0 -94
  87. package/src/charts/line/__tests__/mark-options.test.ts +0 -175
  88. package/src/charts/line/area.ts +0 -484
  89. package/src/charts/line/compute.ts +0 -356
  90. package/src/charts/line/curves.ts +0 -85
  91. package/src/charts/line/index.ts +0 -176
  92. package/src/charts/line/labels.ts +0 -177
  93. package/src/charts/parliament/__tests__/compute.test.ts +0 -411
  94. package/src/charts/parliament/compute.ts +0 -313
  95. package/src/charts/parliament/index.ts +0 -32
  96. package/src/charts/pie/__tests__/compute.test.ts +0 -384
  97. package/src/charts/pie/__tests__/labels.test.ts +0 -132
  98. package/src/charts/pie/compute.ts +0 -324
  99. package/src/charts/pie/index.ts +0 -49
  100. package/src/charts/pie/labels.ts +0 -143
  101. package/src/charts/post-process.ts +0 -229
  102. package/src/charts/range/__tests__/compute.test.ts +0 -486
  103. package/src/charts/range/compute.ts +0 -273
  104. package/src/charts/range/index.ts +0 -82
  105. package/src/charts/range/labels.ts +0 -169
  106. package/src/charts/rect/__tests__/compute.test.ts +0 -120
  107. package/src/charts/rect/index.ts +0 -127
  108. package/src/charts/registry.ts +0 -72
  109. package/src/charts/rule/index.ts +0 -139
  110. package/src/charts/scatter/__tests__/compute.test.ts +0 -488
  111. package/src/charts/scatter/__tests__/trendline.test.ts +0 -191
  112. package/src/charts/scatter/compute.ts +0 -192
  113. package/src/charts/scatter/index.ts +0 -46
  114. package/src/charts/scatter/trendline.ts +0 -100
  115. package/src/charts/text/__tests__/compute.test.ts +0 -307
  116. package/src/charts/text/index.ts +0 -141
  117. package/src/charts/tick/__tests__/compute.test.ts +0 -75
  118. package/src/charts/tick/index.ts +0 -99
  119. package/src/charts/utils.ts +0 -170
  120. package/src/charts/waffle/__tests__/compute.test.ts +0 -305
  121. package/src/charts/waffle/compute.ts +0 -197
  122. package/src/charts/waffle/index.ts +0 -31
  123. package/src/compile/__tests__/color-scale-range.test.ts +0 -158
  124. package/src/compile/__tests__/color-scale-reverse.test.ts +0 -89
  125. package/src/compile/__tests__/data-clip.test.ts +0 -127
  126. package/src/compile/__tests__/fill-patterns.test.ts +0 -154
  127. package/src/compile/__tests__/size-scale.test.ts +0 -108
  128. package/src/compile/__tests__/watermark-obstacle.test.ts +0 -93
  129. package/src/compile/color-scale-range.ts +0 -101
  130. package/src/compile/data-clip.ts +0 -48
  131. package/src/compile/fill-patterns.ts +0 -74
  132. package/src/compile/layer.ts +0 -630
  133. package/src/compile/size-scale.ts +0 -141
  134. package/src/compile/spec-sugar.ts +0 -767
  135. package/src/compile/watermark-obstacle.ts +0 -54
  136. package/src/compile/you-draw-it.ts +0 -123
  137. package/src/compile.ts +0 -1548
  138. package/src/compiler/__tests__/a11y-warnings.test.ts +0 -148
  139. package/src/compiler/__tests__/animation.test.ts +0 -177
  140. package/src/compiler/__tests__/compile.test.ts +0 -87
  141. package/src/compiler/__tests__/fixtures/vl-parity/axis-null.json +0 -19
  142. package/src/compiler/__tests__/fixtures/vl-parity/color-value.json +0 -20
  143. package/src/compiler/__tests__/fixtures/vl-parity/count-aggregate.json +0 -22
  144. package/src/compiler/__tests__/fixtures/vl-parity/data-values.json +0 -19
  145. package/src/compiler/__tests__/fixtures/vl-parity/layer-axis-null.json +0 -14
  146. package/src/compiler/__tests__/fixtures/vl-parity/layer-count.json +0 -34
  147. package/src/compiler/__tests__/fixtures/vl-parity/layer-data-values.json +0 -22
  148. package/src/compiler/__tests__/fixtures/vl-parity/layer-legend-null.json +0 -41
  149. package/src/compiler/__tests__/fixtures/vl-parity/layer-scheme.json +0 -38
  150. package/src/compiler/__tests__/fixtures/vl-parity/layer-sort.json +0 -28
  151. package/src/compiler/__tests__/fixtures/vl-parity/layer-theta.json +0 -28
  152. package/src/compiler/__tests__/fixtures/vl-parity/layer-title.json +0 -30
  153. package/src/compiler/__tests__/fixtures/vl-parity/layer-value-def.json +0 -29
  154. package/src/compiler/__tests__/fixtures/vl-parity/legend-null.json +0 -32
  155. package/src/compiler/__tests__/fixtures/vl-parity/scheme.json +0 -25
  156. package/src/compiler/__tests__/fixtures/vl-parity/sort-by-value.json +0 -19
  157. package/src/compiler/__tests__/fixtures/vl-parity/theta-arc.json +0 -19
  158. package/src/compiler/__tests__/fixtures/vl-parity/title-subtitle.json +0 -21
  159. package/src/compiler/__tests__/fixtures/vl-parity/width-height.json +0 -23
  160. package/src/compiler/__tests__/keys.test.ts +0 -83
  161. package/src/compiler/__tests__/normalize-highlight.test.ts +0 -103
  162. package/src/compiler/__tests__/normalize.test.ts +0 -399
  163. package/src/compiler/__tests__/sparkline-defaults.test.ts +0 -153
  164. package/src/compiler/__tests__/validate-did-you-mean.test.ts +0 -170
  165. package/src/compiler/__tests__/validate-highlight.test.ts +0 -112
  166. package/src/compiler/__tests__/validate-near-miss.test.ts +0 -251
  167. package/src/compiler/__tests__/validate.test.ts +0 -731
  168. package/src/compiler/__tests__/vl-parity.test.ts +0 -68
  169. package/src/compiler/a11y-warnings.ts +0 -110
  170. package/src/compiler/animation.ts +0 -142
  171. package/src/compiler/index.ts +0 -47
  172. package/src/compiler/keys.ts +0 -55
  173. package/src/compiler/normalize.ts +0 -734
  174. package/src/compiler/sparkline-defaults.ts +0 -138
  175. package/src/compiler/types.ts +0 -241
  176. package/src/compiler/validate.ts +0 -2093
  177. package/src/endpoint-labels/__tests__/compute.test.ts +0 -587
  178. package/src/endpoint-labels/compute.ts +0 -621
  179. package/src/endpoint-labels/constants.ts +0 -54
  180. package/src/endpoint-labels/format.ts +0 -60
  181. package/src/endpoint-labels/predict.ts +0 -139
  182. package/src/format/__tests__/field-format.test.ts +0 -164
  183. package/src/format/field-format.ts +0 -27
  184. package/src/geo/__tests__/compile-map.test.ts +0 -1128
  185. package/src/geo/compile-map.ts +0 -1376
  186. package/src/geo/join.ts +0 -115
  187. package/src/geo/projections.ts +0 -65
  188. package/src/geo/types.ts +0 -26
  189. package/src/graphs/__tests__/community.test.ts +0 -228
  190. package/src/graphs/__tests__/compile-graph.test.ts +0 -396
  191. package/src/graphs/__tests__/encoding.test.ts +0 -415
  192. package/src/graphs/community.ts +0 -92
  193. package/src/graphs/compile-graph.ts +0 -329
  194. package/src/graphs/encoding.ts +0 -356
  195. package/src/graphs/types.ts +0 -106
  196. package/src/index.ts +0 -177
  197. package/src/layout/__tests__/metrics.test.ts +0 -97
  198. package/src/layout/__tests__/scales-highlight.test.ts +0 -192
  199. package/src/layout/axes/rotation.ts +0 -152
  200. package/src/layout/axes/thinning.ts +0 -98
  201. package/src/layout/axes/ticks.ts +0 -409
  202. package/src/layout/axes.ts +0 -757
  203. package/src/layout/dimensions.ts +0 -912
  204. package/src/layout/facet.ts +0 -91
  205. package/src/layout/gridlines.ts +0 -84
  206. package/src/layout/metrics.ts +0 -132
  207. package/src/layout/plan.ts +0 -631
  208. package/src/layout/scales.ts +0 -1053
  209. package/src/layout/shared.ts +0 -44
  210. package/src/legend/__tests__/continuous.test.ts +0 -318
  211. package/src/legend/__tests__/redundancy.test.ts +0 -108
  212. package/src/legend/__tests__/size.test.ts +0 -348
  213. package/src/legend/__tests__/suppression.test.ts +0 -382
  214. package/src/legend/compute.ts +0 -748
  215. package/src/legend/continuous.ts +0 -327
  216. package/src/legend/size.ts +0 -407
  217. package/src/legend/suppression.ts +0 -226
  218. package/src/legend/wrap.ts +0 -117
  219. package/src/sankey/__tests__/compile-sankey.test.ts +0 -458
  220. package/src/sankey/__tests__/layout.test.ts +0 -165
  221. package/src/sankey/__tests__/node-label-wrap.test.ts +0 -114
  222. package/src/sankey/__tests__/node-sort.test.ts +0 -45
  223. package/src/sankey/compile-sankey.ts +0 -706
  224. package/src/sankey/layout.ts +0 -184
  225. package/src/sankey/types.ts +0 -41
  226. package/src/tables/__tests__/bar-column.test.ts +0 -147
  227. package/src/tables/__tests__/category-colors.test.ts +0 -230
  228. package/src/tables/__tests__/compile-table.test.ts +0 -236
  229. package/src/tables/__tests__/format-cells.test.ts +0 -143
  230. package/src/tables/__tests__/heatmap.test.ts +0 -148
  231. package/src/tables/__tests__/pagination.test.ts +0 -78
  232. package/src/tables/__tests__/search.test.ts +0 -94
  233. package/src/tables/__tests__/sort.test.ts +0 -107
  234. package/src/tables/__tests__/sparkline.test.ts +0 -122
  235. package/src/tables/bar-column.ts +0 -94
  236. package/src/tables/category-colors.ts +0 -78
  237. package/src/tables/compile-table.ts +0 -427
  238. package/src/tables/format-cells.ts +0 -115
  239. package/src/tables/heatmap.ts +0 -141
  240. package/src/tables/pagination.ts +0 -46
  241. package/src/tables/search.ts +0 -66
  242. package/src/tables/sort.ts +0 -69
  243. package/src/tables/sparkline.ts +0 -113
  244. package/src/tables/utils.ts +0 -16
  245. package/src/tilemap/__tests__/compile-tilemap.test.ts +0 -576
  246. package/src/tilemap/compile-tilemap.ts +0 -755
  247. package/src/tilemap/layout.ts +0 -172
  248. package/src/tilemap/types.ts +0 -33
  249. package/src/tooltips/__tests__/compute.test.ts +0 -582
  250. package/src/tooltips/compute.ts +0 -700
  251. package/src/transforms/__tests__/aggregate.test.ts +0 -159
  252. package/src/transforms/__tests__/bin.test.ts +0 -88
  253. package/src/transforms/__tests__/calculate.test.ts +0 -146
  254. package/src/transforms/__tests__/conditional.test.ts +0 -127
  255. package/src/transforms/__tests__/filter-relative.test.ts +0 -202
  256. package/src/transforms/__tests__/filter.test.ts +0 -59
  257. package/src/transforms/__tests__/fold.test.ts +0 -79
  258. package/src/transforms/__tests__/index.test.ts +0 -93
  259. package/src/transforms/__tests__/predicates.test.ts +0 -193
  260. package/src/transforms/__tests__/timeunit.test.ts +0 -129
  261. package/src/transforms/__tests__/window.test.ts +0 -286
  262. package/src/transforms/aggregate.ts +0 -131
  263. package/src/transforms/bin.ts +0 -87
  264. package/src/transforms/calculate.ts +0 -60
  265. package/src/transforms/conditional.ts +0 -46
  266. package/src/transforms/filter.ts +0 -122
  267. package/src/transforms/fold.ts +0 -49
  268. package/src/transforms/index.ts +0 -60
  269. package/src/transforms/predicates.ts +0 -123
  270. package/src/transforms/timeunit.ts +0 -88
  271. package/src/transforms/window.ts +0 -185
@@ -1,630 +0,0 @@
1
- import type {
2
- ChartLayout,
3
- ChartSpec,
4
- CompileOptions,
5
- DataRow,
6
- Encoding,
7
- LayerSpec,
8
- Mark,
9
- } from '@opendata-ai/openchart-core';
10
- import {
11
- AXIS_TITLE_TRAILING_PAD,
12
- BREAKPOINT_COMPACT_MAX,
13
- computeFieldFormatContext,
14
- defaultNumberFormatter,
15
- estimateTextWidth,
16
- getAxisTitleOffset,
17
- resolveNumberFormatter,
18
- resolveTheme,
19
- TICK_LABEL_OFFSET,
20
- } from '@opendata-ai/openchart-core';
21
- import { scaleLinear } from 'd3-scale';
22
- import { curveMonotoneX, area as d3area, line as d3line } from 'd3-shape';
23
- import { flattenLayers } from '../compiler/index';
24
- import type { MeasureFn } from '../layout/plan';
25
- import { createMeasureFn } from '../layout/plan';
26
-
27
- type ChartCompiler = (spec: unknown, options: CompileOptions) => ChartLayout;
28
-
29
- /**
30
- * Compile a LayerSpec into a single ChartLayout.
31
- *
32
- * Flattens nested layers, merges inherited data/encoding/transforms,
33
- * compiles each leaf layer independently, unions scale domains (shared
34
- * by default), and concatenates marks in layer order.
35
- */
36
- export function compileLayer(
37
- spec: LayerSpec,
38
- options: CompileOptions,
39
- compileChart: ChartCompiler,
40
- ): ChartLayout {
41
- const leaves = flattenLayers(spec);
42
-
43
- if (leaves.length === 0) {
44
- throw new Error('LayerSpec has no leaf chart specs after flattening');
45
- }
46
-
47
- if (leaves.length === 1) {
48
- const singleSpec = buildPrimarySpec(leaves, spec);
49
- return compileChart(singleSpec, options);
50
- }
51
-
52
- if (spec.resolve?.scale?.y === 'independent') {
53
- return compileLayerIndependent(leaves, spec, options, compileChart);
54
- }
55
-
56
- const primarySpec = buildPrimarySpec(leaves, spec);
57
- const primaryLayout = compileChart(primarySpec, options);
58
-
59
- const allMarks: Mark[] = [];
60
- const seenLabels = new Set<string>();
61
- const pLegend = primaryLayout.legend;
62
- const mergedLegendEntries = 'entries' in pLegend ? [...pLegend.entries] : [];
63
- for (const entry of mergedLegendEntries) {
64
- seenLabels.add(entry.label);
65
- }
66
-
67
- const indexedLeaves = leaves.map((leaf, i) => ({
68
- leaf,
69
- zIndex: (leaf as ChartSpec).zIndex ?? i,
70
- }));
71
- indexedLeaves.sort((a, b) => a.zIndex - b.zIndex);
72
-
73
- // Leaf specs lack the layer-level chrome/legend, so left alone they compute
74
- // a different chart area than the primary and their marks drift off the
75
- // axes. Freeze the primary's area (and inherit its theme) for every leaf.
76
- const leafOptions: CompileOptions = { ...options, frozenChartArea: primaryLayout.area };
77
-
78
- // Shared scales means shared *domains*, not just a shared plot rect. Each leaf
79
- // otherwise re-fits its own domain from its own rows, so a layer holding fewer
80
- // or narrower rows than its siblings (a label layer naming only the notable
81
- // points, say) lands on a different scale and its marks slide off the ones
82
- // they annotate. Union the quantitative domains across every leaf and pin them.
83
- const sharedDomains = computeSharedDomains(leaves);
84
-
85
- for (const { leaf } of indexedLeaves) {
86
- const themedLeaf = {
87
- ...withSharedDomains(leaf as ChartSpec, sharedDomains),
88
- theme: (leaf as ChartSpec).theme ?? spec.theme,
89
- darkMode: (leaf as ChartSpec).darkMode ?? spec.darkMode,
90
- };
91
- const leafLayout = compileChart(themedLeaf as unknown, leafOptions);
92
-
93
- allMarks.push(...leafLayout.marks);
94
-
95
- const leafLeg = leafLayout.legend;
96
- if ('entries' in leafLeg) {
97
- for (const entry of leafLeg.entries) {
98
- if (!seenLabels.has(entry.label)) {
99
- seenLabels.add(entry.label);
100
- mergedLegendEntries.push(entry);
101
- }
102
- }
103
- }
104
- }
105
-
106
- const mergedLegend = {
107
- ...primaryLayout.legend,
108
- ...('entries' in pLegend ? { entries: mergedLegendEntries } : {}),
109
- } as typeof primaryLayout.legend;
110
-
111
- return {
112
- ...primaryLayout,
113
- marks: allMarks,
114
- legend: mergedLegend,
115
- // `legends` is what the renderer iterates, so the merged color legend has to
116
- // land in it too. Spreading `primaryLayout` alone would leave legends[0] as
117
- // the *pre-merge* legend and every leaf past the first would vanish from the
118
- // rendered key while `layout.legend` claimed otherwise.
119
- legends: [mergedLegend, ...primaryLayout.legends.slice(1)],
120
- };
121
- }
122
-
123
- // ---------------------------------------------------------------------------
124
- // Independent y-scale compilation (dual-axis charts)
125
- // ---------------------------------------------------------------------------
126
-
127
- function estimateYAxisLabelWidth(
128
- data: DataRow[],
129
- encoding: Encoding | undefined,
130
- baseFontSize: number,
131
- measure?: MeasureFn,
132
- ): number {
133
- if (!encoding?.y) return 40;
134
- const yEnc = encoding.y;
135
- const yField = yEnc.field;
136
- if (!yField) return 40;
137
-
138
- const m = measure ?? estimateTextWidth;
139
-
140
- const yType = yEnc.type;
141
- if (yType === 'nominal' || yType === 'ordinal') {
142
- let maxWidth = 0;
143
- for (const row of data) {
144
- const label = String(row[yField] ?? '');
145
- const w = m(label, baseFontSize, 400);
146
- if (w > maxWidth) maxWidth = w;
147
- }
148
- return maxWidth > 0 ? maxWidth + 10 : 40;
149
- }
150
-
151
- const yAxisFormat = (encoding.y.axis as Record<string, unknown> | undefined)?.format as
152
- | string
153
- | undefined;
154
- let maxAbsVal = 0;
155
- for (const row of data) {
156
- const v = Number(row[yField]);
157
- if (Number.isFinite(v) && Math.abs(v) > maxAbsVal) maxAbsVal = Math.abs(v);
158
- }
159
- const ctx = computeFieldFormatContext(data.map((r) => r[yField]));
160
- let sampleLabel: string;
161
- if (yAxisFormat) {
162
- const fmt = resolveNumberFormatter(yAxisFormat, ctx);
163
- sampleLabel = fmt ? fmt(maxAbsVal) : String(maxAbsVal);
164
- } else {
165
- sampleLabel = defaultNumberFormatter({ ...ctx, extent: ctx.extent ?? [0, maxAbsVal] })(
166
- maxAbsVal,
167
- );
168
- }
169
- const hasNeg = data.some((r) => Number(r[yField]) < 0);
170
- const labelEst = (hasNeg ? '-' : '') + sampleLabel;
171
- return m(labelEst, baseFontSize, 400) + 10;
172
- }
173
-
174
- function compileLayerIndependent(
175
- leaves: ChartSpec[],
176
- layerSpec: LayerSpec,
177
- options: CompileOptions,
178
- compileChart: ChartCompiler,
179
- ): ChartLayout {
180
- if (leaves.length > 2) {
181
- throw new Error(
182
- 'Independent y-scales support at most 2 layers (left and right y-axis). ' +
183
- `Got ${leaves.length} layers.`,
184
- );
185
- }
186
-
187
- const leaf0 = leaves[0];
188
- const leaf1 = leaves[1];
189
-
190
- const xType0 = leaf0.encoding?.x?.type;
191
- const xType1 = leaf1.encoding?.x?.type;
192
- if (xType0 && xType1 && xType0 !== xType1) {
193
- throw new Error(
194
- `Dual-axis charts require matching x-field types across layers. ` +
195
- `Layer 0 has '${xType0}', layer 1 has '${xType1}'.`,
196
- );
197
- }
198
-
199
- const theme = resolveTheme(layerSpec.theme ?? leaf1.theme);
200
- const axisFontSize = theme.fonts?.sizes?.axisTick ?? 11;
201
- const measureFn = createMeasureFn(options.measureText);
202
- const rightAxisWidth = estimateYAxisLabelWidth(
203
- leaf1.data,
204
- leaf1.encoding,
205
- axisFontSize,
206
- measureFn,
207
- );
208
- const yAxisConfig = leaf1.encoding?.y?.axis || undefined;
209
- const hasRightAxisTitle = !!yAxisConfig?.title;
210
- const tickExtent = TICK_LABEL_OFFSET + rightAxisWidth;
211
- const bodyFontSize = theme.fonts?.sizes?.body ?? 13;
212
- const axisTitleOffset = getAxisTitleOffset(options.width);
213
- const halfGlyph = Math.ceil(bodyFontSize / 2);
214
- const titleExtent = hasRightAxisTitle
215
- ? axisTitleOffset +
216
- halfGlyph +
217
- (options.width < BREAKPOINT_COMPACT_MAX ? 0 : AXIS_TITLE_TRAILING_PAD)
218
- : 0;
219
- const rightReserve = Math.max(tickExtent, titleExtent);
220
-
221
- const optionsWithReserve: CompileOptions = {
222
- ...options,
223
- rightAxisReserve: rightReserve,
224
- };
225
-
226
- const xField0 = leaf0.encoding?.x?.field;
227
- const xField1 = leaf1.encoding?.x?.field;
228
- const unionXValues = new Set<unknown>();
229
- if (xField0) for (const row of leaf0.data) unionXValues.add(row[xField0]);
230
- if (xField1) for (const row of leaf1.data) unionXValues.add(row[xField1]);
231
-
232
- let leaf0WithUnionX = ensureXDomainCoverage(leaf0, xField0, unionXValues);
233
- let leaf1WithUnionX = ensureXDomainCoverage(leaf1, xField1, unionXValues);
234
-
235
- const aligned = alignYDomains(leaf0WithUnionX, leaf1WithUnionX);
236
- if (aligned) {
237
- leaf0WithUnionX = withYDomain(leaf0WithUnionX, aligned.domain0);
238
- leaf1WithUnionX = withYDomain(leaf1WithUnionX, aligned.domain1);
239
- }
240
-
241
- const primary0 = buildPrimarySpec([leaf0WithUnionX], layerSpec);
242
- const layout0 = compileChart(primary0, optionsWithReserve);
243
-
244
- const primary1 = buildPrimarySpec([leaf1WithUnionX], layerSpec);
245
- primary1.annotations = [];
246
- const layout1 = compileChart(primary1, optionsWithReserve);
247
-
248
- const y2Axis = layout1.axes.y
249
- ? {
250
- ...layout1.axes.y,
251
- orient: 'right' as const,
252
- gridlines: [],
253
- start: {
254
- x: layout0.area.x + layout0.area.width,
255
- y: layout0.area.y,
256
- },
257
- end: {
258
- x: layout0.area.x + layout0.area.width,
259
- y: layout0.area.y + layout0.area.height,
260
- },
261
- ...(layout1.axes.y.label
262
- ? {
263
- titlePosition: {
264
- x:
265
- layout0.area.x +
266
- layout0.area.width +
267
- getAxisTitleOffset(layout0.dimensions.width),
268
- y: layout0.area.y + layout0.area.height / 2,
269
- angle: 90,
270
- },
271
- }
272
- : {}),
273
- }
274
- : undefined;
275
-
276
- const layer0HasBars = layout0.marks.some((m) => m.type === 'rect');
277
- const layer1HasBars = layout1.marks.some((m) => m.type === 'rect');
278
-
279
- const bandCenterByCategory = new Map<string, number>();
280
- if (layer0HasBars && layout0.axes.x?.ticks) {
281
- for (const tick of layout0.axes.x.ticks) {
282
- bandCenterByCategory.set(String(tick.label), tick.position);
283
- }
284
- } else if (layer1HasBars && layout1.axes.x?.ticks) {
285
- for (const tick of layout1.axes.x.ticks) {
286
- bandCenterByCategory.set(String(tick.label), tick.position);
287
- }
288
- }
289
-
290
- const remapMarkX = (xField: string | undefined, mark: Mark): Mark => {
291
- if (!xField || bandCenterByCategory.size === 0) return mark;
292
- if (mark.type === 'line') {
293
- const newPoints = mark.points.map((p, i) => {
294
- const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
295
- return bx !== undefined ? { ...p, x: bx } : p;
296
- });
297
- const newDataPoints = mark.dataPoints?.map((dp, i) => {
298
- const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
299
- return bx !== undefined ? { ...dp, x: bx } : dp;
300
- });
301
- const newPath =
302
- d3line<{ x: number; y: number }>()
303
- .x((p) => p.x)
304
- .y((p) => p.y)
305
- .curve(curveMonotoneX)(newPoints) ?? undefined;
306
- return { ...mark, points: newPoints, dataPoints: newDataPoints, path: newPath };
307
- }
308
- if (mark.type === 'area') {
309
- const newTopPoints = mark.topPoints.map((p, i) => {
310
- const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
311
- return bx !== undefined ? { ...p, x: bx } : p;
312
- });
313
- const newBottomPoints = mark.bottomPoints.map((p, i) => {
314
- const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
315
- return bx !== undefined ? { ...p, x: bx } : p;
316
- });
317
- const newDataPoints = mark.dataPoints?.map((dp, i) => {
318
- const bx = bandCenterByCategory.get(String(mark.data[i]?.[xField] ?? ''));
319
- return bx !== undefined ? { ...dp, x: bx } : dp;
320
- });
321
- const areaGen = d3area<{ x: number; yTop: number; yBottom: number }>()
322
- .x((p) => p.x)
323
- .y0((p) => p.yBottom)
324
- .y1((p) => p.yTop)
325
- .curve(curveMonotoneX);
326
- const topLineGen = d3line<{ x: number; yTop: number }>()
327
- .x((p) => p.x)
328
- .y((p) => p.yTop)
329
- .curve(curveMonotoneX);
330
- const combined = newTopPoints.map((tp, i) => ({
331
- x: tp.x,
332
- yTop: tp.y,
333
- yBottom: newBottomPoints[i]?.y ?? tp.y,
334
- }));
335
- const newPath = areaGen(combined) ?? '';
336
- const newTopPath = topLineGen(combined) ?? '';
337
- return {
338
- ...mark,
339
- topPoints: newTopPoints,
340
- bottomPoints: newBottomPoints,
341
- dataPoints: newDataPoints,
342
- path: newPath,
343
- topPath: newTopPath,
344
- };
345
- }
346
- if (mark.type === 'point') {
347
- const bx = bandCenterByCategory.get(String(mark.data[xField] ?? ''));
348
- return bx !== undefined ? { ...mark, cx: bx } : mark;
349
- }
350
- return mark;
351
- };
352
-
353
- const adjustedMarks0 =
354
- bandCenterByCategory.size > 0 && !layer0HasBars
355
- ? layout0.marks.map((m) => remapMarkX(xField0, m))
356
- : layout0.marks;
357
-
358
- const taggedMarks1 = layout1.marks.map((mark) => {
359
- const tagged = { ...mark, yScale: 'y2' as const };
360
- if (bandCenterByCategory.size > 0 && !layer1HasBars) {
361
- return remapMarkX(xField1, tagged) as typeof tagged;
362
- }
363
- return tagged;
364
- });
365
-
366
- const seenLabels = new Set<string>();
367
- const l0Legend = layout0.legend;
368
- const l1Legend = layout1.legend;
369
- const mergedLegendEntries = 'entries' in l0Legend ? [...l0Legend.entries] : [];
370
- for (const entry of mergedLegendEntries) seenLabels.add(entry.label);
371
- const l1Entries = 'entries' in l1Legend ? l1Legend.entries : [];
372
- for (const entry of l1Entries) {
373
- if (!seenLabels.has(entry.label)) {
374
- seenLabels.add(entry.label);
375
- mergedLegendEntries.push(entry);
376
- }
377
- }
378
-
379
- const l0Count = layout0.marks.length;
380
- const mergedTooltips = new Map(layout0.tooltipDescriptors);
381
- for (const [key, value] of layout1.tooltipDescriptors) {
382
- const match = /^(rect|point|arc)-(\d+)$/.exec(key);
383
- if (match) {
384
- const offsetKey = `${match[1]}-${Number(match[2]) + l0Count}`;
385
- mergedTooltips.set(offsetKey, value);
386
- } else {
387
- mergedTooltips.set(key, value);
388
- }
389
- }
390
-
391
- const z0 = leaf0.zIndex ?? 0;
392
- const z1 = leaf1.zIndex ?? 1;
393
- const marks =
394
- z0 <= z1 ? [...adjustedMarks0, ...taggedMarks1] : [...taggedMarks1, ...adjustedMarks0];
395
-
396
- const mergedLegend = {
397
- ...layout0.legend,
398
- ...('entries' in l0Legend ? { entries: mergedLegendEntries } : {}),
399
- } as typeof layout0.legend;
400
-
401
- return {
402
- ...layout0,
403
- axes: {
404
- x: layout0.axes.x,
405
- y: layout0.axes.y,
406
- y2: y2Axis,
407
- },
408
- marks,
409
- legend: mergedLegend,
410
- // See the note in compileLayer: the renderer reads `legends`, so the merged
411
- // legend must replace the primary's entry there as well.
412
- legends: [mergedLegend, ...layout0.legends.slice(1)],
413
- tooltipDescriptors: mergedTooltips,
414
- };
415
- }
416
-
417
- function ensureXDomainCoverage(
418
- leaf: ChartSpec,
419
- xField: string | undefined,
420
- allXValues: Set<unknown>,
421
- ): ChartSpec {
422
- if (!xField || allXValues.size === 0) return leaf;
423
-
424
- const existingXValues = new Set<unknown>();
425
- for (const row of leaf.data) existingXValues.add(row[xField]);
426
-
427
- const missingRows: DataRow[] = [];
428
- for (const xVal of allXValues) {
429
- if (!existingXValues.has(xVal)) {
430
- missingRows.push({ [xField]: xVal });
431
- }
432
- }
433
-
434
- if (missingRows.length === 0) return leaf;
435
-
436
- return {
437
- ...leaf,
438
- data: [...leaf.data, ...missingRows],
439
- };
440
- }
441
-
442
- function alignYDomains(
443
- leaf0: ChartSpec,
444
- leaf1: ChartSpec,
445
- ): { domain0: [number, number]; domain1: [number, number] } | undefined {
446
- const yEnc0 = leaf0.encoding?.y;
447
- const yEnc1 = leaf1.encoding?.y;
448
- if (!yEnc0 || !yEnc1) return undefined;
449
- if (yEnc0.type !== 'quantitative' || yEnc1.type !== 'quantitative') return undefined;
450
-
451
- if (yEnc0.scale?.domain || yEnc1.scale?.domain) return undefined;
452
-
453
- const includeZero0 = yEnc0.scale?.zero !== false;
454
- const includeZero1 = yEnc1.scale?.zero !== false;
455
-
456
- const vals0 = leaf0.data.map((r) => Number(r[yEnc0.field])).filter(Number.isFinite);
457
- const vals1 = leaf1.data.map((r) => Number(r[yEnc1.field])).filter(Number.isFinite);
458
- if (vals0.length === 0 || vals1.length === 0) return undefined;
459
-
460
- const niced = (vals: number[], includeZero: boolean): [number, number] => {
461
- let lo = Math.min(...vals);
462
- let hi = Math.max(...vals);
463
- if (includeZero) {
464
- lo = Math.min(0, lo);
465
- hi = Math.max(0, hi);
466
- }
467
- const s = scaleLinear().domain([lo, hi]);
468
- s.nice();
469
- const [dLo, dHi] = s.domain();
470
- return [dLo, dHi];
471
- };
472
-
473
- const [min0, max0] = niced(vals0, includeZero0);
474
- const [min1, max1] = niced(vals1, includeZero1);
475
-
476
- const span0 = max0 - min0;
477
- const span1 = max1 - min1;
478
- if (span0 === 0 || span1 === 0) return undefined;
479
-
480
- const zf0 = (0 - min0) / span0;
481
- const zf1 = (0 - min1) / span1;
482
-
483
- const zeroInDomain0 = zf0 >= -0.001 && zf0 <= 1.001;
484
- const zeroInDomain1 = zf1 >= -0.001 && zf1 <= 1.001;
485
- if (!zeroInDomain0 || !zeroInDomain1) return undefined;
486
-
487
- if (Math.abs(zf0 - zf1) < 0.001) {
488
- return { domain0: [min0, max0], domain1: [min1, max1] };
489
- }
490
-
491
- const targetZf = Math.max(zf0, zf1);
492
-
493
- const align = (dMin: number, dMax: number, currentZf: number): [number, number] => {
494
- if (Math.abs(currentZf - targetZf) < 0.001) return [dMin, dMax];
495
-
496
- if (targetZf > currentZf) {
497
- const newMin = -(targetZf / (1 - targetZf)) * dMax;
498
- return [newMin, dMax];
499
- }
500
- const newMax = (-dMin * (1 - targetZf)) / targetZf;
501
- return [dMin, newMax];
502
- };
503
-
504
- const domain0 = align(min0, max0, zf0);
505
- const domain1 = align(min1, max1, zf1);
506
-
507
- return { domain0, domain1 };
508
- }
509
-
510
- function withYDomain(leaf: ChartSpec, domain: [number, number]): ChartSpec {
511
- if (!leaf.encoding?.y) return leaf;
512
- return {
513
- ...leaf,
514
- encoding: {
515
- ...leaf.encoding,
516
- y: {
517
- ...leaf.encoding.y,
518
- scale: {
519
- ...leaf.encoding.y.scale,
520
- domain,
521
- },
522
- },
523
- },
524
- } as ChartSpec;
525
- }
526
-
527
- type SharedDomains = { x?: [number, number]; y?: [number, number] };
528
-
529
- /**
530
- * Union the quantitative x/y extents across every leaf.
531
- *
532
- * Only channels that every leaf encodes *quantitatively* are unioned — a leaf
533
- * mixing a nominal x with a quantitative one has no common numeric domain, and
534
- * an author-pinned `scale.domain` on any leaf is left to win on its own.
535
- */
536
- function computeSharedDomains(leaves: ChartSpec[]): SharedDomains {
537
- const shared: SharedDomains = {};
538
-
539
- for (const channel of ['x', 'y'] as const) {
540
- let lo = Number.POSITIVE_INFINITY;
541
- let hi = Number.NEGATIVE_INFINITY;
542
- let sawAny = false;
543
- let usable = true;
544
-
545
- for (const leaf of leaves) {
546
- const enc = (leaf.encoding as Encoding | undefined)?.[channel];
547
- // Skip *this channel* if any leaf can't take part: no encoding, a
548
- // non-quantitative type, or a domain the author already pinned. Bailing
549
- // out of the whole function here would abandon the other channel too --
550
- // a nominal x would silently strand a quantitative y, which is the most
551
- // common layered shape there is (bars plus their value labels).
552
- if (!enc || !('field' in enc) || enc.type !== 'quantitative' || enc.scale?.domain) {
553
- usable = false;
554
- break;
555
- }
556
-
557
- for (const row of leaf.data ?? []) {
558
- const v = Number((row as DataRow)[enc.field]);
559
- if (!Number.isFinite(v)) continue;
560
- if (v < lo) lo = v;
561
- if (v > hi) hi = v;
562
- sawAny = true;
563
- }
564
- }
565
-
566
- if (!usable || !sawAny || lo > hi) continue;
567
-
568
- // Pin the union through zero the way an unpinned scale would.
569
- //
570
- // `withSharedDomains` writes this extent onto each leaf as `scale.domain`,
571
- // and `resolveQuantitativeScale` takes an explicit domain *verbatim* --
572
- // skipping the `zero !== false` baselining it would otherwise apply. So a
573
- // raw [50, 100] union lands as a literal domain and the 50-bar collapses
574
- // to a sliver against its own baseline. Fold zero in here, honouring an
575
- // explicit `zero: false` on any leaf (a sparkline opting out of it).
576
- const wantsZero = leaves.every((leaf) => {
577
- const enc = (leaf.encoding as Encoding | undefined)?.[channel];
578
- return enc && 'scale' in enc ? enc.scale?.zero !== false : true;
579
- });
580
- shared[channel] = wantsZero ? [Math.min(0, lo), Math.max(0, hi)] : [lo, hi];
581
- }
582
-
583
- return shared;
584
- }
585
-
586
- /** Pin the shared domains onto a leaf's quantitative x/y channels. */
587
- function withSharedDomains(leaf: ChartSpec, shared: SharedDomains): ChartSpec {
588
- if (!shared.x && !shared.y) return leaf;
589
-
590
- const encoding = { ...(leaf.encoding as Record<string, unknown>) };
591
-
592
- for (const channel of ['x', 'y'] as const) {
593
- const domain = shared[channel];
594
- const ch = encoding[channel] as Record<string, unknown> | undefined;
595
- if (!domain || !ch) continue;
596
- encoding[channel] = {
597
- ...ch,
598
- scale: { ...((ch.scale as object) ?? {}), domain },
599
- };
600
- }
601
-
602
- // ChartSpec is a union discriminated on `mark`, and spreading widens the
603
- // encoding past whichever member `leaf` is, so re-assert the original type.
604
- return { ...leaf, encoding } as unknown as ChartSpec;
605
- }
606
-
607
- function buildPrimarySpec(leaves: ChartSpec[], layerSpec: LayerSpec): ChartSpec {
608
- const allData = leaves.flatMap((leaf) => leaf.data);
609
-
610
- const primary = {
611
- ...leaves[0],
612
- data: allData,
613
- chrome: layerSpec.chrome ?? leaves[0].chrome,
614
- // Annotations come from the parent LayerSpec when present, otherwise
615
- // the first flattened leaf's. Later leaves' annotations are silently
616
- // dropped. The dual-axis path (compileLayerIndependent) explicitly
617
- // clears the secondary axis spec's annotations.
618
- annotations: layerSpec.annotations ?? leaves[0].annotations,
619
- labels: layerSpec.labels ?? leaves[0].labels,
620
- legend: layerSpec.legend ?? leaves[0].legend,
621
- responsive: layerSpec.responsive ?? leaves[0].responsive,
622
- theme: layerSpec.theme ?? leaves[0].theme,
623
- darkMode: layerSpec.darkMode ?? leaves[0].darkMode,
624
- watermark: layerSpec.watermark ?? leaves[0].watermark,
625
- hiddenSeries: layerSpec.hiddenSeries ?? leaves[0].hiddenSeries,
626
- endpointLabels: layerSpec.endpointLabels ?? leaves[0].endpointLabels,
627
- };
628
-
629
- return primary;
630
- }