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

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