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

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 (270) hide show
  1. package/dist/index.js +2 -3
  2. package/dist/index.js.map +1 -1
  3. package/package.json +3 -4
  4. package/src/__test-fixtures__/specs.ts +0 -182
  5. package/src/__tests__/__snapshots__/compile-snapshot.test.ts.snap +0 -2401
  6. package/src/__tests__/annotation-behavior.test.ts +0 -852
  7. package/src/__tests__/axes.test.ts +0 -1579
  8. package/src/__tests__/compile-animation.test.ts +0 -161
  9. package/src/__tests__/compile-chart.test.ts +0 -1303
  10. package/src/__tests__/compile-footnotes.test.ts +0 -277
  11. package/src/__tests__/compile-layer.test.ts +0 -969
  12. package/src/__tests__/compile-snapshot.test.ts +0 -156
  13. package/src/__tests__/compound-labels.test.ts +0 -147
  14. package/src/__tests__/dimensions.test.ts +0 -918
  15. package/src/__tests__/encoding-sugar.test.ts +0 -390
  16. package/src/__tests__/facet.test.ts +0 -359
  17. package/src/__tests__/helpers/invariants.ts +0 -299
  18. package/src/__tests__/known-bugs.test.ts +0 -566
  19. package/src/__tests__/layout-fuzz.test.ts +0 -358
  20. package/src/__tests__/layout-invariants.test.ts +0 -535
  21. package/src/__tests__/legend.test.ts +0 -721
  22. package/src/__tests__/mark-keys.test.ts +0 -294
  23. package/src/__tests__/ranking-recipes.test.ts +0 -260
  24. package/src/__tests__/rotation.test.ts +0 -83
  25. package/src/__tests__/scales.test.ts +0 -323
  26. package/src/__tests__/series-search.test.ts +0 -92
  27. package/src/__tests__/spec-sugar.test.ts +0 -801
  28. package/src/__tests__/you-draw-it.test.ts +0 -160
  29. package/src/annotations/__tests__/compute.test.ts +0 -1672
  30. package/src/annotations/__tests__/geometry.test.ts +0 -66
  31. package/src/annotations/__tests__/placement-fuzz.test.ts +0 -256
  32. package/src/annotations/__tests__/placement-invariants.test.ts +0 -345
  33. package/src/annotations/__tests__/placement.test.ts +0 -316
  34. package/src/annotations/__tests__/resolve-text.test.ts +0 -788
  35. package/src/annotations/__tests__/rich-text.test.ts +0 -91
  36. package/src/annotations/__tests__/thinning.test.ts +0 -285
  37. package/src/annotations/collisions.ts +0 -326
  38. package/src/annotations/compute.ts +0 -333
  39. package/src/annotations/constants.ts +0 -162
  40. package/src/annotations/geometry.ts +0 -376
  41. package/src/annotations/move.ts +0 -135
  42. package/src/annotations/placement.ts +0 -636
  43. package/src/annotations/position.ts +0 -131
  44. package/src/annotations/resolve-range.ts +0 -117
  45. package/src/annotations/resolve-refline.ts +0 -157
  46. package/src/annotations/resolve-text.ts +0 -545
  47. package/src/annotations/rich-text.ts +0 -65
  48. package/src/annotations/thinning.ts +0 -190
  49. package/src/barlist/__tests__/compile-barlist.test.ts +0 -200
  50. package/src/barlist/compile-barlist.ts +0 -391
  51. package/src/barlist/types.ts +0 -28
  52. package/src/charts/__tests__/post-process.test.ts +0 -237
  53. package/src/charts/__tests__/registry.test.ts +0 -116
  54. package/src/charts/__tests__/utils.test.ts +0 -195
  55. package/src/charts/_shared/__tests__/density-filter.test.ts +0 -32
  56. package/src/charts/_shared/density-filter.ts +0 -26
  57. package/src/charts/_shared/format-label-value.ts +0 -16
  58. package/src/charts/bar/__tests__/compute.test.ts +0 -934
  59. package/src/charts/bar/__tests__/gradient-orient.test.ts +0 -127
  60. package/src/charts/bar/__tests__/labels.test.ts +0 -292
  61. package/src/charts/bar/compute.ts +0 -539
  62. package/src/charts/bar/index.ts +0 -60
  63. package/src/charts/bar/labels.ts +0 -311
  64. package/src/charts/beeswarm/__tests__/compute.test.ts +0 -280
  65. package/src/charts/beeswarm/__tests__/dodge.test.ts +0 -148
  66. package/src/charts/beeswarm/compute.ts +0 -203
  67. package/src/charts/beeswarm/dodge.ts +0 -155
  68. package/src/charts/beeswarm/index.ts +0 -32
  69. package/src/charts/builtin.ts +0 -75
  70. package/src/charts/calendar/__tests__/compute.test.ts +0 -417
  71. package/src/charts/calendar/compute.ts +0 -319
  72. package/src/charts/calendar/index.ts +0 -32
  73. package/src/charts/column/__tests__/compute.test.ts +0 -540
  74. package/src/charts/column/__tests__/labels.test.ts +0 -179
  75. package/src/charts/column/compute.ts +0 -493
  76. package/src/charts/column/index.ts +0 -53
  77. package/src/charts/column/labels.ts +0 -229
  78. package/src/charts/dot/__tests__/compute.test.ts +0 -380
  79. package/src/charts/dot/__tests__/labels.test.ts +0 -98
  80. package/src/charts/dot/compute.ts +0 -285
  81. package/src/charts/dot/index.ts +0 -62
  82. package/src/charts/dot/labels.ts +0 -121
  83. package/src/charts/line/__tests__/compute.test.ts +0 -1194
  84. package/src/charts/line/__tests__/curves.test.ts +0 -51
  85. package/src/charts/line/__tests__/labels.test.ts +0 -94
  86. package/src/charts/line/__tests__/mark-options.test.ts +0 -175
  87. package/src/charts/line/area.ts +0 -484
  88. package/src/charts/line/compute.ts +0 -356
  89. package/src/charts/line/curves.ts +0 -85
  90. package/src/charts/line/index.ts +0 -176
  91. package/src/charts/line/labels.ts +0 -177
  92. package/src/charts/parliament/__tests__/compute.test.ts +0 -411
  93. package/src/charts/parliament/compute.ts +0 -313
  94. package/src/charts/parliament/index.ts +0 -32
  95. package/src/charts/pie/__tests__/compute.test.ts +0 -384
  96. package/src/charts/pie/__tests__/labels.test.ts +0 -132
  97. package/src/charts/pie/compute.ts +0 -324
  98. package/src/charts/pie/index.ts +0 -49
  99. package/src/charts/pie/labels.ts +0 -143
  100. package/src/charts/post-process.ts +0 -229
  101. package/src/charts/range/__tests__/compute.test.ts +0 -486
  102. package/src/charts/range/compute.ts +0 -273
  103. package/src/charts/range/index.ts +0 -82
  104. package/src/charts/range/labels.ts +0 -169
  105. package/src/charts/rect/__tests__/compute.test.ts +0 -120
  106. package/src/charts/rect/index.ts +0 -127
  107. package/src/charts/registry.ts +0 -72
  108. package/src/charts/rule/index.ts +0 -139
  109. package/src/charts/scatter/__tests__/compute.test.ts +0 -488
  110. package/src/charts/scatter/__tests__/trendline.test.ts +0 -191
  111. package/src/charts/scatter/compute.ts +0 -192
  112. package/src/charts/scatter/index.ts +0 -46
  113. package/src/charts/scatter/trendline.ts +0 -100
  114. package/src/charts/text/__tests__/compute.test.ts +0 -307
  115. package/src/charts/text/index.ts +0 -141
  116. package/src/charts/tick/__tests__/compute.test.ts +0 -75
  117. package/src/charts/tick/index.ts +0 -99
  118. package/src/charts/utils.ts +0 -170
  119. package/src/charts/waffle/__tests__/compute.test.ts +0 -305
  120. package/src/charts/waffle/compute.ts +0 -197
  121. package/src/charts/waffle/index.ts +0 -31
  122. package/src/compile/__tests__/color-scale-range.test.ts +0 -158
  123. package/src/compile/__tests__/color-scale-reverse.test.ts +0 -89
  124. package/src/compile/__tests__/data-clip.test.ts +0 -127
  125. package/src/compile/__tests__/fill-patterns.test.ts +0 -154
  126. package/src/compile/__tests__/size-scale.test.ts +0 -108
  127. package/src/compile/__tests__/watermark-obstacle.test.ts +0 -93
  128. package/src/compile/color-scale-range.ts +0 -101
  129. package/src/compile/data-clip.ts +0 -48
  130. package/src/compile/fill-patterns.ts +0 -74
  131. package/src/compile/layer.ts +0 -630
  132. package/src/compile/size-scale.ts +0 -141
  133. package/src/compile/spec-sugar.ts +0 -767
  134. package/src/compile/watermark-obstacle.ts +0 -54
  135. package/src/compile/you-draw-it.ts +0 -123
  136. package/src/compile.ts +0 -1548
  137. package/src/compiler/__tests__/a11y-warnings.test.ts +0 -148
  138. package/src/compiler/__tests__/animation.test.ts +0 -177
  139. package/src/compiler/__tests__/compile.test.ts +0 -87
  140. package/src/compiler/__tests__/fixtures/vl-parity/axis-null.json +0 -19
  141. package/src/compiler/__tests__/fixtures/vl-parity/color-value.json +0 -20
  142. package/src/compiler/__tests__/fixtures/vl-parity/count-aggregate.json +0 -22
  143. package/src/compiler/__tests__/fixtures/vl-parity/data-values.json +0 -19
  144. package/src/compiler/__tests__/fixtures/vl-parity/layer-axis-null.json +0 -14
  145. package/src/compiler/__tests__/fixtures/vl-parity/layer-count.json +0 -34
  146. package/src/compiler/__tests__/fixtures/vl-parity/layer-data-values.json +0 -22
  147. package/src/compiler/__tests__/fixtures/vl-parity/layer-legend-null.json +0 -41
  148. package/src/compiler/__tests__/fixtures/vl-parity/layer-scheme.json +0 -38
  149. package/src/compiler/__tests__/fixtures/vl-parity/layer-sort.json +0 -28
  150. package/src/compiler/__tests__/fixtures/vl-parity/layer-theta.json +0 -28
  151. package/src/compiler/__tests__/fixtures/vl-parity/layer-title.json +0 -30
  152. package/src/compiler/__tests__/fixtures/vl-parity/layer-value-def.json +0 -29
  153. package/src/compiler/__tests__/fixtures/vl-parity/legend-null.json +0 -32
  154. package/src/compiler/__tests__/fixtures/vl-parity/scheme.json +0 -25
  155. package/src/compiler/__tests__/fixtures/vl-parity/sort-by-value.json +0 -19
  156. package/src/compiler/__tests__/fixtures/vl-parity/theta-arc.json +0 -19
  157. package/src/compiler/__tests__/fixtures/vl-parity/title-subtitle.json +0 -21
  158. package/src/compiler/__tests__/fixtures/vl-parity/width-height.json +0 -23
  159. package/src/compiler/__tests__/keys.test.ts +0 -83
  160. package/src/compiler/__tests__/normalize-highlight.test.ts +0 -103
  161. package/src/compiler/__tests__/normalize.test.ts +0 -399
  162. package/src/compiler/__tests__/sparkline-defaults.test.ts +0 -153
  163. package/src/compiler/__tests__/validate-did-you-mean.test.ts +0 -170
  164. package/src/compiler/__tests__/validate-highlight.test.ts +0 -112
  165. package/src/compiler/__tests__/validate-near-miss.test.ts +0 -251
  166. package/src/compiler/__tests__/validate.test.ts +0 -731
  167. package/src/compiler/__tests__/vl-parity.test.ts +0 -68
  168. package/src/compiler/a11y-warnings.ts +0 -110
  169. package/src/compiler/animation.ts +0 -142
  170. package/src/compiler/index.ts +0 -47
  171. package/src/compiler/keys.ts +0 -55
  172. package/src/compiler/normalize.ts +0 -734
  173. package/src/compiler/sparkline-defaults.ts +0 -138
  174. package/src/compiler/types.ts +0 -241
  175. package/src/compiler/validate.ts +0 -2093
  176. package/src/endpoint-labels/__tests__/compute.test.ts +0 -587
  177. package/src/endpoint-labels/compute.ts +0 -621
  178. package/src/endpoint-labels/constants.ts +0 -54
  179. package/src/endpoint-labels/format.ts +0 -60
  180. package/src/endpoint-labels/predict.ts +0 -139
  181. package/src/format/__tests__/field-format.test.ts +0 -164
  182. package/src/format/field-format.ts +0 -27
  183. package/src/geo/__tests__/compile-map.test.ts +0 -1128
  184. package/src/geo/compile-map.ts +0 -1376
  185. package/src/geo/join.ts +0 -115
  186. package/src/geo/projections.ts +0 -65
  187. package/src/geo/types.ts +0 -26
  188. package/src/graphs/__tests__/community.test.ts +0 -228
  189. package/src/graphs/__tests__/compile-graph.test.ts +0 -396
  190. package/src/graphs/__tests__/encoding.test.ts +0 -415
  191. package/src/graphs/community.ts +0 -92
  192. package/src/graphs/compile-graph.ts +0 -329
  193. package/src/graphs/encoding.ts +0 -356
  194. package/src/graphs/types.ts +0 -106
  195. package/src/index.ts +0 -177
  196. package/src/layout/__tests__/metrics.test.ts +0 -97
  197. package/src/layout/__tests__/scales-highlight.test.ts +0 -192
  198. package/src/layout/axes/rotation.ts +0 -152
  199. package/src/layout/axes/thinning.ts +0 -98
  200. package/src/layout/axes/ticks.ts +0 -409
  201. package/src/layout/axes.ts +0 -757
  202. package/src/layout/dimensions.ts +0 -912
  203. package/src/layout/facet.ts +0 -91
  204. package/src/layout/gridlines.ts +0 -84
  205. package/src/layout/metrics.ts +0 -132
  206. package/src/layout/plan.ts +0 -631
  207. package/src/layout/scales.ts +0 -1053
  208. package/src/layout/shared.ts +0 -44
  209. package/src/legend/__tests__/continuous.test.ts +0 -318
  210. package/src/legend/__tests__/redundancy.test.ts +0 -108
  211. package/src/legend/__tests__/size.test.ts +0 -348
  212. package/src/legend/__tests__/suppression.test.ts +0 -382
  213. package/src/legend/compute.ts +0 -748
  214. package/src/legend/continuous.ts +0 -327
  215. package/src/legend/size.ts +0 -407
  216. package/src/legend/suppression.ts +0 -226
  217. package/src/legend/wrap.ts +0 -117
  218. package/src/sankey/__tests__/compile-sankey.test.ts +0 -458
  219. package/src/sankey/__tests__/layout.test.ts +0 -165
  220. package/src/sankey/__tests__/node-label-wrap.test.ts +0 -114
  221. package/src/sankey/__tests__/node-sort.test.ts +0 -45
  222. package/src/sankey/compile-sankey.ts +0 -706
  223. package/src/sankey/layout.ts +0 -184
  224. package/src/sankey/types.ts +0 -41
  225. package/src/tables/__tests__/bar-column.test.ts +0 -147
  226. package/src/tables/__tests__/category-colors.test.ts +0 -230
  227. package/src/tables/__tests__/compile-table.test.ts +0 -236
  228. package/src/tables/__tests__/format-cells.test.ts +0 -143
  229. package/src/tables/__tests__/heatmap.test.ts +0 -148
  230. package/src/tables/__tests__/pagination.test.ts +0 -78
  231. package/src/tables/__tests__/search.test.ts +0 -94
  232. package/src/tables/__tests__/sort.test.ts +0 -107
  233. package/src/tables/__tests__/sparkline.test.ts +0 -122
  234. package/src/tables/bar-column.ts +0 -94
  235. package/src/tables/category-colors.ts +0 -78
  236. package/src/tables/compile-table.ts +0 -427
  237. package/src/tables/format-cells.ts +0 -115
  238. package/src/tables/heatmap.ts +0 -141
  239. package/src/tables/pagination.ts +0 -46
  240. package/src/tables/search.ts +0 -66
  241. package/src/tables/sort.ts +0 -69
  242. package/src/tables/sparkline.ts +0 -113
  243. package/src/tables/utils.ts +0 -16
  244. package/src/tilemap/__tests__/compile-tilemap.test.ts +0 -576
  245. package/src/tilemap/compile-tilemap.ts +0 -755
  246. package/src/tilemap/layout.ts +0 -172
  247. package/src/tilemap/types.ts +0 -33
  248. package/src/tooltips/__tests__/compute.test.ts +0 -582
  249. package/src/tooltips/compute.ts +0 -700
  250. package/src/transforms/__tests__/aggregate.test.ts +0 -159
  251. package/src/transforms/__tests__/bin.test.ts +0 -88
  252. package/src/transforms/__tests__/calculate.test.ts +0 -146
  253. package/src/transforms/__tests__/conditional.test.ts +0 -127
  254. package/src/transforms/__tests__/filter-relative.test.ts +0 -202
  255. package/src/transforms/__tests__/filter.test.ts +0 -59
  256. package/src/transforms/__tests__/fold.test.ts +0 -79
  257. package/src/transforms/__tests__/index.test.ts +0 -93
  258. package/src/transforms/__tests__/predicates.test.ts +0 -193
  259. package/src/transforms/__tests__/timeunit.test.ts +0 -129
  260. package/src/transforms/__tests__/window.test.ts +0 -286
  261. package/src/transforms/aggregate.ts +0 -131
  262. package/src/transforms/bin.ts +0 -87
  263. package/src/transforms/calculate.ts +0 -60
  264. package/src/transforms/conditional.ts +0 -46
  265. package/src/transforms/filter.ts +0 -122
  266. package/src/transforms/fold.ts +0 -49
  267. package/src/transforms/index.ts +0 -60
  268. package/src/transforms/predicates.ts +0 -123
  269. package/src/transforms/timeunit.ts +0 -88
  270. package/src/transforms/window.ts +0 -185
@@ -1,734 +0,0 @@
1
- /**
2
- * Spec normalization: fill in defaults and infer types.
3
- *
4
- * Takes a validated VizSpec and produces a NormalizedSpec where:
5
- * - All optional fields have sensible defaults
6
- * - Chrome strings are converted to ChromeText objects
7
- * - Encoding types are inferred from data if not specified
8
- * - Annotations have default styles
9
- */
10
-
11
- import type {
12
- Annotation,
13
- BarListSpec,
14
- ChartSpec,
15
- Chrome,
16
- ChromeText,
17
- DataRow,
18
- Encoding,
19
- FieldType,
20
- GraphSpec,
21
- LabelSpec,
22
- LayerSpec,
23
- MapSpec,
24
- MarkDef,
25
- SankeySpec,
26
- TableSpec,
27
- TileMapSpec,
28
- VizSpec,
29
- } from '@opendata-ai/openchart-core';
30
- import {
31
- isBarListSpec,
32
- isChartSpec,
33
- isGraphSpec,
34
- isLayerSpec,
35
- isMapSpec,
36
- isSankeySpec,
37
- isTableSpec,
38
- isTileMapSpec,
39
- resolveMarkDef,
40
- resolveMarkType,
41
- } from '@opendata-ai/openchart-core';
42
- import type { NormalizedBarListSpec } from '../barlist/types';
43
- import type { NormalizedMapSpec } from '../geo/types';
44
- import type { NormalizedSankeySpec } from '../sankey/types';
45
- import { STATE_CODE_SET } from '../tilemap/layout';
46
- import type { NormalizedTileMapSpec } from '../tilemap/types';
47
- import type {
48
- NormalizedChartSpec,
49
- NormalizedChrome,
50
- NormalizedGraphSpec,
51
- NormalizedSpec,
52
- NormalizedTableSpec,
53
- } from './types';
54
-
55
- // ---------------------------------------------------------------------------
56
- // Chrome normalization
57
- // ---------------------------------------------------------------------------
58
-
59
- /** Convert a string | ChromeText | undefined to ChromeText | undefined. */
60
- function normalizeChromeField(value: string | ChromeText | undefined): ChromeText | undefined {
61
- if (value === undefined) return undefined;
62
- if (typeof value === 'string') return { text: value };
63
- return value;
64
- }
65
-
66
- /** Normalize all chrome fields from strings to ChromeText objects. */
67
- function normalizeChrome(chrome: Chrome | undefined): NormalizedChrome {
68
- if (!chrome) return {};
69
- return {
70
- eyebrow: normalizeChromeField(chrome.eyebrow),
71
- title: normalizeChromeField(chrome.title),
72
- subtitle: normalizeChromeField(chrome.subtitle),
73
- source: normalizeChromeField(chrome.source),
74
- byline: normalizeChromeField(chrome.byline),
75
- footer: normalizeChromeField(chrome.footer),
76
- brand: normalizeChromeField(chrome.brand),
77
- };
78
- }
79
-
80
- // ---------------------------------------------------------------------------
81
- // Type inference
82
- // ---------------------------------------------------------------------------
83
-
84
- /** Sample values from a data column and infer the field type. */
85
- function inferFieldType(data: DataRow[], field: string): FieldType {
86
- // Sample up to 50 rows for more reliable inference on mixed/messy data
87
- const sampleSize = Math.min(50, data.length);
88
- let numericCount = 0;
89
- let dateCount = 0;
90
- let totalNonNull = 0;
91
-
92
- for (let i = 0; i < sampleSize; i++) {
93
- const value = data[i][field];
94
- if (value == null) continue;
95
- totalNonNull++;
96
-
97
- // Check numeric
98
- if (typeof value === 'number' && Number.isFinite(value)) {
99
- numericCount++;
100
- continue;
101
- }
102
-
103
- // Check date-like strings
104
- if (typeof value === 'string') {
105
- // Try as number first
106
- const num = Number(value);
107
- if (!Number.isNaN(num) && Number.isFinite(num) && value.trim() !== '') {
108
- numericCount++;
109
- continue;
110
- }
111
-
112
- // Try as date
113
- const date = new Date(value);
114
- if (!Number.isNaN(date.getTime())) {
115
- dateCount++;
116
- continue;
117
- }
118
- }
119
-
120
- if (value instanceof Date && !Number.isNaN(value.getTime())) {
121
- dateCount++;
122
- }
123
- }
124
-
125
- if (totalNonNull === 0) return 'nominal';
126
-
127
- // If >80% of sampled values are dates, it's temporal
128
- if (dateCount / totalNonNull > 0.8) return 'temporal';
129
- // If >80% are numeric, it's quantitative
130
- if (numericCount / totalNonNull > 0.8) return 'quantitative';
131
- // Otherwise it's nominal
132
- return 'nominal';
133
- }
134
-
135
- /** Infer types for encoding channels that don't have one specified. */
136
- function inferEncodingTypes(encoding: Encoding, data: DataRow[], warnings: string[]): Encoding {
137
- const result = { ...encoding };
138
-
139
- for (const channel of ['x', 'y', 'color', 'size', 'detail', 'key'] as const) {
140
- const spec = result[channel];
141
- if (!spec) continue;
142
-
143
- // Skip conditional value definitions - they don't have field/type at the top level
144
- if ('condition' in spec) continue;
145
- // Skip bare value defs (no field). The sugar expansion moves these to
146
- // mark-level properties before normalize runs on the compile path.
147
- if (!('field' in spec)) continue;
148
-
149
- if (!spec.type) {
150
- const inferred = inferFieldType(data, spec.field);
151
- (result as Record<string, unknown>)[channel] = { ...spec, type: inferred };
152
- warnings.push(
153
- `Inferred encoding.${channel}.type as "${inferred}" from data values for field "${spec.field}"`,
154
- );
155
- } else {
156
- // Check for potential mismatches and warn
157
- const actualType = inferFieldType(data, spec.field);
158
- if (spec.type === 'nominal' && actualType === 'temporal') {
159
- warnings.push(`Field "${spec.field}" looks temporal but was declared as nominal`);
160
- }
161
- if (spec.type === 'nominal' && actualType === 'quantitative') {
162
- warnings.push(`Field "${spec.field}" looks quantitative but was declared as nominal`);
163
- }
164
- }
165
- }
166
-
167
- return result;
168
- }
169
-
170
- // ---------------------------------------------------------------------------
171
- // Annotation normalization
172
- // ---------------------------------------------------------------------------
173
-
174
- /** Apply default styles to annotations that don't have them. */
175
- function normalizeAnnotations(annotations: Annotation[] | undefined): Annotation[] {
176
- if (!annotations || annotations.length === 0) return [];
177
-
178
- // The spec-sugar pass rewrites the deprecated `type: 'rule'` annotation
179
- // alias to `'refline'` (with a warning) before validation/normalization
180
- // ever runs, so by this point every annotation is in canonical form.
181
- return annotations.map((ann) => {
182
- switch (ann.type) {
183
- case 'text':
184
- // Deliberately does NOT default fontSize/fontWeight. The annotation
185
- // layer owns those (DEFAULT_ANNOTATION_FONT_SIZE, and the lede rule
186
- // that promotes a subtitle-bearing primary line to bold). Stamping
187
- // them here makes `annotation.fontWeight` always defined, so
188
- // `resolveLedeFontWeight` can never fire and the size default can
189
- // never apply — both features become dead code.
190
- return {
191
- ...ann,
192
- opacity: ann.opacity ?? 1,
193
- };
194
- case 'range':
195
- return {
196
- ...ann,
197
- opacity: ann.opacity ?? 0.1,
198
- fill: ann.fill ?? '#000000',
199
- };
200
- case 'refline':
201
- return {
202
- ...ann,
203
- style: ann.style ?? 'dashed',
204
- strokeWidth: ann.strokeWidth ?? 1,
205
- stroke: ann.stroke ?? '#666666',
206
- opacity: ann.opacity ?? 0.8,
207
- };
208
- default:
209
- return ann;
210
- }
211
- });
212
- }
213
-
214
- // ---------------------------------------------------------------------------
215
- // Label normalization
216
- // ---------------------------------------------------------------------------
217
-
218
- function normalizeLabels(labels?: LabelSpec): NormalizedChartSpec['labels'] {
219
- if (labels === false) return { density: 'none', format: '', prefix: '' };
220
- if (labels === true || labels === undefined) return { density: 'auto', format: '', prefix: '' };
221
- return {
222
- density: labels.density ?? 'auto',
223
- format: labels.format ?? '',
224
- prefix: labels.prefix ?? '',
225
- suffix: labels.suffix,
226
- offsets: labels.offsets,
227
- color: labels.color,
228
- fontSize: labels.fontSize,
229
- };
230
- }
231
-
232
- // ---------------------------------------------------------------------------
233
- // Highlight normalization
234
- // ---------------------------------------------------------------------------
235
-
236
- /**
237
- * Normalize `encoding.color.highlight` to a flat string array.
238
- * Warns when highlight values don't appear in the data.
239
- */
240
- function normalizeHighlight(encoding: Encoding, data: DataRow[], warnings: string[]): string[] {
241
- const color = encoding.color;
242
- if (!color || !('field' in color)) return [];
243
- const raw = (color as { highlight?: string | string[] }).highlight;
244
- if (raw == null) return [];
245
- const highlight = Array.isArray(raw) ? raw : [raw];
246
-
247
- // Warn on unknown values
248
- if (highlight.length > 0 && data.length > 0) {
249
- const colorField = color.field;
250
- const knownValues = new Set(data.map((row) => String(row[colorField])));
251
- for (const v of highlight) {
252
- if (!knownValues.has(v)) {
253
- warnings.push(
254
- `[openchart] encoding.color.highlight value "${v}" does not match any value in the "${colorField}" data column`,
255
- );
256
- }
257
- }
258
- }
259
-
260
- if (highlight.length > 0 && color.scale?.range) {
261
- warnings.push(
262
- '[openchart] encoding.color.highlight has no effect on color assignment when encoding.color.scale.range is explicitly provided',
263
- );
264
- }
265
-
266
- return highlight;
267
- }
268
-
269
- // ---------------------------------------------------------------------------
270
- // Series search normalization
271
- // ---------------------------------------------------------------------------
272
-
273
- /**
274
- * Normalize `seriesSearch` to a config object, or undefined when disabled.
275
- * Search needs a categorical color encoding to enumerate series values;
276
- * warns and disables when there isn't one.
277
- */
278
- function normalizeSeriesSearch(
279
- spec: ChartSpec,
280
- encoding: Encoding,
281
- warnings: string[],
282
- ): import('@opendata-ai/openchart-core').SeriesSearchConfig | undefined {
283
- if (!spec.seriesSearch) return undefined;
284
- const color = encoding.color;
285
- const hasCategoricalColor =
286
- !!color &&
287
- !('condition' in color) &&
288
- 'field' in color &&
289
- !!color.field &&
290
- color.type !== 'quantitative';
291
- if (!hasCategoricalColor) {
292
- warnings.push(
293
- '[openchart] seriesSearch requires a categorical color encoding (encoding.color.field with a nominal/ordinal type); ignoring seriesSearch.',
294
- );
295
- return undefined;
296
- }
297
- return typeof spec.seriesSearch === 'object' ? { ...spec.seriesSearch } : {};
298
- }
299
-
300
- // ---------------------------------------------------------------------------
301
- // You draw it normalization
302
- // ---------------------------------------------------------------------------
303
-
304
- /**
305
- * Normalize `youDrawIt` to a config object with defaults filled in, or
306
- * undefined when disabled. Mark type, single-series, and `from` presence are
307
- * enforced by validateSpec before normalize runs; this only fills defaults.
308
- */
309
- function normalizeYouDrawIt(
310
- spec: ChartSpec,
311
- ): import('@opendata-ai/openchart-core').YouDrawItConfig | undefined {
312
- if (!spec.youDrawIt) return undefined;
313
- return {
314
- prompt: 'Draw your guess',
315
- revealLabel: 'Show me',
316
- ...spec.youDrawIt,
317
- };
318
- }
319
-
320
- // ---------------------------------------------------------------------------
321
- // Spec-level normalization
322
- // ---------------------------------------------------------------------------
323
-
324
- /**
325
- * Beeswarm point budget. Past this count the dodge layout still resolves
326
- * every collision, but the swarm piles into a solid band that reads no
327
- * better than an overplotted strip, and layout cost keeps growing.
328
- */
329
- const BEESWARM_POINT_BUDGET = 2000;
330
-
331
- /**
332
- * Warn when a parliament `majorityLine.seats` override lands outside the chamber
333
- * (below 1 or above the seat total). The mark falls back to a simple majority in
334
- * that case, so this is a non-fatal warning routed through the shared warnings
335
- * array (dedup + single emit boundary) rather than a raw console.warn in mark
336
- * computation. Only the object form of majorityLine carries a seat count.
337
- */
338
- function warnParliamentMajorityRange(
339
- markDef: MarkDef,
340
- encoding: Encoding,
341
- data: DataRow[],
342
- warnings: string[],
343
- ): void {
344
- const majorityLine = markDef.majorityLine;
345
- if (!majorityLine || typeof majorityLine !== 'object') return;
346
- const requested = majorityLine.seats;
347
- if (requested === undefined) return;
348
-
349
- const valueField = encoding.theta?.field ?? encoding.y?.field;
350
- if (!valueField) return;
351
-
352
- let totalSeats = 0;
353
- for (const row of data) {
354
- const v = Number(row[valueField]);
355
- if (Number.isFinite(v)) totalSeats += v;
356
- }
357
- if (totalSeats <= 0) return;
358
-
359
- if (!Number.isFinite(requested) || requested < 1 || requested > totalSeats) {
360
- const fallback = Math.floor(totalSeats / 2) + 1;
361
- warnings.push(
362
- `[openchart] parliament mark.majorityLine.seats (${requested}) is outside the valid range 1..${totalSeats}; using the default majority threshold of ${fallback}.`,
363
- );
364
- }
365
- }
366
-
367
- function normalizeChartSpec(spec: ChartSpec, warnings: string[]): NormalizedChartSpec {
368
- const encoding = inferEncodingTypes(spec.encoding, spec.data, warnings);
369
- const markType = resolveMarkType(spec.mark);
370
- const markDef = resolveMarkDef(spec.mark);
371
- const display = spec.display ?? 'full';
372
-
373
- if (
374
- display === 'sparkline' &&
375
- markType !== 'line' &&
376
- markType !== 'area' &&
377
- markType !== 'bar' &&
378
- markType !== 'point'
379
- ) {
380
- warnings.push(
381
- `[openchart] display: 'sparkline' works best with mark: 'line' | 'area' | 'bar' | 'point'. Got mark: '${markType}' — rendering may degrade.`,
382
- );
383
- }
384
-
385
- if (markType === 'beeswarm' && spec.data.length > BEESWARM_POINT_BUDGET) {
386
- warnings.push(
387
- `[openchart] beeswarm received ${spec.data.length} data points, past the ~${BEESWARM_POINT_BUDGET}-point budget where individual dots stop being readable and the swarm collapses into a solid band. Sample the data down, or summarize the distribution with mark: 'tick' (strip plot) or a binned histogram (bin transform + mark: 'bar').`,
388
- );
389
- }
390
-
391
- if (markType === 'parliament') {
392
- warnParliamentMajorityRange(markDef, encoding, spec.data, warnings);
393
- }
394
-
395
- return {
396
- markType,
397
- markDef,
398
- data: spec.data,
399
- encoding,
400
- chrome: normalizeChrome(spec.chrome),
401
- metrics: spec.metrics,
402
- seriesSearch: normalizeSeriesSearch(spec, encoding, warnings),
403
- youDrawIt: normalizeYouDrawIt(spec),
404
- annotations: normalizeAnnotations(spec.annotations),
405
- labels: normalizeLabels(spec.labels),
406
- legend: spec.legend,
407
- endpointLabels: spec.endpointLabels,
408
- responsive: typeof spec.responsive === 'object' ? true : (spec.responsive ?? true),
409
- autoThin:
410
- typeof spec.responsive === 'object'
411
- ? (spec.responsive.autoThin ?? true)
412
- : (spec.responsive ?? true),
413
- theme: spec.theme ?? {},
414
- darkMode: spec.darkMode ?? 'off',
415
- hiddenSeries: spec.hiddenSeries ?? [],
416
- seriesStyles: spec.seriesStyles ?? {},
417
- watermark: spec.watermark ?? true,
418
- highlight: normalizeHighlight(encoding, spec.data, warnings),
419
- a11y: spec.a11y,
420
- display,
421
- resolve: spec.resolve,
422
- // Default empty userExplicit; compileChart overwrites this with the real
423
- // descriptor built from the raw expanded spec before normalize runs.
424
- userExplicit: {
425
- chrome: false,
426
- legend: false,
427
- endpointLabels: false,
428
- xAxis: false,
429
- yAxis: false,
430
- labels: false,
431
- animation: false,
432
- watermark: false,
433
- crosshair: false,
434
- },
435
- };
436
- }
437
-
438
- function normalizeTableSpec(spec: TableSpec, _warnings: string[]): NormalizedTableSpec {
439
- return {
440
- type: 'table',
441
- data: spec.data,
442
- columns: spec.columns,
443
- rowKey: spec.rowKey,
444
- chrome: normalizeChrome(spec.chrome),
445
- theme: spec.theme ?? {},
446
- darkMode: spec.darkMode ?? 'off',
447
- search: spec.search ?? false,
448
- pagination: spec.pagination ?? false,
449
- stickyFirstColumn: spec.stickyFirstColumn ?? false,
450
- compact: spec.compact ?? false,
451
- responsive: spec.responsive ?? true,
452
- animation: spec.animation,
453
- watermark: spec.watermark ?? true,
454
- };
455
- }
456
-
457
- function normalizeSankeySpec(spec: SankeySpec, _warnings: string[]): NormalizedSankeySpec {
458
- return {
459
- type: 'sankey',
460
- data: spec.data,
461
- encoding: spec.encoding,
462
- nodeWidth: spec.nodeWidth ?? 12,
463
- nodePadding: spec.nodePadding ?? 16,
464
- nodeAlign: spec.nodeAlign ?? 'justify',
465
- iterations: spec.iterations ?? 6,
466
- linkStyle: spec.linkStyle ?? 'gradient',
467
- nodeLabelAlign: spec.nodeLabelAlign ?? 'auto',
468
- nodeSort: spec.nodeSort,
469
- chrome: normalizeChrome(spec.chrome),
470
- legend: spec.legend,
471
- theme: spec.theme ?? {},
472
- darkMode: spec.darkMode ?? 'off',
473
- animation: spec.animation,
474
- valueFormat: spec.valueFormat,
475
- linkOpacity: spec.linkOpacity,
476
- watermark: spec.watermark ?? true,
477
- };
478
- }
479
-
480
- function normalizeGraphSpec(spec: GraphSpec): NormalizedGraphSpec {
481
- // Default layout with chargeStrength and linkDistance
482
- const defaultLayout = {
483
- type: 'force' as const,
484
- chargeStrength: -300,
485
- linkDistance: 30,
486
- };
487
- const layout = spec.layout
488
- ? {
489
- ...defaultLayout,
490
- ...spec.layout,
491
- }
492
- : defaultLayout;
493
-
494
- return {
495
- type: 'graph',
496
- nodes: spec.nodes,
497
- edges: spec.edges,
498
- encoding: spec.encoding ?? {},
499
- layout,
500
- nodeOverrides: spec.nodeOverrides,
501
- chrome: normalizeChrome(spec.chrome),
502
- annotations: normalizeAnnotations(spec.annotations),
503
- theme: spec.theme ?? {},
504
- darkMode: spec.darkMode ?? 'off',
505
- watermark: spec.watermark ?? true,
506
- };
507
- }
508
-
509
- function normalizeTileMapSpec(spec: TileMapSpec, warnings: string[]): NormalizedTileMapSpec {
510
- // Convert record data to array if needed
511
- let data: Record<string, unknown>[] = Array.isArray(spec.data) ? spec.data : [];
512
-
513
- if (!Array.isArray(spec.data)) {
514
- // Convert record map to array of rows
515
- data = Object.entries(spec.data).map(([state, value]) => ({ state, value }));
516
- }
517
-
518
- // Detect categorical mode: colors map provided, color encoding channel, or string values
519
- const hasStringValues =
520
- !Array.isArray(spec.data) && Object.values(spec.data).some((v) => typeof v === 'string');
521
- const isCategorical =
522
- spec.colors !== undefined || spec.encoding?.color !== undefined || hasStringValues;
523
-
524
- // Warn on mixed number/string values in record map (likely a data quality issue)
525
- if (hasStringValues && !Array.isArray(spec.data)) {
526
- const hasNumericValues = Object.values(spec.data).some((v) => typeof v === 'number');
527
- if (hasNumericValues) {
528
- warnings.push(
529
- 'TileMap data: record map contains mixed number and string values. Treating as categorical. Use all numbers for quantitative or all strings for categorical.',
530
- );
531
- }
532
- }
533
-
534
- // Auto-generate encoding if not provided
535
- let encoding = spec.encoding;
536
- if (!encoding) {
537
- encoding = {
538
- state: { field: 'state', type: 'nominal' },
539
- value: { field: 'value', type: isCategorical ? 'nominal' : 'quantitative' },
540
- };
541
- }
542
-
543
- // For categorical record maps without explicit color encoding, use value as color channel
544
- if (isCategorical && !encoding.color) {
545
- encoding = { ...encoding, color: encoding.value };
546
- }
547
-
548
- // Count matched states and warn if low match ratio
549
- let matchedCount = 0;
550
- for (const row of data) {
551
- const stateCode = String(row[encoding.state.field]);
552
- if (STATE_CODE_SET.has(stateCode)) {
553
- matchedCount++;
554
- }
555
- }
556
-
557
- const matchRatio = data.length > 0 ? matchedCount / data.length : 0;
558
- if (matchRatio < 0.5 && data.length > 0) {
559
- warnings.push(
560
- `TileMap data: only ${matchedCount} of ${data.length} rows have valid US state codes (expected ≥50%)`,
561
- );
562
- }
563
-
564
- return {
565
- type: 'tilemap',
566
- data,
567
- encoding,
568
- palette: spec.palette ?? 'blue',
569
- colors: spec.colors,
570
- chrome: normalizeChrome(spec.chrome),
571
- legend: spec.legend,
572
- theme: spec.theme ?? {},
573
- darkMode: spec.darkMode ?? 'off',
574
- watermark: spec.watermark ?? true,
575
- animation: spec.animation,
576
- valueFormat: spec.valueFormat,
577
- };
578
- }
579
-
580
- function normalizeMapSpec(spec: MapSpec, _warnings: string[]): NormalizedMapSpec {
581
- return {
582
- type: 'map',
583
- geo: {
584
- features: spec.geo.features,
585
- idField: spec.geo.idField ?? 'id',
586
- projection: spec.geo.projection ?? 'albersUsa',
587
- focus: spec.geo.focus ?? null,
588
- },
589
- data: spec.data,
590
- encoding: spec.encoding,
591
- chrome: normalizeChrome(spec.chrome),
592
- legend: spec.legend,
593
- theme: spec.theme ?? {},
594
- darkMode: spec.darkMode ?? 'off',
595
- watermark: spec.watermark ?? true,
596
- animation: spec.animation,
597
- valueFormat: spec.valueFormat,
598
- points: spec.points,
599
- };
600
- }
601
-
602
- function normalizeBarListSpec(spec: BarListSpec, _warnings: string[]): NormalizedBarListSpec {
603
- return {
604
- type: 'barlist',
605
- data: spec.data,
606
- encoding: spec.encoding,
607
- barHeight: spec.barHeight ?? 6,
608
- cornerRadius: spec.cornerRadius ?? 'pill',
609
- maxItems: spec.maxItems ?? 20,
610
- chrome: normalizeChrome(spec.chrome),
611
- theme: spec.theme ?? {},
612
- darkMode: spec.darkMode ?? 'off',
613
- watermark: spec.watermark ?? true,
614
- animation: spec.animation ?? true,
615
- valueFormat: spec.valueFormat,
616
- };
617
- }
618
-
619
- // ---------------------------------------------------------------------------
620
- // Public API
621
- // ---------------------------------------------------------------------------
622
-
623
- /**
624
- * Normalize a validated VizSpec, filling in all defaults.
625
- *
626
- * @param spec - A validated VizSpec (must pass validateSpec first).
627
- * @param warnings - Mutable array to collect non-fatal warnings.
628
- * @returns A NormalizedSpec with all optionals filled.
629
- */
630
- export function normalizeSpec(spec: VizSpec, warnings: string[] = []): NormalizedSpec {
631
- if (isLayerSpec(spec)) {
632
- // For LayerSpec, we flatten and normalize the first leaf to get a valid NormalizedChartSpec.
633
- // The actual layer compilation happens in compileLayer, not here.
634
- // This path exists so the generic compile() pipeline doesn't reject layer specs.
635
- const leaves = flattenLayers(spec);
636
- if (leaves.length === 0) {
637
- throw new Error('LayerSpec has no leaf chart specs after flattening');
638
- }
639
- return normalizeChartSpec(leaves[0], warnings);
640
- }
641
- if (isChartSpec(spec)) {
642
- return normalizeChartSpec(spec, warnings);
643
- }
644
- if (isTableSpec(spec)) {
645
- return normalizeTableSpec(spec, warnings);
646
- }
647
- if (isGraphSpec(spec)) {
648
- return normalizeGraphSpec(spec);
649
- }
650
- if (isSankeySpec(spec)) {
651
- return normalizeSankeySpec(spec, warnings);
652
- }
653
- if (isTileMapSpec(spec)) {
654
- return normalizeTileMapSpec(spec, warnings);
655
- }
656
- if (isMapSpec(spec)) {
657
- return normalizeMapSpec(spec, warnings);
658
- }
659
- if (isBarListSpec(spec)) {
660
- return normalizeBarListSpec(spec, warnings);
661
- }
662
- // Should never happen after validation
663
- throw new Error(
664
- `Unknown spec shape. Expected mark (chart), layer, type: 'table', type: 'graph', type: 'sankey', type: 'tilemap', type: 'map', or type: 'barlist'.`,
665
- );
666
- }
667
-
668
- // ---------------------------------------------------------------------------
669
- // Layer flattening (used by compileLayer in compile.ts)
670
- // ---------------------------------------------------------------------------
671
-
672
- /**
673
- * Recursively flatten a LayerSpec into leaf ChartSpecs.
674
- * Merges parent data, encoding, and transforms down to children.
675
- */
676
- export function flattenLayers(
677
- spec: LayerSpec,
678
- parentData?: DataRow[],
679
- parentEncoding?: Encoding,
680
- parentTransforms?: import('@opendata-ai/openchart-core').Transform[],
681
- parentWatermark?: boolean,
682
- parentEndpointLabels?: boolean | import('@opendata-ai/openchart-core').EndpointLabelsConfig,
683
- ): ChartSpec[] {
684
- const resolvedData = spec.data ?? parentData;
685
- const resolvedEncoding: Encoding | undefined =
686
- parentEncoding && spec.encoding
687
- ? { ...parentEncoding, ...spec.encoding }
688
- : (spec.encoding ?? parentEncoding);
689
- const resolvedTransforms = [...(parentTransforms ?? []), ...(spec.transform ?? [])];
690
- // Layer-level watermark propagates to children (child can still override)
691
- const resolvedWatermark = spec.watermark ?? parentWatermark;
692
- const resolvedEndpointLabels = spec.endpointLabels ?? parentEndpointLabels;
693
-
694
- const leaves: ChartSpec[] = [];
695
-
696
- for (const child of spec.layer) {
697
- if (isLayerSpec(child)) {
698
- // Nested layer: recurse with merged context
699
- leaves.push(
700
- ...flattenLayers(
701
- child,
702
- resolvedData,
703
- resolvedEncoding,
704
- resolvedTransforms,
705
- resolvedWatermark,
706
- resolvedEndpointLabels,
707
- ),
708
- );
709
- } else {
710
- // Leaf ChartSpec: merge inherited properties
711
- const mergedData = child.data ?? resolvedData ?? [];
712
- const mergedEncoding = resolvedEncoding
713
- ? { ...resolvedEncoding, ...child.encoding }
714
- : child.encoding;
715
- const mergedTransforms = [...resolvedTransforms, ...(child.transform ?? [])];
716
-
717
- leaves.push({
718
- ...child,
719
- data: mergedData,
720
- encoding: mergedEncoding,
721
- transform: mergedTransforms.length > 0 ? mergedTransforms : undefined,
722
- // Inherit parent watermark if child doesn't explicitly set one
723
- ...(child.watermark === undefined && resolvedWatermark !== undefined
724
- ? { watermark: resolvedWatermark }
725
- : {}),
726
- ...(child.endpointLabels === undefined && resolvedEndpointLabels !== undefined
727
- ? { endpointLabels: resolvedEndpointLabels }
728
- : {}),
729
- } as ChartSpec);
730
- }
731
- }
732
-
733
- return leaves;
734
- }