plotilla 1.0.0 → 1.1.0

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 (155) hide show
  1. package/README.md +37 -11
  2. package/data/boundaries/world_countries.geojson +1 -1
  3. package/dist/colour/colour_scale.d.ts +55 -0
  4. package/dist/colour/colour_scale.js +80 -0
  5. package/dist/colour/palette.d.ts +176 -0
  6. package/dist/colour/palette.js +220 -0
  7. package/dist/fields/axis_fields.d.ts +56 -0
  8. package/dist/fields/axis_fields.js +46 -0
  9. package/dist/fields/colour_fields.d.ts +32 -0
  10. package/dist/fields/colour_fields.js +31 -0
  11. package/dist/fields/column_fields.d.ts +52 -0
  12. package/{src/fields/column_fields.ts → dist/fields/column_fields.js} +15 -29
  13. package/dist/fields/common_fields.d.ts +9 -0
  14. package/{src/fields/common_fields.ts → dist/fields/common_fields.js} +3 -6
  15. package/dist/fields/decide_plot_axes.d.ts +56 -0
  16. package/dist/fields/decide_plot_axes.js +71 -0
  17. package/dist/fields/marker_fields.d.ts +8 -0
  18. package/dist/fields/marker_fields.js +13 -0
  19. package/dist/fields/read_date_time.d.ts +85 -0
  20. package/dist/fields/read_date_time.js +199 -0
  21. package/dist/figure/check_axis_year_formats.d.ts +36 -0
  22. package/dist/figure/check_axis_year_formats.js +116 -0
  23. package/dist/figure/check_plot_category_limits.d.ts +128 -0
  24. package/dist/figure/check_plot_category_limits.js +284 -0
  25. package/dist/figure/plot_figure.d.ts +861 -0
  26. package/dist/figure/plot_figure.js +58 -0
  27. package/dist/figure/resolve_plot_figure.d.ts +28 -0
  28. package/dist/figure/resolve_plot_figure.js +41 -0
  29. package/dist/figure/validate_plot_figure.d.ts +50 -0
  30. package/dist/figure/validate_plot_figure.js +441 -0
  31. package/dist/map/assign_map_layer_hue_slots.d.ts +89 -0
  32. package/dist/map/assign_map_layer_hue_slots.js +146 -0
  33. package/dist/map/boundary_sets.d.ts +65 -0
  34. package/dist/map/boundary_sets.js +103 -0
  35. package/dist/map/build_world_outline_across_180.d.ts +21 -0
  36. package/dist/map/build_world_outline_across_180.js +23 -0
  37. package/dist/map/check_map_layers.d.ts +16 -0
  38. package/dist/map/check_map_layers.js +31 -0
  39. package/dist/map/fetch_region_outlines.d.ts +25 -0
  40. package/dist/map/fetch_region_outlines.js +39 -0
  41. package/dist/map/geojson.d.ts +150 -0
  42. package/dist/map/geojson.js +248 -0
  43. package/dist/map/join_region_rows.d.ts +40 -0
  44. package/dist/map/join_region_rows.js +45 -0
  45. package/dist/map/map_layers.d.ts +229 -0
  46. package/dist/map/map_layers.js +87 -0
  47. package/dist/model/find_panel_colour_scale.d.ts +25 -0
  48. package/dist/model/find_panel_colour_scale.js +27 -0
  49. package/dist/model/map_model.d.ts +30 -0
  50. package/dist/model/map_model.js +234 -0
  51. package/dist/model/panel_layout.d.ts +42 -0
  52. package/dist/model/panel_layout.js +154 -0
  53. package/dist/model/panel_model.d.ts +223 -0
  54. package/dist/model/panel_model.js +7 -0
  55. package/dist/model/plot_model.d.ts +28 -0
  56. package/dist/model/plot_model.js +431 -0
  57. package/dist/model/statistics.d.ts +83 -0
  58. package/dist/model/statistics.js +107 -0
  59. package/dist/plots/bar_plot.d.ts +46 -0
  60. package/dist/plots/bar_plot.js +30 -0
  61. package/dist/plots/box_plot.d.ts +30 -0
  62. package/dist/plots/box_plot.js +21 -0
  63. package/dist/plots/density_plot.d.ts +36 -0
  64. package/dist/plots/density_plot.js +23 -0
  65. package/dist/plots/heatmap_plot.d.ts +22 -0
  66. package/dist/plots/heatmap_plot.js +18 -0
  67. package/dist/plots/histogram_plot.d.ts +32 -0
  68. package/dist/plots/histogram_plot.js +24 -0
  69. package/dist/plots/line_plot.d.ts +44 -0
  70. package/dist/plots/line_plot.js +25 -0
  71. package/dist/plots/map_plot.d.ts +92 -0
  72. package/dist/plots/map_plot.js +35 -0
  73. package/dist/plots/pie_plot.d.ts +17 -0
  74. package/dist/plots/pie_plot.js +16 -0
  75. package/dist/plots/scatter_plot.d.ts +47 -0
  76. package/dist/plots/scatter_plot.js +27 -0
  77. package/dist/renderers/date_ticks.d.ts +37 -0
  78. package/dist/renderers/date_ticks.js +148 -0
  79. package/dist/renderers/echarts_map.d.ts +47 -0
  80. package/dist/renderers/echarts_map.js +492 -0
  81. package/dist/renderers/echarts_options.d.ts +30 -0
  82. package/dist/renderers/echarts_options.js +449 -0
  83. package/dist/renderers/echarts_pie_radius.d.ts +52 -0
  84. package/dist/renderers/echarts_pie_radius.js +158 -0
  85. package/dist/renderers/escape_html.d.ts +10 -0
  86. package/dist/renderers/escape_html.js +15 -0
  87. package/dist/renderers/line_colour_segments.d.ts +39 -0
  88. package/dist/renderers/line_colour_segments.js +41 -0
  89. package/dist/renderers/plotly_map.d.ts +48 -0
  90. package/dist/renderers/plotly_map.js +159 -0
  91. package/dist/renderers/plotly_options.d.ts +19 -0
  92. package/dist/renderers/plotly_options.js +345 -0
  93. package/dist/renderers/year_ticks.d.ts +27 -0
  94. package/dist/renderers/year_ticks.js +42 -0
  95. package/dist/table/check_column.d.ts +36 -0
  96. package/dist/table/check_column.js +46 -0
  97. package/dist/table/check_values_have_spread.d.ts +30 -0
  98. package/{src/table/check_values_have_spread.ts → dist/table/check_values_have_spread.js} +16 -17
  99. package/dist/table/compute_quantile.d.ts +16 -0
  100. package/dist/table/compute_quantile.js +23 -0
  101. package/dist/table/data_table.d.ts +59 -0
  102. package/dist/table/data_table.js +87 -0
  103. package/dist/table/density_bandwidth.d.ts +64 -0
  104. package/dist/table/density_bandwidth.js +88 -0
  105. package/dist/table/find_line_fit.d.ts +30 -0
  106. package/dist/table/find_line_fit.js +36 -0
  107. package/dist/table/get_number_range.d.ts +16 -0
  108. package/{src/table/get_number_range.ts → dist/table/get_number_range.js} +8 -8
  109. package/dist/table/group_rows.d.ts +40 -0
  110. package/dist/table/group_rows.js +67 -0
  111. package/dist/table/list_categories.d.ts +14 -0
  112. package/{src/table/list_categories.ts → dist/table/list_categories.js} +2 -3
  113. package/dist/table/read_number.d.ts +12 -0
  114. package/dist/table/read_number.js +14 -0
  115. package/package.json +28 -23
  116. package/src/colour/colour_scale.ts +0 -80
  117. package/src/colour/palette.ts +0 -220
  118. package/src/examples/example_figures.ts +0 -320
  119. package/src/fields/axis_fields.ts +0 -32
  120. package/src/fields/colour_fields.ts +0 -40
  121. package/src/fields/decide_plot_axes.ts +0 -77
  122. package/src/fields/marker_fields.ts +0 -16
  123. package/src/figure/plot_figure.ts +0 -67
  124. package/src/figure/resolve_plot_figure.ts +0 -47
  125. package/src/figure/validate_plot_figure.ts +0 -412
  126. package/src/map/boundary_sets.ts +0 -116
  127. package/src/map/check_map_layers.ts +0 -32
  128. package/src/map/fetch_region_outlines.ts +0 -48
  129. package/src/map/geojson.ts +0 -174
  130. package/src/map/map_layers.ts +0 -108
  131. package/src/model/check_axis_shows_years.ts +0 -58
  132. package/src/model/map_model.ts +0 -238
  133. package/src/model/panel_layout.ts +0 -171
  134. package/src/model/panel_model.ts +0 -85
  135. package/src/model/plot_model.ts +0 -347
  136. package/src/model/statistics.ts +0 -134
  137. package/src/plots/bar_plot.ts +0 -36
  138. package/src/plots/box_plot.ts +0 -26
  139. package/src/plots/density_plot.ts +0 -29
  140. package/src/plots/heatmap_plot.ts +0 -24
  141. package/src/plots/histogram_plot.ts +0 -29
  142. package/src/plots/line_plot.ts +0 -29
  143. package/src/plots/map_plot.ts +0 -46
  144. package/src/plots/pie_plot.ts +0 -23
  145. package/src/plots/scatter_plot.ts +0 -32
  146. package/src/renderers/echarts_map.ts +0 -194
  147. package/src/renderers/echarts_options.ts +0 -317
  148. package/src/renderers/plotly_map.ts +0 -170
  149. package/src/renderers/plotly_options.ts +0 -318
  150. package/src/table/check_column.ts +0 -34
  151. package/src/table/compute_quantile.ts +0 -23
  152. package/src/table/data_table.ts +0 -83
  153. package/src/table/density_bandwidth.ts +0 -94
  154. package/src/table/find_line_fit.ts +0 -44
  155. package/src/table/group_rows.ts +0 -71
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Decide which palette slot every hue on one map takes, so a hue names one
3
+ * thing across the map's layers.
4
+ *
5
+ * Hues are assigned map-wide by category label: the same label in two layers
6
+ * is one category and shares one slot, and different labels never share one.
7
+ * Distinct labels take slots in order of first appearance, walking the layers
8
+ * in order and each layer's categories in its own column's first-seen order.
9
+ * Only a drawn category takes a slot, so no hue names something the map does
10
+ * not show: every category of a points or lines layer (each draws a layer,
11
+ * points or not), and of a regions layer only the categories of rows an
12
+ * outline joins to. Before the outlines are loaded, which regions draw is
13
+ * unknown, so a regions layer coloured by category takes no slot yet and the
14
+ * slots are marked incomplete: every later label's slot depends on it.
15
+ * Points, lines and regions layers coloured by category take these slots. An
16
+ * uncoloured points or lines layer then takes the next slot after every
17
+ * category slot, one each, in layer order. Density layers, and layers
18
+ * coloured by a number, take no slot.
19
+ *
20
+ * The model draws with these slots and validation refuses a map whose slots
21
+ * run past the palette, so both read this one function and cannot disagree.
22
+ * Validation also reads the same ordering with every regions layer's
23
+ * categories left out: a lower bound, known before outlines load, so a map
24
+ * certain to run out of hues is refused without fetching them. It reads it
25
+ * only on a map with a regions layer coloured by category, the one map whose
26
+ * slots it can differ from, decided from the table so both passes agree.
27
+ */
28
+ import { type DataTable } from "../table/data_table.ts";
29
+ import type { MapLayer } from "./map_layers.ts";
30
+ /** Every hue slot on one map. */
31
+ export type MapHueSlots = {
32
+ /** Each category label's slot, shared by every layer coloured by that label. */
33
+ slotByCategory: ReadonlyMap<string, number>;
34
+ /** Per layer, in layer order: its drawn categories in its own column's first-seen order, or none for a layer not coloured by category. */
35
+ categoriesByLayer: readonly (readonly string[])[];
36
+ /** Per layer, in layer order: the slot of an uncoloured points or lines layer, or `null` for every other layer. */
37
+ uncolouredSlots: readonly (number | null)[];
38
+ /** Whether every slot is final: false only before outlines load, on a map with a regions layer coloured by category. */
39
+ isEverySlotKnown: boolean;
40
+ };
41
+ /**
42
+ * Assign every category label and every uncoloured points or lines layer on a map its palette slot.
43
+ *
44
+ * @param layers - The map's layers, through the schema, in the order the figure gives them.
45
+ * @param options - The map's own table, read by a layer that brings no `data`, and whether regions outlines are loaded
46
+ * and checked (the model's always are; validation's are not on its first pass).
47
+ * @returns The slot of each drawn category label, each layer's drawn categories, and each uncoloured layer's slot.
48
+ */
49
+ export declare function assignMapLayerHueSlots(layers: readonly MapLayer[], options: {
50
+ table: DataTable;
51
+ areOutlinesLoaded: boolean;
52
+ }): MapHueSlots;
53
+ /**
54
+ * Assign the slots a map's points and lines layers need at the least, counting no regions layer's categories: the
55
+ * same ordering as assignMapLayerHueSlots with every regions layer taking none. A regions layer's labels can only add
56
+ * slots before a later label or uncoloured layer, never remove one, so a slot past the palette here is past it on the
57
+ * drawn map too, and is known before any outline loads.
58
+ *
59
+ * @param layers - The map's layers, through the schema, in the order the figure gives them.
60
+ * @param options - The map's own table, read by a layer that brings no `data`.
61
+ * @returns The slots, every one known, with each regions layer's categories empty.
62
+ */
63
+ export declare function assignMapLayerHueSlotsWithoutRegions(layers: readonly MapLayer[], options: {
64
+ table: DataTable;
65
+ }): MapHueSlots;
66
+ /**
67
+ * Decide whether any of a map's regions layers is coloured by a category, which the table alone settles, outlines loaded
68
+ * or not. Only such a layer can make the drawn map's slots differ from assignMapLayerHueSlotsWithoutRegions's, so
69
+ * validation decides from this, the same in both passes, whether it needs the lower bound.
70
+ *
71
+ * @param layers - The map's layers, through the schema.
72
+ * @param options - The map's own table, read by a layer that brings no `data`.
73
+ * @returns Whether a regions layer's value column holds categories rather than numbers.
74
+ */
75
+ export declare function decideRegionsAreColouredByCategory(layers: readonly MapLayer[], options: {
76
+ table: DataTable;
77
+ }): boolean;
78
+ /**
79
+ * Read the map-wide hue slot of a category, refusing one that has none rather than drawing it in some other hue.
80
+ *
81
+ * @param category - The category's label.
82
+ * @param options - The layer's place in the map, for the message, and the map's slots.
83
+ * @returns The slot.
84
+ * @throws Error when the category was given no slot, which assignMapLayerHueSlots gives every drawn category of a layer coloured by category.
85
+ */
86
+ export declare function readCategorySlot(category: string, options: {
87
+ layerIndex: number;
88
+ hueSlots: MapHueSlots;
89
+ }): number;
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Decide which palette slot every hue on one map takes, so a hue names one
3
+ * thing across the map's layers.
4
+ *
5
+ * Hues are assigned map-wide by category label: the same label in two layers
6
+ * is one category and shares one slot, and different labels never share one.
7
+ * Distinct labels take slots in order of first appearance, walking the layers
8
+ * in order and each layer's categories in its own column's first-seen order.
9
+ * Only a drawn category takes a slot, so no hue names something the map does
10
+ * not show: every category of a points or lines layer (each draws a layer,
11
+ * points or not), and of a regions layer only the categories of rows an
12
+ * outline joins to. Before the outlines are loaded, which regions draw is
13
+ * unknown, so a regions layer coloured by category takes no slot yet and the
14
+ * slots are marked incomplete: every later label's slot depends on it.
15
+ * Points, lines and regions layers coloured by category take these slots. An
16
+ * uncoloured points or lines layer then takes the next slot after every
17
+ * category slot, one each, in layer order. Density layers, and layers
18
+ * coloured by a number, take no slot.
19
+ *
20
+ * The model draws with these slots and validation refuses a map whose slots
21
+ * run past the palette, so both read this one function and cannot disagree.
22
+ * Validation also reads the same ordering with every regions layer's
23
+ * categories left out: a lower bound, known before outlines load, so a map
24
+ * certain to run out of hues is refused without fetching them. It reads it
25
+ * only on a map with a regions layer coloured by category, the one map whose
26
+ * slots it can differ from, decided from the table so both passes agree.
27
+ */
28
+ import { decideColourIsContinuous } from "../colour/colour_scale.js";
29
+ import { findColumn } from "../table/data_table.js";
30
+ import { listCategories } from "../table/list_categories.js";
31
+ import { joinRegionRows } from "./join_region_rows.js";
32
+ /**
33
+ * Assign every category label and every uncoloured points or lines layer on a map its palette slot.
34
+ *
35
+ * @param layers - The map's layers, through the schema, in the order the figure gives them.
36
+ * @param options - The map's own table, read by a layer that brings no `data`, and whether regions outlines are loaded
37
+ * and checked (the model's always are; validation's are not on its first pass).
38
+ * @returns The slot of each drawn category label, each layer's drawn categories, and each uncoloured layer's slot.
39
+ */
40
+ export function assignMapLayerHueSlots(layers, options) {
41
+ return orderMapHueSlots(layers, { table: options.table, knownCategoriesByLayer: layers.map((layer) => findDrawnCategories(layer, options)) });
42
+ }
43
+ /**
44
+ * Assign the slots a map's points and lines layers need at the least, counting no regions layer's categories: the
45
+ * same ordering as assignMapLayerHueSlots with every regions layer taking none. A regions layer's labels can only add
46
+ * slots before a later label or uncoloured layer, never remove one, so a slot past the palette here is past it on the
47
+ * drawn map too, and is known before any outline loads.
48
+ *
49
+ * @param layers - The map's layers, through the schema, in the order the figure gives them.
50
+ * @param options - The map's own table, read by a layer that brings no `data`.
51
+ * @returns The slots, every one known, with each regions layer's categories empty.
52
+ */
53
+ export function assignMapLayerHueSlotsWithoutRegions(layers, options) {
54
+ // A points or lines layer's categories never depend on outlines, so whether they are loaded does not matter here.
55
+ const knownCategoriesByLayer = layers.map((layer) => (layer.type === "regions" ? [] : findDrawnCategories(layer, { table: options.table, areOutlinesLoaded: false })));
56
+ return orderMapHueSlots(layers, { table: options.table, knownCategoriesByLayer });
57
+ }
58
+ /**
59
+ * Decide whether any of a map's regions layers is coloured by a category, which the table alone settles, outlines loaded
60
+ * or not. Only such a layer can make the drawn map's slots differ from assignMapLayerHueSlotsWithoutRegions's, so
61
+ * validation decides from this, the same in both passes, whether it needs the lower bound.
62
+ *
63
+ * @param layers - The map's layers, through the schema.
64
+ * @param options - The map's own table, read by a layer that brings no `data`.
65
+ * @returns Whether a regions layer's value column holds categories rather than numbers.
66
+ */
67
+ export function decideRegionsAreColouredByCategory(layers, options) {
68
+ // Before outlines load, findDrawnCategories gives `null` exactly for a regions layer coloured by category.
69
+ return layers.some((layer) => findDrawnCategories(layer, { table: options.table, areOutlinesLoaded: false }) === null);
70
+ }
71
+ /**
72
+ * Give slots in the one map-wide order: each distinct label in layer order, then each uncoloured points or lines layer.
73
+ *
74
+ * @param layers - The map's layers, in order.
75
+ * @param options - The map's own table, and each layer's drawn categories, or `null` where they are not known yet.
76
+ * @returns The slots, marked incomplete when any layer's categories are not known.
77
+ */
78
+ function orderMapHueSlots(layers, options) {
79
+ const categoriesByLayer = options.knownCategoriesByLayer.map((categories) => categories ?? []);
80
+ const slotByCategory = new Map();
81
+ for (const category of categoriesByLayer.flat()) {
82
+ if (!slotByCategory.has(category))
83
+ slotByCategory.set(category, slotByCategory.size);
84
+ }
85
+ let nextSlot = slotByCategory.size;
86
+ const uncolouredSlots = layers.map((layer) => {
87
+ if (layer.type === "density" || layer.type === "regions" || findColourColumn(layer, options) !== null)
88
+ return null;
89
+ nextSlot += 1;
90
+ return nextSlot - 1;
91
+ });
92
+ return { slotByCategory, categoriesByLayer, uncolouredSlots, isEverySlotKnown: !options.knownCategoriesByLayer.includes(null) };
93
+ }
94
+ /**
95
+ * Read the map-wide hue slot of a category, refusing one that has none rather than drawing it in some other hue.
96
+ *
97
+ * @param category - The category's label.
98
+ * @param options - The layer's place in the map, for the message, and the map's slots.
99
+ * @returns The slot.
100
+ * @throws Error when the category was given no slot, which assignMapLayerHueSlots gives every drawn category of a layer coloured by category.
101
+ */
102
+ export function readCategorySlot(category, options) {
103
+ const slot = options.hueSlots.slotByCategory.get(category);
104
+ if (slot === undefined)
105
+ throw new Error(`Expected map layer ${options.layerIndex}'s category "${category}" to have a hue slot; it had none.`);
106
+ return slot;
107
+ }
108
+ /**
109
+ * List the categories of a layer that the model draws, so take a hue: every category in a points or lines layer's
110
+ * column, and the categories of a regions layer's rows that join an outline.
111
+ *
112
+ * @param layer - The layer.
113
+ * @param options - The map's own table, and whether regions outlines are loaded and checked.
114
+ * @returns The layer's drawn categories in its column's first-seen order, none for a density layer, an uncoloured layer
115
+ * or one coloured by a number, or `null` for a regions layer coloured by category before its outlines are loaded.
116
+ */
117
+ function findDrawnCategories(layer, options) {
118
+ if (layer.type === "density")
119
+ return [];
120
+ const colours = findColourColumn(layer, options);
121
+ if (colours === null || decideColourIsContinuous(colours, { colourType: layer.colour_type }))
122
+ return [];
123
+ const categories = listCategories(colours);
124
+ if (layer.type !== "regions")
125
+ return categories;
126
+ if (!options.areOutlinesLoaded)
127
+ return null;
128
+ // checkMapLayers has refused a layer whose outlines or feature property are missing, before outlines count as loaded.
129
+ if (layer.feature_property === undefined)
130
+ throw new Error("Expected a regions layer to name its feature property by now; it did not.");
131
+ const keys = findColumn(layer.data ?? options.table, { column: layer.key }) ?? [];
132
+ const { joinedRows } = joinRegionRows(layer.geojson, { keys, featureProperty: layer.feature_property });
133
+ const drawn = new Set(listCategories([...joinedRows].map((row) => colours[row] ?? null)));
134
+ return categories.filter((category) => drawn.has(category));
135
+ }
136
+ /**
137
+ * Read a layer's colour column, as the model reads it: `colour` on a points or lines layer, `value` on a regions layer.
138
+ *
139
+ * @param layer - The layer.
140
+ * @param options - The map's own table.
141
+ * @returns The column, or `null` when the layer names none (a column it names but the table lacks is refused in validation).
142
+ */
143
+ function findColourColumn(layer, options) {
144
+ const column = layer.type === "regions" ? layer.value : layer.colour;
145
+ return column === undefined ? null : findColumn(layer.data ?? options.table, { column });
146
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Built-in region outlines for maps, so an agent can colour US states,
3
+ * Canadian provinces, EU or world countries by naming the set. Built from
4
+ * Natural Earth by `npx tsx scripts/build_boundaries.ts` into `data/boundaries`; each
5
+ * region has a canonical `name` and the `aliases` data may use for it.
6
+ */
7
+ import { type DataTable } from "../table/data_table.ts";
8
+ import { type FeatureCollection } from "./geojson.ts";
9
+ /** The sets there are. */
10
+ export type BoundarySetName = "world_countries" | "us_states" | "canada_provinces" | "eu_countries";
11
+ /** Each set, and what data can name its regions by. */
12
+ export declare const BOUNDARY_SETS: Readonly<Record<BoundarySetName, string>>;
13
+ /** Every set's name, for schemas and checks. */
14
+ export declare const BOUNDARY_SET_NAMES: BoundarySetName[];
15
+ /** How a set is loaded: the site's asset store in the Worker (and in tests). */
16
+ export type BoundarySetLoader = (name: BoundarySetName) => Promise<FeatureCollection>;
17
+ /** The feature property that holds each region's canonical name. */
18
+ export declare const BOUNDARY_NAME_PROPERTY = "name";
19
+ /** Where the built-in sets' files are, in this package: data/boundaries/<set>.geojson. */
20
+ export declare const BOUNDARY_SET_FILE_DIRECTORY = "data/boundaries";
21
+ /**
22
+ * Build a loader for the built-in sets from a way to read one set's file
23
+ * (BOUNDARY_SET_FILE_DIRECTORY/<set>.geojson, wherever the host keeps it).
24
+ *
25
+ * @param readSetFile - Reads a set's file and returns its parsed JSON.
26
+ * @returns The loader, which checks what it reads is a FeatureCollection.
27
+ */
28
+ export declare function createBoundaryLoader(readSetFile: (name: BoundarySetName) => Promise<unknown>): BoundarySetLoader;
29
+ /**
30
+ * Put a region name in the form used to match it: lower case, accents and
31
+ * punctuation gone, spaces single. "Québec" and "quebec" match.
32
+ *
33
+ * @param text - A name or code.
34
+ * @returns The form it is matched in.
35
+ */
36
+ export declare function normaliseRegionName(text: string): string;
37
+ /**
38
+ * Map every alias in a set to its region's canonical name.
39
+ *
40
+ * @param collection - A built-in set.
41
+ * @returns normalised alias → canonical name.
42
+ */
43
+ export declare function indexBoundaryAliases(collection: FeatureCollection): Map<string, string>;
44
+ /** A regions layer as resolving needs it (see RegionsLayer in map_layers.ts). */
45
+ type BoundaryLayer = {
46
+ boundaries?: unknown;
47
+ geojson?: unknown;
48
+ feature_property?: string;
49
+ key: string;
50
+ data?: DataTable;
51
+ };
52
+ /**
53
+ * Load a regions layer's built-in set into it, and rewrite the layer's key
54
+ * column to the set's canonical names so every renderer joins on them.
55
+ *
56
+ * @param layer - The regions layer; changed in place.
57
+ * @param options - Its table (the layer's own, the plot's, or the figure's), where it is, and the loader.
58
+ * @returns A note for the agent about rows that matched no region, or null.
59
+ */
60
+ export declare function resolveBoundarySet(layer: BoundaryLayer, options: {
61
+ table: DataTable | undefined;
62
+ where: string;
63
+ loadBoundarySet: BoundarySetLoader;
64
+ }): Promise<string | null>;
65
+ export {};
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Built-in region outlines for maps, so an agent can colour US states,
3
+ * Canadian provinces, EU or world countries by naming the set. Built from
4
+ * Natural Earth by `npx tsx scripts/build_boundaries.ts` into `data/boundaries`; each
5
+ * region has a canonical `name` and the `aliases` data may use for it.
6
+ */
7
+ import { describeCount } from "../colour/palette.js";
8
+ import { findColumn } from "../table/data_table.js";
9
+ import { readFeatureCollection } from "./geojson.js";
10
+ /** Each set, and what data can name its regions by. */
11
+ export const BOUNDARY_SETS = {
12
+ world_countries: "every country (by name, or ISO code: CA, CAN)",
13
+ us_states: "the 50 US states and DC (by name, postal code CA, or US-CA)",
14
+ canada_provinces: "Canada's 13 provinces and territories (by name, postal code ON, or CA-ON)",
15
+ eu_countries: "the 27 EU members, mainland Europe only (by name, or ISO code: FR, FRA)",
16
+ };
17
+ /** Every set's name, for schemas and checks. */
18
+ export const BOUNDARY_SET_NAMES = Object.keys(BOUNDARY_SETS);
19
+ /** The feature property that holds each region's canonical name. */
20
+ export const BOUNDARY_NAME_PROPERTY = "name";
21
+ /** How many unmatched names a note lists before saying "and N more". */
22
+ const UNMATCHED_NAMES_SHOWN = 5;
23
+ /** Where the built-in sets' files are, in this package: data/boundaries/<set>.geojson. */
24
+ export const BOUNDARY_SET_FILE_DIRECTORY = "data/boundaries";
25
+ /**
26
+ * Build a loader for the built-in sets from a way to read one set's file
27
+ * (BOUNDARY_SET_FILE_DIRECTORY/<set>.geojson, wherever the host keeps it).
28
+ *
29
+ * @param readSetFile - Reads a set's file and returns its parsed JSON.
30
+ * @returns The loader, which checks what it reads is a FeatureCollection.
31
+ */
32
+ export function createBoundaryLoader(readSetFile) {
33
+ return async (name) => readFeatureCollection(await readSetFile(name), { where: `boundaries ${name}` });
34
+ }
35
+ /**
36
+ * Put a region name in the form used to match it: lower case, accents and
37
+ * punctuation gone, spaces single. "Québec" and "quebec" match.
38
+ *
39
+ * @param text - A name or code.
40
+ * @returns The form it is matched in.
41
+ */
42
+ export function normaliseRegionName(text) {
43
+ return text.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim();
44
+ }
45
+ /**
46
+ * Map every alias in a set to its region's canonical name.
47
+ *
48
+ * @param collection - A built-in set.
49
+ * @returns normalised alias → canonical name.
50
+ */
51
+ export function indexBoundaryAliases(collection) {
52
+ const index = new Map();
53
+ for (const feature of collection.features) {
54
+ const properties = (feature.properties ?? {});
55
+ if (typeof properties.name !== "string")
56
+ continue;
57
+ const aliases = Array.isArray(properties.aliases) ? properties.aliases : [];
58
+ for (const alias of [properties.name, ...aliases])
59
+ if (typeof alias === "string")
60
+ index.set(normaliseRegionName(alias), properties.name);
61
+ }
62
+ return index;
63
+ }
64
+ /**
65
+ * Load a regions layer's built-in set into it, and rewrite the layer's key
66
+ * column to the set's canonical names so every renderer joins on them.
67
+ *
68
+ * @param layer - The regions layer; changed in place.
69
+ * @param options - Its table (the layer's own, the plot's, or the figure's), where it is, and the loader.
70
+ * @returns A note for the agent about rows that matched no region, or null.
71
+ */
72
+ export async function resolveBoundarySet(layer, options) {
73
+ const name = layer.boundaries;
74
+ if (!BOUNDARY_SET_NAMES.includes(name)) {
75
+ throw new Error(`${options.where}.boundaries: one of ${BOUNDARY_SET_NAMES.join(", ")}; got "${String(layer.boundaries)}".`);
76
+ }
77
+ if (layer.geojson !== undefined)
78
+ throw new Error(`${options.where}: give boundaries or geojson, not both.`);
79
+ const collection = await options.loadBoundarySet(name);
80
+ const index = indexBoundaryAliases(collection);
81
+ const column = options.table === undefined ? null : findColumn(options.table, { column: layer.key });
82
+ if (column === null)
83
+ throw new Error(`${options.where}.key: "${layer.key}" is not a column of the data.`);
84
+ const unmatched = [];
85
+ const canonical = column.map((value) => {
86
+ if (value === null)
87
+ return null;
88
+ const match = index.get(normaliseRegionName(String(value)));
89
+ if (match === undefined)
90
+ unmatched.push(String(value));
91
+ return match ?? value;
92
+ });
93
+ layer.geojson = collection;
94
+ layer.feature_property = BOUNDARY_NAME_PROPERTY;
95
+ // The layer gets its own copy of the table, so other layers keep the names as sent.
96
+ layer.data = { ...options.table, [layer.key]: canonical };
97
+ delete layer.boundaries;
98
+ if (unmatched.length === 0)
99
+ return null;
100
+ const shown = unmatched.slice(0, UNMATCHED_NAMES_SHOWN).join(", ");
101
+ const more = unmatched.length > UNMATCHED_NAMES_SHOWN ? ` and ${unmatched.length - UNMATCHED_NAMES_SHOWN} more` : "";
102
+ return `${options.where}: ${describeCount(unmatched.length, { singular: "row", plural: "rows" })} matched no region of ${name}: ${shown}${more}.`;
103
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The world outline a host registers for ECharts maps with no regions of
3
+ * their own (the `"world"` entry of an option's maps, under WORLD_MAP_NAME).
4
+ */
5
+ import { type FeatureCollection } from "./geojson.ts";
6
+ /**
7
+ * Build the world outline a host registers for ECharts: the world, and a copy
8
+ * of it one turn (360°) east, as features of the one map.
9
+ *
10
+ * ECharts never wraps longitude: a geo draws each position at its longitude
11
+ * on a flat plane, so land exists only where the registered outline has it.
12
+ * A map whose view crosses the 180° line is drawn with the positions west of
13
+ * its view a turn east, past 180 (Fiji's Lau islands at 181.2, not -178.8);
14
+ * the copy is the land there. The copy also fills any margin of a view that
15
+ * reaches past 180°, such as one fitted to points at 170 and 179.5; a view
16
+ * that stays west of 180° everywhere draws none of it.
17
+ *
18
+ * @param world - The world's countries, longitudes between -180 and 180.
19
+ * @returns A new collection: every feature, then every feature again one turn east.
20
+ */
21
+ export declare function buildWorldOutlineAcross180(world: FeatureCollection): FeatureCollection;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The world outline a host registers for ECharts maps with no regions of
3
+ * their own (the `"world"` entry of an option's maps, under WORLD_MAP_NAME).
4
+ */
5
+ import { moveCollectionByTurns } from "./geojson.js";
6
+ /**
7
+ * Build the world outline a host registers for ECharts: the world, and a copy
8
+ * of it one turn (360°) east, as features of the one map.
9
+ *
10
+ * ECharts never wraps longitude: a geo draws each position at its longitude
11
+ * on a flat plane, so land exists only where the registered outline has it.
12
+ * A map whose view crosses the 180° line is drawn with the positions west of
13
+ * its view a turn east, past 180 (Fiji's Lau islands at 181.2, not -178.8);
14
+ * the copy is the land there. The copy also fills any margin of a view that
15
+ * reaches past 180°, such as one fitted to points at 170 and 179.5; a view
16
+ * that stays west of 180° everywhere draws none of it.
17
+ *
18
+ * @param world - The world's countries, longitudes between -180 and 180.
19
+ * @returns A new collection: every feature, then every feature again one turn east.
20
+ */
21
+ export function buildWorldOutlineAcross180(world) {
22
+ return { ...world, features: [...world.features, ...moveCollectionByTurns(world, { turns: 1 }).features] };
23
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The checks only a map needs, once its outlines are loaded. Columns are
3
+ * checked with every other plot's, in validate_plot_figure.
4
+ */
5
+ import type { MapLayer } from "./map_layers.ts";
6
+ /**
7
+ * Check a map's layers: outlines loaded and readable, density only on a flat map, throwing a sentence naming the field at fault.
8
+ *
9
+ * @param layers - The map's layers, through the schema and with their outlines loaded.
10
+ * @param options - Whether the map is a globe, whether its outlines are loaded yet (before they are, only what needs none is checked), and where it is in the figure.
11
+ */
12
+ export declare function checkMapLayers(layers: readonly MapLayer[], options: {
13
+ isGlobe: boolean;
14
+ areOutlinesLoaded: boolean;
15
+ where: string;
16
+ }): void;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The checks only a map needs, once its outlines are loaded. Columns are
3
+ * checked with every other plot's, in validate_plot_figure.
4
+ */
5
+ import { readFeatureCollection } from "./geojson.js";
6
+ /**
7
+ * Check a map's layers: outlines loaded and readable, density only on a flat map, throwing a sentence naming the field at fault.
8
+ *
9
+ * @param layers - The map's layers, through the schema and with their outlines loaded.
10
+ * @param options - Whether the map is a globe, whether its outlines are loaded yet (before they are, only what needs none is checked), and where it is in the figure.
11
+ */
12
+ export function checkMapLayers(layers, options) {
13
+ layers.forEach((layer, index) => {
14
+ const where = `${options.where}.layers[${index}]`;
15
+ if (layer.type === "density" && options.isGlobe) {
16
+ throw new Error(`${where}: density maps are flat only; set projection "flat", or show these as points on the globe.`);
17
+ }
18
+ if (layer.type !== "regions" || !options.areOutlinesLoaded)
19
+ return;
20
+ const unloaded = layer.boundaries !== undefined ? "boundaries" : layer.geojson_url !== undefined ? "geojson_url" : null;
21
+ if (unloaded !== null) {
22
+ throw new Error(`${where}: outlines named by ${unloaded} are loaded by resolvePlotFigure, which validates as well; call it rather than validatePlotFigure.`);
23
+ }
24
+ if (layer.geojson === undefined)
25
+ throw new Error(`${where}: give the region outlines as boundaries (a built-in set), geojson or geojson_url.`);
26
+ if (layer.feature_property === undefined) {
27
+ throw new Error(`${where}.feature_property: the GeoJSON property that names each region, e.g. "AREA_NAME".`);
28
+ }
29
+ readFeatureCollection(layer.geojson, { where: `${where}.geojson` });
30
+ });
31
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Fetch the outlines a regions layer names by address. Fetched once, when the
3
+ * plot is shown, and stored in it, so the map keeps working if the address
4
+ * later changes.
5
+ */
6
+ import type { MapLayer } from "./map_layers.ts";
7
+ /**
8
+ * Fetch outlines from a web address, as the host allows (its own checks on the
9
+ * address, the size, and how it identifies itself).
10
+ *
11
+ * @param url - The address the agent gave.
12
+ * @returns The response's text; throws a sentence the agent can act on if it cannot.
13
+ */
14
+ export type GeoJsonFetcher = (url: string) => Promise<string>;
15
+ /**
16
+ * Fetch every regions layer's geojson_url, putting the outlines in the spec.
17
+ *
18
+ * @param layers - A map's layers; changed in place.
19
+ * @param options - Where it is in the figure, for error messages, and how the host fetches an address.
20
+ * @returns Nothing.
21
+ */
22
+ export declare function fetchRegionOutlines(layers: MapLayer[], options: {
23
+ where: string;
24
+ fetchGeoJson: GeoJsonFetcher;
25
+ }): Promise<void>;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Fetch the outlines a regions layer names by address. Fetched once, when the
3
+ * plot is shown, and stored in it, so the map keeps working if the address
4
+ * later changes.
5
+ */
6
+ import { readFeatureCollection } from "./geojson.js";
7
+ /**
8
+ * Fetch every regions layer's geojson_url, putting the outlines in the spec.
9
+ *
10
+ * @param layers - A map's layers; changed in place.
11
+ * @param options - Where it is in the figure, for error messages, and how the host fetches an address.
12
+ * @returns Nothing.
13
+ */
14
+ export async function fetchRegionOutlines(layers, options) {
15
+ for (const [index, layer] of layers.entries()) {
16
+ if (layer.type !== "regions" || layer.geojson !== undefined || layer.geojson_url === undefined)
17
+ continue;
18
+ const where = `${options.where}.layers[${index}].geojson_url`;
19
+ let text;
20
+ try {
21
+ text = await options.fetchGeoJson(layer.geojson_url);
22
+ }
23
+ catch (error) {
24
+ // Rethrown with the field, so the agent knows which address failed.
25
+ throw new Error(`${where}: ${error instanceof Error ? error.message : String(error)}`);
26
+ }
27
+ let parsed;
28
+ try {
29
+ parsed = JSON.parse(text);
30
+ }
31
+ catch {
32
+ // Rethrown as a sentence the agent can act on.
33
+ throw new Error(`${where}: ${layer.geojson_url} is not JSON.`);
34
+ }
35
+ const collection = readFeatureCollection(parsed, { where });
36
+ layer.geojson = collection;
37
+ delete layer.geojson_url;
38
+ }
39
+ }