@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,706 @@
1
+ /**
2
+ * Sankey diagram compilation pipeline.
3
+ *
4
+ * Takes a raw sankey spec (unknown shape), validates, normalizes, resolves
5
+ * theme, computes chrome, runs d3-sankey layout, builds marks with colors
6
+ * and labels, and returns a SankeyLayout.
7
+ *
8
+ * Pipeline:
9
+ * validate -> normalize -> resolve theme -> dark mode adapt ->
10
+ * compute chrome -> compute drawing area -> d3-sankey layout ->
11
+ * build node marks -> build link marks -> legend -> tooltips ->
12
+ * a11y -> animation -> return SankeyLayout
13
+ */
14
+
15
+ import type {
16
+ CompileOptions,
17
+ LegendEntry,
18
+ LegendLayout,
19
+ NumberFormatter,
20
+ Rect,
21
+ ResolvedAnimation,
22
+ ResolvedTheme,
23
+ SankeyLayout,
24
+ SankeyLinkMark,
25
+ SankeyNodeMark,
26
+ TextStyle,
27
+ TooltipContent,
28
+ TooltipField,
29
+ } from '@opendata-ai/openchart-core';
30
+ import {
31
+ adaptTheme,
32
+ computeChrome,
33
+ defaultNumberFormatter,
34
+ estimateTextWidth,
35
+ resolveTheme,
36
+ } from '@opendata-ai/openchart-core';
37
+ import { emitSpecWarnings, expandSpecSugar } from '../compile/spec-sugar';
38
+ import { resolveAnimation } from '../compiler/animation';
39
+ import { compile as compileSpec } from '../compiler/index';
40
+ import { resolveFieldFormatter } from '../format/field-format';
41
+ import { ENTRY_GAP, measureLegendWrap, SWATCH_GAP, SWATCH_SIZE } from '../legend/wrap';
42
+ import { type ComputedNode, computeSankeyLayout, generateLinkPath } from './layout';
43
+ import type { NormalizedSankeySpec } from './types';
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Constants
47
+ // ---------------------------------------------------------------------------
48
+
49
+ const LABEL_GAP = 6;
50
+ const LINK_OPACITY_LIGHT = 0.5;
51
+ const LINK_OPACITY_DARK = 0.75;
52
+ const NODE_CORNER_RADIUS = 2;
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // Helpers
56
+ // ---------------------------------------------------------------------------
57
+
58
+ /** Assign a color from the categorical palette, cycling through it. */
59
+ function pickColor(palette: string[], index: number): string {
60
+ return palette[index % palette.length];
61
+ }
62
+
63
+ /**
64
+ * Build a color map for nodes.
65
+ * If encoding.color is specified, groups by that field's value.
66
+ * Otherwise, assigns by unique node ID cycling the palette.
67
+ * Accepts any array with `id` field (works with ComputedNode[] or plain objects).
68
+ */
69
+ function buildNodeColorMap(
70
+ nodes: Array<{ id: string }>,
71
+ palette: string[],
72
+ colorField: string | undefined,
73
+ data: Record<string, unknown>[],
74
+ sourceField: string,
75
+ targetField: string,
76
+ ): Map<string, string> {
77
+ const colorMap = new Map<string, string>();
78
+
79
+ if (colorField) {
80
+ // Build a mapping from node ID to color category value
81
+ const nodeCategoryMap = new Map<string, string>();
82
+ for (const row of data) {
83
+ const src = String(row[sourceField]);
84
+ const tgt = String(row[targetField]);
85
+ const cat = String(row[colorField]);
86
+ if (!nodeCategoryMap.has(src)) nodeCategoryMap.set(src, cat);
87
+ if (!nodeCategoryMap.has(tgt)) nodeCategoryMap.set(tgt, cat);
88
+ }
89
+
90
+ // Assign colors by unique category
91
+ const categoryIndex = new Map<string, number>();
92
+ let nextIdx = 0;
93
+ for (const node of nodes) {
94
+ const category = nodeCategoryMap.get(node.id) ?? node.id;
95
+ if (!categoryIndex.has(category)) {
96
+ categoryIndex.set(category, nextIdx++);
97
+ }
98
+ colorMap.set(node.id, pickColor(palette, categoryIndex.get(category)!));
99
+ }
100
+ } else {
101
+ // Default: assign colors cycling through palette by node order
102
+ for (let i = 0; i < nodes.length; i++) {
103
+ colorMap.set(nodes[i].id, pickColor(palette, i));
104
+ }
105
+ }
106
+
107
+ return colorMap;
108
+ }
109
+
110
+ /**
111
+ * Get colors for a link based on the linkStyle strategy.
112
+ */
113
+ function getLinkColors(
114
+ linkStyle: string,
115
+ sourceColor: string,
116
+ targetColor: string,
117
+ neutralColor: string,
118
+ ): { sourceColor: string; targetColor: string } {
119
+ switch (linkStyle) {
120
+ case 'source':
121
+ return { sourceColor, targetColor: sourceColor };
122
+ case 'target':
123
+ return { sourceColor: targetColor, targetColor };
124
+ case 'neutral':
125
+ return { sourceColor: neutralColor, targetColor: neutralColor };
126
+ default:
127
+ return { sourceColor, targetColor };
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Determine label position for a node based on its column depth.
133
+ * Default ('auto'): leftmost/middle columns label right, rightmost column labels left.
134
+ * 'right': all labels to the right. 'left': all labels to the left.
135
+ */
136
+ function computeNodeLabel(
137
+ node: ComputedNode,
138
+ maxDepth: number,
139
+ theme: ResolvedTheme,
140
+ nodeWidth: number,
141
+ nodeLabelAlign: 'auto' | 'left' | 'right' = 'auto',
142
+ containerWidth?: number,
143
+ padding?: number,
144
+ ): SankeyNodeMark['label'] {
145
+ const depth = node.depth ?? 0;
146
+
147
+ // Determine which side to place the label
148
+ let placeLeft: boolean;
149
+ if (nodeLabelAlign === 'left') {
150
+ placeLeft = true;
151
+ } else if (nodeLabelAlign === 'right') {
152
+ placeLeft = false;
153
+ } else {
154
+ // 'auto': rightmost column goes left, everything else goes right
155
+ placeLeft = depth === maxDepth;
156
+ }
157
+
158
+ const style: TextStyle = {
159
+ fontFamily: theme.fonts.family,
160
+ fontSize: theme.fonts.sizes.small,
161
+ fontWeight: theme.fonts.weights.normal,
162
+ fill: theme.colors.text,
163
+ lineHeight: 1.3,
164
+ };
165
+
166
+ const x0 = node.x0 ?? 0;
167
+ const x1 = node.x1 ?? nodeWidth;
168
+ const y0 = node.y0 ?? 0;
169
+ const y1 = node.y1 ?? 0;
170
+ const midY = (y0 + y1) / 2;
171
+
172
+ // Compute maxWidth: space from label position to the container edge
173
+ const pad = padding ?? 0;
174
+ let maxWidth: number | undefined;
175
+ if (containerWidth !== undefined) {
176
+ if (placeLeft) {
177
+ // Label goes left from x0: available space is from left padding to x0
178
+ maxWidth = x0 - LABEL_GAP - pad;
179
+ } else {
180
+ // Label goes right from x1: available space is from x1 to right edge
181
+ maxWidth = containerWidth - pad - (x1 + LABEL_GAP);
182
+ }
183
+ if (maxWidth !== undefined && maxWidth < 0) maxWidth = 0;
184
+ }
185
+
186
+ if (placeLeft) {
187
+ return {
188
+ text: node.label ?? node.id,
189
+ x: x0 - LABEL_GAP,
190
+ y: midY,
191
+ style: { ...style, textAnchor: 'end', dominantBaseline: 'central' },
192
+ visible: true,
193
+ maxWidth,
194
+ };
195
+ }
196
+
197
+ return {
198
+ text: node.label ?? node.id,
199
+ x: x1 + LABEL_GAP,
200
+ y: midY,
201
+ style: { ...style, textAnchor: 'start', dominantBaseline: 'central' },
202
+ visible: true,
203
+ maxWidth,
204
+ };
205
+ }
206
+
207
+ // ---------------------------------------------------------------------------
208
+ // Public API
209
+ // ---------------------------------------------------------------------------
210
+
211
+ /**
212
+ * Compile a sankey spec into a SankeyLayout.
213
+ *
214
+ * @param spec - Raw sankey spec (validated at runtime).
215
+ * @param options - Compile options (width, height, theme, darkMode).
216
+ * @returns SankeyLayout with all computed positions and visual properties.
217
+ * @throws Error if spec is invalid or not a sankey type.
218
+ */
219
+ export function compileSankey(spec: unknown, options: CompileOptions): SankeyLayout {
220
+ // 1. Expand deprecated top-level sugar (valueFormat -> encoding.value.format)
221
+ // before validation, then validate + normalize via the shared compiler pipeline.
222
+ const sugarWarnings: string[] = [];
223
+ const expandedSpec =
224
+ spec && typeof spec === 'object' && !Array.isArray(spec)
225
+ ? expandSpecSugar(spec as Record<string, unknown>, sugarWarnings)
226
+ : spec;
227
+ const { spec: normalized, warnings } = compileSpec(expandedSpec);
228
+ emitSpecWarnings([...sugarWarnings, ...warnings], options.onWarn);
229
+
230
+ if (!('type' in normalized) || normalized.type !== 'sankey') {
231
+ throw new Error(
232
+ 'compileSankey received a non-sankey spec. Use compileChart, compileTable, or compileGraph instead.',
233
+ );
234
+ }
235
+
236
+ const sankeySpec = normalized as NormalizedSankeySpec;
237
+
238
+ // Resolve format: encoding-level (v8 canonical) wins over deprecated top-level valueFormat
239
+ const resolvedValueFormat = sankeySpec.encoding.value.format ?? sankeySpec.valueFormat;
240
+
241
+ // Resolve watermark: explicit spec value wins, then options fallback, then default true.
242
+ const rawWatermark = (spec as Record<string, unknown>).watermark;
243
+ const watermark = rawWatermark !== undefined ? sankeySpec.watermark : (options.watermark ?? true);
244
+
245
+ // 2. Resolve theme
246
+ const mergedThemeConfig = options.theme
247
+ ? { ...sankeySpec.theme, ...options.theme }
248
+ : sankeySpec.theme;
249
+ const lightTheme: ResolvedTheme = resolveTheme(mergedThemeConfig);
250
+ let theme: ResolvedTheme = lightTheme;
251
+ if (options.darkMode) {
252
+ theme = adaptTheme(theme);
253
+ // Sankey nodes and link gradients need vivid colors that stand out on dark
254
+ // backgrounds. The adapted palette preserves contrast ratios designed for
255
+ // text, but those contrast-matched colors are too dark for filled shapes.
256
+ // Use the original light-theme categorical palette for node/link colors.
257
+ theme = {
258
+ ...theme,
259
+ colors: { ...theme.colors, categorical: lightTheme.colors.categorical },
260
+ };
261
+ }
262
+
263
+ // 3. Compute chrome
264
+ const chrome = computeChrome(
265
+ {
266
+ title: sankeySpec.chrome.title,
267
+ subtitle: sankeySpec.chrome.subtitle,
268
+ source: sankeySpec.chrome.source,
269
+ byline: sankeySpec.chrome.byline,
270
+ footer: sankeySpec.chrome.footer,
271
+ },
272
+ theme,
273
+ options.width,
274
+ options.measureText,
275
+ 'full',
276
+ undefined,
277
+ watermark,
278
+ );
279
+
280
+ // 4. Compute drawing area (total space minus chrome)
281
+ const padding = theme.spacing.padding;
282
+ const fullArea: Rect = {
283
+ x: padding,
284
+ y: padding + chrome.topHeight,
285
+ width: options.width - padding * 2,
286
+ height: options.height - chrome.topHeight - chrome.bottomHeight - padding * 2,
287
+ };
288
+
289
+ // Guard against negative dimensions
290
+ if (fullArea.width <= 0 || fullArea.height <= 0) {
291
+ return emptyLayout(fullArea, chrome, theme, options, watermark);
292
+ }
293
+
294
+ // 5. Extract encoding fields
295
+ const sourceField = sankeySpec.encoding.source.field;
296
+ const targetField = sankeySpec.encoding.target.field;
297
+ const valueField = sankeySpec.encoding.value.field;
298
+ const colorField = sankeySpec.encoding.color?.field;
299
+ const flowFmt = resolveFieldFormatter({
300
+ surfaceFormat: resolvedValueFormat,
301
+ values: sankeySpec.data.map((r) => r[valueField]),
302
+ });
303
+
304
+ // 5b. Pre-compute legend to reserve vertical space
305
+ // We need the color map first, so build a temporary one from raw data
306
+ const tempNodeIds = new Set<string>();
307
+ for (const row of sankeySpec.data) {
308
+ tempNodeIds.add(String(row[sourceField]));
309
+ tempNodeIds.add(String(row[targetField]));
310
+ }
311
+ const tempColorMap = buildNodeColorMap(
312
+ [...tempNodeIds].map((id) => ({ id })),
313
+ theme.colors.categorical,
314
+ colorField,
315
+ sankeySpec.data,
316
+ sourceField,
317
+ targetField,
318
+ );
319
+ const legend = buildSankeyLegend(
320
+ tempColorMap,
321
+ colorField,
322
+ sankeySpec.data,
323
+ sourceField,
324
+ targetField,
325
+ theme,
326
+ fullArea,
327
+ );
328
+
329
+ // Reserve legend space by shrinking the drawing area
330
+ const legendGap = 'entries' in legend && legend.entries.length > 0 ? 4 : 0;
331
+ const area: Rect = {
332
+ x: fullArea.x,
333
+ y: fullArea.y + legend.bounds.height + legendGap,
334
+ width: fullArea.width,
335
+ height: fullArea.height - legend.bounds.height - legendGap,
336
+ };
337
+
338
+ if (area.height <= 0) {
339
+ return emptyLayout(area, chrome, theme, options, watermark);
340
+ }
341
+
342
+ // 6. Run d3-sankey layout (may re-run once if labels overflow)
343
+ const labelFontSize = theme.fonts.sizes.small;
344
+ const labelFontWeight = theme.fonts.weights.normal;
345
+ const nodeWidth = sankeySpec.nodeWidth ?? 12;
346
+
347
+ let layoutArea: Rect = { ...area };
348
+ let { nodes, links } = computeSankeyLayout(
349
+ sankeySpec.data,
350
+ sourceField,
351
+ targetField,
352
+ valueField,
353
+ layoutArea,
354
+ sankeySpec.nodeWidth,
355
+ sankeySpec.nodePadding,
356
+ sankeySpec.nodeAlign,
357
+ sankeySpec.iterations,
358
+ sankeySpec.nodeSort,
359
+ );
360
+
361
+ // 6b. Check if any right-side node labels overflow the right edge.
362
+ const nodeLabelAlign = sankeySpec.nodeLabelAlign ?? 'auto';
363
+ const maxDepthFirst = nodes.reduce((max, n) => Math.max(max, n.depth ?? 0), 0);
364
+ const rightEdge = area.x + area.width;
365
+ let maxOverflow = 0;
366
+ for (const node of nodes) {
367
+ const depth = node.depth ?? 0;
368
+ // Skip nodes whose labels go left (they can't overflow the right edge)
369
+ const labelsLeft =
370
+ nodeLabelAlign === 'left' || (nodeLabelAlign === 'auto' && depth === maxDepthFirst);
371
+ if (labelsLeft) continue;
372
+ const labelX = (node.x1 ?? nodeWidth) + LABEL_GAP;
373
+ const labelText = node.label ?? node.id;
374
+ const labelWidth = estimateTextWidth(labelText, labelFontSize, labelFontWeight);
375
+ const overflow = labelX + labelWidth - rightEdge;
376
+ if (overflow > maxOverflow) maxOverflow = overflow;
377
+ }
378
+
379
+ // Re-run layout with tighter width if labels would clip
380
+ if (maxOverflow > 0) {
381
+ const margin = Math.ceil(maxOverflow) + 4; // small extra buffer
382
+ layoutArea = {
383
+ x: area.x,
384
+ y: area.y,
385
+ width: Math.max(area.width - margin, 40),
386
+ height: area.height,
387
+ };
388
+ ({ nodes, links } = computeSankeyLayout(
389
+ sankeySpec.data,
390
+ sourceField,
391
+ targetField,
392
+ valueField,
393
+ layoutArea,
394
+ sankeySpec.nodeWidth,
395
+ sankeySpec.nodePadding,
396
+ sankeySpec.nodeAlign,
397
+ sankeySpec.iterations,
398
+ sankeySpec.nodeSort,
399
+ ));
400
+ }
401
+
402
+ // 7. Build node color map
403
+ const nodeColorMap = buildNodeColorMap(
404
+ nodes,
405
+ theme.colors.categorical,
406
+ colorField,
407
+ sankeySpec.data,
408
+ sourceField,
409
+ targetField,
410
+ );
411
+
412
+ // 8. Compute max depth for label positioning
413
+ const maxDepth = nodes.reduce((max, n) => Math.max(max, n.depth ?? 0), 0);
414
+
415
+ // 9. Build SankeyNodeMark[]
416
+ const nodeMarks: SankeyNodeMark[] = nodes.map((node) => {
417
+ const fill = nodeColorMap.get(node.id) ?? theme.colors.categorical[0];
418
+ const depth = node.depth ?? 0;
419
+
420
+ return {
421
+ type: 'sankeyNode' as const,
422
+ x: node.x0 ?? 0,
423
+ y: node.y0 ?? 0,
424
+ width: (node.x1 ?? 0) - (node.x0 ?? 0),
425
+ height: (node.y1 ?? 0) - (node.y0 ?? 0),
426
+ fill,
427
+ cornerRadius: NODE_CORNER_RADIUS,
428
+ label: computeNodeLabel(
429
+ node,
430
+ maxDepth,
431
+ theme,
432
+ sankeySpec.nodeWidth,
433
+ nodeLabelAlign,
434
+ options.width,
435
+ padding,
436
+ ),
437
+ nodeId: node.id,
438
+ value: node.value ?? 0,
439
+ depth,
440
+ data: { id: node.id, label: node.label },
441
+ aria: {
442
+ role: 'img',
443
+ label: `${node.label}: ${formatFlowValue(node.value ?? 0, flowFmt)}`,
444
+ },
445
+ animationIndex: 0, // Reassigned below after sorting by depth
446
+ };
447
+ });
448
+
449
+ // 10. Assign node animation indices by column (left-to-right, top-to-bottom within column)
450
+ nodeMarks.sort((a, b) => a.depth - b.depth || a.y - b.y);
451
+ for (let i = 0; i < nodeMarks.length; i++) {
452
+ nodeMarks[i].animationIndex = i;
453
+ }
454
+
455
+ // 11. Build SankeyLinkMark[]
456
+ const neutralColor = theme.colors.gridline;
457
+ const linkMarks: SankeyLinkMark[] = links.map((link, i) => {
458
+ const sourceNode = link.source as ComputedNode;
459
+ const targetNode = link.target as ComputedNode;
460
+ const srcColor = nodeColorMap.get(sourceNode.id) ?? theme.colors.categorical[0];
461
+ const tgtColor = nodeColorMap.get(targetNode.id) ?? theme.colors.categorical[0];
462
+ const colors = getLinkColors(sankeySpec.linkStyle, srcColor, tgtColor, neutralColor);
463
+
464
+ return {
465
+ type: 'sankeyLink' as const,
466
+ path: generateLinkPath(link),
467
+ sourceColor: colors.sourceColor,
468
+ targetColor: colors.targetColor,
469
+ fillOpacity:
470
+ sankeySpec.linkOpacity ?? (options.darkMode ? LINK_OPACITY_DARK : LINK_OPACITY_LIGHT),
471
+ sourceId: sourceNode.id,
472
+ targetId: targetNode.id,
473
+ width: link.width ?? 0,
474
+ value: link.value,
475
+ data: (link as unknown as { data: Record<string, unknown> }).data ?? {},
476
+ aria: {
477
+ role: 'img',
478
+ label: `${sourceNode.label} to ${targetNode.label}: ${formatFlowValue(link.value, flowFmt)}`,
479
+ },
480
+ // Links animate after nodes
481
+ animationIndex: nodeMarks.length + i,
482
+ };
483
+ });
484
+
485
+ // 12. Rebuild legend with final color map (temp map may differ in node order)
486
+ const finalLegend = buildSankeyLegend(
487
+ nodeColorMap,
488
+ colorField,
489
+ sankeySpec.data,
490
+ sourceField,
491
+ targetField,
492
+ theme,
493
+ fullArea,
494
+ );
495
+
496
+ // 13. Build tooltip descriptors
497
+ const tooltipDescriptors = buildTooltipDescriptors(nodeMarks, linkMarks, flowFmt);
498
+
499
+ // 14. Build a11y metadata
500
+ const a11y = {
501
+ altText: `Sankey diagram with ${nodeMarks.length} nodes and ${linkMarks.length} links`,
502
+ dataTableFallback: linkMarks.map((l) => [l.sourceId, l.targetId, String(l.value)]),
503
+ role: 'img',
504
+ keyboardNavigable: nodeMarks.length > 0,
505
+ };
506
+
507
+ // 15. Resolve animation
508
+ const resolvedAnimation: ResolvedAnimation | undefined = resolveAnimation(sankeySpec.animation);
509
+
510
+ return {
511
+ area,
512
+ chrome,
513
+ nodes: nodeMarks,
514
+ links: linkMarks,
515
+ legend: finalLegend,
516
+ tooltipDescriptors,
517
+ a11y,
518
+ theme,
519
+ dimensions: {
520
+ width: options.width,
521
+ height: options.height,
522
+ },
523
+ animation: resolvedAnimation,
524
+ watermark,
525
+ measureText: options.measureText,
526
+ };
527
+ }
528
+
529
+ // ---------------------------------------------------------------------------
530
+ // Legend builder
531
+ // ---------------------------------------------------------------------------
532
+
533
+ function buildSankeyLegend(
534
+ nodeColorMap: Map<string, string>,
535
+ colorField: string | undefined,
536
+ data: Record<string, unknown>[],
537
+ sourceField: string,
538
+ targetField: string,
539
+ theme: ResolvedTheme,
540
+ area: Rect,
541
+ ): LegendLayout {
542
+ const labelStyle: TextStyle = {
543
+ fontFamily: theme.fonts.family,
544
+ fontSize: theme.fonts.sizes.small,
545
+ fontWeight: theme.fonts.weights.normal,
546
+ fill: theme.colors.text,
547
+ lineHeight: 1.3,
548
+ };
549
+
550
+ let entries: LegendEntry[];
551
+
552
+ if (colorField) {
553
+ // Group by color field value for legend entries
554
+ const categoryColors = new Map<string, string>();
555
+ const nodeCategoryMap = new Map<string, string>();
556
+ for (const row of data) {
557
+ const src = String(row[sourceField]);
558
+ const tgt = String(row[targetField]);
559
+ const cat = String(row[colorField]);
560
+ if (!nodeCategoryMap.has(src)) nodeCategoryMap.set(src, cat);
561
+ if (!nodeCategoryMap.has(tgt)) nodeCategoryMap.set(tgt, cat);
562
+ }
563
+ for (const [nodeId, category] of nodeCategoryMap) {
564
+ if (!categoryColors.has(category)) {
565
+ categoryColors.set(category, nodeColorMap.get(nodeId) ?? theme.colors.categorical[0]);
566
+ }
567
+ }
568
+
569
+ entries = [...categoryColors.entries()].map(([label, color]) => ({
570
+ label,
571
+ color,
572
+ shape: 'square' as const,
573
+ active: true,
574
+ }));
575
+ } else {
576
+ // No color encoding: no legend needed (nodes are individually colored)
577
+ entries = [];
578
+ }
579
+
580
+ // Compute bounds for horizontal top legend
581
+ let bounds = { x: 0, y: 0, width: 0, height: 0 };
582
+
583
+ if (entries.length > 0) {
584
+ const ROW_HEIGHT = SWATCH_SIZE + 4;
585
+ const availableWidth = area.width;
586
+
587
+ // Compute row count via shared wrap geometry, then cap at 2 rows.
588
+ const { rowCount } = measureLegendWrap(entries, availableWidth, labelStyle);
589
+ const cappedRowCount = Math.min(rowCount, 2);
590
+ const legendHeight = cappedRowCount * ROW_HEIGHT;
591
+
592
+ bounds = {
593
+ x: area.x,
594
+ y: area.y,
595
+ width: availableWidth,
596
+ height: legendHeight,
597
+ };
598
+ }
599
+
600
+ return {
601
+ position: 'top',
602
+ entries,
603
+ bounds,
604
+ labelStyle,
605
+ swatchSize: SWATCH_SIZE,
606
+ swatchGap: SWATCH_GAP,
607
+ entryGap: ENTRY_GAP,
608
+ swatchChipFill: theme.colors.annotationFill,
609
+ };
610
+ }
611
+
612
+ // ---------------------------------------------------------------------------
613
+ // Tooltip builder
614
+ // ---------------------------------------------------------------------------
615
+
616
+ const defaultFmt = defaultNumberFormatter();
617
+
618
+ function formatFlowValue(value: number, formatter?: NumberFormatter | null): string {
619
+ if (formatter) return formatter(value);
620
+ return defaultFmt(value);
621
+ }
622
+
623
+ function buildTooltipDescriptors(
624
+ nodes: SankeyNodeMark[],
625
+ links: SankeyLinkMark[],
626
+ formatter?: NumberFormatter | null,
627
+ ): Map<string, TooltipContent> {
628
+ const descriptors = new Map<string, TooltipContent>();
629
+
630
+ for (const node of nodes) {
631
+ const fields: TooltipField[] = [
632
+ {
633
+ label: 'Total flow',
634
+ value: formatFlowValue(node.value, formatter),
635
+ },
636
+ ];
637
+ descriptors.set(`node-${node.nodeId}`, {
638
+ title: node.label.text,
639
+ fields,
640
+ });
641
+ }
642
+
643
+ for (let i = 0; i < links.length; i++) {
644
+ const link = links[i];
645
+ const fields: TooltipField[] = [
646
+ {
647
+ label: 'Flow',
648
+ value: formatFlowValue(link.value, formatter),
649
+ },
650
+ ];
651
+ descriptors.set(`link-${link.sourceId}-${link.targetId}-${i}`, {
652
+ title: `${link.sourceId} \u2192 ${link.targetId}`,
653
+ fields,
654
+ });
655
+ }
656
+
657
+ return descriptors;
658
+ }
659
+
660
+ // ---------------------------------------------------------------------------
661
+ // Empty layout fallback
662
+ // ---------------------------------------------------------------------------
663
+
664
+ function emptyLayout(
665
+ area: Rect,
666
+ chrome: ReturnType<typeof computeChrome>,
667
+ theme: ResolvedTheme,
668
+ options: CompileOptions,
669
+ watermark: boolean,
670
+ ): SankeyLayout {
671
+ return {
672
+ area,
673
+ chrome,
674
+ nodes: [],
675
+ links: [],
676
+ legend: {
677
+ position: 'top',
678
+ entries: [],
679
+ bounds: { x: 0, y: 0, width: 0, height: 0 },
680
+ labelStyle: {
681
+ fontFamily: theme.fonts.family,
682
+ fontSize: theme.fonts.sizes.small,
683
+ fontWeight: theme.fonts.weights.normal,
684
+ fill: theme.colors.text,
685
+ lineHeight: 1.3,
686
+ },
687
+ swatchSize: SWATCH_SIZE,
688
+ swatchGap: SWATCH_GAP,
689
+ entryGap: ENTRY_GAP,
690
+ swatchChipFill: theme.colors.annotationFill,
691
+ },
692
+ tooltipDescriptors: new Map(),
693
+ a11y: {
694
+ altText: 'Empty sankey diagram',
695
+ dataTableFallback: [],
696
+ role: 'img',
697
+ keyboardNavigable: false,
698
+ },
699
+ theme,
700
+ dimensions: {
701
+ width: options.width,
702
+ height: options.height,
703
+ },
704
+ watermark,
705
+ };
706
+ }