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

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 +0 -7
  2. package/dist/index.js +161 -579
  3. package/dist/index.js.map +1 -1
  4. package/package.json +4 -3
  5. package/src/__test-fixtures__/specs.ts +182 -0
  6. package/src/__tests__/__snapshots__/compile-snapshot.test.ts.snap +2339 -0
  7. package/src/__tests__/annotation-behavior.test.ts +721 -0
  8. package/src/__tests__/axes.test.ts +1579 -0
  9. package/src/__tests__/compile-animation.test.ts +161 -0
  10. package/src/__tests__/compile-chart.test.ts +1303 -0
  11. package/src/__tests__/compile-footnotes.test.ts +277 -0
  12. package/src/__tests__/compile-layer.test.ts +969 -0
  13. package/src/__tests__/compile-snapshot.test.ts +156 -0
  14. package/src/__tests__/compound-labels.test.ts +147 -0
  15. package/src/__tests__/dimensions.test.ts +918 -0
  16. package/src/__tests__/encoding-sugar.test.ts +390 -0
  17. package/src/__tests__/facet.test.ts +215 -0
  18. package/src/__tests__/helpers/invariants.ts +299 -0
  19. package/src/__tests__/known-bugs.test.ts +566 -0
  20. package/src/__tests__/layout-fuzz.test.ts +358 -0
  21. package/src/__tests__/layout-invariants.test.ts +535 -0
  22. package/src/__tests__/legend.test.ts +721 -0
  23. package/src/__tests__/mark-keys.test.ts +294 -0
  24. package/src/__tests__/ranking-recipes.test.ts +260 -0
  25. package/src/__tests__/rotation.test.ts +83 -0
  26. package/src/__tests__/scales.test.ts +323 -0
  27. package/src/__tests__/series-search.test.ts +92 -0
  28. package/src/__tests__/spec-sugar.test.ts +801 -0
  29. package/src/__tests__/you-draw-it.test.ts +160 -0
  30. package/src/annotations/__tests__/compute.test.ts +1672 -0
  31. package/src/annotations/__tests__/geometry.test.ts +66 -0
  32. package/src/annotations/__tests__/placement-fuzz.test.ts +256 -0
  33. package/src/annotations/__tests__/placement-invariants.test.ts +345 -0
  34. package/src/annotations/__tests__/placement.test.ts +316 -0
  35. package/src/annotations/__tests__/resolve-text.test.ts +788 -0
  36. package/src/annotations/__tests__/rich-text.test.ts +91 -0
  37. package/src/annotations/__tests__/thinning.test.ts +285 -0
  38. package/src/annotations/collisions.ts +326 -0
  39. package/src/annotations/compute.ts +333 -0
  40. package/src/annotations/constants.ts +162 -0
  41. package/src/annotations/geometry.ts +370 -0
  42. package/src/annotations/move.ts +135 -0
  43. package/src/annotations/placement.ts +636 -0
  44. package/src/annotations/position.ts +131 -0
  45. package/src/annotations/resolve-range.ts +117 -0
  46. package/src/annotations/resolve-refline.ts +157 -0
  47. package/src/annotations/resolve-text.ts +539 -0
  48. package/src/annotations/rich-text.ts +65 -0
  49. package/src/annotations/thinning.ts +190 -0
  50. package/src/barlist/__tests__/compile-barlist.test.ts +200 -0
  51. package/src/barlist/compile-barlist.ts +391 -0
  52. package/src/barlist/types.ts +28 -0
  53. package/src/charts/__tests__/post-process.test.ts +237 -0
  54. package/src/charts/__tests__/registry.test.ts +116 -0
  55. package/src/charts/__tests__/utils.test.ts +195 -0
  56. package/src/charts/_shared/__tests__/density-filter.test.ts +32 -0
  57. package/src/charts/_shared/density-filter.ts +26 -0
  58. package/src/charts/_shared/format-label-value.ts +16 -0
  59. package/src/charts/bar/__tests__/compute.test.ts +934 -0
  60. package/src/charts/bar/__tests__/gradient-orient.test.ts +127 -0
  61. package/src/charts/bar/__tests__/labels.test.ts +292 -0
  62. package/src/charts/bar/compute.ts +539 -0
  63. package/src/charts/bar/index.ts +60 -0
  64. package/src/charts/bar/labels.ts +311 -0
  65. package/src/charts/beeswarm/__tests__/compute.test.ts +280 -0
  66. package/src/charts/beeswarm/__tests__/dodge.test.ts +148 -0
  67. package/src/charts/beeswarm/compute.ts +203 -0
  68. package/src/charts/beeswarm/dodge.ts +155 -0
  69. package/src/charts/beeswarm/index.ts +32 -0
  70. package/src/charts/builtin.ts +75 -0
  71. package/src/charts/calendar/__tests__/compute.test.ts +417 -0
  72. package/src/charts/calendar/compute.ts +319 -0
  73. package/src/charts/calendar/index.ts +32 -0
  74. package/src/charts/column/__tests__/compute.test.ts +540 -0
  75. package/src/charts/column/__tests__/labels.test.ts +179 -0
  76. package/src/charts/column/compute.ts +493 -0
  77. package/src/charts/column/index.ts +53 -0
  78. package/src/charts/column/labels.ts +229 -0
  79. package/src/charts/dot/__tests__/compute.test.ts +380 -0
  80. package/src/charts/dot/__tests__/labels.test.ts +98 -0
  81. package/src/charts/dot/compute.ts +285 -0
  82. package/src/charts/dot/index.ts +62 -0
  83. package/src/charts/dot/labels.ts +121 -0
  84. package/src/charts/line/__tests__/compute.test.ts +1194 -0
  85. package/src/charts/line/__tests__/curves.test.ts +51 -0
  86. package/src/charts/line/__tests__/labels.test.ts +94 -0
  87. package/src/charts/line/__tests__/mark-options.test.ts +175 -0
  88. package/src/charts/line/area.ts +484 -0
  89. package/src/charts/line/compute.ts +356 -0
  90. package/src/charts/line/curves.ts +85 -0
  91. package/src/charts/line/index.ts +176 -0
  92. package/src/charts/line/labels.ts +177 -0
  93. package/src/charts/parliament/__tests__/compute.test.ts +411 -0
  94. package/src/charts/parliament/compute.ts +313 -0
  95. package/src/charts/parliament/index.ts +32 -0
  96. package/src/charts/pie/__tests__/compute.test.ts +384 -0
  97. package/src/charts/pie/__tests__/labels.test.ts +132 -0
  98. package/src/charts/pie/compute.ts +324 -0
  99. package/src/charts/pie/index.ts +49 -0
  100. package/src/charts/pie/labels.ts +143 -0
  101. package/src/charts/post-process.ts +229 -0
  102. package/src/charts/range/__tests__/compute.test.ts +486 -0
  103. package/src/charts/range/compute.ts +273 -0
  104. package/src/charts/range/index.ts +82 -0
  105. package/src/charts/range/labels.ts +169 -0
  106. package/src/charts/rect/__tests__/compute.test.ts +120 -0
  107. package/src/charts/rect/index.ts +127 -0
  108. package/src/charts/registry.ts +72 -0
  109. package/src/charts/rule/index.ts +139 -0
  110. package/src/charts/scatter/__tests__/compute.test.ts +488 -0
  111. package/src/charts/scatter/__tests__/trendline.test.ts +191 -0
  112. package/src/charts/scatter/compute.ts +192 -0
  113. package/src/charts/scatter/index.ts +46 -0
  114. package/src/charts/scatter/trendline.ts +100 -0
  115. package/src/charts/text/__tests__/compute.test.ts +307 -0
  116. package/src/charts/text/index.ts +141 -0
  117. package/src/charts/tick/__tests__/compute.test.ts +75 -0
  118. package/src/charts/tick/index.ts +99 -0
  119. package/src/charts/utils.ts +170 -0
  120. package/src/charts/waffle/__tests__/compute.test.ts +305 -0
  121. package/src/charts/waffle/compute.ts +197 -0
  122. package/src/charts/waffle/index.ts +31 -0
  123. package/src/compile/__tests__/color-scale-range.test.ts +158 -0
  124. package/src/compile/__tests__/color-scale-reverse.test.ts +89 -0
  125. package/src/compile/__tests__/data-clip.test.ts +127 -0
  126. package/src/compile/__tests__/fill-patterns.test.ts +154 -0
  127. package/src/compile/__tests__/size-scale.test.ts +108 -0
  128. package/src/compile/__tests__/watermark-obstacle.test.ts +93 -0
  129. package/src/compile/color-scale-range.ts +101 -0
  130. package/src/compile/data-clip.ts +48 -0
  131. package/src/compile/fill-patterns.ts +74 -0
  132. package/src/compile/layer.ts +626 -0
  133. package/src/compile/size-scale.ts +141 -0
  134. package/src/compile/spec-sugar.ts +758 -0
  135. package/src/compile/watermark-obstacle.ts +54 -0
  136. package/src/compile/you-draw-it.ts +123 -0
  137. package/src/compile.ts +1450 -0
  138. package/src/compiler/__tests__/a11y-warnings.test.ts +148 -0
  139. package/src/compiler/__tests__/animation.test.ts +177 -0
  140. package/src/compiler/__tests__/compile.test.ts +87 -0
  141. package/src/compiler/__tests__/fixtures/vl-parity/axis-null.json +19 -0
  142. package/src/compiler/__tests__/fixtures/vl-parity/color-value.json +20 -0
  143. package/src/compiler/__tests__/fixtures/vl-parity/count-aggregate.json +22 -0
  144. package/src/compiler/__tests__/fixtures/vl-parity/data-values.json +19 -0
  145. package/src/compiler/__tests__/fixtures/vl-parity/layer-axis-null.json +14 -0
  146. package/src/compiler/__tests__/fixtures/vl-parity/layer-count.json +34 -0
  147. package/src/compiler/__tests__/fixtures/vl-parity/layer-data-values.json +22 -0
  148. package/src/compiler/__tests__/fixtures/vl-parity/layer-legend-null.json +41 -0
  149. package/src/compiler/__tests__/fixtures/vl-parity/layer-scheme.json +38 -0
  150. package/src/compiler/__tests__/fixtures/vl-parity/layer-sort.json +28 -0
  151. package/src/compiler/__tests__/fixtures/vl-parity/layer-theta.json +28 -0
  152. package/src/compiler/__tests__/fixtures/vl-parity/layer-title.json +30 -0
  153. package/src/compiler/__tests__/fixtures/vl-parity/layer-value-def.json +29 -0
  154. package/src/compiler/__tests__/fixtures/vl-parity/legend-null.json +32 -0
  155. package/src/compiler/__tests__/fixtures/vl-parity/scheme.json +25 -0
  156. package/src/compiler/__tests__/fixtures/vl-parity/sort-by-value.json +19 -0
  157. package/src/compiler/__tests__/fixtures/vl-parity/theta-arc.json +19 -0
  158. package/src/compiler/__tests__/fixtures/vl-parity/title-subtitle.json +21 -0
  159. package/src/compiler/__tests__/fixtures/vl-parity/width-height.json +23 -0
  160. package/src/compiler/__tests__/keys.test.ts +83 -0
  161. package/src/compiler/__tests__/normalize-highlight.test.ts +103 -0
  162. package/src/compiler/__tests__/normalize.test.ts +399 -0
  163. package/src/compiler/__tests__/sparkline-defaults.test.ts +153 -0
  164. package/src/compiler/__tests__/validate-did-you-mean.test.ts +86 -0
  165. package/src/compiler/__tests__/validate-highlight.test.ts +112 -0
  166. package/src/compiler/__tests__/validate-near-miss.test.ts +89 -0
  167. package/src/compiler/__tests__/validate.test.ts +629 -0
  168. package/src/compiler/__tests__/vl-parity.test.ts +68 -0
  169. package/src/compiler/a11y-warnings.ts +110 -0
  170. package/src/compiler/animation.ts +142 -0
  171. package/src/compiler/index.ts +47 -0
  172. package/src/compiler/keys.ts +55 -0
  173. package/src/compiler/normalize.ts +734 -0
  174. package/src/compiler/sparkline-defaults.ts +138 -0
  175. package/src/compiler/types.ts +241 -0
  176. package/src/compiler/validate.ts +1871 -0
  177. package/src/endpoint-labels/__tests__/compute.test.ts +587 -0
  178. package/src/endpoint-labels/compute.ts +621 -0
  179. package/src/endpoint-labels/constants.ts +54 -0
  180. package/src/endpoint-labels/format.ts +60 -0
  181. package/src/endpoint-labels/predict.ts +139 -0
  182. package/src/format/__tests__/field-format.test.ts +164 -0
  183. package/src/format/field-format.ts +27 -0
  184. package/src/geo/__tests__/compile-map.test.ts +832 -0
  185. package/src/geo/compile-map.ts +1243 -0
  186. package/src/geo/join.ts +115 -0
  187. package/src/geo/projections.ts +45 -0
  188. package/src/geo/types.ts +26 -0
  189. package/src/graphs/__tests__/community.test.ts +228 -0
  190. package/src/graphs/__tests__/compile-graph.test.ts +396 -0
  191. package/src/graphs/__tests__/encoding.test.ts +415 -0
  192. package/src/graphs/community.ts +92 -0
  193. package/src/graphs/compile-graph.ts +329 -0
  194. package/src/graphs/encoding.ts +356 -0
  195. package/src/graphs/types.ts +106 -0
  196. package/src/index.ts +177 -0
  197. package/src/layout/__tests__/metrics.test.ts +97 -0
  198. package/src/layout/__tests__/scales-highlight.test.ts +192 -0
  199. package/src/layout/axes/rotation.ts +152 -0
  200. package/src/layout/axes/thinning.ts +98 -0
  201. package/src/layout/axes/ticks.ts +409 -0
  202. package/src/layout/axes.ts +757 -0
  203. package/src/layout/dimensions.ts +912 -0
  204. package/src/layout/facet.ts +91 -0
  205. package/src/layout/gridlines.ts +84 -0
  206. package/src/layout/metrics.ts +132 -0
  207. package/src/layout/plan.ts +631 -0
  208. package/src/layout/scales.ts +1053 -0
  209. package/src/layout/shared.ts +44 -0
  210. package/src/legend/__tests__/continuous.test.ts +318 -0
  211. package/src/legend/__tests__/redundancy.test.ts +108 -0
  212. package/src/legend/__tests__/size.test.ts +348 -0
  213. package/src/legend/__tests__/suppression.test.ts +382 -0
  214. package/src/legend/compute.ts +747 -0
  215. package/src/legend/continuous.ts +327 -0
  216. package/src/legend/size.ts +407 -0
  217. package/src/legend/suppression.ts +226 -0
  218. package/src/legend/wrap.ts +117 -0
  219. package/src/sankey/__tests__/compile-sankey.test.ts +458 -0
  220. package/src/sankey/__tests__/layout.test.ts +165 -0
  221. package/src/sankey/__tests__/node-label-wrap.test.ts +114 -0
  222. package/src/sankey/__tests__/node-sort.test.ts +45 -0
  223. package/src/sankey/compile-sankey.ts +706 -0
  224. package/src/sankey/layout.ts +184 -0
  225. package/src/sankey/types.ts +41 -0
  226. package/src/tables/__tests__/bar-column.test.ts +147 -0
  227. package/src/tables/__tests__/category-colors.test.ts +230 -0
  228. package/src/tables/__tests__/compile-table.test.ts +236 -0
  229. package/src/tables/__tests__/format-cells.test.ts +143 -0
  230. package/src/tables/__tests__/heatmap.test.ts +148 -0
  231. package/src/tables/__tests__/pagination.test.ts +78 -0
  232. package/src/tables/__tests__/search.test.ts +94 -0
  233. package/src/tables/__tests__/sort.test.ts +107 -0
  234. package/src/tables/__tests__/sparkline.test.ts +122 -0
  235. package/src/tables/bar-column.ts +94 -0
  236. package/src/tables/category-colors.ts +78 -0
  237. package/src/tables/compile-table.ts +427 -0
  238. package/src/tables/format-cells.ts +115 -0
  239. package/src/tables/heatmap.ts +141 -0
  240. package/src/tables/pagination.ts +46 -0
  241. package/src/tables/search.ts +66 -0
  242. package/src/tables/sort.ts +69 -0
  243. package/src/tables/sparkline.ts +113 -0
  244. package/src/tables/utils.ts +16 -0
  245. package/src/tilemap/__tests__/compile-tilemap.test.ts +576 -0
  246. package/src/tilemap/compile-tilemap.ts +755 -0
  247. package/src/tilemap/layout.ts +172 -0
  248. package/src/tilemap/types.ts +33 -0
  249. package/src/tooltips/__tests__/compute.test.ts +582 -0
  250. package/src/tooltips/compute.ts +700 -0
  251. package/src/transforms/__tests__/aggregate.test.ts +159 -0
  252. package/src/transforms/__tests__/bin.test.ts +88 -0
  253. package/src/transforms/__tests__/calculate.test.ts +146 -0
  254. package/src/transforms/__tests__/conditional.test.ts +127 -0
  255. package/src/transforms/__tests__/filter-relative.test.ts +202 -0
  256. package/src/transforms/__tests__/filter.test.ts +59 -0
  257. package/src/transforms/__tests__/fold.test.ts +79 -0
  258. package/src/transforms/__tests__/index.test.ts +93 -0
  259. package/src/transforms/__tests__/predicates.test.ts +193 -0
  260. package/src/transforms/__tests__/timeunit.test.ts +129 -0
  261. package/src/transforms/__tests__/window.test.ts +286 -0
  262. package/src/transforms/aggregate.ts +131 -0
  263. package/src/transforms/bin.ts +87 -0
  264. package/src/transforms/calculate.ts +60 -0
  265. package/src/transforms/conditional.ts +46 -0
  266. package/src/transforms/filter.ts +122 -0
  267. package/src/transforms/fold.ts +49 -0
  268. package/src/transforms/index.ts +60 -0
  269. package/src/transforms/predicates.ts +123 -0
  270. package/src/transforms/timeunit.ts +88 -0
  271. package/src/transforms/window.ts +185 -0
@@ -0,0 +1,626 @@
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: layerSpec.annotations ?? leaves[0].annotations,
615
+ labels: layerSpec.labels ?? leaves[0].labels,
616
+ legend: layerSpec.legend ?? leaves[0].legend,
617
+ responsive: layerSpec.responsive ?? leaves[0].responsive,
618
+ theme: layerSpec.theme ?? leaves[0].theme,
619
+ darkMode: layerSpec.darkMode ?? leaves[0].darkMode,
620
+ watermark: layerSpec.watermark ?? leaves[0].watermark,
621
+ hiddenSeries: layerSpec.hiddenSeries ?? leaves[0].hiddenSeries,
622
+ endpointLabels: layerSpec.endpointLabels ?? leaves[0].endpointLabels,
623
+ };
624
+
625
+ return primary;
626
+ }