@urban-toolkit/autk-grammar 4.4.1 → 5.0.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.
@@ -1,167 +1,249 @@
1
- import { AutkDb as z, DEFAULT_WORKSPACE_COORDINATE_FORMAT as k } from "@urban-toolkit/autk-db";
2
- import { AutkMap as Z, MapEvent as B } from "@urban-toolkit/autk-map";
3
- import { AutkPlot as tt, PlotEvent as I } from "@urban-toolkit/autk-plot";
4
- import { ColorMapInterpolator as et, ColorMapDomainStrategy as M, ColorMap as v } from "@urban-toolkit/autk-core";
5
- import { AutkComputeEngine as rt } from "@urban-toolkit/autk-compute";
6
- function ot(t) {
1
+ import { DEFAULT_WORKSPACE_NAME as lt, AutkDb as St, DEFAULT_WORKSPACE_COORDINATE_FORMAT as ut, isRenderableTable as vt } from "@urban-toolkit/autk-db";
2
+ import { AutkMap as Ct, MapEvent as D } from "@urban-toolkit/autk-map";
3
+ import { AutkPlot as It, PlotEvent as O } from "@urban-toolkit/autk-plot";
4
+ import { ColorMapInterpolator as Lt, ColorMapDomainStrategy as I, ColorMap as B } from "@urban-toolkit/autk-core";
5
+ import { AutkComputeEngine as X } from "@urban-toolkit/autk-compute";
6
+ function Pt(t) {
7
7
  const { spec: e, adapters: r } = t;
8
8
  let o;
9
- async function i() {
10
- let a;
9
+ async function n() {
10
+ let i;
11
11
  if (e.data)
12
- for (const s of e.data)
13
- a = await r.db.resolveSource(a, s);
12
+ for (const l of e.data)
13
+ i = await r.db.resolveSource(i, l);
14
14
  if (e.compute)
15
- for (const s of e.compute)
16
- a = await r.compute.resolveCompute(a, s);
15
+ for (const l of e.compute)
16
+ i = await r.compute.resolveCompute(i, l);
17
17
  if (e.map)
18
18
  if (Array.isArray(e.map))
19
- for (let s = 0; s < e.map.length; s++) {
20
- let u = e.map[s];
21
- await r.map.resolveMap(a, u, s);
19
+ for (let l = 0; l < e.map.length; l++) {
20
+ let u = e.map[l];
21
+ await r.map.resolveMap(i, u, l);
22
22
  }
23
23
  else
24
- await r.map.resolveMap(a, e.map);
24
+ await r.map.resolveMap(i, e.map);
25
25
  if (e.plot)
26
26
  if (Array.isArray(e.plot))
27
- for (const s of e.plot)
28
- await r.plot.resolvePlot(a, s);
27
+ for (let l = 0; l < e.plot.length; l++)
28
+ await r.plot.resolvePlot(i, e.plot[l], l);
29
29
  else
30
- await r.plot.resolvePlot(a, e.plot);
31
- o = a;
30
+ await r.plot.resolvePlot(i, e.plot);
31
+ o = i;
32
32
  }
33
- function n(a) {
34
- return console.log("Spec to update", a), new Promise((s) => {
35
- s();
33
+ function a(i) {
34
+ return console.log("Spec to update", i), new Promise((l) => {
35
+ l();
36
36
  });
37
37
  }
38
- function l() {
38
+ function s() {
39
39
  console.log("Function not implemented yet");
40
40
  }
41
- return { run: i, updatedSpec: n, destroy: l, get context() {
41
+ return { run: n, updatedSpec: a, destroy: s, get context() {
42
42
  return o;
43
43
  } };
44
44
  }
45
- var nt = /* @__PURE__ */ ((t) => (t.CAT_ACCENT = "schemeAccent", t.CAT_DARK2 = "schemeDark2", t.CAT_CATEGORY10 = "schemeCategory10", t.CAT_OBSERVABLE10 = "schemeObservable10", t.CAT_PAIRED = "schemePaired", t.CAT_PASTEL1 = "schemePastel1", t.CAT_PASTEL2 = "schemePastel2", t.CAT_SET1 = "schemeSet1", t.CAT_SET2 = "schemeSet2", t.CAT_SET3 = "schemeSet3", t.CAT_TABLEAU10 = "schemeTableau10", t.SEQ_REDS = "interpolateReds", t.SEQ_BLUES = "interpolateBlues", t.SEQ_GREENS = "interpolateGreens", t.SEQ_GREYS = "interpolateGreys", t.SEQ_ORANGES = "interpolateOranges", t.SEQ_PURPLES = "interpolatePurples", t.SEQ_TURBO = "interpolateTurbo", t.SEQ_VIRIDIS = "interpolateViridis", t.SEQ_INFERNO = "interpolateInferno", t.SEQ_MAGMA = "interpolateMagma", t.SEQ_PLASMA = "interpolatePlasma", t.SEQ_CIVIDIS = "interpolateCividis", t.SEQ_WARM = "interpolateWarm", t.SEQ_COOL = "interpolateCool", t.SEQ_CUBEHELIX_DEFAULT = "interpolateCubehelixDefault", t.SEQ_BU_GN = "interpolateBuGn", t.SEQ_BU_PU = "interpolateBuPu", t.SEQ_GN_BU = "interpolateGnBu", t.SEQ_OR_RD = "interpolateOrRd", t.SEQ_PU_BU_GN = "interpolatePuBuGn", t.SEQ_PU_BU = "interpolatePuBu", t.SEQ_PU_RD = "interpolatePuRd", t.SEQ_RD_PU = "interpolateRdPu", t.SEQ_YL_GN_BU = "interpolateYlGnBu", t.SEQ_YL_GN = "interpolateYlGn", t.SEQ_YL_OR_BR = "interpolateYlOrBr", t.SEQ_YL_OR_RD = "interpolateYlOrRd", t.DIV_BR_BG = "interpolateBrBG", t.DIV_PR_GN = "interpolatePRGn", t.DIV_PI_YG = "interpolatePiYG", t.DIV_PU_OR = "interpolatePuOr", t.DIV_RED_BLUE = "interpolateRdBu", t.DIV_RED_GREY = "interpolateRdGy", t.DIV_RED_YELLOW_BLUE = "interpolateRdYlBu", t.DIV_RED_YELLOW_GREEN = "interpolateRdYlGn", t.DIV_SPECTRAL = "interpolateSpectral", t))(nt || {}), H = /* @__PURE__ */ ((t) => (t.MIN_MAX = "minMax", t.PERCENTILE = "percentile", t))(H || {});
46
- function at(t) {
45
+ function z(t) {
46
+ return t === void 0 ? [] : Array.isArray(t) ? t : [t];
47
+ }
48
+ function Re(t) {
49
+ const e = t.layout ?? {}, r = e.type ?? "vertical";
50
+ if (r !== "vertical" && r !== "horizontal" && r !== "grid")
51
+ throw new Error(`Layout type must be vertical, horizontal or grid, not ${JSON.stringify(r)}.`);
52
+ const o = e.gap ?? 0;
53
+ if (typeof o != "number" || !Number.isFinite(o) || o < 0)
54
+ throw new Error(`Layout gap must be a number of pixels, 0 or more, not ${JSON.stringify(o)}.`);
55
+ const n = e.columns ?? 2;
56
+ if (!Number.isInteger(n) || n < 1)
57
+ throw new Error(`Layout columns must be a whole number, 1 or more, not ${JSON.stringify(n)}.`);
58
+ const a = [
59
+ ...z(t.map).map((l, u) => ({ kind: "map", index: u, id: l.id, key: l.id ?? u })),
60
+ ...z(t.plot).map((l, u) => ({ kind: "plot", index: u, id: l.id, key: l.id ?? l.dataRef }))
61
+ ], s = r === "vertical" ? 1 : r === "horizontal" ? Math.max(a.length, 1) : n, i = a.map(({ kind: l, index: u, id: c, key: f }, p) => ({
62
+ kind: l,
63
+ index: u,
64
+ ...c !== void 0 && { id: c },
65
+ key: f,
66
+ row: Math.floor(p / s),
67
+ column: p % s
68
+ }));
69
+ return { type: r, rows: Math.ceil(a.length / s), columns: s, gap: o, panes: i };
70
+ }
71
+ var Nt = /* @__PURE__ */ ((t) => (t.CAT_ACCENT = "schemeAccent", t.CAT_DARK2 = "schemeDark2", t.CAT_CATEGORY10 = "schemeCategory10", t.CAT_OBSERVABLE10 = "schemeObservable10", t.CAT_PAIRED = "schemePaired", t.CAT_PASTEL1 = "schemePastel1", t.CAT_PASTEL2 = "schemePastel2", t.CAT_SET1 = "schemeSet1", t.CAT_SET2 = "schemeSet2", t.CAT_SET3 = "schemeSet3", t.CAT_TABLEAU10 = "schemeTableau10", t.SEQ_REDS = "interpolateReds", t.SEQ_BLUES = "interpolateBlues", t.SEQ_GREENS = "interpolateGreens", t.SEQ_GREYS = "interpolateGreys", t.SEQ_ORANGES = "interpolateOranges", t.SEQ_PURPLES = "interpolatePurples", t.SEQ_TURBO = "interpolateTurbo", t.SEQ_VIRIDIS = "interpolateViridis", t.SEQ_INFERNO = "interpolateInferno", t.SEQ_MAGMA = "interpolateMagma", t.SEQ_PLASMA = "interpolatePlasma", t.SEQ_CIVIDIS = "interpolateCividis", t.SEQ_WARM = "interpolateWarm", t.SEQ_COOL = "interpolateCool", t.SEQ_CUBEHELIX_DEFAULT = "interpolateCubehelixDefault", t.SEQ_BU_GN = "interpolateBuGn", t.SEQ_BU_PU = "interpolateBuPu", t.SEQ_GN_BU = "interpolateGnBu", t.SEQ_OR_RD = "interpolateOrRd", t.SEQ_PU_BU_GN = "interpolatePuBuGn", t.SEQ_PU_BU = "interpolatePuBu", t.SEQ_PU_RD = "interpolatePuRd", t.SEQ_RD_PU = "interpolateRdPu", t.SEQ_YL_GN_BU = "interpolateYlGnBu", t.SEQ_YL_GN = "interpolateYlGn", t.SEQ_YL_OR_BR = "interpolateYlOrBr", t.SEQ_YL_OR_RD = "interpolateYlOrRd", t.DIV_BR_BG = "interpolateBrBG", t.DIV_PR_GN = "interpolatePRGn", t.DIV_PI_YG = "interpolatePiYG", t.DIV_PU_OR = "interpolatePuOr", t.DIV_RED_BLUE = "interpolateRdBu", t.DIV_RED_GREY = "interpolateRdGy", t.DIV_RED_YELLOW_BLUE = "interpolateRdYlBu", t.DIV_RED_YELLOW_GREEN = "interpolateRdYlGn", t.DIV_SPECTRAL = "interpolateSpectral", t))(Nt || {}), ct = /* @__PURE__ */ ((t) => (t.MIN_MAX = "minMax", t.PERCENTILE = "percentile", t))(ct || {});
72
+ async function N(t, e) {
73
+ const r = e ?? lt;
74
+ t.getCurrentWorkspace() !== r && await t.setWorkspace(r);
75
+ }
76
+ function A(t, e) {
77
+ return t === void 0 || t === lt ? e : `${t}/${e}`;
78
+ }
79
+ function ft(t) {
80
+ const e = /* @__PURE__ */ new Set();
81
+ for (const o of t)
82
+ o?.id != null && e.add(JSON.stringify(o.id));
83
+ const r = /* @__PURE__ */ new Set();
84
+ return t.map((o, n) => {
85
+ if (o?.id != null) return o.id;
86
+ let a = `autk-feature-${n}`;
87
+ for (; e.has(JSON.stringify(a)) || r.has(JSON.stringify(a)); ) a = `${a}-generated`;
88
+ return r.add(JSON.stringify(a)), a;
89
+ });
90
+ }
91
+ function pt(t) {
92
+ const e = /* @__PURE__ */ new Map();
93
+ return ft(t).map((r) => {
94
+ const o = JSON.stringify(r), n = e.get(o) ?? 0;
95
+ return e.set(o, n + 1), n === 0 ? o : `${o} ${n}`;
96
+ });
97
+ }
98
+ const Z = /* @__PURE__ */ new WeakMap();
99
+ function Tt(t) {
100
+ let e = Z.get(t);
101
+ return e || (e = /* @__PURE__ */ new Map(), t.forEach((r, o) => {
102
+ const n = e.get(r);
103
+ n ? n.push(o) : e.set(r, [o]);
104
+ }), Z.set(t, e), e);
105
+ }
106
+ function x(t, e, r) {
107
+ const o = Tt(r), n = /* @__PURE__ */ new Set();
108
+ for (const a of t) {
109
+ const s = e[a];
110
+ if (s !== void 0)
111
+ for (const i of o.get(s) ?? []) n.add(i);
112
+ }
113
+ return [...n];
114
+ }
115
+ const $t = { type: "GeometryCollection", geometries: [] };
116
+ function Ot(t) {
117
+ const e = t.features ?? [], r = ft(e);
118
+ let o = !1;
119
+ const n = e.map((s, i) => s == null || s.id != null && s.geometry != null ? s : (o = !0, { ...s, id: r[i], geometry: s.geometry ?? $t })), a = e.findIndex((s) => s?.geometry != null);
120
+ return a > 0 && e[0] != null && e[0].geometry == null && ([n[0], n[a]] = [n[a], n[0]], o = !0), o ? { ...t, features: n } : t;
121
+ }
122
+ function Ft(t) {
47
123
  const { queryArea: e } = t;
48
124
  if (e.bbox === void 0) return { geocodeArea: e.geocodeArea, areas: e.areas };
49
- const r = (s) => new Error(`OSM source "${t.outputTableName}": ${s}`);
125
+ const r = (l) => new Error(`OSM source "${t.outputTableName}": ${l}`);
50
126
  if (e.geocodeArea !== void 0 || e.areas !== void 0)
51
127
  throw r("queryArea takes either bbox or geocodeArea with areas, not both.");
52
128
  const o = e.bbox;
53
- if (!Array.isArray(o) || o.length !== 4 || !o.every((s) => typeof s == "number" && Number.isFinite(s)))
129
+ if (!Array.isArray(o) || o.length !== 4 || !o.every((l) => typeof l == "number" && Number.isFinite(l)))
54
130
  throw r("queryArea.bbox must hold four numbers, [west, south, east, north] in degrees.");
55
- const [i, n, l, a] = e.bbox;
56
- if (Math.abs(i) > 180 || Math.abs(l) > 180)
131
+ const [n, a, s, i] = e.bbox;
132
+ if (Math.abs(n) > 180 || Math.abs(s) > 180)
57
133
  throw r("queryArea.bbox west and east must be longitudes from -180 to 180.");
58
- if (Math.abs(n) > 90 || Math.abs(a) > 90)
134
+ if (Math.abs(a) > 90 || Math.abs(i) > 90)
59
135
  throw r("queryArea.bbox south and north must be latitudes from -90 to 90.");
60
- if (i >= l)
61
- throw r(`queryArea.bbox west (${i}) must be less than east (${l}); a box across the antimeridian is not supported.`);
62
- if (n >= a)
63
- throw r(`queryArea.bbox south (${n}) must be less than north (${a}).`);
64
- return { bbox: [i, n, l, a] };
136
+ if (n >= s)
137
+ throw r(`queryArea.bbox west (${n}) must be less than east (${s}); a box across the antimeridian is not supported.`);
138
+ if (a >= i)
139
+ throw r(`queryArea.bbox south (${a}) must be less than north (${i}).`);
140
+ return { bbox: [n, a, s, i] };
65
141
  }
66
- function it(t) {
142
+ function Bt(t) {
67
143
  const { autoLoadLayers: e, ...r } = t;
68
- return { ...r, queryArea: at(t), autoLoadLayers: { layers: e?.layers ?? [] } };
144
+ return { ...r, queryArea: Ft(t), autoLoadLayers: { layers: e?.layers ?? [] } };
69
145
  }
70
- function D(t) {
146
+ function tt(t) {
71
147
  return `${t ? `coordinateFormat is set to "${t}"` : "no coordinateFormat was specified, so it defaults to EPSG:4326 (WGS84 per RFC 7946)"}. Verify that coordinateFormat matches the actual CRS of the input data.`;
72
148
  }
73
- function st(t) {
74
- let e = 1 / 0, r = 1 / 0, o = -1 / 0, i = -1 / 0;
75
- const n = (a) => {
76
- if (Array.isArray(a)) {
77
- if (typeof a[0] == "number") {
78
- const [s, u] = a;
79
- s < e && (e = s), s > o && (o = s), u < r && (r = u), u > i && (i = u);
149
+ function dt(t) {
150
+ let e = 1 / 0, r = 1 / 0, o = -1 / 0, n = -1 / 0;
151
+ const a = (i) => {
152
+ if (Array.isArray(i)) {
153
+ if (typeof i[0] == "number") {
154
+ const [l, u] = i;
155
+ l < e && (e = l), l > o && (o = l), u < r && (r = u), u > n && (n = u);
80
156
  return;
81
157
  }
82
- for (const s of a) n(s);
158
+ for (const l of i) a(l);
83
159
  }
84
- }, l = (a) => {
85
- a && (a.type === "GeometryCollection" ? a.geometries.forEach(l) : n(a.coordinates));
160
+ }, s = (i) => {
161
+ i && (i.type === "GeometryCollection" ? i.geometries.forEach(s) : a(i.coordinates));
86
162
  };
87
- for (const a of t.features ?? []) l(a?.geometry);
88
- return e <= o ? [e, r, o, i] : void 0;
163
+ for (const i of t.features ?? []) s(i?.geometry);
164
+ return e <= o ? [e, r, o, n] : void 0;
89
165
  }
90
- function lt(t, e) {
91
- function r(o, i) {
92
- if (!i || !i.db)
166
+ function xt(t, e) {
167
+ function r(o, n) {
168
+ if (!n || !n.db)
93
169
  return;
94
- const n = document.getElementById(i.db);
95
- if (n) {
96
- const l = o.getTablesMetadata();
97
- n.innerHTML += "<ul>";
98
- for (const a of l)
99
- n.innerHTML += `<li>${a.name}: (${a.source}, ${a.type}) </li>`;
100
- n.innerHTML += "</ul>", n.innerHTML += `<p>Number of tables: ${l.length}</p>`;
170
+ const a = document.getElementById(n.db);
171
+ if (a) {
172
+ const s = o.getTablesMetadata();
173
+ a.innerHTML += "<ul>";
174
+ for (const i of s)
175
+ a.innerHTML += `<li>${i.name}: (${i.source}, ${i.type}) </li>`;
176
+ a.innerHTML += "</ul>", a.innerHTML += `<p>Number of tables: ${s.length}</p>`;
101
177
  }
102
178
  }
103
179
  return {
104
- async resolveSource(o, i) {
105
- let n = o;
106
- n || (n = new z(), await n.init());
107
- let { type: l, ...a } = i;
108
- switch (l) {
180
+ async resolveSource(o, n) {
181
+ let a = o;
182
+ a || (a = new St(), await a.init());
183
+ const { workspace: s } = n;
184
+ await N(a, s);
185
+ let { type: i, workspace: l, ...u } = n;
186
+ switch (i) {
109
187
  case "osm":
110
- return await n.loadOsm(it(a)), r(n, t), n;
188
+ return await a.loadOsm(Bt(u)), r(a, t), a;
111
189
  case "csv":
112
- return await n.loadCsv(a), r(n, t), n;
190
+ return await a.loadCsv(u), r(a, t), a;
113
191
  case "json":
114
- return await n.loadJson(a), r(n, t), n;
192
+ return await a.loadJson(u), r(a, t), a;
115
193
  case "geojson": {
116
- const s = a;
117
- let u;
118
- s.geojsonFileUrl ? u = await (await fetch(s.geojsonFileUrl)).json() : u = s.geojsonObject, e && u && e.set(s.outputTableName, u);
119
- const c = u ? (() => {
120
- const f = { ...s, geojsonObject: u };
121
- return delete f.geojsonFileUrl, f;
122
- })() : s, d = /^EPSG:4326$/i.test(c.coordinateFormat ?? "EPSG:4326"), p = u && d ? st(u) : void 0;
123
- if (p && (p[1] < -90 || p[3] > 90))
194
+ const c = u;
195
+ let f;
196
+ c.geojsonFileUrl ? f = await (await fetch(c.geojsonFileUrl)).json() : f = c.geojsonObject, e && f && e.set(A(s, c.outputTableName), f);
197
+ const p = f ? (() => {
198
+ const m = { ...c, geojsonObject: Ot(f) };
199
+ return delete m.geojsonFileUrl, m;
200
+ })() : c, y = /^EPSG:4326$/i.test(p.coordinateFormat ?? "EPSG:4326"), d = f && y ? dt(f) : void 0;
201
+ if (d && (d[1] < -90 || d[3] > 90))
124
202
  throw new Error(
125
- `GeoJSON layer "${c.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${p.join(", ")}]), so they cannot be EPSG:4326 degrees. ${D(c.coordinateFormat)}`
203
+ `GeoJSON layer "${p.outputTableName}" has y coordinates outside -90 to 90 (bbox: [${d.join(", ")}]), so they cannot be EPSG:4326 degrees. ${tt(p.coordinateFormat)}`
126
204
  );
127
205
  try {
128
- await n.loadGeojson(c);
129
- } catch (f) {
130
- throw new Error(`Failed to load GeoJSON layer "${c.outputTableName}": ${f instanceof Error ? f.message : String(f)}`);
206
+ await a.loadGeojson(p);
207
+ } catch (m) {
208
+ throw new Error(`Failed to load GeoJSON layer "${p.outputTableName}": ${m instanceof Error ? m.message : String(m)}`);
131
209
  }
132
210
  try {
133
- const f = await n.getBoundingBoxFromLayer(c.outputTableName), m = 25e6;
134
- if (!isFinite(f.minLon) || !isFinite(f.minLat) || !isFinite(f.maxLon) || !isFinite(f.maxLat) || Math.abs(f.minLon) > m || Math.abs(f.maxLon) > m || Math.abs(f.minLat) > m || Math.abs(f.maxLat) > m)
211
+ const m = await a.getBoundingBoxFromLayer(p.outputTableName), h = 25e6;
212
+ if (!isFinite(m.minLon) || !isFinite(m.minLat) || !isFinite(m.maxLon) || !isFinite(m.maxLat) || Math.abs(m.minLon) > h || Math.abs(m.maxLon) > h || Math.abs(m.minLat) > h || Math.abs(m.maxLat) > h)
135
213
  throw new Error(
136
- `Geometry bounding box after transform is invalid for layer "${c.outputTableName}" (bbox: [${f.minLon}, ${f.minLat}, ${f.maxLon}, ${f.maxLat}]). ${D(c.coordinateFormat)} The workspace uses ${k}; input is expected in EPSG:4326 by default.`
214
+ `Geometry bounding box after transform is invalid for layer "${p.outputTableName}" (bbox: [${m.minLon}, ${m.minLat}, ${m.maxLon}, ${m.maxLat}]). ${tt(p.coordinateFormat)} The workspace uses ${ut}; input is expected in EPSG:4326 by default.`
137
215
  );
138
- } catch (f) {
139
- if (f instanceof Error && f.message.includes("bounding box after transform")) throw f;
216
+ } catch (m) {
217
+ if (m instanceof Error && m.message.includes("bounding box after transform")) throw m;
140
218
  }
141
- return r(n, t), n;
219
+ return r(a, t), a;
142
220
  }
221
+ case "geotiff":
222
+ return await a.loadGeoTiff(u), r(a, t), a;
143
223
  case "heatmap": {
144
- const s = a;
145
- return await n.buildHeatmap({
146
- tableJoinName: s.tableJoinName,
147
- near: { distance: s.near.distance },
148
- outputTableName: s.outputTableName,
149
- grid: s.grid,
150
- ...s.groupBy && { groupBy: s.groupBy }
151
- }), r(n, t), n;
224
+ const c = u;
225
+ if (c.groupBy?.some((f) => f.aggregateFn === "collect"))
226
+ throw new Error(`Heatmap "${c.outputTableName}": aggregateFn "collect" lists the rows near a cell, and a cell holds one value; use sum, avg, count, min, max or weighted.`);
227
+ return await a.buildHeatmap({
228
+ tableJoinName: c.joinDataRef,
229
+ near: c.near,
230
+ outputTableName: c.outputTableName,
231
+ grid: c.grid,
232
+ ...c.groupBy && { groupBy: c.groupBy }
233
+ }), r(a, t), a;
152
234
  }
153
235
  case "join": {
154
- const s = a;
155
- if (await n.spatialQuery({
156
- tableRootName: s.tableRootName,
157
- tableJoinName: s.tableJoinName,
158
- ...s.near && { near: s.near },
159
- ...s.groupBy && { groupBy: s.groupBy }
236
+ const c = u;
237
+ if (await a.spatialQuery({
238
+ tableRootName: c.dataRef,
239
+ tableJoinName: c.joinDataRef,
240
+ ...c.near && { near: c.near },
241
+ ...c.groupBy && { groupBy: c.groupBy }
160
242
  }), e) {
161
- const u = await n.getLayer(s.tableRootName);
162
- e.set(s.tableRootName, u);
243
+ const f = await a.getLayer(c.dataRef);
244
+ e.set(A(s, c.dataRef), f);
163
245
  }
164
- return r(n, t), n;
246
+ return r(a, t), a;
165
247
  }
166
248
  default:
167
249
  return;
@@ -169,159 +251,236 @@ function lt(t, e) {
169
251
  }
170
252
  };
171
253
  }
172
- function N(t) {
254
+ function mt(t, e, r) {
255
+ if (!t) return r();
256
+ let o = t.get(e);
257
+ return o || (o = r(), t.set(e, o)), o;
258
+ }
259
+ function ht(t, e) {
260
+ return t?.id ?? e;
261
+ }
262
+ function G(t, e) {
263
+ return e === void 0 ? !0 : typeof e == "number" ? t.mapIndex === e : t.mapId === e;
264
+ }
265
+ function yt(t, e, r) {
266
+ const o = t?.get(e) ?? [];
267
+ o.includes(r) || t?.set(e, [...o, r]);
268
+ }
269
+ const gt = 6378137, j = 0.0818191908426215;
270
+ function kt(t, e) {
271
+ if (t === void 0 || typeof t == "number" && Number.isFinite(t) && t > 0) return;
272
+ const r = typeof t == "number" ? String(t) : JSON.stringify(t);
273
+ throw new Error(`Layer "${e}": pointSize must be a number of meters greater than 0, not ${r}.`);
274
+ }
275
+ function Gt(t) {
276
+ const e = Math.exp(-t / gt);
277
+ let r = Math.PI / 2 - 2 * Math.atan(e);
278
+ for (let o = 0; o < 10; o++) {
279
+ const n = j * Math.sin(r), a = Math.PI / 2 - 2 * Math.atan(e * ((1 - n) / (1 + n)) ** (j / 2));
280
+ if (Math.abs(a - r) < 1e-12) return a;
281
+ r = a;
282
+ }
283
+ return r;
284
+ }
285
+ function Dt(t, e) {
286
+ if (/^EPSG:3395$/i.test(t)) {
287
+ const r = Gt(e), o = j * Math.sin(r);
288
+ return Math.sqrt(1 - o * o) / Math.cos(r);
289
+ }
290
+ return /^EPSG:3857$/i.test(t) ? Math.cosh(e / gt) : 1;
291
+ }
292
+ function jt(t, e, r, o) {
293
+ if (t === void 0 || e !== "points") return;
294
+ const n = o();
295
+ if (n)
296
+ return t * Dt(r, (n[1] + n[3]) / 2);
297
+ }
298
+ function S(t) {
173
299
  return typeof t.title == "string" && t.title !== "" ? t.title : t.dataRef;
174
300
  }
175
- function ut(t, e) {
301
+ function Ut(t, e) {
176
302
  const r = /* @__PURE__ */ new Set();
177
303
  for (const o of t.layerRefs) {
178
- const i = N(o);
179
- if (r.has(i))
180
- throw new Error(`Map ${e} draws two layers with the id "${i}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);
181
- r.add(i);
304
+ const n = S(o);
305
+ if (r.has(n))
306
+ throw new Error(`Map ${e} draws two layers with the id "${n}". A layer's id is its title, else its dataRef: give each layer of a map its own title.`);
307
+ r.add(n);
182
308
  }
183
309
  }
184
- const ct = /^#[0-9a-fA-F]{6}$/;
185
- function G(t, e, r) {
186
- if (!ct.test(t))
310
+ const Qt = /^#[0-9a-fA-F]{6}$/;
311
+ function et(t, e, r) {
312
+ if (!Qt.test(t))
187
313
  throw new Error(`Layer "${r}": ${e} must be a color written #rrggbb, not "${t}".`);
188
- return v.hexToRgb(t);
314
+ return B.hexToRgb(t);
189
315
  }
190
- function ft(t, e) {
316
+ function Yt(t, e) {
191
317
  const r = {};
192
- return t.color != null && (r.color = G(t.color, "color", e)), t.stroke === !1 ? r.showBorders = !1 : t.stroke != null && (r.strokeColor = G(t.stroke, "stroke", e)), t.width != null && (r.polylinesWidth = t.width), r;
318
+ return t.color != null && (r.color = et(t.color, "color", e)), t.stroke === !1 ? r.showBorders = !1 : t.stroke != null && (r.strokeColor = et(t.stroke, "stroke", e)), t.width != null && (r.polylinesWidth = t.width), r;
193
319
  }
194
- function pt(t, e) {
320
+ function Vt(t, e) {
195
321
  return t.isColorMap != null ? t.isColorMap : e === "raster" ? t.colorMapInterpolator != null || t.colorMapRange != null || t.colorMapCenter != null || t.colorMapReverse === !0 : t.color != null ? !1 : t.colorMapInterpolator != null || t.getFnv != null;
196
322
  }
197
- function mt(t, e) {
323
+ function Ht(t, e) {
198
324
  const r = t.features?.[0]?.properties?.[e];
199
325
  return r instanceof Float32Array ? r : ArrayBuffer.isView(r) && !(r instanceof DataView) || Array.isArray(r) ? Float32Array.from(r, (o) => Number.isFinite(Number(o)) ? Number(o) : NaN) : null;
200
326
  }
201
- function dt(t, e, r, o, i) {
202
- if (v.isCategorical(e.interpolator)) return;
203
- if (i != null) {
204
- const u = r != null ? [i[0], r, i[1]] : [i[0], i[1]];
327
+ function Wt(t, e, r, o, n) {
328
+ if (B.isCategorical(e.interpolator)) return;
329
+ if (n != null) {
330
+ const u = r != null ? [n[0], r, n[1]] : [n[0], n[1]];
205
331
  return o === !0 ? u.reverse() : u;
206
332
  }
207
333
  if (!t) return;
208
- let n = 0, l = 0;
334
+ let a = 0, s = 0;
209
335
  for (let u = 0; u < t.length; u++) {
210
336
  const c = t[u];
211
- Number.isFinite(c) && (l++, r != null && (n = Math.max(n, Math.abs(c - r))));
337
+ Number.isFinite(c) && (s++, r != null && (a = Math.max(a, Math.abs(c - r))));
212
338
  }
213
- const a = r != null && n > 0;
214
- if (l === 0 || !a && o !== !0) return;
215
- const s = a && r != null ? [r - n, r, r + n] : v.resolveDomainFromData(t, e);
216
- return o === !0 ? [...s].reverse() : s;
339
+ const i = r != null && a > 0;
340
+ if (s === 0 || !i && o !== !0) return;
341
+ const l = i && r != null ? [r - a, r, r + a] : B.resolveDomainFromData(t, e);
342
+ return o === !0 ? [...l].reverse() : l;
217
343
  }
218
- function ht(t, e) {
219
- if (!(e == null || v.isCategorical(t.interpolator)))
344
+ function Jt(t, e) {
345
+ if (!(e == null || B.isCategorical(t.interpolator)))
220
346
  return [e[0], e[1]];
221
347
  }
222
- function yt(t) {
348
+ function qt(t) {
223
349
  const e = t.colorMapRange;
224
350
  if (e === void 0) return;
225
- const r = (l) => new Error(`Layer "${N(t)}": ${l}`);
226
- if (!Array.isArray(e) || e.length !== 2 || !e.every((l) => typeof l == "number" && Number.isFinite(l)))
351
+ const r = (s) => new Error(`Layer "${S(t)}": ${s}`);
352
+ if (!Array.isArray(e) || e.length !== 2 || !e.every((s) => typeof s == "number" && Number.isFinite(s)))
227
353
  throw r("colorMapRange must hold two numbers, [low, high].");
228
- const [o, i] = e;
229
- if (o >= i)
230
- throw r(`colorMapRange low (${o}) must be less than high (${i}).`);
354
+ const [o, n] = e;
355
+ if (o >= n)
356
+ throw r(`colorMapRange low (${o}) must be less than high (${n}).`);
231
357
  if (t.colorMapDomain !== void 0)
232
358
  throw r("set colorMapRange or colorMapDomain, not both.");
233
- const n = t.colorMapCenter;
234
- if (n != null && (n < o || n > i))
235
- throw r(`colorMapCenter (${n}) must lie within colorMapRange [${o}, ${i}].`);
359
+ const a = t.colorMapCenter;
360
+ if (a != null && (a < o || a > n))
361
+ throw r(`colorMapCenter (${a}) must lie within colorMapRange [${o}, ${n}].`);
236
362
  }
237
- function gt(t, e) {
238
- return e && e.length > 0 ? { type: M.USER, params: e } : t?.mode === H.PERCENTILE ? t.lowerPercentile !== void 0 || t.upperPercentile !== void 0 ? {
239
- type: M.PERCENTILE,
363
+ function Kt(t, e) {
364
+ return e && e.length > 0 ? { type: I.USER, params: e } : t?.mode === ct.PERCENTILE ? t.lowerPercentile !== void 0 || t.upperPercentile !== void 0 ? {
365
+ type: I.PERCENTILE,
240
366
  params: [t.lowerPercentile ?? 0, t.upperPercentile ?? 100]
241
- } : { type: M.PERCENTILE } : { type: M.MIN_MAX };
367
+ } : { type: I.PERCENTILE } : { type: I.MIN_MAX };
242
368
  }
243
- function bt(t, e) {
369
+ function Xt(t, e) {
244
370
  return e.split(".").reduce((r, o) => {
245
371
  if (!(r == null || typeof r != "object"))
246
372
  return r[o];
247
373
  }, t);
248
374
  }
249
- function _t(t, e, r) {
250
- const o = e.split("."), i = { ...t };
251
- let n = i;
252
- for (let l = 0; l < o.length - 1; l++)
253
- n[o[l]] = { ...n[o[l]] ?? {} }, n = n[o[l]];
254
- return n[o[o.length - 1]] = r, i;
375
+ function zt(t, e, r) {
376
+ const o = e.split("."), n = { ...t };
377
+ let a = n;
378
+ for (let s = 0; s < o.length - 1; s++)
379
+ a[o[s]] = { ...a[o[s]] ?? {} }, a = a[o[s]];
380
+ return a[o[o.length - 1]] = r, n;
255
381
  }
256
- function Et(t, e) {
382
+ function Zt(t, e) {
257
383
  const o = t.features?.[0]?.properties?.bands ?? [];
258
- return o.find((n) => n.id === e || n.label === e?.replace(/\./g, "_"))?.id ?? o[0]?.id ?? e ?? "";
259
- }
260
- function wt(t, e, r, o, i) {
261
- async function n(l, a, s) {
262
- let u = {};
263
- for (const c of a.getTablesMetadata())
264
- c.type !== void 0 && (u[c.name] = c.type);
265
- for (const c of s.layerRefs) {
266
- const d = c.dataRef, p = N(c), f = u[d], m = c.getFnv, h = r?.get(d) ?? await a.getLayer(d), y = f === "raster" ? h : {
267
- ...h,
268
- features: (h.features ?? []).filter((g) => g.geometry != null)
269
- }, w = f === "raster" ? Et(y, m) : "";
270
- f === "raster" ? l.loadCollection(p, { collection: y, type: "raster", property: w }) : l.loadCollection(p, { collection: y, type: f }), c.opacity != null && l.updateRenderInfo(p, { opacity: c.opacity });
271
- const A = ft(c, p);
272
- Object.keys(A).length > 0 && l.updateRenderInfo(p, A), pt(c, f) && l.updateRenderInfo(p, { isColorMap: !0 }), c.isPick && l.updateRenderInfo(p, { isPick: !0 }), c.isSkip && l.updateRenderInfo(p, { isSkip: !0 });
273
- const { catchAllCategory: b, colorMapDomain: R } = c;
274
- let F = y, T = R;
275
- if (m && b && R?.length) {
276
- const g = new Set(R);
277
- F = {
278
- ...y,
279
- features: y.features.map((_) => {
280
- const $ = _.properties, P = bt($, m);
281
- return P == null || !g.has(String(P)) ? { ..._, properties: _t($, m, b) } : _;
384
+ return o.find((a) => a.id === e || a.label === e?.replace(/\./g, "_"))?.id ?? o[0]?.id ?? e ?? "";
385
+ }
386
+ function te(t, e) {
387
+ if (e.zoom === void 0 && !e.pitch && !e.bearing) return;
388
+ const r = t.camera, [o, n] = r.getLookAt(), a = e.zoom !== void 0 ? 1e4 / Math.pow(2, e.zoom - 10) : Math.abs(r.getEye()[2]), s = (e.pitch ?? 0) * Math.PI / 180, i = (e.bearing ?? 0) * Math.PI / 180, l = [
389
+ o - a * Math.sin(s) * Math.sin(i),
390
+ n - a * Math.sin(s) * Math.cos(i),
391
+ a * Math.cos(s)
392
+ ];
393
+ r.resetCamera([Math.sin(i), Math.cos(i), 0], [o, n, 0], l);
394
+ }
395
+ function ee(t, e, r, o) {
396
+ const a = t.layerManager.searchByLayerId(e)?.components;
397
+ return Array.isArray(a) ? a.map((s, i) => {
398
+ const l = Number.isInteger(s?.featureIndex) ? s.featureIndex : i;
399
+ return r[o[l]] ?? "";
400
+ }) : o.map((s) => r[s] ?? "");
401
+ }
402
+ function re(t, e, r, o, n, a) {
403
+ async function s(i, l, u) {
404
+ let c = {};
405
+ for (const p of l.getTablesMetadata())
406
+ p.type !== void 0 && (c[p.name] = p.type);
407
+ const f = [];
408
+ for (const p of u.layerRefs) {
409
+ const y = p.dataRef, d = S(p), m = A(u.workspace, y), h = n?.get(m) ?? c[y], g = p.getFnv, _ = r?.get(m) ?? (h === "raster" ? await l.getRaster(y) : await mt(a, m, () => l.getLayer(y))), b = _.features ?? [], U = h === "raster" ? [] : b.flatMap((w, E) => w?.geometry != null ? [E] : []), M = h === "raster" ? _ : { ..._, features: U.map((w) => b[w]) }, Q = h === "raster" ? Zt(M, g) : "";
410
+ h === "raster" ? i.loadCollection(d, { collection: M, type: "raster", property: Q }) : i.loadCollection(d, { collection: M, type: h }), p.opacity != null && i.updateRenderInfo(d, { opacity: p.opacity });
411
+ const Y = Yt(p, d);
412
+ Object.keys(Y).length > 0 && i.updateRenderInfo(d, Y);
413
+ const Rt = l.getWorkspaceConfiguration().coordinateFormat, V = jt(p.pointSize, h, Rt, () => dt(M));
414
+ V !== void 0 && i.updateRenderInfo(d, { pointSize: V }), Vt(p, h) && i.updateRenderInfo(d, { isColorMap: !0 }), p.isPick && i.updateRenderInfo(d, { isPick: !0 }), p.isSkip && i.updateRenderInfo(d, { isSkip: !0 });
415
+ const { catchAllCategory: T, colorMapDomain: C } = p;
416
+ let H = M, W = C;
417
+ if (g && T && C?.length) {
418
+ const w = new Set(C);
419
+ H = {
420
+ ...M,
421
+ features: M.features.map((E) => {
422
+ const K = E.properties, k = Xt(K, g);
423
+ return k == null || !w.has(String(k)) ? { ...E, properties: zt(K, g, T) } : E;
282
424
  })
283
- }, T = g.has(b) ? R : [...R, b];
425
+ }, W = w.has(T) ? C : [...C, T];
284
426
  }
285
- const O = f === "raster" && c.transferFunction != null;
286
- O && l.layerManager.searchByLayerId(p)?.setTransferFunction?.(c.transferFunction);
287
- const C = c.colorMapRange, x = f === "raster" && (C != null || c.colorMapCenter != null || c.colorMapReverse === !0);
288
- if (c.colorMapInterpolator || x || C) {
289
- const g = {
427
+ const J = h === "raster" && p.transferFunction != null;
428
+ J && i.layerManager.searchByLayerId(d)?.setTransferFunction?.(p.transferFunction);
429
+ const $ = p.colorMapRange, q = h === "raster" && ($ != null || p.colorMapCenter != null || p.colorMapReverse === !0);
430
+ if (p.colorMapInterpolator || q || $) {
431
+ const w = {
290
432
  // urban-grammar ColorMapInterpolator values are string-compatible
291
433
  // with autk-core ColorMapInterpolator at runtime
292
- interpolator: c.colorMapInterpolator ?? l.layerManager.searchByLayerId(p)?.layerRenderInfo.colormap.config.interpolator ?? et.SEQ_REDS,
293
- domainSpec: gt(c.normalization, T)
434
+ interpolator: p.colorMapInterpolator ?? i.layerManager.searchByLayerId(d)?.layerRenderInfo.colormap.config.interpolator ?? Lt.SEQ_REDS,
435
+ domainSpec: Kt(p.normalization, W)
294
436
  };
295
- let _;
296
- x ? _ = dt(mt(y, w), g, c.colorMapCenter, c.colorMapReverse, C) : f !== "raster" && (_ = ht(g, C)), _ && (g.domainSpec = { type: M.USER, params: _ }), l.updateColorMap(p, { colorMap: g });
297
- } else O && l.updateColorMap(p, { colorMap: {} });
298
- if (m && f !== "raster") {
299
- const g = m.startsWith("properties.") ? m : `properties.${m}`;
300
- l.updateThematic(p, { collection: F, property: g });
437
+ let E;
438
+ q ? E = Wt(Ht(M, Q), w, p.colorMapCenter, p.colorMapReverse, $) : h !== "raster" && (E = Jt(w, $)), E && (w.domainSpec = { type: I.USER, params: E }), i.updateColorMap(d, { colorMap: w });
439
+ } else J && i.updateColorMap(d, { colorMap: {} });
440
+ if (g && h !== "raster") {
441
+ const w = g.startsWith("properties.") ? g : `properties.${g}`;
442
+ i.updateThematic(d, { collection: H, property: w });
301
443
  }
444
+ f.push(h === "raster" ? [] : ee(i, d, pt(b), U));
302
445
  }
446
+ return f;
303
447
  }
304
448
  return {
305
- async resolveMap(l, a, s = 0) {
306
- if (t && t.map && l) {
307
- ut(a, s);
308
- for (const d of a.layerRefs)
309
- yt(d);
310
- let u;
311
- if (Array.isArray(t.map) ? u = document.getElementById(t.map[s]) : u = document.getElementById(t.map), !u)
449
+ async resolveMap(i, l, u = 0) {
450
+ if (t && t.map && i) {
451
+ Ut(l, u);
452
+ for (const d of l.layerRefs)
453
+ qt(d), kt(d.pointSize, S(d));
454
+ let c;
455
+ if (Array.isArray(t.map) ? c = document.getElementById(t.map[u]) : c = document.getElementById(t.map), !c)
312
456
  throw new Error("Could not find rendering target for map: " + t.map);
313
- if (!(u instanceof HTMLCanvasElement))
457
+ if (!(c instanceof HTMLCanvasElement))
314
458
  throw new Error("Target for map is not a canvas: " + t.map);
315
- const c = new Z(u);
316
- a.style && c.style.setPredefinedStyle(a.style), await c.init(), await n(c, l, a);
317
- for (const d of a.layerRefs)
318
- e?.set(d.dataRef, c), i?.set(d.dataRef, N(d));
319
- o && (o[s] = c), c.draw();
459
+ const f = new Ct(c);
460
+ let p;
461
+ try {
462
+ l.style && f.style.setPredefinedStyle(l.style), await f.init(), await N(i, l.workspace), p = await s(f, i, l);
463
+ } catch (d) {
464
+ try {
465
+ f.destroy();
466
+ } catch {
467
+ }
468
+ throw d;
469
+ }
470
+ const y = ht(l, u);
471
+ l.layerRefs.forEach((d, m) => e?.push({
472
+ map: f,
473
+ mapIndex: u,
474
+ mapId: y,
475
+ layerId: S(d),
476
+ dataRef: d.dataRef,
477
+ rows: p[m]
478
+ })), o && (o[u] = f), l.camera && te(f, l.camera), f.draw();
320
479
  }
321
480
  }
322
481
  };
323
482
  }
324
- function At(t) {
483
+ function oe(t) {
325
484
  return {
326
485
  scatter: "scatterplot",
327
486
  bar: "barchart",
@@ -332,229 +491,280 @@ function At(t) {
332
491
  heatmatrix: "heatmatrix"
333
492
  }[t];
334
493
  }
335
- function Rt(t, e, r, o, i, n) {
494
+ function L(t) {
495
+ return t.id ?? t.dataRef;
496
+ }
497
+ function wt(t, e, r, o) {
498
+ const { map: n, layerId: a } = o;
499
+ n.updateRenderInfo(a, { isPick: !0 }), n.events.on(D.PICKING, ({ layerId: s, selection: i }) => {
500
+ s === a && t.setSelection(x(i, o.rows, e));
501
+ });
502
+ for (const s of r)
503
+ t.events.on(s, ({ selection: i }) => {
504
+ n.setHighlightedIds(a, x(i, e, o.rows));
505
+ });
506
+ }
507
+ async function ne(t, e, r, o) {
508
+ const n = t.getTablesMetadata().find((a) => a.name === e);
509
+ return n && !vt(n) ? { type: "FeatureCollection", features: (await t.getTable(e)).map((s) => ({ type: "Feature", geometry: null, properties: s })) } : mt(o, r, () => t.getLayer(e));
510
+ }
511
+ function ae(t, e, r, o, n, a, s, i) {
336
512
  return {
337
- async resolvePlot(l, a) {
513
+ async resolvePlot(l, u, c = 0) {
338
514
  if (!t || !t.plot) return;
339
- const s = document.getElementById(t.plot);
340
- if (!s) throw new Error(`Could not find plot target: ${t.plot}`);
341
- const u = l;
342
- if (!u) throw new Error("No data context available for plot.");
343
- const c = i?.get(a.dataRef) ?? await u.getLayer(a.dataRef), d = a.events ?? [], p = new tt(s, {
344
- type: At(a.mark),
345
- collection: c,
346
- attributes: { axis: a.axis, ...a.color && { color: a.color } },
347
- labels: { axis: a.axis, title: a.title },
348
- events: d,
349
- ...a.width && { width: a.width },
350
- ...a.height && { height: a.height },
351
- ...a.margins && { margins: a.margins },
352
- ...a.transform && { transform: a.transform }
515
+ const f = Array.isArray(t.plot) ? t.plot[c] : t.plot;
516
+ if (f === void 0) throw new Error(`Plot ${c} has no target: the plot targets name ${t.plot.length} elements.`);
517
+ const p = document.getElementById(f);
518
+ if (!p) throw new Error(`Could not find plot target: ${f}`);
519
+ const y = l;
520
+ if (!y) throw new Error("No data context available for plot.");
521
+ await N(y, u.workspace);
522
+ const d = A(u.workspace, u.dataRef), m = a?.get(d) ?? n?.get(d) ?? await ne(y, u.dataRef, d, i), h = u.events ?? [], g = new It(p, {
523
+ type: oe(u.mark),
524
+ collection: m,
525
+ attributes: { axis: u.axis, ...u.color && { color: u.color } },
526
+ labels: { axis: u.axis, title: u.title },
527
+ events: h,
528
+ ...u.width && { width: u.width },
529
+ ...u.height && { height: u.height },
530
+ ...u.margins && { margins: u.margins },
531
+ ...u.transform && { transform: u.transform }
353
532
  });
354
- if (r?.set(a.dataRef, p), a.mapRef && o?.set(a.dataRef, a.mapRef), a.mapRef && e) {
355
- const f = e.get(a.mapRef), m = n?.get(a.mapRef) ?? a.mapRef;
356
- if (f) {
357
- f.updateRenderInfo(m, { isPick: !0 }), f.events.on(B.PICKING, ({ selection: h }) => {
358
- p.setSelection(h);
359
- });
360
- for (const h of d)
361
- p.events.on(h, ({ selection: y }) => {
362
- f.setHighlightedIds(m, y);
363
- });
364
- }
365
- }
533
+ r?.set(L(u), g);
534
+ const _ = pt(m.features ?? []);
535
+ s?.set(L(u), _);
536
+ for (const b of e ?? [])
537
+ !u.mapRef || b.dataRef !== u.mapRef || (wt(g, _, h, b), yt(o, L(u), b));
366
538
  }
367
539
  };
368
540
  }
369
- const q = 134217728, Mt = 4, St = 32;
370
- function Ct(t) {
541
+ const bt = 134217728, ie = 4, se = 32;
542
+ function le(t) {
371
543
  return Array.isArray(t) ? t.join(`
372
544
  `) : t;
373
545
  }
374
- function E(t) {
546
+ function R(t) {
375
547
  return !!t && typeof t == "object" && !Array.isArray(t) && typeof t.fromFeature == "object" && t.fromFeature !== null;
376
548
  }
377
- function S(t, e) {
549
+ function P(t, e) {
378
550
  return t instanceof Map ? t.get(e) : t[e];
379
551
  }
380
- function L(t, e) {
552
+ function F(t, e) {
381
553
  return e.split(".").reduce((r, o) => {
382
554
  if (!(r == null || typeof r != "object"))
383
555
  return r[o];
384
556
  }, t);
385
557
  }
386
- function W(t) {
558
+ function _t(t) {
387
559
  const e = [];
388
560
  for (const r of [t.uniforms, t.uniformMatrices])
389
561
  for (const o of Object.values(r ?? {}))
390
- E(o) && e.push(o);
562
+ R(o) && e.push(o);
391
563
  return e;
392
564
  }
393
- function It(t) {
394
- return [.../* @__PURE__ */ new Set([t.dataRef, ...W(t).map((e) => e.fromFeature.layer)])];
565
+ function ue(t) {
566
+ return [.../* @__PURE__ */ new Set([t.dataRef, ..._t(t).map((e) => e.fromFeature.layer)])];
395
567
  }
396
- function X(t) {
397
- for (const e of W(t)) {
568
+ function Et(t) {
569
+ for (const e of _t(t)) {
398
570
  const { iterate: r, layer: o } = e.fromFeature;
399
571
  if (r === "all" || r === "batched") return { mode: r, layer: o };
400
572
  }
401
573
  return null;
402
574
  }
403
- function J(t, e, r) {
404
- const o = t.fromFeature, i = r !== void 0 && o.iterate === "all" ? r : o.index ?? 0, n = S(e, o.layer)?.features?.[i];
405
- return n ? L(n, o.path) : void 0;
575
+ function At(t, e, r) {
576
+ const o = t.fromFeature, n = r !== void 0 && o.iterate === "all" ? r : o.index ?? 0, a = P(e, o.layer)?.features?.[n];
577
+ return a ? F(a, o.path) : void 0;
406
578
  }
407
- function j(t, e, r) {
579
+ function rt(t, e, r) {
408
580
  if (!t) return;
409
581
  const o = {};
410
- for (const [i, n] of Object.entries(t)) {
411
- if (!E(n)) {
412
- o[i] = n;
582
+ for (const [n, a] of Object.entries(t)) {
583
+ if (!R(a)) {
584
+ o[n] = a;
413
585
  continue;
414
586
  }
415
- const l = Number(J(n, e, r) ?? NaN);
416
- Number.isFinite(l) ? o[i] = l : typeof n.default == "number" && (o[i] = n.default);
587
+ const s = Number(At(a, e, r) ?? NaN);
588
+ Number.isFinite(s) ? o[n] = s : typeof a.default == "number" && (o[n] = a.default);
417
589
  }
418
590
  return o;
419
591
  }
420
- function U(t, e, r) {
592
+ function ot(t, e, r) {
421
593
  if (!t) return;
422
594
  const o = {};
423
- for (const [i, n] of Object.entries(t)) {
424
- if (!E(n)) {
425
- o[i] = n;
595
+ for (const [n, a] of Object.entries(t)) {
596
+ if (!R(a)) {
597
+ o[n] = a;
426
598
  continue;
427
599
  }
428
- const l = J(n, e, r), a = Array.isArray(l) ? l : Array.isArray(n.default) ? n.default : void 0;
429
- if (!a) continue;
430
- const s = n.cols ?? (Array.isArray(a[0]) ? a[0].length : 0);
431
- s > 0 ? o[i] = { data: a, cols: s } : console.warn(`[autk-grammar] uniform matrix "${i}" has no column count; entry dropped`);
600
+ const s = At(a, e, r), i = Array.isArray(s) ? s : Array.isArray(a.default) ? a.default : void 0;
601
+ if (!i) continue;
602
+ const l = a.cols ?? (Array.isArray(i[0]) ? i[0].length : 0);
603
+ l > 0 ? o[n] = { data: i, cols: l } : console.warn(`[autk-grammar] uniform matrix "${n}" has no column count; entry dropped`);
432
604
  }
433
605
  return o;
434
606
  }
435
- function Lt(t) {
607
+ function ce(t) {
436
608
  return t != null && !(typeof t == "number" && !Number.isFinite(t));
437
609
  }
438
- function Q(t) {
439
- return E(t) && t.fromFeature.iterate === "batched";
610
+ function nt(t) {
611
+ return R(t) && t.fromFeature.iterate === "batched";
440
612
  }
441
- function K(t, e) {
442
- return Object.values(e ?? {}).some(Q) ? St : Object.values(t ?? {}).some(Q) ? Mt : 0;
613
+ function Mt(t, e) {
614
+ return Object.values(e ?? {}).some(nt) ? se : Object.values(t ?? {}).some(nt) ? ie : 0;
443
615
  }
444
- function vt(t, e, r = q) {
445
- const o = K(t, e);
616
+ function fe(t, e, r = bt) {
617
+ const o = Mt(t, e);
446
618
  return o > 0 ? Math.floor(r / o) : Number.POSITIVE_INFINITY;
447
619
  }
448
- function Nt(t, e, r, o = q) {
449
- const i = {}, n = {}, l = [];
450
- for (const s of [t, e])
451
- for (const u of Object.values(s ?? {}))
452
- E(u) && u.fromFeature.iterate === "batched" && u.fromFeature.required && l.push(u.fromFeature.path);
453
- if (l.length > 0) {
454
- const s = r.length;
455
- r = r.filter((u) => l.every((c) => Lt(L(u, c)))), r.length < s && console.info(`[autk-grammar] batched compute dropped ${s - r.length} feature(s) missing ${l.join(", ")}`);
456
- }
457
- const a = vt(t, e, o);
458
- r.length > a && (console.warn(
459
- `[autk-grammar] batched compute capped at ${a} features (got ${r.length}): its largest packed array takes ${K(t, e)} B per feature, and a storage buffer binding holds ${o} B`
460
- ), r = r.slice(0, a));
461
- for (const [s, u] of Object.entries(t ?? {}))
462
- if (E(u) && u.fromFeature.iterate === "batched") {
620
+ function pe(t, e, r, o = bt) {
621
+ const n = {}, a = {}, s = [];
622
+ for (const l of [t, e])
623
+ for (const u of Object.values(l ?? {}))
624
+ R(u) && u.fromFeature.iterate === "batched" && u.fromFeature.required && s.push(u.fromFeature.path);
625
+ if (s.length > 0) {
626
+ const l = r.length;
627
+ r = r.filter((u) => s.every((c) => ce(F(u, c)))), r.length < l && console.info(`[autk-grammar] batched compute dropped ${l - r.length} feature(s) missing ${s.join(", ")}`);
628
+ }
629
+ const i = fe(t, e, o);
630
+ r.length > i && (console.warn(
631
+ `[autk-grammar] batched compute capped at ${i} features (got ${r.length}): its largest packed array takes ${Mt(t, e)} B per feature, and a storage buffer binding holds ${o} B`
632
+ ), r = r.slice(0, i));
633
+ for (const [l, u] of Object.entries(t ?? {}))
634
+ if (R(u) && u.fromFeature.iterate === "batched") {
463
635
  const c = typeof u.default == "number" ? u.default : void 0;
464
- n[s] = r.map((d) => {
465
- const p = Number(L(d, u.fromFeature.path) ?? c);
636
+ a[l] = r.map((f) => {
637
+ const p = Number(F(f, u.fromFeature.path) ?? c);
466
638
  return Number.isFinite(p) ? p : 0;
467
639
  });
468
- } else typeof u == "number" && (i[s] = u);
469
- for (const [s, u] of Object.entries(e ?? {})) {
470
- if (!E(u) || u.fromFeature.iterate !== "batched") continue;
640
+ } else typeof u == "number" && (n[l] = u);
641
+ for (const [l, u] of Object.entries(e ?? {})) {
642
+ if (!R(u) || u.fromFeature.iterate !== "batched") continue;
471
643
  const c = [];
472
- for (const d of r) {
473
- const p = L(d, u.fromFeature.path);
474
- let f = 1 / 0, m = 1 / 0, h = -1 / 0, y = -1 / 0;
644
+ for (const f of r) {
645
+ const p = F(f, u.fromFeature.path);
646
+ let y = 1 / 0, d = 1 / 0, m = -1 / 0, h = -1 / 0;
475
647
  if (Array.isArray(p))
476
- for (const w of p) {
477
- if (!Array.isArray(w) || w.length < 2) continue;
478
- const A = Number(w[0]), b = Number(w[1]);
479
- !Number.isFinite(A) || !Number.isFinite(b) || (f = Math.min(f, A), m = Math.min(m, b), h = Math.max(h, A), y = Math.max(y, b));
648
+ for (const g of p) {
649
+ if (!Array.isArray(g) || g.length < 2) continue;
650
+ const _ = Number(g[0]), b = Number(g[1]);
651
+ !Number.isFinite(_) || !Number.isFinite(b) || (y = Math.min(y, _), d = Math.min(d, b), m = Math.max(m, _), h = Math.max(h, b));
480
652
  }
481
- Number.isFinite(f) || (f = 0, m = 0, h = 0, y = 0), c.push(f, m, h, m, h, y, f, y);
653
+ Number.isFinite(y) || (y = 0, d = 0, m = 0, h = 0), c.push(y, d, m, d, m, h, y, h);
482
654
  }
483
- n[s] = c;
655
+ a[l] = c;
484
656
  }
485
- return i.num_features = r.length, { uniforms: i, uniformArrays: n };
657
+ return n.num_features = r.length, { uniforms: n, uniformArrays: a };
486
658
  }
487
- function Y(t, e, r) {
488
- const o = S(e, t.dataRef);
659
+ function at(t, e, r) {
660
+ const o = P(e, t.dataRef);
489
661
  if (!o) throw new Error(`compute: table "${t.dataRef}" is not loaded`);
490
- const i = {
662
+ const n = {
491
663
  collection: o,
492
664
  variableMapping: t.attributes,
493
- wgslBody: Ct(t.wglsFunction)
665
+ wgslBody: le(t.wgslFunction)
494
666
  };
495
- t.attributeArrays && (i.attributeArrays = t.attributeArrays), t.attributeMatrices && (i.attributeMatrices = t.attributeMatrices), t.uniformArrays && (i.uniformArrays = t.uniformArrays), t.outputColumnName && (i.resultField = t.outputColumnName), t.outputColumns && (i.outputColumns = t.outputColumns);
496
- const n = X(t);
497
- if (n?.mode === "batched") {
498
- const u = S(e, n.layer)?.features ?? [], c = Nt(t.uniforms, t.uniformMatrices, u), d = j(V(t.uniforms), e) ?? {}, p = U(V(t.uniformMatrices), e);
499
- return i.uniforms = { ...d, ...c.uniforms }, i.uniformArrays = { ...i.uniformArrays ?? {}, ...c.uniformArrays }, p && Object.keys(p).length > 0 && (i.uniformMatrices = p), i;
667
+ t.attributeArrays && (n.attributeArrays = t.attributeArrays), t.attributeMatrices && (n.attributeMatrices = t.attributeMatrices), t.uniformArrays && (n.uniformArrays = t.uniformArrays), t.outputColumnName && (n.resultField = t.outputColumnName), t.outputColumns && (n.outputColumns = t.outputColumns);
668
+ const a = Et(t);
669
+ if (a?.mode === "batched") {
670
+ const u = P(e, a.layer)?.features ?? [], c = pe(t.uniforms, t.uniformMatrices, u), f = rt(it(t.uniforms), e) ?? {}, p = ot(it(t.uniformMatrices), e);
671
+ return n.uniforms = { ...f, ...c.uniforms }, n.uniformArrays = { ...n.uniformArrays ?? {}, ...c.uniformArrays }, p && Object.keys(p).length > 0 && (n.uniformMatrices = p), n;
500
672
  }
501
- const l = n?.mode === "all" ? r : void 0, a = j(t.uniforms, e, l), s = U(t.uniformMatrices, e, l);
502
- return a && (i.uniforms = a), s && (i.uniformMatrices = s), i;
673
+ const s = a?.mode === "all" ? r : void 0, i = rt(t.uniforms, e, s), l = ot(t.uniformMatrices, e, s);
674
+ return i && (n.uniforms = i), l && (n.uniformMatrices = l), n;
503
675
  }
504
- function V(t) {
676
+ function it(t) {
505
677
  if (t)
506
- return Object.fromEntries(Object.entries(t).filter(([, e]) => !(E(e) && e.fromFeature.iterate === "batched")));
678
+ return Object.fromEntries(Object.entries(t).filter(([, e]) => !(R(e) && e.fromFeature.iterate === "batched")));
507
679
  }
508
- function Pt(t) {
680
+ function de(t) {
509
681
  return t.outputColumns ?? (t.outputColumnName ? [t.outputColumnName] : []);
510
682
  }
511
- async function Bt(t, e, r) {
512
- const o = X(t);
513
- if (o?.mode !== "all") return r(Y(t, e));
514
- const i = S(e, t.dataRef);
515
- if (!i) throw new Error(`compute: table "${t.dataRef}" is not loaded`);
516
- const n = Pt(t), l = structuredClone(i);
517
- for (const s of l.features) {
518
- const u = s.properties ??= {}, c = u.compute ??= {};
519
- for (const d of n) c[d] = 0;
520
- }
521
- const a = S(e, o.layer)?.features?.length ?? 0;
522
- for (let s = 0; s < a; s++) {
523
- const u = await r({ ...Y(t, e, s), collection: l });
524
- l.features.forEach((c, d) => {
525
- const p = c.properties?.compute, f = u.features[d]?.properties?.compute;
526
- if (!(!p || !f))
527
- for (const m of n) {
528
- const h = Number(f[m]);
529
- Number.isFinite(h) && (p[m] += h);
683
+ async function me(t, e, r) {
684
+ const o = Et(t);
685
+ if (o?.mode !== "all") return r(at(t, e));
686
+ const n = P(e, t.dataRef);
687
+ if (!n) throw new Error(`compute: table "${t.dataRef}" is not loaded`);
688
+ const a = de(t), s = structuredClone(n);
689
+ for (const l of s.features) {
690
+ const u = l.properties ??= {}, c = u.compute ??= {};
691
+ for (const f of a) c[f] = 0;
692
+ }
693
+ const i = P(e, o.layer)?.features?.length ?? 0;
694
+ for (let l = 0; l < i; l++) {
695
+ const u = await r({ ...at(t, e, l), collection: s });
696
+ s.features.forEach((c, f) => {
697
+ const p = c.properties?.compute, y = u.features[f]?.properties?.compute;
698
+ if (!(!p || !y))
699
+ for (const d of a) {
700
+ const m = Number(y[d]);
701
+ Number.isFinite(m) && (p[d] += m);
530
702
  }
531
703
  });
532
704
  }
533
- return l;
705
+ return s;
534
706
  }
535
- function Ft(t) {
536
- return {
537
- async resolveCompute(e, r) {
538
- if (e) {
539
- const o = {};
540
- for (const l of It(r)) {
541
- const a = t?.get(l);
542
- if (a) o[l] = a;
543
- else if (l === r.dataRef) o[l] = await e.getLayer(l);
544
- else
545
- try {
546
- o[l] = await e.getLayer(l);
547
- } catch {
548
- o[l] = void 0;
549
- }
707
+ const st = ["surface", "parks", "water", "roads", "buildings", "polygons", "polylines"];
708
+ function he(t, e, r, o) {
709
+ return o?.get(A(r, e)) ?? t.getTablesMetadata().find((n) => n.name === e)?.type;
710
+ }
711
+ function ye(t, e) {
712
+ async function r(s, i, l) {
713
+ return t?.get(A(l, i)) ?? await s.getLayer(i);
714
+ }
715
+ function o(s, i, l, u, c) {
716
+ if (!t) return;
717
+ const f = u.outputTableName ?? l;
718
+ t.set(A(u.workspace, f), i);
719
+ const p = u.layerType ?? c ?? he(s, l, u.workspace, e);
720
+ u.outputTableName && p && e?.set(A(u.workspace, f), p);
721
+ }
722
+ async function n(s, i) {
723
+ for (const c of i.layers)
724
+ if (!st.includes(c.type))
725
+ throw new Error(`Render pass "${i.outputTableName}": layer "${c.id}" has the type "${c.type}", which a render pass cannot draw. A layer's type is one of ${st.join(", ")}.`);
726
+ const l = await Promise.all(i.layers.map(async (c) => ({
727
+ id: c.id,
728
+ collection: await r(s, c.dataRef, i.workspace),
729
+ type: c.type,
730
+ objectIdProperty: c.objectIdProperty
731
+ }))), u = await new X().renderPipeline({
732
+ layers: l,
733
+ viewpoints: {
734
+ collection: await r(s, i.viewpoints.dataRef, i.workspace),
735
+ strategy: i.viewpoints.strategy,
736
+ sampling: i.viewpoints.sampling
737
+ },
738
+ aggregation: i.aggregation,
739
+ camera: i.camera,
740
+ tileSize: i.tileSize
741
+ });
742
+ o(s, u, i.viewpoints.dataRef, i, i.viewpoints.strategy?.type === "building-windows" ? "points" : void 0);
743
+ }
744
+ async function a(s, i) {
745
+ const l = {};
746
+ for (const f of ue(i)) {
747
+ const p = t?.get(A(i.workspace, f));
748
+ if (p) l[f] = p;
749
+ else if (f === i.dataRef) l[f] = await s.getLayer(f);
750
+ else
751
+ try {
752
+ l[f] = await s.getLayer(f);
753
+ } catch {
754
+ l[f] = void 0;
550
755
  }
551
- const i = new rt(), n = await Bt(r, o, (l) => i.gpgpuPipeline(l));
552
- return t && t.set(r.dataRef, n), e;
553
- }
756
+ }
757
+ const u = new X(), c = await me(i, l, (f) => u.gpgpuPipeline(f));
758
+ o(s, c, i.dataRef, i);
759
+ }
760
+ return {
761
+ async resolveCompute(s, i) {
762
+ if (s)
763
+ return await N(s, i.workspace), i.type === "render" ? await n(s, i) : await a(s, i), s;
554
764
  }
555
765
  };
556
766
  }
557
- class Tt {
767
+ class ge {
558
768
  _listeners = /* @__PURE__ */ new Map();
559
769
  on(e, r) {
560
770
  this._listeners.has(e) || this._listeners.set(e, /* @__PURE__ */ new Set());
@@ -566,24 +776,46 @@ class Tt {
566
776
  this._listeners.get(e)?.forEach((o) => o(r));
567
777
  }
568
778
  }
569
- class jt {
779
+ function v(t) {
780
+ return t === void 0 ? [] : Array.isArray(t) ? t : [t];
781
+ }
782
+ function we(t) {
783
+ const e = /* @__PURE__ */ new Set();
784
+ for (const o of [...v(t.map), ...v(t.plot)])
785
+ if (o.id !== void 0) {
786
+ if (o.id === "") throw new Error("A map or plot has an empty id.");
787
+ if (e.has(o.id)) throw new Error(`Two maps or plots have the id "${o.id}"; an id names one view.`);
788
+ e.add(o.id);
789
+ }
790
+ const r = /* @__PURE__ */ new Map();
791
+ for (const o of v(t.plot)) {
792
+ const n = L(o), a = r.get(n);
793
+ if (a)
794
+ throw new Error(a.id === void 0 && o.id === void 0 ? `Two plots of the table "${n}" have no id; give each plot an id.` : `A plot's id "${n}" is the dataRef of a plot without an id; give each plot an id.`);
795
+ r.set(n, o);
796
+ }
797
+ }
798
+ class Se {
570
799
  dataAdapter;
571
800
  mapAdapter;
572
801
  plotAdapter;
573
802
  computeAdapter;
574
803
  grammarEngine;
575
804
  _computeCache = /* @__PURE__ */ new Map();
805
+ _computeTypes = /* @__PURE__ */ new Map();
576
806
  _data = {};
577
- _mapRegistry = /* @__PURE__ */ new Map();
578
- _mapLayerIds = /* @__PURE__ */ new Map();
807
+ _layers = [];
579
808
  _maps = [];
580
809
  _plotRegistry = /* @__PURE__ */ new Map();
581
810
  _fwdCleanups = [];
582
- _plotMapLinks = /* @__PURE__ */ new Map();
583
- interactions = new Tt();
811
+ _plotLinks = /* @__PURE__ */ new Map();
812
+ _plotRows = /* @__PURE__ */ new Map();
813
+ _exports = /* @__PURE__ */ new Map();
814
+ /** Each GeoJSON table a run loaded and each table a join wrote, which its plots read before the database. */
815
+ _geojsonCache = /* @__PURE__ */ new Map();
816
+ interactions = new ge();
584
817
  constructor(e) {
585
- const r = /* @__PURE__ */ new Map();
586
- this.dataAdapter = lt(e, r), this.mapAdapter = wt(e, this._mapRegistry, this._computeCache, this._maps, this._mapLayerIds), this.plotAdapter = Rt(e, this._mapRegistry, this._plotRegistry, this._plotMapLinks, r, this._mapLayerIds), this.computeAdapter = Ft(this._computeCache);
818
+ this.dataAdapter = xt(e, this._geojsonCache), this.mapAdapter = re(e, this._layers, this._computeCache, this._maps, this._computeTypes, this._exports), this.plotAdapter = ae(e, this._layers, this._plotRegistry, this._plotLinks, this._geojsonCache, this._computeCache, this._plotRows, this._exports), this.computeAdapter = ye(this._computeCache, this._computeTypes);
587
819
  }
588
820
  /**
589
821
  * The coordinate reference system used internally by the autk workspace.
@@ -594,7 +826,7 @@ class jt {
594
826
  * instead of hard-coding a CRS string.
595
827
  */
596
828
  get workspaceCrs() {
597
- return k;
829
+ return ut;
598
830
  }
599
831
  get data() {
600
832
  return this._data;
@@ -610,18 +842,51 @@ class jt {
610
842
  get maps() {
611
843
  return this._maps;
612
844
  }
845
+ /**
846
+ * Every layer the maps of the last {@link run} draw for a table, found by the table's name (a layer's `dataRef`):
847
+ * for each, the map that draws it and the layer's id in that map, which is its `title`, else its `dataRef`. The
848
+ * maps come in the spec's order, each map's layers bottom first. Empty when no map draws the table.
849
+ *
850
+ * @param dataRef The table's name.
851
+ * @param mapId The map to look in, by its {@link MapId}: a string names a map by its `id`, a number by its index in
852
+ * the spec's `map` list. Without it, every map.
853
+ */
854
+ mapLayers(e, r) {
855
+ return this._layersOf(e, r).map(({ map: o, layerId: n }) => ({ map: o, layerId: n }));
856
+ }
613
857
  /**
614
858
  * The layer a map of the last {@link run} draws for a table, found by the table's name (a layer's `dataRef`):
615
859
  * the map that draws it, and the layer's id in that map, which is its `title`, else its `dataRef`.
616
- * `undefined` when no map draws the table. When several layers draw it, the last one.
860
+ * `undefined` when no map draws the table. When several layers draw it, the last one, which is the last map's;
861
+ * {@link mapLayers} lists them all.
862
+ *
863
+ * @param dataRef The table's name.
864
+ * @param mapId The map to look in, by its {@link MapId}: a string names a map by its `id`, a number by its index in
865
+ * the spec's `map` list. Without it, every map.
617
866
  *
618
867
  * @example
619
868
  * const layer = grammar.mapLayer('buildings');
620
869
  * layer?.map.updateRenderInfo(layer.layerId, { opacity: 0.5 });
621
870
  */
622
- mapLayer(e) {
623
- const r = this._mapRegistry.get(e);
624
- return r ? { map: r, layerId: this._mapLayerIds.get(e) ?? e } : void 0;
871
+ mapLayer(e, r) {
872
+ return this.mapLayers(e, r).pop();
873
+ }
874
+ /** The drawn layers of a table, on every map or on the one `mapId` names. */
875
+ _layersOf(e, r) {
876
+ return this._layers.filter((o) => o.dataRef === e && G(o, r));
877
+ }
878
+ /**
879
+ * Releases what the last run created: every map (its layers' GPU buffers, its textures, its canvas context, the
880
+ * controls it adds to the page and its event handlers) and the grammar's own registries, caches and event
881
+ * forwarding. autk-map's maps share one GPU device, which stays for the maps of the next run. Call it before the
882
+ * page or the container goes away; `run` calls it before it starts, so running a new spec on the same instance
883
+ * does not leak the maps of the old one.
884
+ */
885
+ destroy() {
886
+ for (const e of this._fwdCleanups) e();
887
+ this._fwdCleanups = [];
888
+ for (const e of this._maps) e.destroy();
889
+ this._maps.length = 0, this._layers.length = 0, this._plotRegistry.clear(), this._plotLinks.clear(), this._plotRows.clear(), this._exports.clear(), this._geojsonCache.clear(), this._computeCache.clear(), this._computeTypes.clear(), this.grammarEngine = void 0, this._data = {};
625
890
  }
626
891
  async run(e) {
627
892
  if (!this.dataAdapter)
@@ -632,7 +897,7 @@ class jt {
632
897
  throw new Error("Plot adapter not initialized. Please call the constructor first.");
633
898
  if (!this.computeAdapter)
634
899
  throw new Error("Compute adapter not initialized. Please call the constructor first.");
635
- this._mapRegistry.clear(), this._mapLayerIds.clear(), this._maps.length = 0, this._plotRegistry.clear(), this._plotMapLinks.clear(), this._computeCache.clear(), this.grammarEngine = ot({
900
+ we(e), this.destroy(), this.grammarEngine = Pt({
636
901
  spec: e,
637
902
  adapters: {
638
903
  db: this.dataAdapter,
@@ -640,103 +905,164 @@ class jt {
640
905
  plot: this.plotAdapter,
641
906
  compute: this.computeAdapter
642
907
  }
643
- }), await this.grammarEngine.run(), this._rewireInteractions();
908
+ }), await this.grammarEngine.run();
644
909
  const r = this.grammarEngine.context;
645
- if (!r) {
910
+ if (r && await N(r), this._wireLinks(e), this._rewireInteractions(e), !r) {
646
911
  console.warn("Grammar engine produced no data context."), this._data = {};
647
912
  return;
648
913
  }
649
914
  const o = {};
650
- for (const i of r.getLayersMetadata())
651
- Object.defineProperty(o, i.name, {
915
+ for (const n of r.getLayersMetadata())
916
+ Object.defineProperty(o, n.name, {
652
917
  get: () => {
653
- const n = this._computeCache.get(i.name);
654
- return n ? Promise.resolve(n) : r.getLayer(i.name);
918
+ const a = this._computeCache.get(n.name);
919
+ return a ? Promise.resolve(a) : r.getLayer(n.name);
655
920
  },
656
921
  enumerable: !0,
657
922
  configurable: !0
658
923
  });
924
+ for (const n of this._computeCache.keys())
925
+ n in o || Object.defineProperty(o, n, {
926
+ get: () => Promise.resolve(this._computeCache.get(n)),
927
+ enumerable: !0,
928
+ configurable: !0
929
+ });
659
930
  this._data = o;
660
931
  }
661
932
  /**
662
- * Highlights features on the map layer that draws the table `dataRef` (see {@link mapLayer}).
663
- * If that layer is linked to a plot via `mapRef`, the plot selection is updated too.
933
+ * Highlights features on every layer that draws the table `dataRef`, in every map (see {@link mapLayers}), or only
934
+ * in the map `mapId` names. If a plot is linked to one of those layers, by a link or its `mapRef`, the plot
935
+ * selection is updated too, to the same rows: the plot finds them by their feature ids, since it can draw the
936
+ * table's rows in another order and draws the rows without a geometry, which a layer leaves out.
937
+ *
938
+ * @param dataRef The table's name.
939
+ * @param featureIds The features to highlight: their positions among those the layer draws.
940
+ * @param mapId The map to highlight on, by its {@link MapId}: a string names a map by its `id`, a number by its
941
+ * index in the spec's `map` list. Without it, every map that draws the table.
664
942
  */
665
- highlightOnMap(e, r) {
666
- const o = this.mapLayer(e);
667
- o?.map.setHighlightedIds(o.layerId, r);
668
- for (const [i, n] of this._plotMapLinks)
669
- n === e && this._plotRegistry.get(i)?.setSelection(r);
943
+ highlightOnMap(e, r, o) {
944
+ const n = this._layersOf(e, o);
945
+ for (const { map: a, layerId: s } of n) a.setHighlightedIds(s, r);
946
+ this._selectInLinkedPlots(n, r);
670
947
  }
671
948
  /**
672
- * Clears highlighted features on the map layer that draws the table `dataRef` (see {@link mapLayer}).
673
- * If that layer is linked to a plot via `mapRef`, the plot selection is cleared too.
949
+ * Clears highlighted features on every layer that draws the table `dataRef`, in every map (see {@link mapLayers}),
950
+ * or only in the map `mapId` names. If a plot is linked to one of those layers, by a link or its `mapRef`, the plot
951
+ * selection is cleared too.
952
+ *
953
+ * @param dataRef The table's name.
954
+ * @param mapId The map to clear, by its {@link MapId}: a string names a map by its `id`, a number by its index in
955
+ * the spec's `map` list. Without it, every map that draws the table.
674
956
  */
675
- clearHighlightOnMap(e) {
676
- const r = this.mapLayer(e);
677
- r?.map.clearHighlightedIds(r.layerId);
678
- for (const [o, i] of this._plotMapLinks)
679
- i === e && this._plotRegistry.get(o)?.setSelection([]);
957
+ clearHighlightOnMap(e, r) {
958
+ const o = this._layersOf(e, r);
959
+ for (const { map: n, layerId: a } of o) n.clearHighlightedIds(a);
960
+ this._selectInLinkedPlots(o, []);
680
961
  }
681
962
  /**
682
- * Clears the selection on the plot identified by `plotId` (its dataRef).
683
- * If that plot is linked to a map via `mapRef`, the map highlight is cleared too.
963
+ * Clears the selection on the plot `plotId` names: its `id`, else its `dataRef`.
964
+ * If that plot is linked to map layers, by links or its `mapRef`, their highlights are cleared too: on every map,
965
+ * or only on the map `mapId` names.
966
+ *
967
+ * @param plotId The plot: its `id`, else its `dataRef`.
968
+ * @param mapId The map whose linked layers to clear, by its {@link MapId}: a string names a map by its `id`, a
969
+ * number by its index in the spec's `map` list. Without it, every linked layer.
684
970
  */
685
- clearHighlightOnPlot(e) {
971
+ clearHighlightOnPlot(e, r) {
686
972
  this._plotRegistry.get(e)?.setSelection([]);
687
- const r = this._plotMapLinks.get(e), o = r ? this.mapLayer(r) : void 0;
688
- o?.map.clearHighlightedIds(o.layerId);
973
+ for (const o of this._plotLinks.get(e) ?? [])
974
+ G(o, r) && o.map.clearHighlightedIds(o.layerId);
689
975
  }
690
976
  /**
691
- * Applies a selection to the plot identified by `plotId` (its dataRef).
692
- * If that plot is linked to a map via `mapRef`, the map highlight is updated too.
977
+ * Applies a selection to the plot `plotId` names: its `id`, else its `dataRef`.
978
+ * If that plot is linked to map layers, by links or its `mapRef`, their highlights are updated too, to the same rows
979
+ * (see {@link highlightOnMap}): on every map, or only on the map `mapId` names.
980
+ *
981
+ * @param plotId The plot: its `id`, else its `dataRef`.
982
+ * @param featureIds The features to select: their positions among those the plot draws.
983
+ * @param mapId The map whose linked layers to highlight, by its {@link MapId}: a string names a map by its `id`, a
984
+ * number by its index in the spec's `map` list. Without it, every linked layer.
693
985
  */
694
- setPlotSelection(e, r) {
986
+ setPlotSelection(e, r, o) {
695
987
  this._plotRegistry.get(e)?.setSelection(r);
696
- const o = this._plotMapLinks.get(e), i = o ? this.mapLayer(o) : void 0;
697
- i?.map.setHighlightedIds(i.layerId, r);
988
+ const n = this._plotRows.get(e) ?? [];
989
+ for (const a of this._plotLinks.get(e) ?? [])
990
+ G(a, o) && a.map.setHighlightedIds(a.layerId, x(r, n, a.rows));
991
+ }
992
+ /**
993
+ * Applies a selection made on `layers`, by their positions `featureIds`, to every plot linked to one of them, at the
994
+ * plot's own positions of the selected rows.
995
+ */
996
+ _selectInLinkedPlots(e, r) {
997
+ for (const [o, n] of this._plotLinks) {
998
+ const a = n.filter((l) => e.includes(l));
999
+ if (a.length === 0) continue;
1000
+ const s = this._plotRows.get(o) ?? [], i = new Set(a.flatMap((l) => x(r, l.rows, s)));
1001
+ this._plotRegistry.get(o)?.setSelection([...i]);
1002
+ }
1003
+ }
1004
+ /** Wires each entry of `links` between a plot and a layer of a map, both now drawn. */
1005
+ _wireLinks(e) {
1006
+ const r = v(e.map), o = v(e.plot);
1007
+ for (const n of e.links ?? []) {
1008
+ const a = o.find((f) => L(f) === n.source), s = this._plotRegistry.get(n.source);
1009
+ if (!a || !s)
1010
+ throw new Error(`Link source "${n.source}" is not the id (or the dataRef) of a plot of this specification.`);
1011
+ const i = r.findIndex((f) => f.id === n.target), l = this._maps[i];
1012
+ if (i < 0 || !l)
1013
+ throw new Error(`Link target "${n.target}" is not the id of a map of this specification.`);
1014
+ const u = r[i].layerRefs.find((f) => n.layer !== void 0 ? S(f) === n.layer : f.dataRef === a.dataRef);
1015
+ if (!u)
1016
+ throw new Error(n.layer !== void 0 ? `Link from "${n.source}": map "${n.target}" has no layer "${n.layer}".` : `Link from "${n.source}": map "${n.target}" draws no layer of the table "${a.dataRef}"; name the layer.`);
1017
+ const c = this._layers.find((f) => f.mapIndex === i && f.layerId === S(u));
1018
+ c && (wt(s, this._plotRows.get(n.source) ?? [], a.events ?? [], c), yt(this._plotLinks, n.source, c));
1019
+ }
698
1020
  }
699
- _rewireInteractions() {
700
- for (const r of this._fwdCleanups) r();
1021
+ _rewireInteractions(e) {
1022
+ for (const o of this._fwdCleanups) o();
701
1023
  this._fwdCleanups = [];
702
- const e = /* @__PURE__ */ new Set();
703
- for (const [r, o] of this._mapRegistry) {
704
- if (e.has(o)) continue;
705
- e.add(o);
706
- const i = ({ selection: n }) => {
707
- this.interactions.emit("map:picking", { layerId: r, selection: n });
1024
+ const r = v(e.map);
1025
+ this._maps.forEach((o, n) => {
1026
+ const a = ht(r[n], n), s = ({ layerId: i, selection: l }) => {
1027
+ this.interactions.emit("map:picking", { mapId: a, layerId: i, selection: l });
708
1028
  };
709
- o.events.on(B.PICKING, i), this._fwdCleanups.push(() => o.events.off(B.PICKING, i));
710
- }
711
- for (const [r, o] of this._plotRegistry)
712
- for (const i of [I.CLICK, I.BRUSH, I.BRUSH_X, I.BRUSH_Y]) {
713
- const n = ({ selection: l }) => {
1029
+ o.events.on(D.PICKING, s), this._fwdCleanups.push(() => o.events.off(D.PICKING, s));
1030
+ });
1031
+ for (const [o, n] of this._plotRegistry)
1032
+ for (const a of [O.CLICK, O.BRUSH, O.BRUSH_X, O.BRUSH_Y]) {
1033
+ const s = ({ selection: i }) => {
714
1034
  this.interactions.emit("plot:selection", {
715
- plotId: r,
716
- event: i,
717
- selection: l
1035
+ plotId: o,
1036
+ event: a,
1037
+ selection: i
718
1038
  });
719
1039
  };
720
- o.events.on(i, n), this._fwdCleanups.push(() => o.events.off(i, n));
1040
+ n.events.on(a, s), this._fwdCleanups.push(() => n.events.off(a, s));
721
1041
  }
722
1042
  }
723
1043
  }
724
1044
  export {
725
- jt as AutkGrammar,
726
- nt as ColorMapInterpolator,
727
- Tt as GrammarEventEmitter,
728
- H as NormalizationMode,
729
- q as STORAGE_BUFFER_BINDING_SIZE,
730
- Nt as buildBatchedUniforms,
731
- It as computeLayerNames,
732
- ot as createEngine,
733
- X as findIterateSource,
734
- E as isFromFeature,
735
- Ct as joinWgsl,
736
- vt as maxBatchedFeatures,
737
- Y as resolveComputeParams,
738
- U as resolveUniformMatrices,
739
- j as resolveUniforms,
740
- Bt as runCompute
1045
+ Se as AutkGrammar,
1046
+ Nt as ColorMapInterpolator,
1047
+ ge as GrammarEventEmitter,
1048
+ ct as NormalizationMode,
1049
+ bt as STORAGE_BUFFER_BINDING_SIZE,
1050
+ te as applyCamera,
1051
+ Re as arrangeViews,
1052
+ pe as buildBatchedUniforms,
1053
+ ue as computeLayerNames,
1054
+ ye as createComputeAdapter,
1055
+ xt as createDataAdapter,
1056
+ Pt as createEngine,
1057
+ N as enterWorkspace,
1058
+ Et as findIterateSource,
1059
+ R as isFromFeature,
1060
+ le as joinWgsl,
1061
+ fe as maxBatchedFeatures,
1062
+ at as resolveComputeParams,
1063
+ ot as resolveUniformMatrices,
1064
+ rt as resolveUniforms,
1065
+ me as runCompute,
1066
+ A as tableKey
741
1067
  };
742
1068
  //# sourceMappingURL=autk-grammar.js.map