plotilla 0.2.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 +30 -25
  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,116 @@
1
+ /**
2
+ * Check a plot's declared year formats (x_year_format, y_year_format)
3
+ * against what its axes hold. Years are whole numbers, so a declaration on
4
+ * text, dates or fractions could only print something false, and is refused
5
+ * naming the field rather than ignored (`.claude/rules/plot_interface.md`).
6
+ * Years are also a calendar, not a magnitude, so a year format on a log axis
7
+ * is refused too: ECharts ticks such an axis only at powers of ten, so no
8
+ * year would be labelled (issue #97).
9
+ */
10
+ import { decidePlotAxes } from "../fields/decide_plot_axes.js";
11
+ import { findColumn } from "../table/data_table.js";
12
+ import { findPlotSchema } from "./plot_figure.js";
13
+ /** What an axis that is not numbers holds, as a caller is told it. */
14
+ const NOT_NUMBERS_DESCRIPTIONS = {
15
+ category: "text, drawn as categories, which print as they are",
16
+ time: "dates, which print as 2024.01, 2024.01.15 or 2024.01.15 08:30 by themselves",
17
+ };
18
+ /**
19
+ * Check each year format a plot declares: its axis's scale is not "log",
20
+ * its axis holds numbers, and every drawn one is whole.
21
+ *
22
+ * @param plot - The plot, through the schema.
23
+ * @param options - Its table, which rows become marks, and where it is in the figure.
24
+ */
25
+ export function checkAxisYearFormats(plot, options) {
26
+ if ("x_year_format" in plot && plot.x_year_format !== undefined) {
27
+ const field = `${options.where}.x_year_format`;
28
+ checkScaleIsLinear({ scale: "x_scale" in plot ? plot.x_scale : undefined, field, scaleField: `${options.where}.x_scale` });
29
+ const kind = decidePlotAxes(plot, { table: options.table }).x?.kind;
30
+ if (kind !== undefined && kind !== "value") {
31
+ throw new Error(`${field}: years are whole numbers, and "${plot.x}" holds ${NOT_NUMBERS_DESCRIPTIONS[kind]}; leave it out.`);
32
+ }
33
+ checkColumnIsWhole({ column: plot.x, field, ...options });
34
+ }
35
+ if ("y_year_format" in plot && plot.y_year_format !== undefined) {
36
+ const field = `${options.where}.y_year_format`;
37
+ checkScaleIsLinear({ scale: "y_scale" in plot ? plot.y_scale : undefined, field, scaleField: `${options.where}.y_scale` });
38
+ checkColumnIsWhole({ column: plot.y, field, ...options });
39
+ }
40
+ }
41
+ /**
42
+ * Check a year format's axis is not log: years are a calendar, not a
43
+ * magnitude, so spacing them by order of magnitude means nothing, and
44
+ * ECharts would tick the axis only at 1000 and 10000, labelling no year.
45
+ *
46
+ * @param options - The axis's declared scale, the year format's field, and the scale's field.
47
+ */
48
+ function checkScaleIsLinear(options) {
49
+ if (options.scale !== "log")
50
+ return;
51
+ throw new Error(`${options.field}: years are a calendar, not a magnitude, and ${options.scaleField} is "log", ` +
52
+ `which spaces them by order of magnitude; leave the year format out, or set ${options.scaleField} to "linear".`);
53
+ }
54
+ /**
55
+ * Check every drawn number in a column is whole, so it can print as a year.
56
+ *
57
+ * @param options - The column, the field that declared it, its table, which rows become marks.
58
+ */
59
+ function checkColumnIsWhole(options) {
60
+ const values = findColumn(options.table, { column: options.column }) ?? [];
61
+ const fraction = values.find((value, row) => options.isDrawn(row) && typeof value === "number" && !Number.isInteger(value));
62
+ if (fraction === undefined)
63
+ return;
64
+ throw new Error(`${options.field}: years are whole numbers, and "${options.column}" has ${fraction}; leave it out, or round the column to whole years.`);
65
+ }
66
+ /**
67
+ * Check that plots on a shared axis declare one year format: a shared
68
+ * axis is drawn once, so it prints its numbers one way. Each plot's format
69
+ * is the one of the field `decidePlotAxes` puts on that axis (a horizontal
70
+ * bar's y on the shared x), the same rule its scale follows. The refusal
71
+ * names a plot that declares a format, so the field it names always exists.
72
+ *
73
+ * @param figure - The figure, its shared axes checked to be linkable.
74
+ * @param options - Which axis is shared.
75
+ */
76
+ export function checkSharedAxisYearFormats(figure, options) {
77
+ const plotsWithAxis = figure.plots.flatMap((plot, index) => {
78
+ const axis = decidePlotAxes(plot, { table: plot.data ?? figure.data })[options.direction];
79
+ if (axis === null)
80
+ return [];
81
+ const field = `${axis.plotField}_year_format`;
82
+ const hasField = field in findPlotSchema(plot.type).shape;
83
+ return [{ field, hasField, yearFormat: findYearFormat(plot, { plotField: axis.plotField }), type: plot.type, where: `plots[${index}]` }];
84
+ });
85
+ const [first, ...others] = plotsWithAxis;
86
+ if (first === undefined)
87
+ return;
88
+ const differing = others.find((other) => other.yearFormat !== first.yearFormat);
89
+ if (differing === undefined)
90
+ return;
91
+ const named = differing.yearFormat === null ? first : differing;
92
+ const describe = (plot) => {
93
+ if (plot.yearFormat !== null)
94
+ return `${plot.where}.${plot.field} "${plot.yearFormat}"`;
95
+ return plot.hasField ? `${plot.where}.${plot.field} none` : `${plot.where} none (a ${plot.type} has no ${plot.field})`;
96
+ };
97
+ // A plot that cannot declare a format holds the shared axis to plain numbers, so only removing the declaration agrees.
98
+ const lacking = plotsWithAxis.find((plot) => !plot.hasField);
99
+ const change = lacking === undefined
100
+ ? `Remove ${named.where}.${named.field}, or declare the same on every plot sharing the axis.`
101
+ : `Remove ${named.where}.${named.field}: ${lacking.where} cannot declare one, so the shared axis prints plain numbers.`;
102
+ throw new Error(`${named.where}.${named.field}: plots on a shared ${options.direction} axis print its numbers one way; ` +
103
+ `${describe(first)} and ${describe(differing)}. ${change}`);
104
+ }
105
+ /**
106
+ * Find the year format a plot declares for one of its fields.
107
+ *
108
+ * @param plot - The plot.
109
+ * @param options - Which of its fields, x or y.
110
+ * @returns The declared format; null when none is declared, or the plot type has no such field.
111
+ */
112
+ function findYearFormat(plot, options) {
113
+ if (options.plotField === "x")
114
+ return "x_year_format" in plot ? plot.x_year_format ?? null : null;
115
+ return "y_year_format" in plot ? plot.y_year_format ?? null : null;
116
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Refuse a plot whose grouping columns hold more categories than drawing can
3
+ * tell apart: more colour categories than the palette has hues, more
4
+ * marker_shape categories than there are shapes, more line_type categories
5
+ * than there are dashes. Without this the model refuses them while drawing,
6
+ * with a message that names no field.
7
+ *
8
+ * The categories are counted as the model counts them, through `groupRows`
9
+ * over the drawn rows: a category keeps its place in the column's
10
+ * first-seen order whether or not it is drawn, so the slot a drawn row needs
11
+ * is its category's index, not how many categories are drawn.
12
+ *
13
+ * Pies and map layers take their hues as their own models give them: a pie
14
+ * one per slice drawn, a points or lines layer one per category in its
15
+ * colour column, a regions layer its category's place in its value column;
16
+ * across a map's layers, each category label takes one hue, map-wide.
17
+ */
18
+ import type { MapLayer } from "../map/map_layers.ts";
19
+ import { type DataTable } from "../table/data_table.ts";
20
+ import type { Plot } from "./plot_figure.ts";
21
+ /** What the colour limit stands for, in every refusal that names it. */
22
+ export declare const COLOUR_LIMIT_MEANS = "one per hue in the palette";
23
+ /**
24
+ * Check every grouping column of a plot against what drawing can tell apart.
25
+ *
26
+ * @param plot - The plot, through the schema.
27
+ * @param options - The table, its row count, whether colour is by category, which rows become marks, and the plot's path.
28
+ * @throws Error naming `colour`, `marker_shape` or `line_type` when that column needs more categories than drawing has.
29
+ */
30
+ export declare function checkPlotCategoryLimits(plot: Plot, options: {
31
+ table: DataTable;
32
+ rowCount: number;
33
+ isColourCategorical: boolean;
34
+ isDrawn: (row: number) => boolean;
35
+ where: string;
36
+ }): void;
37
+ /**
38
+ * Refuse a column whose drawn categories need more slots than drawing has.
39
+ *
40
+ * @param options - The field's path, what tells the categories apart, the column, the limit and what it means,
41
+ * the column's categories in first-seen order, the slots the drawn ones need, how to list the drawn ones,
42
+ * and what to advise, given how many categories are drawn, when more are drawn than the limit.
43
+ * @throws Error naming the field when the drawn categories need more slots than the limit.
44
+ */
45
+ export declare function checkCategorySlots(options: {
46
+ where: string;
47
+ subject: string;
48
+ column: string;
49
+ limit: number;
50
+ means: string;
51
+ categories: readonly string[];
52
+ slotsNeeded: number;
53
+ readDrawnCategories: () => string[];
54
+ adviseTooMany: (drawnCount: number) => string;
55
+ }): void;
56
+ /**
57
+ * Refuse a pie with more slices than the palette has hues. Each slice drawn
58
+ * takes the next hue, as the model gives them, so slices are counted, not
59
+ * distinct labels: a row with no label or no amount draws no slice.
60
+ *
61
+ * @param plot - The pie, through the schema.
62
+ * @param options - The table, its row count, and the plot's path.
63
+ * @throws Error naming `label` when the pie draws more slices than the palette has hues.
64
+ */
65
+ export declare function checkPieSliceLimit(plot: Extract<Plot, {
66
+ type: "pie";
67
+ }>, options: {
68
+ table: DataTable;
69
+ rowCount: number;
70
+ where: string;
71
+ }): void;
72
+ /**
73
+ * Refuse a points or lines map layer coloured by more categories than the
74
+ * palette has hues. The model gives every category in the column a layer and
75
+ * a hue, drawn or not, so every category counts.
76
+ *
77
+ * @param layer - The layer, through the schema.
78
+ * @param options - The layer's table, which rows have every coordinate, and the layer's path.
79
+ * @throws Error naming `colour` when the column holds more categories than the palette has hues.
80
+ */
81
+ export declare function checkMapLayerColourLimit(layer: Extract<MapLayer, {
82
+ type: "points" | "lines";
83
+ }>, options: {
84
+ table: DataTable;
85
+ isDrawn: (row: number) => boolean;
86
+ where: string;
87
+ }): void;
88
+ /**
89
+ * Refuse a map whose hues run past the palette: a category a layer draws, or
90
+ * an uncoloured points or lines layer, whose map-wide slot does not fit. The
91
+ * slots come from the function the model draws with, which gives a slot only
92
+ * to a drawn category. Runs after every layer's own colour check, so a layer
93
+ * over the limit by itself is refused with that check's advice.
94
+ *
95
+ * On a map with a regions layer coloured by category, which the table alone
96
+ * settles, the lower bound runs first in both passes: the same ordering
97
+ * counting only the points and lines layers, which regions can only add to,
98
+ * so a map it refuses is refused before its outlines are fetched, with the
99
+ * same refusal in both passes. Then, when that fits, the drawn map's slots,
100
+ * which before outlines load are known only on a map with no regions layer
101
+ * coloured by category; on that map the lower bound is the drawn map's slots,
102
+ * so it is not run and the refusal counts every coloured layer.
103
+ *
104
+ * @param layers - The map's layers, through the schema.
105
+ * @param options - The map's own table, the map's path, and whether regions outlines are loaded and checked.
106
+ * @throws Error naming the first layer, in layer order, that needs a hue past the palette.
107
+ */
108
+ export declare function checkMapLayerHueSlots(layers: readonly MapLayer[], options: {
109
+ table: DataTable;
110
+ where: string;
111
+ areOutlinesLoaded: boolean;
112
+ }): void;
113
+ /**
114
+ * Refuse a regions layer whose drawn regions need more colour categories than
115
+ * the palette has hues. A region takes the hue of its row's category's place
116
+ * among every category in the column, so the place of the last category an
117
+ * outline joins to is what counts.
118
+ *
119
+ * @param layer - The layer, through the schema, its outlines loaded and checked.
120
+ * @param options - The layer's table and the layer's path.
121
+ * @throws Error naming `value` when the regions drawn need more colour categories than the palette has hues.
122
+ */
123
+ export declare function checkRegionsColourLimit(layer: Extract<MapLayer, {
124
+ type: "regions";
125
+ }>, options: {
126
+ table: DataTable;
127
+ where: string;
128
+ }): void;
@@ -0,0 +1,284 @@
1
+ /**
2
+ * Refuse a plot whose grouping columns hold more categories than drawing can
3
+ * tell apart: more colour categories than the palette has hues, more
4
+ * marker_shape categories than there are shapes, more line_type categories
5
+ * than there are dashes. Without this the model refuses them while drawing,
6
+ * with a message that names no field.
7
+ *
8
+ * The categories are counted as the model counts them, through `groupRows`
9
+ * over the drawn rows: a category keeps its place in the column's
10
+ * first-seen order whether or not it is drawn, so the slot a drawn row needs
11
+ * is its category's index, not how many categories are drawn.
12
+ *
13
+ * Pies and map layers take their hues as their own models give them: a pie
14
+ * one per slice drawn, a points or lines layer one per category in its
15
+ * colour column, a regions layer its category's place in its value column;
16
+ * across a map's layers, each category label takes one hue, map-wide.
17
+ */
18
+ import { decideColourIsContinuous } from "../colour/colour_scale.js";
19
+ import { adviseGroupingIntoOther, advisePlotGrouping, countCategoriesKeptBesideOther, describeCount, LINE_DASHES, MARKER_SHAPES, MAXIMUM_COLOUR_CATEGORIES, } from "../colour/palette.js";
20
+ import { assignMapLayerHueSlots, assignMapLayerHueSlotsWithoutRegions, decideRegionsAreColouredByCategory, readCategorySlot, } from "../map/assign_map_layer_hue_slots.js";
21
+ import { joinRegionRows } from "../map/join_region_rows.js";
22
+ import { findColumn } from "../table/data_table.js";
23
+ import { groupRows } from "../table/group_rows.js";
24
+ import { listCategories } from "../table/list_categories.js";
25
+ import { readNumber } from "../table/read_number.js";
26
+ /** What the colour limit stands for, in every refusal that names it. */
27
+ export const COLOUR_LIMIT_MEANS = "one per hue in the palette";
28
+ /** What a map layer's categories can be split across instead of grouping them: a map's layers share its hues, so not its layers. */
29
+ const LAYER_SPLIT_ACROSS = "maps in a grid";
30
+ /**
31
+ * Describe how many categories a column has, in words, singular for one: `1 "ward" category`, `2 "ward" categories`.
32
+ *
33
+ * @param count - How many categories.
34
+ * @param options - The column they are in.
35
+ * @returns The count, the quoted column and the noun in the number the count needs.
36
+ */
37
+ function describeCategoryCount(count, options) {
38
+ return describeCount(count, { singular: `"${options.column}" category`, plural: `"${options.column}" categories` });
39
+ }
40
+ /**
41
+ * Check every grouping column of a plot against what drawing can tell apart.
42
+ *
43
+ * @param plot - The plot, through the schema.
44
+ * @param options - The table, its row count, whether colour is by category, which rows become marks, and the plot's path.
45
+ * @throws Error naming `colour`, `marker_shape` or `line_type` when that column needs more categories than drawing has.
46
+ */
47
+ export function checkPlotCategoryLimits(plot, options) {
48
+ // Every plot with a colour field gives each colour category its own series and hue, so the field itself selects them.
49
+ const colour = options.isColourCategorical && "colour" in plot ? plot.colour : undefined;
50
+ const style = plot.type === "scatter" ? { field: "marker_shape", column: plot.marker_shape, limit: MARKER_SHAPES.length, means: "one per marker shape" }
51
+ : plot.type === "line" ? { field: "line_type", column: plot.line_type, limit: LINE_DASHES.length, means: "one per dash" }
52
+ : null;
53
+ const styleColumn = style === null ? undefined : style.column;
54
+ if (colour === undefined && styleColumn === undefined)
55
+ return;
56
+ const { grouping, groups, drawnRows } = groupRows(options.table, { rowCount: options.rowCount, colour, style: styleColumn, isDrawn: options.isDrawn });
57
+ const readDrawnCategories = (column) => {
58
+ const columnValues = findColumn(options.table, { column }) ?? [];
59
+ return listCategories(drawnRows.map((row) => columnValues[row] ?? null));
60
+ };
61
+ // The slot the last drawn category takes, counting every category before it, drawn or not, as the model does.
62
+ // A reduce, not a spread into Math.max, so a column of very many categories cannot overflow the call stack.
63
+ const countSlotsNeeded = (readIndex) => groups.reduce((largest, group) => Math.max(largest, readIndex(group) + 1), 0);
64
+ if (colour !== undefined) {
65
+ checkCategorySlots({
66
+ where: `${options.where}.colour`, subject: "colour", column: colour, limit: MAXIMUM_COLOUR_CATEGORIES, means: COLOUR_LIMIT_MEANS,
67
+ categories: grouping.colourCategories, slotsNeeded: countSlotsNeeded((group) => group.colourIndex), readDrawnCategories: () => readDrawnCategories(colour),
68
+ adviseTooMany: () => advisePlotGrouping({ limit: MAXIMUM_COLOUR_CATEGORIES }),
69
+ });
70
+ }
71
+ if (style !== null && styleColumn !== undefined) {
72
+ checkCategorySlots({
73
+ where: `${options.where}.${style.field}`, subject: style.field, column: styleColumn, limit: style.limit, means: style.means,
74
+ categories: grouping.styleCategories, slotsNeeded: countSlotsNeeded((group) => group.styleIndex), readDrawnCategories: () => readDrawnCategories(styleColumn),
75
+ adviseTooMany: () => advisePlotGrouping({ limit: style.limit }),
76
+ });
77
+ }
78
+ }
79
+ /**
80
+ * Refuse a column whose drawn categories need more slots than drawing has.
81
+ *
82
+ * @param options - The field's path, what tells the categories apart, the column, the limit and what it means,
83
+ * the column's categories in first-seen order, the slots the drawn ones need, how to list the drawn ones,
84
+ * and what to advise, given how many categories are drawn, when more are drawn than the limit.
85
+ * @throws Error naming the field when the drawn categories need more slots than the limit.
86
+ */
87
+ export function checkCategorySlots(options) {
88
+ if (options.slotsNeeded <= options.limit)
89
+ return;
90
+ const drawnCategories = new Set(options.readDrawnCategories());
91
+ const limitClause = `${options.where}: ${options.subject} can tell apart at most ${options.limit} categories, ${options.means}`;
92
+ if (drawnCategories.size <= options.limit) {
93
+ // Few enough are drawn: the slots run out only because categories that draw nothing still hold their place.
94
+ const undrawn = options.categories.slice(0, options.slotsNeeded).filter((category) => !drawnCategories.has(category));
95
+ throw new Error(`${limitClause}. The rows drawn have ${describeCategoryCount(drawnCategories.size, { column: options.column })}, but a category keeps its place ` +
96
+ `whether or not it is drawn, and ${undrawn.map((category) => `"${category}"`).join(", ")} ${undrawn.length === 1 ? "comes" : "come"} before the last of them, ` +
97
+ `which needs place ${options.slotsNeeded}. Drop the rows of the categories that draw nothing, or give them values that draw.`);
98
+ }
99
+ throw new Error(`${limitClause}, and the rows drawn have ${describeCategoryCount(drawnCategories.size, { column: options.column })}. ` +
100
+ options.adviseTooMany(drawnCategories.size));
101
+ }
102
+ /**
103
+ * Refuse a pie with more slices than the palette has hues. Each slice drawn
104
+ * takes the next hue, as the model gives them, so slices are counted, not
105
+ * distinct labels: a row with no label or no amount draws no slice.
106
+ *
107
+ * @param plot - The pie, through the schema.
108
+ * @param options - The table, its row count, and the plot's path.
109
+ * @throws Error naming `label` when the pie draws more slices than the palette has hues.
110
+ */
111
+ export function checkPieSliceLimit(plot, options) {
112
+ const labels = findColumn(options.table, { column: plot.label }) ?? [];
113
+ const amounts = findColumn(options.table, { column: plot.value }) ?? [];
114
+ let slices = 0;
115
+ for (let row = 0; row < options.rowCount; row += 1) {
116
+ if (labels[row] !== null && labels[row] !== undefined && readNumber(amounts[row]) !== null)
117
+ slices += 1;
118
+ }
119
+ if (slices <= MAXIMUM_COLOUR_CATEGORIES)
120
+ return;
121
+ // The "Other" row is a slice with a hue of its own, so only one fewer than the palette's hues stay beside it.
122
+ const mergedSlices = slices - countCategoriesKeptBesideOther({ limit: MAXIMUM_COLOUR_CATEGORIES });
123
+ throw new Error(`${options.where}.label: a pie can tell apart at most ${MAXIMUM_COLOUR_CATEGORIES} slices, ${COLOUR_LIMIT_MEANS}, and ${slices} rows have both a label in "${plot.label}" ` +
124
+ `and a value in "${plot.value}", each a slice. Put the ${mergedSlices} smallest in one "Other" row, or split them across pies in a grid.`);
125
+ }
126
+ /**
127
+ * Refuse a points or lines map layer coloured by more categories than the
128
+ * palette has hues. The model gives every category in the column a layer and
129
+ * a hue, drawn or not, so every category counts.
130
+ *
131
+ * @param layer - The layer, through the schema.
132
+ * @param options - The layer's table, which rows have every coordinate, and the layer's path.
133
+ * @throws Error naming `colour` when the column holds more categories than the palette has hues.
134
+ */
135
+ export function checkMapLayerColourLimit(layer, options) {
136
+ if (layer.colour === undefined)
137
+ return;
138
+ const colours = findColumn(options.table, { column: layer.colour }) ?? [];
139
+ if (decideColourIsContinuous(colours, { colourType: layer.colour_type }))
140
+ return;
141
+ const categories = listCategories(colours);
142
+ if (categories.length <= MAXIMUM_COLOUR_CATEGORIES)
143
+ return;
144
+ // Not checkCategorySlots: its reason, that undrawn categories come before the last drawn one, is not why a layer runs
145
+ // out of hues. Here every category takes a hue, so undrawn ones may come after every drawn one and still count.
146
+ const drawnCount = listCategories(colours.filter((_, row) => options.isDrawn(row))).length;
147
+ throw new Error(`${options.where}.colour: colour can tell apart at most ${MAXIMUM_COLOUR_CATEGORIES} categories, ${COLOUR_LIMIT_MEANS}, ` +
148
+ `and the layer's column has ${describeCategoryCount(categories.length, { column: layer.colour })}, ${drawnCount} of them drawn. A map layer gives every ` +
149
+ `category in its colour column its own hue, drawn or not. ${adviseMapLayerGrouping({ drawnCount, categoryCount: categories.length })}`);
150
+ }
151
+ /** What a map's categories and uncoloured layers count as, in every refusal that names its hues. */
152
+ const MAP_HUE_SHARING = "shared by its categories and uncoloured layers";
153
+ /** The drawn map's slots: every layer coloured by a category. With none, "the map has" opens both clauses. */
154
+ const EVERY_COLOURED_LAYER = {
155
+ holders: "layers coloured by a category",
156
+ describeNoCategory: (uncolouredLayers) => `the map has no layer coloured by a category and ${uncolouredLayers}`,
157
+ describeHueNeeded: (subject, options) => `${subject} needs hue ${options.hue}`,
158
+ };
159
+ /**
160
+ * The lower bound's slots: the points and lines layers only, before any regions layer's categories are counted. A
161
+ * regions layer's labels only add hues, so the hue named is the fewest the drawn map needs, not the one it gives.
162
+ */
163
+ const POINTS_AND_LINES_LAYERS_ALONE = {
164
+ holders: "points and lines layers alone",
165
+ describeNoCategory: (uncolouredLayers) => `its points and lines layers alone have no category and the map has ${uncolouredLayers}`,
166
+ describeHueNeeded: (subject, options) => `counted on the map's points and lines layers alone, ${subject} takes hue ${options.hue}, ` +
167
+ `so the map needs at least ${describeCount(options.hue, { singular: "hue", plural: "hues" })}`,
168
+ };
169
+ /**
170
+ * Refuse a map whose hues run past the palette: a category a layer draws, or
171
+ * an uncoloured points or lines layer, whose map-wide slot does not fit. The
172
+ * slots come from the function the model draws with, which gives a slot only
173
+ * to a drawn category. Runs after every layer's own colour check, so a layer
174
+ * over the limit by itself is refused with that check's advice.
175
+ *
176
+ * On a map with a regions layer coloured by category, which the table alone
177
+ * settles, the lower bound runs first in both passes: the same ordering
178
+ * counting only the points and lines layers, which regions can only add to,
179
+ * so a map it refuses is refused before its outlines are fetched, with the
180
+ * same refusal in both passes. Then, when that fits, the drawn map's slots,
181
+ * which before outlines load are known only on a map with no regions layer
182
+ * coloured by category; on that map the lower bound is the drawn map's slots,
183
+ * so it is not run and the refusal counts every coloured layer.
184
+ *
185
+ * @param layers - The map's layers, through the schema.
186
+ * @param options - The map's own table, the map's path, and whether regions outlines are loaded and checked.
187
+ * @throws Error naming the first layer, in layer order, that needs a hue past the palette.
188
+ */
189
+ export function checkMapLayerHueSlots(layers, options) {
190
+ // Decided from the table, never from loaded outlines, so the lower bound runs in exactly the same cases in both passes.
191
+ if (decideRegionsAreColouredByCategory(layers, { table: options.table })) {
192
+ const lowerBound = assignMapLayerHueSlotsWithoutRegions(layers, { table: options.table });
193
+ refuseHueSlotPastPalette(layers, { hueSlots: lowerBound, count: POINTS_AND_LINES_LAYERS_ALONE, where: options.where });
194
+ }
195
+ const hueSlots = assignMapLayerHueSlots(layers, { table: options.table, areOutlinesLoaded: options.areOutlinesLoaded });
196
+ // Before outlines load, a regions layer's drawn categories are unknown, and so is every slot after them: refusing on a
197
+ // guess would name the wrong layer or refuse a map that fits, so the rest waits for the pass with outlines loaded.
198
+ if (hueSlots.isEverySlotKnown)
199
+ refuseHueSlotPastPalette(layers, { hueSlots, count: EVERY_COLOURED_LAYER, where: options.where });
200
+ }
201
+ /**
202
+ * Refuse the first layer, in layer order, whose slot is past the palette: a category first, then an uncoloured layer.
203
+ *
204
+ * @param layers - The map's layers, through the schema.
205
+ * @param options - The slots, which layers' categories they count and how to say so, and the map's path.
206
+ * @throws Error naming the layer that needs a hue past the palette.
207
+ */
208
+ function refuseHueSlotPastPalette(layers, options) {
209
+ const { hueSlots, count } = options;
210
+ const { slotByCategory, categoriesByLayer, uncolouredSlots } = hueSlots;
211
+ const categories = describeCount(slotByCategory.size, { singular: "category", plural: "categories" });
212
+ layers.forEach((layer, index) => {
213
+ const slotOf = (category) => readCategorySlot(category, { layerIndex: index, hueSlots });
214
+ const category = (categoriesByLayer[index] ?? []).find((candidate) => slotOf(candidate) >= MAXIMUM_COLOUR_CATEGORIES);
215
+ if (category === undefined)
216
+ return;
217
+ const field = layer.type === "regions" ? "value" : "colour";
218
+ throw new Error(`${options.where}.layers[${index}].${field}: a map can tell apart at most ${MAXIMUM_COLOUR_CATEGORIES} hues, ${MAP_HUE_SHARING}, ` +
219
+ `and ${count.describeHueNeeded(`this layer's "${category}" category`, { hue: slotOf(category) + 1 })}: a category takes one hue on the whole map, ` +
220
+ `shared by every layer that has it, and the map's ${count.holders} have ${categories} between them. ` +
221
+ `Give the same thing the same label in every layer and group the rest into fewer categories, or split the layers across ${LAYER_SPLIT_ACROSS}.`);
222
+ });
223
+ const index = uncolouredSlots.findIndex((slot) => slot !== null && slot >= MAXIMUM_COLOUR_CATEGORIES);
224
+ if (index === -1)
225
+ return;
226
+ const slot = uncolouredSlots[index];
227
+ const uncolouredCount = uncolouredSlots.filter((candidate) => candidate !== null).length;
228
+ const uncolouredLayers = describeCount(uncolouredCount, { singular: "uncoloured points or lines layer", plural: "uncoloured points or lines layers" });
229
+ // A layer coloured by a number takes no slot (it draws a colour scale), so both branches name only category colouring.
230
+ const takers = slotByCategory.size === 0
231
+ ? count.describeNoCategory(uncolouredLayers)
232
+ : `its ${count.holders} have ${categories} between them and the map has ${uncolouredLayers}`;
233
+ // With one uncoloured layer there is nothing to merge: colouring it, or freeing hues from the categories, is what fits it.
234
+ const advice = uncolouredCount === 1
235
+ ? "Colour that layer by a category column, or group the coloured layers' categories into fewer so the uncoloured layer fits."
236
+ : `Merge the uncoloured layers into one coloured by a category column, or split them across ${LAYER_SPLIT_ACROSS}.`;
237
+ throw new Error(`${options.where}.layers[${index}].colour: a map can tell apart at most ${MAXIMUM_COLOUR_CATEGORIES} hues, ${MAP_HUE_SHARING}, ` +
238
+ `and ${count.describeHueNeeded("this uncoloured layer", { hue: slot + 1 })}: a points or lines layer with no colour takes the next hue after every category ` +
239
+ `a coloured layer uses, and ${takers}. ${advice}`);
240
+ }
241
+ /**
242
+ * Advise a map layer with more colour categories than the palette has hues: group them, split them across maps in a grid,
243
+ * and, when some but not all draw, drop the rows of those that draw nothing.
244
+ *
245
+ * @param options - How many of the column's categories are drawn, and how many it holds.
246
+ * @returns The advice, one sentence.
247
+ */
248
+ function adviseMapLayerGrouping(options) {
249
+ const groupOrSplit = adviseGroupingIntoOther({ limit: MAXIMUM_COLOUR_CATEGORIES, splitAcross: LAYER_SPLIT_ACROSS });
250
+ // Dropping the categories that draw nothing is advice only when some, but not all, draw: with none drawn it would drop every row.
251
+ const isSomeButNotAllDrawn = options.drawnCount > 0 && options.drawnCount < options.categoryCount;
252
+ return isSomeButNotAllDrawn ? `Drop the rows of the categories that draw nothing, put ${groupOrSplit}` : `Put ${groupOrSplit}`;
253
+ }
254
+ /**
255
+ * Refuse a regions layer whose drawn regions need more colour categories than
256
+ * the palette has hues. A region takes the hue of its row's category's place
257
+ * among every category in the column, so the place of the last category an
258
+ * outline joins to is what counts.
259
+ *
260
+ * @param layer - The layer, through the schema, its outlines loaded and checked.
261
+ * @param options - The layer's table and the layer's path.
262
+ * @throws Error naming `value` when the regions drawn need more colour categories than the palette has hues.
263
+ */
264
+ export function checkRegionsColourLimit(layer, options) {
265
+ if (layer.value === undefined)
266
+ return;
267
+ const values = findColumn(options.table, { column: layer.value }) ?? [];
268
+ if (decideColourIsContinuous(values, { colourType: layer.colour_type }))
269
+ return;
270
+ // checkMapLayers has refused a layer whose outlines or feature property are missing, before this runs.
271
+ if (layer.feature_property === undefined)
272
+ throw new Error(`Expected ${options.where} to name its feature property by now; it did not.`);
273
+ const keys = findColumn(options.table, { column: layer.key }) ?? [];
274
+ const { joinedRows } = joinRegionRows(layer.geojson, { keys, featureProperty: layer.feature_property });
275
+ const categories = listCategories(values);
276
+ const placeByCategory = new Map(categories.map((category, index) => [category, index]));
277
+ const drawnValues = [...joinedRows].map((row) => values[row] ?? null);
278
+ const slotsNeeded = drawnValues.reduce((largest, value) => (value === null ? largest : Math.max(largest, (placeByCategory.get(String(value)) ?? -1) + 1)), 0);
279
+ checkCategorySlots({
280
+ where: `${options.where}.value`, subject: "colour", column: layer.value, limit: MAXIMUM_COLOUR_CATEGORIES, means: COLOUR_LIMIT_MEANS,
281
+ categories, slotsNeeded, readDrawnCategories: () => listCategories(drawnValues),
282
+ adviseTooMany: (drawnCount) => adviseMapLayerGrouping({ drawnCount, categoryCount: categories.length }),
283
+ });
284
+ }