@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,1243 @@
1
+ import type {
2
+ CategoricalLegendLayout,
3
+ CompileOptions,
4
+ CompileWarning,
5
+ ContinuousLegendLayout,
6
+ EncodingChannel,
7
+ LegendEntry,
8
+ MapBorders,
9
+ MapFeatureMark,
10
+ MapFocus,
11
+ MapFocusLayout,
12
+ MapLayout,
13
+ MapPointMark,
14
+ ResolvedAnimation,
15
+ ResolvedTheme,
16
+ TextStyle,
17
+ TooltipContent,
18
+ TooltipField,
19
+ } from '@opendata-ai/openchart-core';
20
+ import {
21
+ adaptTheme,
22
+ buildD3Formatter,
23
+ CATEGORICAL_PALETTE,
24
+ computeChrome,
25
+ estimateTextWidth,
26
+ formatNumber,
27
+ getBreakpoint,
28
+ HPAD_COMPACT_FRACTION,
29
+ HPAD_COMPACT_MIN,
30
+ resolveTheme,
31
+ SEQUENTIAL_PALETTES,
32
+ } from '@opendata-ai/openchart-core';
33
+ import { geoArea, geoPath } from 'd3-geo';
34
+ import { scaleQuantile } from 'd3-scale';
35
+ import { feature as topoFeature, mesh as topoMesh } from 'topojson-client';
36
+ import type { GeometryCollection, Topology } from 'topojson-specification';
37
+ import { buildSizeScale, SIZE_SCALE_DEFAULTS } from '../compile/size-scale';
38
+ import { emitSpecWarnings, expandSpecSugar } from '../compile/spec-sugar';
39
+ import { resolveAnimation } from '../compiler/animation';
40
+ import { compile as compileSpec } from '../compiler/index';
41
+ import {
42
+ CONTINUOUS_BAR_HEIGHT,
43
+ CONTINUOUS_LABEL_GAP,
44
+ computeContinuousLegendContentForChannel,
45
+ } from '../legend/continuous';
46
+ import { joinDataToFeatures } from './join';
47
+ import { createProjection } from './projections';
48
+ import type { NormalizedMapSpec } from './types';
49
+
50
+ function validateGeoFeatures(geo: NormalizedMapSpec['geo']): Topology {
51
+ if (!geo.features) {
52
+ throw new Error(
53
+ 'Map spec error: geo.features is required but missing.\n\n' +
54
+ 'The map needs a TopoJSON topology object as geo.features. ' +
55
+ 'Install a standard atlas package and import it:\n\n' +
56
+ ' npm i us-atlas\n' +
57
+ ' import us from "us-atlas/states-albers-10m.json";\n\n' +
58
+ ' // or for world maps:\n' +
59
+ ' npm i world-atlas\n' +
60
+ ' import world from "world-atlas/countries-110m.json";\n\n' +
61
+ 'Then pass it as geo.features:\n\n' +
62
+ ' { type: "map", geo: { features: us }, data: [...], encoding: { ... } }',
63
+ );
64
+ }
65
+
66
+ const topo = geo.features as Record<string, unknown>;
67
+ if (typeof topo !== 'object' || topo === null || topo.type !== 'Topology' || !topo.objects) {
68
+ throw new Error(
69
+ 'Map spec error: geo.features must be a valid TopoJSON Topology ' +
70
+ '(expected an object with type: "Topology" and an "objects" property).\n\n' +
71
+ 'Make sure you are passing the full TopoJSON file, not a GeoJSON FeatureCollection. ' +
72
+ 'Atlas packages like us-atlas and world-atlas export TopoJSON by default:\n\n' +
73
+ ' npm i us-atlas\n' +
74
+ ' import us from "us-atlas/states-albers-10m.json";\n' +
75
+ ' { type: "map", geo: { features: us }, ... }',
76
+ );
77
+ }
78
+
79
+ const objects = topo.objects as Record<string, unknown>;
80
+ if (Object.keys(objects).length === 0) {
81
+ throw new Error(
82
+ 'Map spec error: geo.features.objects is empty (no geometry collections found). ' +
83
+ 'The TopoJSON file must contain at least one named geometry collection.',
84
+ );
85
+ }
86
+
87
+ return topo as unknown as Topology;
88
+ }
89
+
90
+ export function compileMap(spec: unknown, options: CompileOptions): MapLayout {
91
+ // 1. Sugar expansion + validate + normalize
92
+ const sugarWarnings: string[] = [];
93
+ const expandedSpec =
94
+ spec && typeof spec === 'object' && !Array.isArray(spec)
95
+ ? expandSpecSugar(spec as Record<string, unknown>, sugarWarnings)
96
+ : spec;
97
+ const { spec: normalized, warnings } = compileSpec(expandedSpec);
98
+ emitSpecWarnings([...sugarWarnings, ...warnings], options.onWarn);
99
+
100
+ if (!('type' in normalized) || normalized.type !== 'map') {
101
+ throw new Error(
102
+ 'compileMap received a non-map spec. Use compileChart, compileTileMap, compileSankey, or compileBarList instead.',
103
+ );
104
+ }
105
+
106
+ const mapSpec = normalized as NormalizedMapSpec;
107
+
108
+ // 2. Validate geo features
109
+ const topology = validateGeoFeatures(mapSpec.geo);
110
+
111
+ // Resolve watermark
112
+ const rawWatermark = (spec as Record<string, unknown>).watermark;
113
+ const watermark = rawWatermark !== undefined ? mapSpec.watermark : (options.watermark ?? true);
114
+
115
+ // 3. Resolve theme
116
+ const mergedThemeConfig = options.theme ? { ...mapSpec.theme, ...options.theme } : mapSpec.theme;
117
+ const lightTheme: ResolvedTheme = resolveTheme(mergedThemeConfig);
118
+ let theme: ResolvedTheme = lightTheme;
119
+ if (options.darkMode) {
120
+ theme = adaptTheme(theme);
121
+ }
122
+ const isDarkMode = options.darkMode;
123
+
124
+ // 4. Chrome
125
+ const chrome = computeChrome(
126
+ {
127
+ title: mapSpec.chrome.title,
128
+ subtitle: mapSpec.chrome.subtitle,
129
+ source: mapSpec.chrome.source,
130
+ byline: mapSpec.chrome.byline,
131
+ footer: mapSpec.chrome.footer,
132
+ },
133
+ theme,
134
+ options.width,
135
+ options.measureText,
136
+ 'full',
137
+ undefined,
138
+ watermark,
139
+ );
140
+
141
+ // 5. Drawing area
142
+ const padding =
143
+ getBreakpoint(options.width) === 'compact'
144
+ ? Math.max(HPAD_COMPACT_MIN, Math.round(theme.spacing.padding * HPAD_COMPACT_FRACTION))
145
+ : theme.spacing.padding;
146
+ const fullArea = {
147
+ x: padding,
148
+ y: padding + chrome.topHeight,
149
+ width: options.width - padding * 2,
150
+ height: options.height - chrome.topHeight - chrome.bottomHeight - padding * 2,
151
+ };
152
+
153
+ if (fullArea.width <= 0 || fullArea.height <= 0) {
154
+ return emptyLayout(chrome, theme, options, watermark);
155
+ }
156
+
157
+ // 6. Parse TopoJSON -> GeoJSON
158
+ const objectKey = Object.keys(topology.objects)[0];
159
+ const geoCollection = topoFeature(topology, topology.objects[objectKey] as GeometryCollection);
160
+ const geoFeatures = geoCollection.features;
161
+
162
+ // 7. Compile warnings
163
+ const compileWarnings: CompileWarning[] = [];
164
+
165
+ // 8. Legend height reserve
166
+ const showLegend = mapSpec.legend?.show !== false;
167
+ const colorEncoding = mapSpec.encoding.color;
168
+ const isQuantitative = colorEncoding?.type === 'quantitative';
169
+ const legendPosition = mapSpec.legend?.position === 'bottom' ? 'bottom' : 'top';
170
+
171
+ // Compute legend block height. For quantitative maps, use the continuous
172
+ // legend infrastructure; for categorical, estimate a single swatch row.
173
+ let legendBlockHeight = 0;
174
+ let continuousContent: ReturnType<typeof computeContinuousLegendContentForChannel> = null;
175
+ if (showLegend && colorEncoding && isQuantitative) {
176
+ const colorValues: number[] = [];
177
+ for (const row of mapSpec.data) {
178
+ const v = row[colorEncoding.field];
179
+ if (v != null) {
180
+ const n = Number(v);
181
+ if (!Number.isNaN(n)) colorValues.push(n);
182
+ }
183
+ }
184
+ // Maps always use a quantile color scale, so tell the legend infra
185
+ // to produce binned swatches rather than a gradient bar.
186
+ const legendChannel: EncodingChannel = {
187
+ ...colorEncoding,
188
+ scale: { ...colorEncoding.scale, type: 'quantile' },
189
+ };
190
+ continuousContent = computeContinuousLegendContentForChannel(
191
+ colorValues,
192
+ legendChannel,
193
+ theme,
194
+ fullArea.width,
195
+ );
196
+ if (continuousContent) {
197
+ const labelRowHeight = Math.ceil(theme.fonts.sizes.small * 1.3);
198
+ legendBlockHeight = continuousContent.barHeight + CONTINUOUS_LABEL_GAP + labelRowHeight;
199
+ }
200
+ } else if (showLegend && colorEncoding) {
201
+ const labelHeight = Math.ceil(theme.fonts.sizes.small * 1.3);
202
+ legendBlockHeight = Math.max(10, labelHeight) + 6;
203
+ }
204
+
205
+ // Reserve height for point color legend if applicable
206
+ if (showLegend && mapSpec.points?.color) {
207
+ if (mapSpec.points.color.type === 'quantitative') {
208
+ const labelRowHeight = Math.ceil(theme.fonts.sizes.small * 1.3);
209
+ legendBlockHeight += CONTINUOUS_BAR_HEIGHT + CONTINUOUS_LABEL_GAP + labelRowHeight + 8;
210
+ } else {
211
+ const ptLabelHeight = Math.ceil(theme.fonts.sizes.small * 1.3);
212
+ legendBlockHeight += Math.max(10, ptLabelHeight) + 6 + 8; // swatch row + gap
213
+ }
214
+ }
215
+
216
+ const legendReserveGap = legendBlockHeight > 0 ? 8 : 0;
217
+
218
+ const mapAreaHeight = fullArea.height - legendBlockHeight - legendReserveGap;
219
+ if (mapAreaHeight <= 0) {
220
+ return emptyLayout(chrome, theme, options, watermark);
221
+ }
222
+
223
+ // 9. Projection + path generator
224
+ const projectionType = mapSpec.geo.projection;
225
+ const projection = createProjection(projectionType, fullArea.width, mapAreaHeight, geoCollection);
226
+ const pathGen = geoPath(projection);
227
+
228
+ // 10. Check winding order (skip for identity: geoArea uses spherical math
229
+ // and gives false positives on planar pre-projected coordinates)
230
+ if (projectionType !== 'identity') {
231
+ for (const feat of geoFeatures) {
232
+ const area = geoArea(feat);
233
+ if (area > 2 * Math.PI) {
234
+ const name =
235
+ ((feat.properties as Record<string, unknown> | null)?.name as string) ??
236
+ ((feat.properties as Record<string, unknown> | null)?.NAME as string) ??
237
+ String(feat.id);
238
+ compileWarnings.push({
239
+ code: 'INVERTED_WINDING',
240
+ message:
241
+ `Feature "${name}" has inverted winding order (geoArea > 2π). ` +
242
+ 'This usually means the exterior ring is wound clockwise (RFC 7946) instead of ' +
243
+ 'counter-clockwise (d3-geo convention). Fix with: npx topojson-rewind your-file.json',
244
+ context: { featureId: feat.id, featureName: name },
245
+ });
246
+ }
247
+ }
248
+ }
249
+
250
+ // 11. Join data to features
251
+ const featureObjs = geoFeatures.map((f) => ({
252
+ id: f.id as string | number,
253
+ properties: (f.properties ?? {}) as Record<string, unknown>,
254
+ }));
255
+ const { joined, warnings: joinWarnings } = joinDataToFeatures(
256
+ featureObjs,
257
+ mapSpec.data,
258
+ mapSpec.encoding.key.field,
259
+ mapSpec.geo.idField,
260
+ );
261
+ // In basemap-only mode (empty data + points layer), all features are intentionally unmatched
262
+ const filteredJoinWarnings =
263
+ mapSpec.data.length === 0 && mapSpec.points
264
+ ? joinWarnings.filter((w) => w.code !== 'UNMATCHED_FEATURES')
265
+ : joinWarnings;
266
+ compileWarnings.push(...filteredJoinWarnings);
267
+
268
+ // 12. Check for null-projecting features (albersUsa drops territories)
269
+ const droppedFeatures: string[] = [];
270
+
271
+ // 13. Build color scale + feature marks
272
+ const formatter = buildD3Formatter(mapSpec.valueFormat) ?? formatNumber;
273
+ const neutralFill = isDarkMode ? '#2a2a2a' : '#e8e8e8';
274
+ const neutralStroke = isDarkMode ? 'rgba(255,255,255,0.08)' : 'rgba(0,0,0,0.06)';
275
+
276
+ let featureMarks: MapFeatureMark[];
277
+ let continuousLegend: ContinuousLegendLayout | null = null;
278
+ let categoricalLegend: CategoricalLegendLayout | null = null;
279
+
280
+ if (!colorEncoding) {
281
+ // Basemap-only mode: all features get neutral fill, no legend
282
+ featureMarks = buildBasemapMarks({
283
+ geoFeatures,
284
+ pathGen,
285
+ neutralFill,
286
+ neutralStroke,
287
+ droppedFeatures,
288
+ });
289
+ } else if (isQuantitative) {
290
+ const result = buildQuantitativeMarks({
291
+ geoFeatures,
292
+ pathGen,
293
+ joined,
294
+ colorField: colorEncoding.field,
295
+ palette: colorEncoding.scale?.scheme ?? 'blue',
296
+ isDarkMode: !!isDarkMode,
297
+ neutralFill,
298
+ neutralStroke,
299
+ formatter,
300
+ droppedFeatures,
301
+ });
302
+ featureMarks = result.marks;
303
+
304
+ // Build the continuous legend. Maps place it directly (not via placeLegend,
305
+ // which does cartesian-specific positioning above the chart area).
306
+ if (showLegend && continuousContent) {
307
+ const labelStyle: TextStyle = {
308
+ fontFamily: theme.fonts.family,
309
+ fontSize: theme.fonts.sizes.small,
310
+ fontWeight: theme.fonts.weights.normal,
311
+ fill: theme.colors.text,
312
+ lineHeight: 1.3,
313
+ fontVariant: 'tabular-nums',
314
+ };
315
+ const legendX = fullArea.x;
316
+ const legendY =
317
+ legendPosition === 'bottom'
318
+ ? fullArea.y + mapAreaHeight + legendReserveGap
319
+ : fullArea.y + legendReserveGap;
320
+ const bounds = {
321
+ x: legendX,
322
+ y: legendY,
323
+ width: continuousContent.barWidth,
324
+ height: legendBlockHeight,
325
+ };
326
+ const bar = {
327
+ x: bounds.x,
328
+ y: bounds.y,
329
+ width: continuousContent.barWidth,
330
+ height: continuousContent.barHeight,
331
+ };
332
+ continuousLegend = {
333
+ type: 'continuous' as const,
334
+ mode: continuousContent.mode,
335
+ position: legendPosition,
336
+ bounds,
337
+ labelStyle,
338
+ bar,
339
+ colorStops: continuousContent.colorStops,
340
+ bins: continuousContent.bins.map((b) => ({ ...b, x: b.x + bar.x })),
341
+ ticks: continuousContent.ticks.map((t) => ({ ...t, x: t.x + bar.x })),
342
+ labelY: bar.y + bar.height + CONTINUOUS_LABEL_GAP + labelStyle.fontSize,
343
+ };
344
+ }
345
+ } else {
346
+ const result = buildCategoricalMarks({
347
+ geoFeatures,
348
+ pathGen,
349
+ joined,
350
+ colorField: colorEncoding.field,
351
+ isDarkMode: !!isDarkMode,
352
+ neutralFill,
353
+ neutralStroke,
354
+ theme,
355
+ fullArea,
356
+ mapAreaHeight,
357
+ legendReserveGap,
358
+ showLegend,
359
+ droppedFeatures,
360
+ });
361
+ featureMarks = result.marks;
362
+ categoricalLegend = result.legend;
363
+ }
364
+
365
+ // Report dropped features (null-projecting)
366
+ if (droppedFeatures.length > 0) {
367
+ compileWarnings.push({
368
+ code: 'NULL_PROJECTION',
369
+ message:
370
+ `${droppedFeatures.length} feature(s) project to null and were dropped: ${droppedFeatures.join(', ')}. ` +
371
+ 'This is common with albersUsa which excludes territories (PR, GU, VI, AS, MP). ' +
372
+ 'If your data includes these, consider using projection: "mercator" or "equalEarth".',
373
+ context: { features: droppedFeatures },
374
+ });
375
+ }
376
+
377
+ // 15. Borders via topojson mesh
378
+ const interiorMesh = topoMesh(
379
+ topology,
380
+ topology.objects[objectKey] as GeometryCollection,
381
+ (a, b) => a !== b,
382
+ );
383
+ const outlineMesh = topoMesh(
384
+ topology,
385
+ topology.objects[objectKey] as GeometryCollection,
386
+ (a, b) => a === b,
387
+ );
388
+
389
+ const interiorPath = pathGen(interiorMesh) ?? '';
390
+ const outlinePath = pathGen(outlineMesh) ?? '';
391
+
392
+ const interiorStroke = isDarkMode ? 'rgba(255,255,255,0.3)' : 'rgba(0,0,0,0.15)';
393
+ const outlineStroke = isDarkMode ? 'rgba(255,255,255,0.5)' : 'rgba(0,0,0,0.3)';
394
+ const borders: MapBorders = { interiorPath, outlinePath, interiorStroke, outlineStroke };
395
+
396
+ // 15b. Point marks (symbol layer above choropleth)
397
+ const pointMarks: MapPointMark[] = [];
398
+ let pointCategoricalLegend: CategoricalLegendLayout | null = null;
399
+ let pointContinuousLegend: ContinuousLegendLayout | null = null;
400
+
401
+ if (mapSpec.points) {
402
+ const pts = mapSpec.points;
403
+ const lonField = pts.longitude.field;
404
+ const latField = pts.latitude.field;
405
+ const keyChannel = pts.key;
406
+
407
+ // Size scale
408
+ const sizeScale = buildSizeScale(pts.size, pts.data, SIZE_SCALE_DEFAULTS.mapPoint);
409
+
410
+ // Color scale (independent from choropleth)
411
+ let pointColorScale: ((val: unknown) => string) | null = null;
412
+ const pointCategories: string[] = [];
413
+ const pointCategoryColors = new Map<string, string>();
414
+
415
+ if (pts.color) {
416
+ if (pts.color.type === 'quantitative') {
417
+ const colorValues: number[] = [];
418
+ for (const row of pts.data) {
419
+ const raw = row[pts.color.field];
420
+ if (raw != null) {
421
+ const v = Number(raw);
422
+ if (Number.isFinite(v)) colorValues.push(v);
423
+ }
424
+ }
425
+ if (colorValues.length > 0) {
426
+ const palette = pts.color.scale?.scheme ?? 'blue';
427
+ const paletteStops = [...(SEQUENTIAL_PALETTES[palette] ?? SEQUENTIAL_PALETTES.blue)];
428
+ const qScale = scaleQuantile<string>().domain(colorValues).range(paletteStops);
429
+ pointColorScale = (val: unknown) => {
430
+ const v = Number(val);
431
+ return Number.isFinite(v) ? qScale(v) : CATEGORICAL_PALETTE[0];
432
+ };
433
+ }
434
+ } else {
435
+ // nominal / ordinal
436
+ const seen = new Set<string>();
437
+ for (const row of pts.data) {
438
+ const raw = row[pts.color.field];
439
+ if (raw != null) {
440
+ const cat = String(raw);
441
+ if (!seen.has(cat)) {
442
+ seen.add(cat);
443
+ pointCategories.push(cat);
444
+ pointCategoryColors.set(
445
+ cat,
446
+ CATEGORICAL_PALETTE[(pointCategories.length - 1) % CATEGORICAL_PALETTE.length],
447
+ );
448
+ }
449
+ }
450
+ }
451
+ pointColorScale = (val: unknown) => {
452
+ if (val == null) return CATEGORICAL_PALETTE[0];
453
+ return pointCategoryColors.get(String(val)) ?? CATEGORICAL_PALETTE[0];
454
+ };
455
+ }
456
+ }
457
+
458
+ const defaultFill = CATEGORICAL_PALETTE[0];
459
+ let animIndex = 0;
460
+
461
+ for (let i = 0; i < pts.data.length; i++) {
462
+ const row = pts.data[i];
463
+ const lon = Number(row[lonField]);
464
+ const lat = Number(row[latField]);
465
+ if (!Number.isFinite(lon) || !Number.isFinite(lat)) continue;
466
+
467
+ const projected = projection([lon, lat]);
468
+ if (!projected) {
469
+ compileWarnings.push({
470
+ code: 'POINT_NULL_PROJECTION',
471
+ message: `Point at [${lon}, ${lat}] projects to null and was dropped.`,
472
+ context: { lon, lat },
473
+ });
474
+ continue;
475
+ }
476
+
477
+ const r = sizeScale ? sizeScale.scale(Number(row[sizeScale.field])) : 5;
478
+ const fill =
479
+ pointColorScale && pts.color ? pointColorScale(row[pts.color.field]) : defaultFill;
480
+ const key = keyChannel ? String(row[keyChannel.field] ?? i) : String(i);
481
+ const stroke = isDarkMode ? 'rgba(0,0,0,0.5)' : 'rgba(255,255,255,0.8)';
482
+
483
+ pointMarks.push({
484
+ type: 'map-point',
485
+ cx: projected[0],
486
+ cy: projected[1],
487
+ r,
488
+ fill,
489
+ stroke,
490
+ strokeWidth: 1,
491
+ key,
492
+ data: row as Record<string, unknown>,
493
+ aria: { role: 'img', label: key },
494
+ animationIndex: animIndex++,
495
+ });
496
+ }
497
+
498
+ // Point categorical legend
499
+ if (
500
+ pts.color &&
501
+ pts.color.type !== 'quantitative' &&
502
+ pointCategories.length > 0 &&
503
+ showLegend
504
+ ) {
505
+ const labelStyle: TextStyle = {
506
+ fontFamily: theme.fonts.family,
507
+ fontSize: theme.fonts.sizes.small,
508
+ fontWeight: theme.fonts.weights.normal,
509
+ fill: theme.colors.text,
510
+ lineHeight: 1.2,
511
+ };
512
+
513
+ const entries: LegendEntry[] = pointCategories.map((cat) => ({
514
+ label: cat,
515
+ color: pointCategoryColors.get(cat)!,
516
+ shape: 'circle' as const,
517
+ }));
518
+
519
+ // Position below the choropleth legend (or at the legend position if none)
520
+ const choroplethLegendHeight = continuousLegend
521
+ ? continuousLegend.bounds.height
522
+ : categoricalLegend
523
+ ? categoricalLegend.bounds.height
524
+ : 0;
525
+ const choroplethLegendGap = choroplethLegendHeight > 0 ? 8 : 0;
526
+ const legendX = fullArea.x;
527
+ const legendY =
528
+ fullArea.y +
529
+ mapAreaHeight +
530
+ legendReserveGap +
531
+ choroplethLegendHeight +
532
+ choroplethLegendGap;
533
+ const legendWidth = fullArea.width;
534
+ const swatchSize = 10;
535
+ const swatchGap = 6;
536
+ const entryGap = 16;
537
+
538
+ pointCategoricalLegend = {
539
+ type: 'categorical',
540
+ position: 'bottom',
541
+ bounds: { x: legendX, y: legendY, width: legendWidth, height: swatchSize + 6 },
542
+ labelStyle,
543
+ entries,
544
+ swatchSize,
545
+ swatchGap,
546
+ entryGap,
547
+ swatchChipFill: isDarkMode ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)',
548
+ };
549
+ }
550
+
551
+ // Point continuous legend (quantitative color)
552
+ if (pts.color && pts.color.type === 'quantitative' && showLegend) {
553
+ const ptColorValues: number[] = [];
554
+ for (const row of pts.data) {
555
+ const v = row[pts.color.field];
556
+ if (v != null) {
557
+ const n = Number(v);
558
+ if (Number.isFinite(n)) ptColorValues.push(n);
559
+ }
560
+ }
561
+ const ptLegendChannel: EncodingChannel = {
562
+ ...pts.color,
563
+ scale: { ...pts.color.scale, type: 'quantile' },
564
+ };
565
+ const ptContinuousContent = computeContinuousLegendContentForChannel(
566
+ ptColorValues,
567
+ ptLegendChannel,
568
+ theme,
569
+ fullArea.width,
570
+ );
571
+ if (ptContinuousContent) {
572
+ const labelStyle: TextStyle = {
573
+ fontFamily: theme.fonts.family,
574
+ fontSize: theme.fonts.sizes.small,
575
+ fontWeight: theme.fonts.weights.normal,
576
+ fill: theme.colors.text,
577
+ lineHeight: 1.3,
578
+ fontVariant: 'tabular-nums',
579
+ };
580
+ const choroplethLegendHeight = continuousLegend
581
+ ? continuousLegend.bounds.height
582
+ : categoricalLegend
583
+ ? categoricalLegend.bounds.height
584
+ : 0;
585
+ const choroplethLegendGap = choroplethLegendHeight > 0 ? 8 : 0;
586
+ const legendX = fullArea.x;
587
+ const legendY =
588
+ fullArea.y +
589
+ mapAreaHeight +
590
+ legendReserveGap +
591
+ choroplethLegendHeight +
592
+ choroplethLegendGap;
593
+ const ptLabelRowHeight = Math.ceil(theme.fonts.sizes.small * 1.3);
594
+ const ptLegendHeight =
595
+ ptContinuousContent.barHeight + CONTINUOUS_LABEL_GAP + ptLabelRowHeight;
596
+ const bounds = {
597
+ x: legendX,
598
+ y: legendY,
599
+ width: ptContinuousContent.barWidth,
600
+ height: ptLegendHeight,
601
+ };
602
+ const bar = {
603
+ x: bounds.x,
604
+ y: bounds.y,
605
+ width: ptContinuousContent.barWidth,
606
+ height: ptContinuousContent.barHeight,
607
+ };
608
+ pointContinuousLegend = {
609
+ type: 'continuous' as const,
610
+ mode: ptContinuousContent.mode,
611
+ position: 'bottom',
612
+ bounds,
613
+ labelStyle,
614
+ bar,
615
+ colorStops: ptContinuousContent.colorStops,
616
+ bins: ptContinuousContent.bins.map((b) => ({ ...b, x: b.x + bar.x })),
617
+ ticks: ptContinuousContent.ticks.map((t) => ({ ...t, x: t.x + bar.x })),
618
+ labelY: bar.y + bar.height + CONTINUOUS_LABEL_GAP + labelStyle.fontSize,
619
+ };
620
+ }
621
+ }
622
+ }
623
+
624
+ // 16. Tooltips
625
+ const tooltipChannels = mapSpec.encoding.tooltip
626
+ ? Array.isArray(mapSpec.encoding.tooltip)
627
+ ? mapSpec.encoding.tooltip
628
+ : [mapSpec.encoding.tooltip]
629
+ : null;
630
+
631
+ const tooltipDescriptors = new Map<string, TooltipContent>();
632
+ for (const mark of featureMarks) {
633
+ if (!mark.data) continue;
634
+ const fields: TooltipField[] = [];
635
+ const name = mark.name ?? String(mark.id);
636
+ fields.push({ label: 'Region', value: name });
637
+
638
+ if (tooltipChannels) {
639
+ for (const ch of tooltipChannels) {
640
+ const val = mark.data[ch.field];
641
+ if (val != null) {
642
+ fields.push({
643
+ label: ch.title ?? ch.field,
644
+ value: ch.type === 'quantitative' ? formatter(Number(val)) : String(val),
645
+ });
646
+ }
647
+ }
648
+ } else if (colorEncoding && isQuantitative && mark.data[colorEncoding.field] != null) {
649
+ fields.push({
650
+ label: colorEncoding.title ?? colorEncoding.field,
651
+ value: formatter(Number(mark.data[colorEncoding.field])),
652
+ });
653
+ } else if (colorEncoding && !isQuantitative && mark.data[colorEncoding.field] != null) {
654
+ fields.push({
655
+ label: colorEncoding.title ?? colorEncoding.field,
656
+ value: String(mark.data[colorEncoding.field]),
657
+ });
658
+ }
659
+ tooltipDescriptors.set(String(mark.id), { fields });
660
+ }
661
+
662
+ // Point tooltips (keyed with 'point:' prefix to disambiguate from feature IDs)
663
+ if (mapSpec.points && pointMarks.length > 0) {
664
+ const ptTooltipChannels = mapSpec.points.tooltip
665
+ ? Array.isArray(mapSpec.points.tooltip)
666
+ ? mapSpec.points.tooltip
667
+ : [mapSpec.points.tooltip]
668
+ : null;
669
+
670
+ for (const pm of pointMarks) {
671
+ const fields: TooltipField[] = [];
672
+ if (ptTooltipChannels) {
673
+ for (const ch of ptTooltipChannels) {
674
+ const val = pm.data[ch.field];
675
+ if (val != null) {
676
+ fields.push({
677
+ label: ch.title ?? ch.field,
678
+ value: ch.type === 'quantitative' ? formatter(Number(val)) : String(val),
679
+ });
680
+ }
681
+ }
682
+ } else {
683
+ // Auto-populate from key, color, and size channels
684
+ const pts = mapSpec.points!;
685
+ if (pts.key) {
686
+ const val = pm.data[pts.key.field];
687
+ if (val != null)
688
+ fields.push({ label: pts.key.title ?? pts.key.field, value: String(val) });
689
+ }
690
+ if (pts.color) {
691
+ const val = pm.data[pts.color.field];
692
+ if (val != null)
693
+ fields.push({
694
+ label: pts.color.title ?? pts.color.field,
695
+ value: pts.color.type === 'quantitative' ? formatter(Number(val)) : String(val),
696
+ });
697
+ }
698
+ if (pts.size) {
699
+ const val = pm.data[pts.size.field];
700
+ if (val != null)
701
+ fields.push({ label: pts.size.title ?? pts.size.field, value: formatter(Number(val)) });
702
+ }
703
+ }
704
+ if (fields.length > 0) {
705
+ tooltipDescriptors.set(`point:${pm.key}`, { fields });
706
+ }
707
+ }
708
+ }
709
+
710
+ // 17. Accessibility
711
+ const a11yDataField = colorEncoding?.field;
712
+ const a11y = {
713
+ altText:
714
+ pointMarks.length > 0
715
+ ? colorEncoding
716
+ ? `Map showing ${geoFeatures.length} regions with ${isQuantitative ? 'quantitative' : 'categorical'} data and ${pointMarks.length} point markers`
717
+ : `Map showing ${geoFeatures.length} regions with ${pointMarks.length} point markers`
718
+ : colorEncoding
719
+ ? `Map showing ${geoFeatures.length} regions with ${isQuantitative ? 'quantitative' : 'categorical'} data`
720
+ : `Map showing ${geoFeatures.length} regions`,
721
+ dataTableFallback: [
722
+ ...featureMarks
723
+ .filter((m) => m.data)
724
+ .map((m) => [
725
+ m.name ?? String(m.id),
726
+ a11yDataField ? String(m.data?.[a11yDataField] ?? '') : '',
727
+ ]),
728
+ ...pointMarks.map((pm) => [
729
+ pm.key,
730
+ mapSpec.points?.color ? String(pm.data[mapSpec.points.color.field] ?? '') : '',
731
+ ]),
732
+ ],
733
+ role: 'img' as const,
734
+ keyboardNavigable: featureMarks.length > 0 || pointMarks.length > 0,
735
+ };
736
+
737
+ // 18. Resolve focus
738
+ const resolvedFocus = resolveFocus(mapSpec.geo.focus, featureMarks, compileWarnings);
739
+
740
+ // 19. Animation
741
+ const resolvedAnimation: ResolvedAnimation | undefined = resolveAnimation(mapSpec.animation);
742
+
743
+ // 20. Compute the map drawing area (offset when legend is at top)
744
+ const mapAreaY =
745
+ legendPosition === 'top' && legendBlockHeight > 0
746
+ ? fullArea.y + legendBlockHeight + legendReserveGap
747
+ : fullArea.y;
748
+ const mapArea = {
749
+ x: fullArea.x,
750
+ y: mapAreaY,
751
+ width: fullArea.width,
752
+ height: mapAreaHeight,
753
+ };
754
+
755
+ // 21. Anchor bottom chrome below the map + legend, then compute total height
756
+ chrome.bottomAnchorY = fullArea.y + fullArea.height;
757
+ const contentHeight =
758
+ fullArea.y +
759
+ mapAreaHeight +
760
+ legendReserveGap +
761
+ legendBlockHeight +
762
+ chrome.bottomHeight +
763
+ padding;
764
+
765
+ // 22. Emit compile warnings
766
+ for (const w of compileWarnings) {
767
+ if (options.onWarn) {
768
+ options.onWarn(w.message);
769
+ }
770
+ }
771
+
772
+ return {
773
+ area: mapArea,
774
+ chrome,
775
+ features: featureMarks,
776
+ borders,
777
+ continuousLegend,
778
+ categoricalLegend,
779
+ pointMarks,
780
+ pointCategoricalLegend,
781
+ pointContinuousLegend,
782
+ tooltipDescriptors,
783
+ a11y,
784
+ theme,
785
+ width: options.width,
786
+ height: contentHeight,
787
+ animation: resolvedAnimation,
788
+ watermark,
789
+ measureText:
790
+ options.measureText ??
791
+ ((text, fontSize) => ({ width: estimateTextWidth(text, fontSize), height: fontSize })),
792
+ warnings: compileWarnings,
793
+ mapSize: { width: fullArea.width, height: mapAreaHeight },
794
+ focus: resolvedFocus,
795
+ };
796
+ }
797
+
798
+ // ---------------------------------------------------------------------------
799
+ // Basemap-only marks (neutral fill, no color encoding)
800
+ // ---------------------------------------------------------------------------
801
+
802
+ interface BasemapOptions {
803
+ geoFeatures: GeoJSON.Feature[];
804
+ pathGen: ReturnType<typeof geoPath>;
805
+ neutralFill: string;
806
+ neutralStroke: string;
807
+ droppedFeatures: string[];
808
+ }
809
+
810
+ function buildBasemapMarks(opts: BasemapOptions): MapFeatureMark[] {
811
+ const { geoFeatures, pathGen, neutralFill, neutralStroke, droppedFeatures } = opts;
812
+ const marks: MapFeatureMark[] = [];
813
+ let animIndex = 0;
814
+
815
+ for (const feat of geoFeatures) {
816
+ const pathD = pathGen(feat);
817
+ if (!pathD) {
818
+ const name =
819
+ ((feat.properties as Record<string, unknown> | null)?.name as string) ?? String(feat.id);
820
+ droppedFeatures.push(name);
821
+ continue;
822
+ }
823
+
824
+ const featureId = feat.id as string | number;
825
+ const props = feat.properties as Record<string, unknown> | null;
826
+ const name = (props?.name as string) ?? (props?.NAME as string);
827
+
828
+ const b = pathGen.bounds(feat);
829
+ const bx = Number.isFinite(b[0][0]) ? b[0][0] : 0;
830
+ const by = Number.isFinite(b[0][1]) ? b[0][1] : 0;
831
+ const bw = Number.isFinite(b[1][0]) ? b[1][0] - bx : 0;
832
+ const bh = Number.isFinite(b[1][1]) ? b[1][1] - by : 0;
833
+ const bounds = { x: bx, y: by, width: bw, height: bh };
834
+ const rawCentroid = pathGen.centroid(feat);
835
+ const cx = Number.isFinite(rawCentroid[0]) ? rawCentroid[0] : bx + bw / 2;
836
+ const cy = Number.isFinite(rawCentroid[1]) ? rawCentroid[1] : by + bh / 2;
837
+
838
+ marks.push({
839
+ type: 'map-feature',
840
+ path: pathD,
841
+ fill: neutralFill,
842
+ stroke: neutralStroke,
843
+ strokeWidth: 0.5,
844
+ id: featureId,
845
+ name,
846
+ data: null,
847
+ aria: { role: 'img', label: name ?? String(featureId) },
848
+ animationIndex: animIndex++,
849
+ bounds,
850
+ centroid: [cx, cy],
851
+ });
852
+ }
853
+
854
+ return marks;
855
+ }
856
+
857
+ // ---------------------------------------------------------------------------
858
+ // Quantitative marks (sequential color scale)
859
+ // ---------------------------------------------------------------------------
860
+
861
+ interface QuantitativeOptions {
862
+ geoFeatures: GeoJSON.Feature[];
863
+ pathGen: ReturnType<typeof geoPath>;
864
+ joined: Map<string | number, Record<string, unknown>>;
865
+ colorField: string;
866
+ palette: string;
867
+ isDarkMode: boolean;
868
+ neutralFill: string;
869
+ neutralStroke: string;
870
+ formatter: (n: number) => string;
871
+ droppedFeatures: string[];
872
+ }
873
+
874
+ function buildQuantitativeMarks(opts: QuantitativeOptions): {
875
+ marks: MapFeatureMark[];
876
+ } {
877
+ const {
878
+ geoFeatures,
879
+ pathGen,
880
+ joined,
881
+ colorField,
882
+ palette,
883
+ isDarkMode,
884
+ neutralFill,
885
+ neutralStroke,
886
+ formatter,
887
+ droppedFeatures,
888
+ } = opts;
889
+
890
+ // Collect values for scale domain
891
+ const values: number[] = [];
892
+ for (const row of joined.values()) {
893
+ const raw = row[colorField];
894
+ if (raw != null) {
895
+ const v = Number(raw);
896
+ if (!Number.isNaN(v)) values.push(v);
897
+ }
898
+ }
899
+
900
+ const paletteStops = [...(SEQUENTIAL_PALETTES[palette] ?? SEQUENTIAL_PALETTES.blue)];
901
+ const colorScale = scaleQuantile<string>().domain(values).range(paletteStops);
902
+
903
+ const marks: MapFeatureMark[] = [];
904
+ let animIndex = 0;
905
+
906
+ for (const feat of geoFeatures) {
907
+ const pathD = pathGen(feat);
908
+ if (!pathD) {
909
+ const name =
910
+ ((feat.properties as Record<string, unknown> | null)?.name as string) ?? String(feat.id);
911
+ droppedFeatures.push(name);
912
+ continue;
913
+ }
914
+
915
+ const featureId = feat.id as string | number;
916
+ const dataRow = joined.get(featureId) ?? null;
917
+ const hasData = dataRow !== null;
918
+
919
+ let fill = neutralFill;
920
+ let stroke = neutralStroke;
921
+ if (hasData) {
922
+ const raw = dataRow[colorField];
923
+ if (raw != null) {
924
+ const v = Number(raw);
925
+ if (!Number.isNaN(v)) {
926
+ fill = colorScale(v);
927
+ }
928
+ }
929
+ stroke = isDarkMode ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)';
930
+ }
931
+
932
+ const props = feat.properties as Record<string, unknown> | null;
933
+ const name = (props?.name as string) ?? (props?.NAME as string);
934
+
935
+ // Compute projected geometry (guard non-finite bounds from degenerate features)
936
+ const b = pathGen.bounds(feat);
937
+ const bx = Number.isFinite(b[0][0]) ? b[0][0] : 0;
938
+ const by = Number.isFinite(b[0][1]) ? b[0][1] : 0;
939
+ const bw = Number.isFinite(b[1][0]) ? b[1][0] - bx : 0;
940
+ const bh = Number.isFinite(b[1][1]) ? b[1][1] - by : 0;
941
+ const bounds = { x: bx, y: by, width: bw, height: bh };
942
+ const rawCentroid = pathGen.centroid(feat);
943
+ const cx = Number.isFinite(rawCentroid[0]) ? rawCentroid[0] : bx + bw / 2;
944
+ const cy = Number.isFinite(rawCentroid[1]) ? rawCentroid[1] : by + bh / 2;
945
+
946
+ marks.push({
947
+ type: 'map-feature',
948
+ path: pathD,
949
+ fill,
950
+ stroke,
951
+ strokeWidth: 0.5,
952
+ id: featureId,
953
+ name,
954
+ data: dataRow,
955
+ aria: {
956
+ role: 'img',
957
+ label: name
958
+ ? `${name}: ${hasData && dataRow[colorField] != null && !Number.isNaN(Number(dataRow[colorField])) ? formatter(Number(dataRow[colorField])) : 'no data'}`
959
+ : String(featureId),
960
+ },
961
+ animationIndex: animIndex++,
962
+ bounds,
963
+ centroid: [cx, cy],
964
+ });
965
+ }
966
+
967
+ return { marks };
968
+ }
969
+
970
+ // ---------------------------------------------------------------------------
971
+ // Categorical marks (distinct fill colors)
972
+ // ---------------------------------------------------------------------------
973
+
974
+ interface CategoricalOptions {
975
+ geoFeatures: GeoJSON.Feature[];
976
+ pathGen: ReturnType<typeof geoPath>;
977
+ joined: Map<string | number, Record<string, unknown>>;
978
+ colorField: string;
979
+ isDarkMode: boolean;
980
+ neutralFill: string;
981
+ neutralStroke: string;
982
+ theme: ResolvedTheme;
983
+ fullArea: { x: number; y: number; width: number; height: number };
984
+ mapAreaHeight: number;
985
+ legendReserveGap: number;
986
+ showLegend: boolean;
987
+ droppedFeatures: string[];
988
+ }
989
+
990
+ function buildCategoricalMarks(opts: CategoricalOptions): {
991
+ marks: MapFeatureMark[];
992
+ legend: CategoricalLegendLayout | null;
993
+ } {
994
+ const {
995
+ geoFeatures,
996
+ pathGen,
997
+ joined,
998
+ colorField,
999
+ isDarkMode,
1000
+ neutralFill,
1001
+ neutralStroke,
1002
+ theme,
1003
+ fullArea,
1004
+ mapAreaHeight,
1005
+ legendReserveGap,
1006
+ showLegend,
1007
+ droppedFeatures,
1008
+ } = opts;
1009
+
1010
+ // Collect unique categories in data order
1011
+ const categories: string[] = [];
1012
+ const seen = new Set<string>();
1013
+ for (const row of joined.values()) {
1014
+ const raw = row[colorField];
1015
+ if (raw != null) {
1016
+ const cat = String(raw);
1017
+ if (!seen.has(cat)) {
1018
+ seen.add(cat);
1019
+ categories.push(cat);
1020
+ }
1021
+ }
1022
+ }
1023
+
1024
+ const categoryColors = new Map<string, string>();
1025
+ for (let i = 0; i < categories.length; i++) {
1026
+ categoryColors.set(categories[i], CATEGORICAL_PALETTE[i % CATEGORICAL_PALETTE.length]);
1027
+ }
1028
+
1029
+ const marks: MapFeatureMark[] = [];
1030
+ let animIndex = 0;
1031
+
1032
+ for (const feat of geoFeatures) {
1033
+ const pathD = pathGen(feat);
1034
+ if (!pathD) {
1035
+ const name =
1036
+ ((feat.properties as Record<string, unknown> | null)?.name as string) ?? String(feat.id);
1037
+ droppedFeatures.push(name);
1038
+ continue;
1039
+ }
1040
+
1041
+ const featureId = feat.id as string | number;
1042
+ const dataRow = joined.get(featureId) ?? null;
1043
+ const hasData = dataRow !== null;
1044
+
1045
+ let fill = neutralFill;
1046
+ let stroke = neutralStroke;
1047
+ if (hasData) {
1048
+ const raw = dataRow[colorField];
1049
+ if (raw != null) {
1050
+ const cat = String(raw);
1051
+ fill = categoryColors.get(cat) ?? neutralFill;
1052
+ }
1053
+ stroke = isDarkMode ? 'rgba(255,255,255,0.1)' : 'rgba(0,0,0,0.1)';
1054
+ }
1055
+
1056
+ const props = feat.properties as Record<string, unknown> | null;
1057
+ const name = (props?.name as string) ?? (props?.NAME as string);
1058
+
1059
+ // Compute projected geometry (guard non-finite bounds from degenerate features)
1060
+ const b = pathGen.bounds(feat);
1061
+ const bx = Number.isFinite(b[0][0]) ? b[0][0] : 0;
1062
+ const by = Number.isFinite(b[0][1]) ? b[0][1] : 0;
1063
+ const bw = Number.isFinite(b[1][0]) ? b[1][0] - bx : 0;
1064
+ const bh = Number.isFinite(b[1][1]) ? b[1][1] - by : 0;
1065
+ const bounds = { x: bx, y: by, width: bw, height: bh };
1066
+ const rawCentroid = pathGen.centroid(feat);
1067
+ const cx = Number.isFinite(rawCentroid[0]) ? rawCentroid[0] : bx + bw / 2;
1068
+ const cy = Number.isFinite(rawCentroid[1]) ? rawCentroid[1] : by + bh / 2;
1069
+
1070
+ marks.push({
1071
+ type: 'map-feature',
1072
+ path: pathD,
1073
+ fill,
1074
+ stroke,
1075
+ strokeWidth: 0.5,
1076
+ id: featureId,
1077
+ name,
1078
+ data: dataRow,
1079
+ aria: {
1080
+ role: 'img',
1081
+ label: name
1082
+ ? `${name}: ${hasData ? String(dataRow[colorField]) : 'no data'}`
1083
+ : String(featureId),
1084
+ },
1085
+ animationIndex: animIndex++,
1086
+ bounds,
1087
+ centroid: [cx, cy],
1088
+ });
1089
+ }
1090
+
1091
+ // Legend
1092
+ let legend: CategoricalLegendLayout | null = null;
1093
+ if (showLegend && categories.length > 0) {
1094
+ const labelStyle: TextStyle = {
1095
+ fontFamily: theme.fonts.family,
1096
+ fontSize: 11,
1097
+ fontWeight: 400,
1098
+ fill: theme.colors.text,
1099
+ lineHeight: 1.2,
1100
+ };
1101
+
1102
+ const entries: LegendEntry[] = categories.map((cat) => ({
1103
+ label: cat,
1104
+ color: categoryColors.get(cat)!,
1105
+ shape: 'square' as const,
1106
+ }));
1107
+
1108
+ const legendX = fullArea.x;
1109
+ const legendY = fullArea.y + mapAreaHeight + legendReserveGap;
1110
+ const legendWidth = fullArea.width;
1111
+ const swatchSize = 10;
1112
+ const swatchGap = 6;
1113
+ const entryGap = 16;
1114
+
1115
+ legend = {
1116
+ type: 'categorical',
1117
+ position: 'bottom',
1118
+ bounds: { x: legendX, y: legendY, width: legendWidth, height: swatchSize + 6 },
1119
+ labelStyle,
1120
+ entries,
1121
+ swatchSize,
1122
+ swatchGap,
1123
+ entryGap,
1124
+ swatchChipFill: isDarkMode ? 'rgba(255,255,255,0.06)' : 'rgba(0,0,0,0.04)',
1125
+ };
1126
+ }
1127
+
1128
+ return { marks, legend };
1129
+ }
1130
+
1131
+ // ---------------------------------------------------------------------------
1132
+ // Focus resolution
1133
+ // ---------------------------------------------------------------------------
1134
+
1135
+ function resolveFocus(
1136
+ focus: MapFocus | null,
1137
+ features: MapFeatureMark[],
1138
+ warnings: CompileWarning[],
1139
+ ): MapFocusLayout | null {
1140
+ if (focus === null || focus === undefined) return null;
1141
+
1142
+ // Normalize to { ids, padding }
1143
+ let ids: Array<string | number>;
1144
+ let padding = 16;
1145
+
1146
+ if (typeof focus === 'string' || typeof focus === 'number') {
1147
+ ids = [focus];
1148
+ } else if (Array.isArray(focus)) {
1149
+ ids = focus;
1150
+ } else {
1151
+ // Object form: { features, padding? }
1152
+ const feats = focus.features;
1153
+ ids = typeof feats === 'string' || typeof feats === 'number' ? [feats] : feats;
1154
+ padding = focus.padding ?? 16;
1155
+ }
1156
+
1157
+ // Find matching features and compute union bounds
1158
+ const idSet = new Set(ids.map(String));
1159
+ let minX = Infinity;
1160
+ let minY = Infinity;
1161
+ let maxX = -Infinity;
1162
+ let maxY = -Infinity;
1163
+ const matchedIds: Array<string | number> = [];
1164
+
1165
+ for (const f of features) {
1166
+ if (idSet.has(String(f.id))) {
1167
+ matchedIds.push(f.id);
1168
+ minX = Math.min(minX, f.bounds.x);
1169
+ minY = Math.min(minY, f.bounds.y);
1170
+ maxX = Math.max(maxX, f.bounds.x + f.bounds.width);
1171
+ maxY = Math.max(maxY, f.bounds.y + f.bounds.height);
1172
+ }
1173
+ }
1174
+
1175
+ // Warn on unmatched ids
1176
+ const unmatchedIds = ids.filter((id) => !matchedIds.some((m) => String(m) === String(id)));
1177
+ if (unmatchedIds.length > 0) {
1178
+ warnings.push({
1179
+ code: 'FOCUS_UNMATCHED',
1180
+ message: `geo.focus references feature id(s) not found in the map: ${unmatchedIds.join(', ')}`,
1181
+ context: { unmatchedIds },
1182
+ });
1183
+ }
1184
+
1185
+ if (matchedIds.length === 0) return null;
1186
+
1187
+ return {
1188
+ target: {
1189
+ x: minX,
1190
+ y: minY,
1191
+ width: maxX - minX,
1192
+ height: maxY - minY,
1193
+ padding,
1194
+ },
1195
+ ids: matchedIds,
1196
+ };
1197
+ }
1198
+
1199
+ // ---------------------------------------------------------------------------
1200
+ // Empty layout fallback
1201
+ // ---------------------------------------------------------------------------
1202
+
1203
+ function emptyLayout(
1204
+ chrome: ReturnType<typeof computeChrome>,
1205
+ theme: ResolvedTheme,
1206
+ options: CompileOptions,
1207
+ watermark: boolean,
1208
+ ): MapLayout {
1209
+ return {
1210
+ area: { x: 0, y: 0, width: 0, height: 0 },
1211
+ chrome,
1212
+ features: [],
1213
+ borders: {
1214
+ interiorPath: '',
1215
+ outlinePath: '',
1216
+ interiorStroke: 'rgba(0,0,0,0.15)',
1217
+ outlineStroke: 'rgba(0,0,0,0.3)',
1218
+ },
1219
+ continuousLegend: null,
1220
+ categoricalLegend: null,
1221
+ pointMarks: [],
1222
+ pointCategoricalLegend: null,
1223
+ pointContinuousLegend: null,
1224
+ tooltipDescriptors: new Map(),
1225
+ a11y: {
1226
+ altText: 'Empty map',
1227
+ dataTableFallback: [],
1228
+ role: 'img',
1229
+ keyboardNavigable: false,
1230
+ },
1231
+ theme,
1232
+ width: options.width,
1233
+ height: options.height,
1234
+ animation: undefined,
1235
+ watermark,
1236
+ measureText:
1237
+ options.measureText ??
1238
+ ((text, fontSize) => ({ width: estimateTextWidth(text, fontSize), height: fontSize })),
1239
+ warnings: [],
1240
+ mapSize: { width: 0, height: 0 },
1241
+ focus: null,
1242
+ };
1243
+ }