@emuanalytics/flow-rdf-core 4.0.4 → 4.0.6

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 (89) hide show
  1. package/README.md +1 -64
  2. package/dist/index.d.mts +36 -31
  3. package/dist/index.d.ts +36 -31
  4. package/dist/index.mjs +20 -3249
  5. package/dist/lib/context/context-registry.mjs +63 -0
  6. package/dist/lib/context/debugger.mjs +240 -0
  7. package/dist/lib/context/flow-context.mjs +61 -0
  8. package/dist/lib/context/global-state.mjs +70 -0
  9. package/dist/lib/context/map-registry.mjs +59 -0
  10. package/dist/lib/context/query-registry.mjs +53 -0
  11. package/dist/lib/errors/flow-error.mjs +10 -0
  12. package/dist/lib/errors/flow-expression-error.mjs +14 -0
  13. package/dist/lib/errors/flow-map-error.mjs +9 -0
  14. package/dist/lib/expressions/expression-parser.mjs +198 -0
  15. package/dist/lib/expressions/functions/from-palette.mjs +75 -0
  16. package/dist/lib/expressions/functions/regex.mjs +25 -0
  17. package/dist/lib/expressions/functions/state.mjs +25 -0
  18. package/dist/lib/expressions/parser-helpers.mjs +37 -0
  19. package/dist/lib/expressions/reactive-expression.mjs +253 -0
  20. package/dist/lib/map/flow-core-map.mjs +749 -0
  21. package/dist/lib/map/plugins/annotations/annotation-layers.mjs +163 -0
  22. package/dist/lib/map/plugins/annotations/annotation.events.mjs +27 -0
  23. package/dist/lib/map/plugins/annotations/annotation.plugin.mjs +498 -0
  24. package/dist/lib/map/plugins/annotations/maplibre-gl-draw-circle/lib/modes/DirectModeOverride.mjs +67 -0
  25. package/dist/lib/map/plugins/annotations/maplibre-gl-draw-circle/lib/modes/DragCircleMode.mjs +65 -0
  26. package/dist/lib/map/plugins/annotations/maplibre-gl-draw-circle/lib/utils/create_supplementary_points_circle.mjs +15 -0
  27. package/dist/lib/map/plugins/annotations/maplibre-gl-draw-circle/lib/utils/drag_pan.mjs +20 -0
  28. package/dist/lib/map/plugins/data-join.plugin.mjs +173 -0
  29. package/dist/lib/map/plugins/export/export.plugin.mjs +21 -0
  30. package/dist/lib/map/plugins/export/map-exporter.mjs +177 -0
  31. package/dist/lib/map/plugins/hover-effect.plugin.mjs +58 -0
  32. package/dist/lib/map/plugins/index.d.mts +37 -72
  33. package/dist/lib/map/plugins/index.d.ts +37 -72
  34. package/dist/lib/map/plugins/index.mjs +11 -1810
  35. package/dist/lib/map/plugins/keyboard-shortcut-manager.mjs +120 -0
  36. package/dist/lib/map/plugins/map-plugin-base.mjs +25 -0
  37. package/dist/lib/map/plugins/plugin-manager.mjs +135 -0
  38. package/dist/lib/map/plugins/popup.plugin.mjs +55 -0
  39. package/dist/lib/map/plugins/selection/selection.events.mjs +21 -0
  40. package/dist/lib/map/plugins/selection/selection.plugin.mjs +136 -0
  41. package/dist/lib/map/plugins/selection/source-selection.mjs +156 -0
  42. package/dist/lib/map/plugins/url-sync.plugin.mjs +55 -0
  43. package/dist/lib/map/support/image-registry.mjs +82 -0
  44. package/dist/lib/map/support/map-events.mjs +71 -0
  45. package/dist/lib/map/support/map-feature-stream.mjs +158 -0
  46. package/dist/lib/map/support/map-popup.mjs +159 -0
  47. package/dist/lib/map/types.mjs +7 -0
  48. package/dist/lib/map-style/map-data-source.mjs +192 -0
  49. package/dist/lib/map-style/map-layer-style-builder-generated.mjs +1307 -0
  50. package/dist/lib/map-style/map-layer-style-builder.mjs +86 -0
  51. package/dist/lib/map-style/map-layer.mjs +223 -0
  52. package/dist/lib/map-style/map-style.mjs +178 -0
  53. package/dist/lib/queries/async-committer.mjs +30 -0
  54. package/dist/lib/queries/query.mjs +172 -0
  55. package/dist/lib/state-store/decorators.mjs +83 -0
  56. package/dist/lib/state-store/state-store.mjs +534 -0
  57. package/dist/lib/state-store/utils.mjs +7 -0
  58. package/dist/lib/utils/announce.mjs +12 -0
  59. package/dist/lib/utils/assert.mjs +12 -0
  60. package/dist/{shared/flow-rdf-core.187cb345.mjs → lib/utils/debounce.mjs} +3 -39
  61. package/dist/lib/utils/decorators.mjs +59 -0
  62. package/dist/lib/utils/deferred.mjs +11 -0
  63. package/dist/lib/utils/ensure-array.mjs +16 -0
  64. package/dist/{shared/flow-rdf-core.1f0901c5.mjs → lib/utils/feature-type-checks.mjs} +2 -2
  65. package/dist/lib/utils/functional.mjs +22 -0
  66. package/dist/lib/utils/global.mjs +18 -0
  67. package/dist/lib/utils/index.mjs +8 -5
  68. package/dist/lib/utils/random-id.mjs +9 -0
  69. package/dist/lib/utils/string-utils.mjs +3 -0
  70. package/dist/lib/utils/throttle.mjs +20 -0
  71. package/dist/{shared/flow-rdf-core.25e5f6d7.mjs → lib/utils/type-checks.mjs} +1 -26
  72. package/dist/lib/utils/watchable-promise.mjs +55 -0
  73. package/dist/package.json.mjs +3 -0
  74. package/dist/shared/{flow-rdf-core.4dde996e.d.cts → flow-rdf-core.cef13c7e.d.mts} +1315 -172
  75. package/dist/shared/{flow-rdf-core.4dde996e.d.ts → flow-rdf-core.cef13c7e.d.ts} +1315 -172
  76. package/package.json +4 -8
  77. package/dist/index.cjs +0 -3316
  78. package/dist/index.d.cts +0 -90
  79. package/dist/lib/map/plugins/index.cjs +0 -1850
  80. package/dist/lib/map/plugins/index.d.cts +0 -345
  81. package/dist/lib/utils/index.cjs +0 -48
  82. package/dist/lib/utils/index.d.cts +0 -160
  83. package/dist/shared/flow-rdf-core.06e85a6c.cjs +0 -1394
  84. package/dist/shared/flow-rdf-core.4dde996e.d.mts +0 -1916
  85. package/dist/shared/flow-rdf-core.55c169ca.cjs +0 -150
  86. package/dist/shared/flow-rdf-core.63162669.d.cts +0 -10
  87. package/dist/shared/flow-rdf-core.65045caf.mjs +0 -1360
  88. package/dist/shared/flow-rdf-core.a82b9be4.cjs +0 -34
  89. package/dist/shared/flow-rdf-core.f50908f0.cjs +0 -102
@@ -1,1394 +0,0 @@
1
- 'use strict';
2
-
3
- const mobx = require('mobx');
4
- const randomId = require('./flow-rdf-core.f50908f0.cjs');
5
- const maplibreSpec = require('@emuanalytics/maplibre-gl-style-spec');
6
- const mobxUtils = require('mobx-utils');
7
- const P = require('parsimmon');
8
- const colorbrewer = require('colorbrewer');
9
- const Debug = require('debug');
10
-
11
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; }
12
-
13
- function _interopNamespaceCompat(e) {
14
- if (e && typeof e === 'object' && 'default' in e) return e;
15
- const n = Object.create(null);
16
- if (e) {
17
- for (const k in e) {
18
- n[k] = e[k];
19
- }
20
- }
21
- n.default = e;
22
- return n;
23
- }
24
-
25
- const mobx__namespace = /*#__PURE__*/_interopNamespaceCompat(mobx);
26
- const maplibreSpec__namespace = /*#__PURE__*/_interopNamespaceCompat(maplibreSpec);
27
- const P__default = /*#__PURE__*/_interopDefaultCompat(P);
28
- const colorbrewer__default = /*#__PURE__*/_interopDefaultCompat(colorbrewer);
29
- const Debug__default = /*#__PURE__*/_interopDefaultCompat(Debug);
30
-
31
- class FlowError extends Error {
32
- constructor(message, cause) {
33
- super(message);
34
- this.cause = cause;
35
- this.name = this.constructor.name;
36
- this.cause = cause;
37
- }
38
- }
39
-
40
- class FlowExpressionError extends FlowError {
41
- constructor(expression, reason, errors) {
42
- super(`Failed to evaluate expression:
43
- ${expression}
44
- ------
45
- ${errors.join(", ")}`);
46
- this.reason = reason;
47
- this.errors = errors;
48
- }
49
- }
50
-
51
- function PREFIX(operatorsParser, nextParser) {
52
- const parser = P__default.lazy(() => {
53
- return P__default.seq(operatorsParser, parser).or(nextParser);
54
- });
55
- return parser;
56
- }
57
- function BINARY_RIGHT(operatorsParser, nextParser) {
58
- const parser = P__default.lazy(() => nextParser.chain((next) => P__default.seq(operatorsParser, P__default.of(next), parser).or(P__default.of(next))));
59
- return parser;
60
- }
61
- function TERNARY_RIGHT(operatorsParser, nextParser) {
62
- const parser = P__default.lazy(
63
- () => nextParser.chain(
64
- (next) => P__default.seqMap(
65
- operatorsParser,
66
- P__default.of(next),
67
- parser,
68
- P__default.string(":").trim(P__default.optWhitespace),
69
- parser,
70
- (op, cond, val1, _colon, val2) => [op, ["to-boolean", cond], val1, val2]
71
- ).or(P__default.of(next))
72
- )
73
- );
74
- return parser;
75
- }
76
- function BINARY_LEFT(operatorsParser, nextParser) {
77
- return P__default.seqMap(nextParser, P__default.seq(operatorsParser, nextParser).many(), (first, rest) => {
78
- return rest.reduce((acc, ch) => {
79
- const [op, another] = ch;
80
- return [op, acc, another];
81
- }, first);
82
- });
83
- }
84
-
85
- var __defProp$7 = Object.defineProperty;
86
- var __defNormalProp$7 = (obj, key, value) => key in obj ? __defProp$7(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
87
- var __publicField$7 = (obj, key, value) => {
88
- __defNormalProp$7(obj, typeof key !== "symbol" ? key + "" : key, value);
89
- return value;
90
- };
91
- class ExpressionParser {
92
- constructor() {
93
- __publicField$7(this, "language");
94
- this.language = this.createLanguage();
95
- }
96
- /**
97
- * Parse an expression
98
- *
99
- * @param expr Expression to parse
100
- */
101
- parseExpression(expr) {
102
- return this.language.Expr.parse(expr);
103
- }
104
- /**
105
- * Parse a complete assignment program of the form:
106
- * a: expr1;
107
- * b: expr2;
108
- *
109
- * @param program Program to parse
110
- */
111
- parseProgram(program) {
112
- return this.language.ProgramOrEmpty.parse(program);
113
- }
114
- createLanguage() {
115
- const operatorTable = [
116
- { type: PREFIX, ops: this.operators({ "-": "-", "!": "!" }) },
117
- { type: BINARY_RIGHT, ops: this.operators({ "^": "**" }) },
118
- { type: BINARY_LEFT, ops: this.operators({ "*": "*", "/": "/", "%": "%" }) },
119
- { type: BINARY_LEFT, ops: this.operators({ "+": "+", "-": "-" }) },
120
- { type: BINARY_LEFT, ops: this.operators({ ">=": ">=", "<=": "<=" }) },
121
- { type: BINARY_LEFT, ops: this.operators({ "<": "<", ">": ">" }) },
122
- {
123
- type: BINARY_LEFT,
124
- ops: this.operators({ regexi: "~*", equali: "=*", "==": "==", "!=": "!=", "~": "~" })
125
- },
126
- { type: BINARY_LEFT, ops: this.operators({ all: "&&" }) },
127
- { type: BINARY_LEFT, ops: this.operators({ any: "||" }) },
128
- { type: TERNARY_RIGHT, ops: this.operators({ case: "?" }) }
129
- ];
130
- return P__default.createLanguage({
131
- Whitespace: () => P__default.regexp(/[ \n]*/).desc("whitespace"),
132
- NotNewline: () => P__default.regexp(/[^\n]*/).desc("non-newline"),
133
- LineComment: (r) => r.NotNewline.wrap(P__default.string("//"), P__default.alt(P__default.string("\n"), P__default.eof)),
134
- BlockComment: () => P__default.regexp(/\/\*[\s\S]*?\*\//),
135
- Comment: (r) => P__default.alt(r.LineComment, r.BlockComment).desc("comment"),
136
- End: () => P__default.alt(P__default.string(";"), P__default.eof),
137
- _: (r) => r.Comment.sepBy(r.Whitespace).trim(r.Whitespace),
138
- Integer: () => {
139
- return P__default.regexp(/-?[0-9]+/).map(Number);
140
- },
141
- Decimal: () => {
142
- return P__default.regexp(/-?[0-9]+\.[0-9]+/).map(Number);
143
- },
144
- Number: (r) => {
145
- return P__default.alt(r.Decimal, r.Integer).desc("number");
146
- },
147
- Boolean: () => {
148
- return P__default.alt(P__default.string("true"), P__default.string("false")).map((val) => val === "true").desc("boolean");
149
- },
150
- Null: () => {
151
- return P__default.string("null").result(null).desc("null");
152
- },
153
- DoubleQuoteString: () => {
154
- return P__default.regexp(/"((?:\\.|.)*?)"/, 1).desc("string");
155
- },
156
- SingleQuoteString: () => {
157
- return P__default.regexp(/'((?:\\.|.)*?)'/, 1).desc("string");
158
- },
159
- UnquotedString: () => {
160
- return P__default.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/).desc("string");
161
- },
162
- HexColor: () => {
163
- return P__default.regexp(/#(?:[0-9a-f]{3}){1,2}/i).desc("hex color");
164
- },
165
- String: (r) => {
166
- return P__default.alt(r.SingleQuoteString, r.DoubleQuoteString, r.HexColor, r.UnquotedString).map(
167
- (s) => s.replace(/\\n/gm, "\n")
168
- );
169
- },
170
- Symbol: () => {
171
- return P__default.regexp(/[a-zA-Z_][a-zA-Z0-9_-]*/).desc("symbol");
172
- },
173
- PartialSymbol: () => {
174
- return P__default.regexp(/[a-zA-Z0-9_-]+/).desc("symbol");
175
- },
176
- Feature: (r) => {
177
- return P__default.seqMap(
178
- P__default.string("@"),
179
- r.PartialSymbol.sepBy(P__default.string(".")),
180
- (_feat, symbols) => ["get"].concat(symbols)
181
- );
182
- },
183
- FeatureState: (r) => {
184
- return P__default.seqMap(
185
- P__default.string("@@"),
186
- r.PartialSymbol.sepBy(P__default.string(".")),
187
- (_feat, symbols) => this.expandFeatureState(symbols)
188
- );
189
- },
190
- Array: (r) => P__default.string("[").trim(r._).then(r.Value.trim(r._).sepBy(P__default.string(","))).skip(P__default.string("]")),
191
- State: (r) => {
192
- return P__default.seqMap(
193
- P__default.string("$"),
194
- r.PartialSymbol.sepBy(P__default.string(".")),
195
- (_state, symbols) => ["state"].concat(symbols)
196
- );
197
- },
198
- Paren: (r) => {
199
- return P__default.seqMap(P__default.string("("), r.Expr.trim(r._), P__default.string(")"), (_lb, expr, _rb) => expr);
200
- },
201
- Func: (r) => {
202
- return P__default.seqMap(
203
- r.Symbol.trim(r._),
204
- P__default.string("("),
205
- r.Expr.trim(r._).sepBy(P__default.string(",")),
206
- P__default.string(")"),
207
- (func, _lb, args, _rb) => [func, ...args]
208
- );
209
- },
210
- Value: (r) => {
211
- return P__default.alt(
212
- r.Paren,
213
- r.Array,
214
- r.Func,
215
- r.Boolean,
216
- r.Null,
217
- r.Number,
218
- r.String,
219
- r.FeatureState,
220
- r.Feature,
221
- r.State
222
- );
223
- },
224
- Expr: (r) => {
225
- return this.tableParser(operatorTable, r.Value);
226
- },
227
- PropertyName: () => {
228
- return P__default.regexp(/[a-zA-Z_-][a-zA-Z0-9_-]*/).desc("symbol");
229
- },
230
- Assignment: (r) => {
231
- return P__default.seqMap(
232
- r.PropertyName,
233
- P__default.string(":").trim(r._),
234
- r.Expr.trim(r._).node("expr"),
235
- r.End,
236
- (key, _colon, node) => [key, { expr: node.value, start: node.start, end: node.end }]
237
- );
238
- },
239
- Program: (r) => {
240
- return r.Assignment.trim(r._).many().map((statements) => {
241
- return statements.filter((s) => s !== "").reduce((acc, s) => {
242
- acc[s[0]] = s[1];
243
- return acc;
244
- }, {});
245
- });
246
- },
247
- EmptyProgram: (r) => {
248
- return P__default.seqMap(r._, P__default.eof, () => null);
249
- },
250
- ProgramOrEmpty: (r) => {
251
- return P__default.alt(r.EmptyProgram, r.Program);
252
- }
253
- });
254
- }
255
- /**
256
- * Helper function to create a parser that parsers a set of operators at the same precedence level
257
- *
258
- * @param ops Operator table
259
- */
260
- operators(ops) {
261
- const keys = Object.keys(ops);
262
- const ps = keys.map((k) => P__default.string(ops[k]).trim(P__default.optWhitespace).result(k));
263
- return P__default.alt.apply(null, ps);
264
- }
265
- /**
266
- * Helper function to create a table-driver operator parser
267
- *
268
- */
269
- tableParser(operatorTable, valueParser) {
270
- return operatorTable.reduce((acc, level) => level.type(level.ops, acc), valueParser);
271
- }
272
- expandFeatureState(symbols) {
273
- let expandedFeatureState = ["feature-state", symbols.shift()];
274
- symbols.forEach((s) => expandedFeatureState = ["get", s, expandedFeatureState]);
275
- return expandedFeatureState;
276
- }
277
- }
278
-
279
- const palettes = {};
280
- function registerColorBrewerPalettes() {
281
- Object.keys(colorbrewer__default).filter((key) => key !== "schemeGroups").forEach(
282
- (key) => palettes[key.toLowerCase()] = {
283
- id: key,
284
- colors: colorbrewer__default[key][5]
285
- }
286
- );
287
- }
288
- function fromPalette(expr, parentExpression) {
289
- const paletteIdOrArray = expr[1];
290
- const property = expr[2];
291
- let colorStops = expr.slice(3);
292
- let palette;
293
- if (randomId.isString(paletteIdOrArray)) {
294
- palette = palettes[paletteIdOrArray.toLowerCase()]?.colors || palettes["Greys"].colors;
295
- } else if (randomId.isArray(paletteIdOrArray) && paletteIdOrArray[0] === "literal") {
296
- palette = paletteIdOrArray[1];
297
- } else {
298
- throw new FlowExpressionError(parentExpression.expression, "evaluationError", [
299
- "from-palette requires palette id as string or custom palette array"
300
- ]);
301
- }
302
- const numPaletteEntries = palette.length;
303
- let reversePalette = false;
304
- if (numPaletteEntries < 5) {
305
- throw new FlowExpressionError(parentExpression.expression, "evaluationError", [
306
- "custom palette requires at least 5 color entries"
307
- ]);
308
- }
309
- switch (colorStops.length) {
310
- case 2:
311
- break;
312
- case 3:
313
- reversePalette = !!colorStops[2];
314
- colorStops = colorStops.slice(0, 2);
315
- break;
316
- case numPaletteEntries:
317
- break;
318
- case numPaletteEntries + 1:
319
- reversePalette = !!colorStops[numPaletteEntries];
320
- colorStops = colorStops.slice(0, numPaletteEntries);
321
- break;
322
- default:
323
- throw new FlowExpressionError(parentExpression.expression, "evaluationError", [
324
- "incorrect color stop arguments"
325
- ]);
326
- }
327
- if (colorStops.length === 2) {
328
- const min = colorStops[0];
329
- const max = colorStops[1];
330
- colorStops = [];
331
- const step = (max - min) / (numPaletteEntries - 1);
332
- for (let i = 0; i < numPaletteEntries; i++) {
333
- colorStops.push(min + i * step);
334
- }
335
- }
336
- expr = ["interpolate-lab", ["linear"], property];
337
- for (let i = 0; i < colorStops.length; i++) {
338
- expr.push(colorStops[i]);
339
- expr.push(reversePalette ? palette[colorStops.length - i - 1] : palette[i]);
340
- }
341
- return expr;
342
- }
343
- const customFromPaletteFn = {
344
- name: "from-palette",
345
- initialize: registerColorBrewerPalettes,
346
- fn: fromPalette
347
- };
348
-
349
- function regexFunction(operator, caseSensitive = true) {
350
- return (expr, _) => {
351
- expr[0] = operator;
352
- expr.push(["collator", { "case-sensitive": caseSensitive }]);
353
- return expr;
354
- };
355
- }
356
- const equal = {
357
- name: "equal",
358
- fn: regexFunction("==", true)
359
- };
360
- const equali = {
361
- name: "iequal",
362
- fn: regexFunction("==", false)
363
- };
364
- const regex = {
365
- name: "regex",
366
- fn: regexFunction("~", true)
367
- };
368
- const regexi = {
369
- name: "regexi",
370
- fn: regexFunction("~", false)
371
- };
372
-
373
- function stateCustomFunction(expr, parentExpression) {
374
- if (!parentExpression.store) {
375
- console.warn(
376
- `The reactive expression '${parentExpression.expression}' references state properties but is not bound to a state store. The expression cannot be evaluated - returning null.`
377
- );
378
- return null;
379
- }
380
- const path = expr.slice(1).join(".");
381
- const val = parentExpression.store.get(path);
382
- if (randomId.isNil(val)) {
383
- return null;
384
- } else if (typeof val === "object") {
385
- return ["literal", val];
386
- } else {
387
- return val;
388
- }
389
- }
390
- const customStateFn = {
391
- name: "state",
392
- fn: stateCustomFunction
393
- };
394
-
395
- var __defProp$6 = Object.defineProperty;
396
- var __defNormalProp$6 = (obj, key, value) => key in obj ? __defProp$6(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
397
- var __publicField$6 = (obj, key, value) => {
398
- __defNormalProp$6(obj, typeof key !== "symbol" ? key + "" : key, value);
399
- return value;
400
- };
401
- const _ReactiveExpression = class _ReactiveExpression {
402
- constructor(expression, parsedExpression) {
403
- __publicField$6(this, "_expression", "");
404
- __publicField$6(this, "parsedResult");
405
- __publicField$6(this, "_store", null);
406
- mobx.makeObservable(
407
- this,
408
- {
409
- _store: mobx.observable.ref,
410
- maplibreExpression: mobx.computed,
411
- value: mobx.computed,
412
- bindState: mobx.action
413
- },
414
- { name: this.formatName(expression) }
415
- );
416
- this._expression = expression;
417
- if (randomId.isDefined(parsedExpression)) {
418
- this.parsedResult = {
419
- status: true,
420
- value: parsedExpression
421
- };
422
- } else {
423
- this.parsedResult = _ReactiveExpression.parser.parseExpression(expression);
424
- }
425
- }
426
- static hasCustomFunction(fn) {
427
- return !!this.customFunctions[fn];
428
- }
429
- static registerCustomFunction(fn) {
430
- if (fn.initialize)
431
- fn.initialize();
432
- this.customFunctions[fn.name] = fn;
433
- }
434
- static parseProgram(program) {
435
- const parsedProgram = this.parser.parseProgram(program);
436
- if (randomId.isString(program) && program.length === 0) {
437
- return {};
438
- }
439
- if (parsedProgram.status) {
440
- const keys = Object.keys(parsedProgram.value);
441
- const expressions = keys.reduce((accum, key) => {
442
- const expr = parsedProgram.value[key];
443
- const expressionString = program.slice(expr.start.offset, expr.end.offset);
444
- accum[key] = new _ReactiveExpression(expressionString, expr.expr);
445
- return accum;
446
- }, {});
447
- return expressions;
448
- } else {
449
- throw new FlowExpressionError(program, "parseError", [
450
- `expected ${parsedProgram.expected.join(" ")} at line ${parsedProgram.index.line}, column ${parsedProgram.index.column}]`
451
- ]);
452
- }
453
- }
454
- // Computed
455
- get maplibreExpression() {
456
- if (this.isParseError(this.parsedResult)) {
457
- throw this.parseError;
458
- }
459
- return this.expandCustomFunctions(this.parsedResult.value);
460
- }
461
- // Computed
462
- get value() {
463
- return this.evaluateExpression();
464
- }
465
- get parseError() {
466
- if (this.isParseError(this.parsedResult)) {
467
- return new FlowExpressionError(this._expression, "parseError", [
468
- `index: ${this.parsedResult.index.offset}`,
469
- `expected: ${this.parsedResult.expected.join(" ")}`
470
- ]);
471
- }
472
- return null;
473
- }
474
- get expression() {
475
- return this._expression;
476
- }
477
- get store() {
478
- return this._store;
479
- }
480
- bindState(store) {
481
- this._store = store;
482
- return this;
483
- }
484
- toStream(fireImmediately = true) {
485
- return mobxUtils.toStream(() => this.value, fireImmediately);
486
- }
487
- evaluateExpression() {
488
- const { result, value } = maplibreSpec__namespace.expression.createExpression(this.maplibreExpression);
489
- if (result === "success") {
490
- return value.evaluate({ zoom: 0 });
491
- }
492
- throw new FlowExpressionError(
493
- this.expression,
494
- "evaluationError",
495
- value.map((value2) => value2.message)
496
- );
497
- }
498
- expandCustomFunctions(expr) {
499
- if (this.isFunctionExpression(expr)) {
500
- const func = expr[0];
501
- const args = expr.slice(1).map((arg) => this.expandCustomFunctions(arg));
502
- expr = [func, ...args];
503
- return _ReactiveExpression.hasCustomFunction(func) ? _ReactiveExpression.customFunctions[func].fn(expr, this) : expr;
504
- }
505
- return expr;
506
- }
507
- isParseError(val) {
508
- return !val.status;
509
- }
510
- isFunctionExpression(expr) {
511
- return Array.isArray(expr);
512
- }
513
- formatName(expr) {
514
- return `FlowCoreExpression<${expr}>}`;
515
- }
516
- };
517
- __publicField$6(_ReactiveExpression, "parser", new ExpressionParser());
518
- __publicField$6(_ReactiveExpression, "customFunctions", {});
519
- let ReactiveExpression = _ReactiveExpression;
520
- ReactiveExpression.registerCustomFunction(customStateFn);
521
- ReactiveExpression.registerCustomFunction(customFromPaletteFn);
522
- ReactiveExpression.registerCustomFunction(regex);
523
- ReactiveExpression.registerCustomFunction(regexi);
524
- ReactiveExpression.registerCustomFunction(equal);
525
- ReactiveExpression.registerCustomFunction(equali);
526
-
527
- var __defProp$5 = Object.defineProperty;
528
- var __defNormalProp$5 = (obj, key, value) => key in obj ? __defProp$5(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
529
- var __publicField$5 = (obj, key, value) => {
530
- __defNormalProp$5(obj, typeof key !== "symbol" ? key + "" : key, value);
531
- return value;
532
- };
533
- const _MapDataSource = class _MapDataSource {
534
- constructor(options) {
535
- __publicField$5(this, "_options");
536
- __publicField$5(this, "_srcExpression", null);
537
- __publicField$5(this, "_parameters", {});
538
- __publicField$5(this, "_state", null);
539
- this._options = {
540
- ..._MapDataSource.defaultOptions,
541
- ...options
542
- };
543
- if (!randomId.isIn(options.type, ["vector", "geojson", "raster"])) {
544
- throw new FlowError(`${this.formattedName()}: unrecognized type '${options.type}'`);
545
- }
546
- this.setSrcExpression(options.src);
547
- mobx__namespace.makeObservable(
548
- this,
549
- {
550
- //observable
551
- _options: mobx__namespace.observable.shallow,
552
- _srcExpression: mobx__namespace.observable,
553
- _parameters: mobx__namespace.observable,
554
- //computed
555
- dataSourceSpecification: mobx__namespace.computed,
556
- // actions
557
- bindState: mobx__namespace.action,
558
- setSrc: mobx__namespace.action,
559
- setParameter: mobx__namespace.action
560
- },
561
- { name: this.formattedName(options.id) }
562
- );
563
- }
564
- get id() {
565
- return this._options.id;
566
- }
567
- get type() {
568
- return this._options.type;
569
- }
570
- get featureId() {
571
- return this._options.featureId;
572
- }
573
- get dataSourceSpecification() {
574
- let src = this._srcExpression ? mobx__namespace.toJS(this._srcExpression.value) : this._options.src;
575
- if (randomId.isString(src)) {
576
- src = this.expandSrc(src, this._options.type);
577
- }
578
- let ds;
579
- switch (this._options.type) {
580
- case "vector":
581
- ds = randomId.isStringFull(src) ? {
582
- type: "vector",
583
- url: src
584
- } : (
585
- // For null src use an empty geojson datasource as a placeholder
586
- {
587
- type: "geojson",
588
- data: { type: "FeatureCollection", features: [] }
589
- }
590
- );
591
- if (this._options.featureId) {
592
- ds.promoteId = this._options.featureId;
593
- }
594
- return ds;
595
- case "raster":
596
- ds = randomId.isStringFull(src) ? {
597
- type: "raster",
598
- url: src
599
- } : (
600
- // For null src use an empty geojson datasource as a placeholder
601
- {
602
- type: "geojson",
603
- data: { type: "FeatureCollection", features: [] }
604
- }
605
- );
606
- return ds;
607
- case "geojson":
608
- ds = {
609
- type: "geojson",
610
- data: src || { type: "FeatureCollection", features: [] }
611
- };
612
- if (this._options.cluster) {
613
- ds.cluster = true;
614
- ds.clusterMaxZoom = this._options.clusterMaxZoom;
615
- ds.clusterMinPoints = this._options.clusterMinPoints;
616
- ds.clusterRadius = this._options.clusterRadius;
617
- }
618
- if (this._options.featureId) {
619
- ds.promoteId = this._options.featureId;
620
- }
621
- return ds;
622
- default:
623
- throw new FlowError(`${this.formattedName()}: unrecognized type '${this._options.type}'`);
624
- }
625
- }
626
- bindState(state) {
627
- this._state = state;
628
- if (this._srcExpression) {
629
- this._srcExpression?.bindState(state);
630
- }
631
- Object.values(this._parameters).forEach((expr) => expr.bindState(state));
632
- return this;
633
- }
634
- setSrc(val) {
635
- this._options.src = val;
636
- this.setSrcExpression(val);
637
- }
638
- setParameter(name, expression) {
639
- if (randomId.isNil(expression)) {
640
- delete this._parameters[name];
641
- } else {
642
- const expr = new ReactiveExpression(expression);
643
- this._parameters[name] = expr.bindState(this._state);
644
- }
645
- }
646
- setFlowEndpoint(endpoint) {
647
- this._options.flowHost = endpoint.host;
648
- this._options.flowApiKey = endpoint.apiKey;
649
- }
650
- formattedName(id) {
651
- return `MapDataSource<${id || this._options.id}>`;
652
- }
653
- setSrcExpression(src) {
654
- if (randomId.isString(src)) {
655
- if (randomId.isURL(src))
656
- src = `'${src}'`;
657
- this._srcExpression = new ReactiveExpression(src);
658
- this._srcExpression.bindState(this._state);
659
- } else {
660
- this._srcExpression = null;
661
- }
662
- }
663
- /**
664
- * Convert a src parameter to final URL
665
- *
666
- * @param src Data source url/dataset/tilesource ID
667
- * @param type Data source type
668
- * @returns URL
669
- */
670
- expandSrc(src, type) {
671
- const host = this._options.flowHost;
672
- let isGeoJSON = false;
673
- if (!randomId.isURL(src)) {
674
- switch (type) {
675
- case "vector":
676
- case "raster":
677
- src = `${host}/tiles/${src}/index.json`;
678
- break;
679
- case "geojson":
680
- src = `${host}/api/v1/datasets/${src}/query`;
681
- isGeoJSON = true;
682
- break;
683
- default:
684
- throw new FlowError(`${this.formattedName()}: unrecognized type '${this._options.type}'`);
685
- }
686
- }
687
- const urlObj = new URL(src);
688
- const combinedParams = new URLSearchParams(urlObj.searchParams);
689
- Object.entries(this._parameters).filter(([_, expr]) => !randomId.isNil(expr.value)).forEach(([key, expr]) => combinedParams.append(key, expr.value));
690
- if (this._options.flowHost && src.startsWith(this._options.flowHost) && !combinedParams.has("apikey") && this._options.flowApiKey) {
691
- combinedParams.append("apikey", this._options.flowApiKey);
692
- }
693
- if (this._options.limit) {
694
- combinedParams.append("limit", this._options.limit.toString(10));
695
- }
696
- if (isGeoJSON) {
697
- combinedParams.append("format", "geojson");
698
- }
699
- urlObj.search = combinedParams.toString();
700
- return urlObj.toString();
701
- }
702
- };
703
- __publicField$5(_MapDataSource, "defaultOptions", {
704
- type: "vector",
705
- cluster: false,
706
- clusterRadius: 50,
707
- clusterMaxZoom: 20,
708
- clusterMinPoints: 2,
709
- flowHost: "https://flow.emu-analytics.net"
710
- });
711
- let MapDataSource = _MapDataSource;
712
-
713
- var __defProp$4 = Object.defineProperty;
714
- var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
715
- var __publicField$4 = (obj, key, value) => {
716
- __defNormalProp$4(obj, typeof key !== "symbol" ? key + "" : key, value);
717
- return value;
718
- };
719
- const _MapLayer = class _MapLayer {
720
- constructor(options) {
721
- __publicField$4(this, "_options");
722
- __publicField$4(this, "_state", null);
723
- __publicField$4(this, "_filter", null);
724
- __publicField$4(this, "_paintProps", {});
725
- __publicField$4(this, "_layoutProps", {});
726
- this._options = {
727
- ..._MapLayer._defaultOptions,
728
- ...options
729
- };
730
- this.getPropertyMetadata("visibility", options.type);
731
- mobx.makeObservable(
732
- this,
733
- {
734
- //observable
735
- _paintProps: mobx.observable,
736
- _layoutProps: mobx.observable,
737
- _filter: mobx.observable,
738
- _options: mobx.observable,
739
- //computed
740
- layerSpecification: mobx.computed,
741
- // actions
742
- bindState: mobx.action,
743
- setMinZoom: mobx.action,
744
- setMaxZoom: mobx.action,
745
- setInteractive: mobx.action,
746
- setAbove: mobx.action,
747
- setBelow: mobx.action,
748
- setStyle: mobx.action,
749
- setStyleProperty: mobx.action,
750
- setFilter: mobx.action
751
- },
752
- { name: this.formattedName(options.id) }
753
- );
754
- if (options.filter) {
755
- this.setFilter(options.filter);
756
- }
757
- if (options.style) {
758
- this.setStyle(options.style);
759
- }
760
- }
761
- get layerSpecification() {
762
- this._options.above;
763
- this._options.below;
764
- const layer = {
765
- id: this._options.id,
766
- type: this._options.type,
767
- source: this._options.source
768
- };
769
- if (randomId.isDefined(this._options.minZoom)) {
770
- layer.minzoom = this._options.minZoom;
771
- }
772
- if (randomId.isDefined(this._options.maxZoom)) {
773
- layer.maxzoom = this._options.maxZoom;
774
- }
775
- if (randomId.isDefined(this._options.sourceLayer)) {
776
- layer["source-layer"] = this._options.sourceLayer;
777
- }
778
- if (randomId.isDefined(this._filter)) {
779
- layer.filter = this._filter.maplibreExpression;
780
- }
781
- if (randomId.isObjectFull(this._paintProps)) {
782
- layer.paint = Object.keys(this._paintProps).reduce((accum, key) => {
783
- accum[key] = this._paintProps[key].maplibreExpression;
784
- return accum;
785
- }, {});
786
- }
787
- if (randomId.isObjectFull(this._layoutProps)) {
788
- layer.layout = Object.keys(this._layoutProps).reduce((accum, key) => {
789
- let expr = this._layoutProps[key].maplibreExpression;
790
- if (key === "visibility") {
791
- expr = this._layoutProps[key].value ? "visible" : "none";
792
- }
793
- accum[key] = expr;
794
- return accum;
795
- }, {});
796
- }
797
- return layer;
798
- }
799
- get id() {
800
- return this._options.id;
801
- }
802
- get type() {
803
- return this._options.type;
804
- }
805
- get source() {
806
- return this._options.source;
807
- }
808
- get interactive() {
809
- return !!this._options.interactive;
810
- }
811
- get above() {
812
- return this._options.above;
813
- }
814
- get below() {
815
- return this._options.below;
816
- }
817
- bindState(state) {
818
- this._state = state;
819
- if (this._filter) {
820
- this._filter.bindState(state);
821
- }
822
- Object.values(this._paintProps).forEach((prop) => prop.bindState(state));
823
- Object.values(this._layoutProps).forEach((prop) => prop.bindState(state));
824
- return this;
825
- }
826
- setMinZoom(zoom) {
827
- this._options.minZoom = zoom;
828
- return this;
829
- }
830
- setMaxZoom(zoom) {
831
- this._options.maxZoom = zoom;
832
- return this;
833
- }
834
- setInteractive(interactive) {
835
- this._options.interactive = interactive;
836
- return this;
837
- }
838
- setAbove(layerId) {
839
- this._options.above = layerId;
840
- return this;
841
- }
842
- setBelow(layerId) {
843
- this._options.below = layerId;
844
- return this;
845
- }
846
- setStyle(styleProgram) {
847
- const parsedProgram = ReactiveExpression.parseProgram(styleProgram);
848
- const props = Object.keys(parsedProgram);
849
- props.forEach((prop) => {
850
- const metadata = this.getPropertyMetadata(prop, this._options.type);
851
- const layerProps = metadata.type === "paint" ? this._paintProps : this._layoutProps;
852
- layerProps[prop] = parsedProgram[prop].bindState(this._state);
853
- });
854
- }
855
- /**
856
- * Set an individual style property.
857
- *
858
- * @param property Property name.
859
- * @param expression Property style expression.
860
- */
861
- setStyleProperty(property, expression) {
862
- const metadata = this.getPropertyMetadata(property, this._options.type);
863
- const props = metadata.type === "paint" ? this._paintProps : this._layoutProps;
864
- if (randomId.isNil(expression)) {
865
- delete props[property];
866
- } else {
867
- const expr = new ReactiveExpression(expression).bindState(this._state);
868
- if (expr.parseError) {
869
- throw expr.parseError;
870
- }
871
- props[property] = expr;
872
- }
873
- }
874
- setFilter(expression) {
875
- this._filter = null;
876
- if (randomId.isDefined(expression)) {
877
- let expr = new ReactiveExpression(expression).bindState(this._state);
878
- if (expr.parseError) {
879
- throw expr.parseError;
880
- }
881
- if (!maplibreSpec__namespace.expression.isExpressionFilter(expr.maplibreExpression)) {
882
- expr = new ReactiveExpression(expr.expression, ["to-boolean", expr.maplibreExpression]);
883
- }
884
- this._filter = expr;
885
- }
886
- }
887
- formattedName(id) {
888
- return `MapLayer<${id || this._options.id}>`;
889
- }
890
- getPropertyMetadata(property, layerType) {
891
- if (!_MapLayer._propertyMetadataIndex) {
892
- _MapLayer.initializePropertyMetadataIndex();
893
- }
894
- const layerMetadata = _MapLayer._propertyMetadataIndex[layerType];
895
- if (!layerMetadata) {
896
- throw new FlowError(`${this.formattedName()}: unknown layer type '${layerType}'`);
897
- }
898
- const propertyMetadata = layerMetadata[property];
899
- if (!propertyMetadata) {
900
- throw new FlowError(`${this.formattedName()}: unknown layer property '${property}'`);
901
- }
902
- return propertyMetadata;
903
- }
904
- static initializePropertyMetadataIndex() {
905
- const layerTypes = Object.keys(maplibreSpec__namespace.latest.layer.type.values);
906
- this._propertyMetadataIndex = layerTypes.reduce((acc, layerType) => {
907
- acc[layerType] = {};
908
- ["layout", "paint"].forEach((propType) => {
909
- Object.keys(maplibreSpec__namespace.latest[`${propType}_${layerType}`]).forEach((prop) => {
910
- acc[layerType][prop] = {
911
- property: prop,
912
- type: propType,
913
- definition: maplibreSpec__namespace.latest[`${propType}_${layerType}`][prop]
914
- };
915
- });
916
- });
917
- return acc;
918
- }, {});
919
- }
920
- };
921
- __publicField$4(_MapLayer, "_propertyMetadataIndex");
922
- __publicField$4(_MapLayer, "_defaultOptions", {
923
- interactive: true,
924
- minZoom: 0,
925
- maxZoom: 18
926
- });
927
- let MapLayer = _MapLayer;
928
-
929
- class FlowMapError extends FlowError {
930
- constructor(message, originalError) {
931
- super(message, originalError);
932
- }
933
- }
934
-
935
- function assert(condition, message) {
936
- if (!condition) {
937
- throw new FlowError(message ?? "Assertion failed");
938
- }
939
- }
940
- function die(message) {
941
- throw new FlowError(message);
942
- }
943
-
944
- var __defProp$3 = Object.defineProperty;
945
- var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
946
- var __publicField$3 = (obj, key, value) => {
947
- __defNormalProp$3(obj, typeof key !== "symbol" ? key + "" : key, value);
948
- return value;
949
- };
950
- class KeyboardShortcutManager {
951
- constructor() {
952
- __publicField$3(this, "listeners");
953
- /**
954
- * Handles key events of the root handler and passes them down to listeners.
955
- * @param event
956
- */
957
- __publicField$3(this, "handleKeyboardEvent", (event) => {
958
- if (this.isInputEvent(event))
959
- return;
960
- const key = this.keyDefinitionFromEvent(event);
961
- for (const listener of this.listeners) {
962
- const handler = listener.bindings[key];
963
- if (handler) {
964
- const propagate = handler(event);
965
- if (propagate === true) {
966
- continue;
967
- } else {
968
- event.stopPropagation();
969
- return;
970
- }
971
- }
972
- }
973
- });
974
- this.listeners = [];
975
- document.addEventListener("keydown", this.handleKeyboardEvent);
976
- }
977
- /**
978
- * Adds listener to keyboard events.
979
- * @param bindings Object containing key/value pairs of keyCode/eventHandler function. Can add multiple comma separated `,` keyCodes for the same handler. Can optionally return `false` to stop propagation of other handlers.
980
- * @param priority Can optionally set the priority of event handler, higher value means higher priority. Defaults to 0.
981
- * @returns Function that can be used to unbind the listener.
982
- */
983
- addListener(bindings, priority) {
984
- bindings = this.splitEventBindings(bindings);
985
- const listener = this.addToListeners({ bindings, priority: priority ?? 0 });
986
- const removeListener = () => {
987
- this.removeFromListeners(listener);
988
- };
989
- return removeListener;
990
- }
991
- /**
992
- * Splits multiple keyCode events and creates a new bindings map.
993
- * @param bindings
994
- */
995
- splitEventBindings(bindings) {
996
- const splitBindings = {};
997
- for (const event in bindings) {
998
- event.split(",").forEach((splitEvent) => {
999
- splitBindings[this.normalizeKeyDefinition(splitEvent)] = bindings[event];
1000
- });
1001
- }
1002
- return splitBindings;
1003
- }
1004
- /**
1005
- * Checks is the event comes from an input type.
1006
- * @param event
1007
- */
1008
- isInputEvent(event) {
1009
- if (event.target instanceof Node) {
1010
- switch (event.target.nodeName) {
1011
- case "INPUT":
1012
- case "SELECT":
1013
- case "TEXTAREA":
1014
- return true;
1015
- default:
1016
- return false;
1017
- }
1018
- }
1019
- return false;
1020
- }
1021
- /**
1022
- * Adds listener into internal array of listeners and sorts in `descending` order.
1023
- * @param listener
1024
- */
1025
- addToListeners(listener) {
1026
- this.listeners.push(listener);
1027
- this.listeners.sort((a, b) => b.priority - a.priority);
1028
- return listener;
1029
- }
1030
- /**
1031
- * Removes listener from internal array of listeners.
1032
- * @param listenerToRemove
1033
- */
1034
- removeFromListeners(listenerToRemove) {
1035
- this.listeners = this.listeners.filter((listener) => listener !== listenerToRemove);
1036
- }
1037
- normalizeKeyDefinition(keyDef) {
1038
- const parts = keyDef.split("+");
1039
- const ev = {
1040
- ctrlKey: parts.includes("Ctrl"),
1041
- shiftKey: parts.includes("Shift"),
1042
- altKey: parts.includes("Alt"),
1043
- metaKey: parts.includes("Meta"),
1044
- code: parts[parts.length - 1]
1045
- };
1046
- return this.keyDefinitionFromEvent(ev);
1047
- }
1048
- keyDefinitionFromEvent(ev) {
1049
- let keyDef = "";
1050
- if (ev.ctrlKey)
1051
- keyDef += "Ctrl+";
1052
- if (ev.shiftKey)
1053
- keyDef += "Shift+";
1054
- if (ev.altKey)
1055
- keyDef += "Alt+";
1056
- if (ev.metaKey)
1057
- keyDef += "Meta+";
1058
- keyDef += ev.code;
1059
- return keyDef;
1060
- }
1061
- }
1062
-
1063
- var __defProp$2 = Object.defineProperty;
1064
- var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1065
- var __publicField$2 = (obj, key, value) => {
1066
- __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1067
- return value;
1068
- };
1069
- const debug = Debug__default("flow:map-plugin-manager");
1070
- class PluginManager {
1071
- constructor(map) {
1072
- __publicField$2(this, "_map");
1073
- __publicField$2(this, "_keyboardShortcutManager", new KeyboardShortcutManager());
1074
- __publicField$2(this, "_plugins", /* @__PURE__ */ new Map());
1075
- __publicField$2(this, "_initialized", false);
1076
- __publicField$2(this, "_exclusivePlugins", /* @__PURE__ */ new Set());
1077
- this._map = map;
1078
- this.map.initialized.then(() => {
1079
- this._initialized = true;
1080
- for (const plugin of this._plugins.values()) {
1081
- if (plugin.initialize) {
1082
- plugin.initialize();
1083
- }
1084
- }
1085
- });
1086
- }
1087
- get map() {
1088
- return this._map;
1089
- }
1090
- usePlugin(plugin, options) {
1091
- if (this._plugins.has(plugin)) {
1092
- const oldInstance = this._plugins.get(plugin);
1093
- if (oldInstance.destroy) {
1094
- oldInstance.destroy();
1095
- }
1096
- }
1097
- const pluginInstance = new plugin(this, options);
1098
- this._plugins.set(plugin, pluginInstance);
1099
- debug(`FlowMap<${this.map.id}>: Using plugin '${pluginInstance.name}'`);
1100
- if (this._initialized && pluginInstance.initialize)
1101
- pluginInstance.initialize();
1102
- return pluginInstance;
1103
- }
1104
- getPlugin(pluginOrName) {
1105
- let name;
1106
- let pluginInstance;
1107
- if (randomId.isString(pluginOrName)) {
1108
- pluginInstance = Array.from(this._plugins.values()).find((p) => p.name === pluginOrName);
1109
- name = pluginOrName;
1110
- } else {
1111
- pluginInstance = this._plugins.get(pluginOrName);
1112
- name = pluginOrName.name;
1113
- }
1114
- if (!pluginInstance) {
1115
- throw new FlowError(`<${name}>: plugin not registered`);
1116
- }
1117
- return pluginInstance;
1118
- }
1119
- removePlugin(pluginOrName) {
1120
- let pluginConstructor;
1121
- let pluginInstance;
1122
- if (randomId.isString(pluginOrName)) {
1123
- const pair = Array.from(this._plugins.entries()).find(([_, p]) => p.name === pluginOrName);
1124
- pluginConstructor = pair && pair[0];
1125
- pluginInstance = pair && pair[1];
1126
- } else {
1127
- pluginConstructor = pluginOrName;
1128
- pluginInstance = this._plugins.get(pluginOrName);
1129
- }
1130
- if (pluginInstance && pluginInstance.destroy) {
1131
- pluginInstance.destroy();
1132
- }
1133
- if (pluginConstructor)
1134
- this._plugins.delete(pluginConstructor);
1135
- return this;
1136
- }
1137
- removeAllPlugins() {
1138
- this._plugins.forEach((plugin) => {
1139
- if (plugin.destroy)
1140
- plugin.destroy();
1141
- });
1142
- this._plugins.clear();
1143
- return this;
1144
- }
1145
- setExclusivePlugin(plugin) {
1146
- this._exclusivePlugins.add(plugin);
1147
- this.forwardSetExclusivePlugin();
1148
- return this;
1149
- }
1150
- removeExclusivePlugin(plugin) {
1151
- this._exclusivePlugins.delete(plugin);
1152
- this.forwardSetExclusivePlugin();
1153
- return this;
1154
- }
1155
- addKeyboardShortcuts(keyboardShortcuts, priority = 0) {
1156
- return this._keyboardShortcutManager.addListener(keyboardShortcuts, priority);
1157
- }
1158
- forwardEvent(eventName, ...args) {
1159
- const handlerName = `handle${randomId.capitalize(eventName)}`;
1160
- this._plugins.forEach((plugin) => {
1161
- if (this._exclusivePlugins.size && !this._exclusivePlugins.has(plugin))
1162
- return;
1163
- const handler = plugin[handlerName];
1164
- if (handler) {
1165
- handler.apply(plugin, args);
1166
- }
1167
- });
1168
- }
1169
- forwardStyleChangeEvent(event) {
1170
- this._plugins.forEach((plugin) => {
1171
- if (this._exclusivePlugins.size && !this._exclusivePlugins.has(plugin))
1172
- return;
1173
- if (plugin.handleBeforeStyleChanged) {
1174
- const result = plugin.handleBeforeStyleChanged(event);
1175
- if (result) {
1176
- event.newStyle = result;
1177
- }
1178
- }
1179
- });
1180
- return event.newStyle;
1181
- }
1182
- forwardSetExclusivePlugin() {
1183
- this._plugins.forEach((plugin) => {
1184
- if (plugin.handleSetExclusivePlugin) {
1185
- plugin.handleSetExclusivePlugin(Array.from(this._exclusivePlugins));
1186
- }
1187
- });
1188
- }
1189
- }
1190
-
1191
- var __defProp$1 = Object.defineProperty;
1192
- var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1193
- var __publicField$1 = (obj, key, value) => {
1194
- __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
1195
- return value;
1196
- };
1197
- class MapEvent {
1198
- constructor(type, map, originalEvent) {
1199
- __publicField$1(this, "type");
1200
- __publicField$1(this, "map");
1201
- __publicField$1(this, "originalEvent");
1202
- this.type = type;
1203
- this.map = map;
1204
- this.originalEvent = originalEvent;
1205
- }
1206
- static fromMaplibreEvent(type, map, maplibreEvent) {
1207
- return new MapEvent(type, map, maplibreEvent.originalEvent);
1208
- }
1209
- }
1210
- class MapMouseEvent extends MapEvent {
1211
- constructor(type, map, point, lngLat, features, originalEvent) {
1212
- super(type, map, originalEvent);
1213
- /**
1214
- * The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner.
1215
- */
1216
- __publicField$1(this, "point");
1217
- /**
1218
- * The geographic location on the map of the mouse cursor.
1219
- */
1220
- __publicField$1(this, "lngLat");
1221
- __publicField$1(this, "features");
1222
- this.point = point;
1223
- this.lngLat = lngLat;
1224
- this.features = features;
1225
- }
1226
- static fromMaplibreMouseEvent(type, maplibreMouseEvent, map, features) {
1227
- return new MapMouseEvent(
1228
- type,
1229
- map,
1230
- [maplibreMouseEvent.point.x, maplibreMouseEvent.point.y],
1231
- [maplibreMouseEvent.lngLat.lng, maplibreMouseEvent.lngLat.lat],
1232
- features,
1233
- maplibreMouseEvent.originalEvent
1234
- );
1235
- }
1236
- }
1237
- class MapSourceEvent extends MapEvent {
1238
- constructor(type, map, source) {
1239
- super(type, map);
1240
- __publicField$1(this, "source");
1241
- this.source = source;
1242
- }
1243
- }
1244
- class MapLoadingEvent extends MapEvent {
1245
- constructor(map, loading) {
1246
- super("loading", map);
1247
- __publicField$1(this, "loading");
1248
- this.loading = loading;
1249
- }
1250
- }
1251
- class MapStyleChangeEvent extends MapEvent {
1252
- constructor(type, map, oldStyle, newStyle) {
1253
- super(type, map);
1254
- __publicField$1(this, "oldStyle");
1255
- __publicField$1(this, "newStyle");
1256
- this.oldStyle = oldStyle;
1257
- this.newStyle = newStyle;
1258
- }
1259
- }
1260
-
1261
- var __defProp = Object.defineProperty;
1262
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1263
- var __publicField = (obj, key, value) => {
1264
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
1265
- return value;
1266
- };
1267
- Debug__default("flow:map-feature-stream");
1268
- class MapFeatureStream {
1269
- constructor(options) {
1270
- __publicField(this, "_boundHandleLoading");
1271
- __publicField(this, "_boundHandleSourceFeatureState");
1272
- __publicField(this, "_options");
1273
- __publicField(this, "_sourceLoadCount", 0);
1274
- __publicField(this, "_sourceLoaded", true);
1275
- var _a;
1276
- this._options = {
1277
- fireImmediately: true,
1278
- ...options
1279
- };
1280
- const sourceType = options.map.getSource(options.source).type;
1281
- if (sourceType === "vector")
1282
- (_a = this._options).sourceLayer ?? (_a.sourceLayer = "geometry");
1283
- mobx.makeObservable(this, {
1284
- _options: mobx.observable,
1285
- _sourceLoadCount: mobx.observable,
1286
- featureData: mobx.computed.struct
1287
- });
1288
- this._boundHandleLoading = this.handleLoading.bind(this);
1289
- this._boundHandleSourceFeatureState = this.handleSourceFeatureState.bind(this);
1290
- mobx.onBecomeObserved(this, "featureData", this.resume.bind(this));
1291
- mobx.onBecomeUnobserved(this, "featureData", this.suspend.bind(this));
1292
- }
1293
- // Computed
1294
- get featureData() {
1295
- this._sourceLoadCount;
1296
- const featureData = this.queryFeatureData(this._options.featureIds);
1297
- return featureData;
1298
- }
1299
- get featureIds() {
1300
- return this._options.featureIds;
1301
- }
1302
- set featureIds(featureIds) {
1303
- mobx.runInAction(() => {
1304
- this._options.featureIds = featureIds;
1305
- });
1306
- }
1307
- subscribe(handler) {
1308
- const mobxSubscription = mobxUtils.toStream(() => this.featureData, this._options.fireImmediately).subscribe(handler);
1309
- return {
1310
- unsubscribe: () => {
1311
- mobxSubscription.unsubscribe();
1312
- }
1313
- };
1314
- }
1315
- featureFromMaplibreFeature(feature) {
1316
- return {
1317
- id: feature.id,
1318
- geometry: feature.geometry,
1319
- source: this._options.source,
1320
- sourceLayer: this._options.sourceLayer,
1321
- properties: feature.properties,
1322
- state: this._options.map.maplibreMap.getFeatureState({
1323
- id: feature.id,
1324
- source: this._options.source,
1325
- sourceLayer: this._options.sourceLayer
1326
- })
1327
- };
1328
- }
1329
- handleLoading(event) {
1330
- let loaded = false;
1331
- if (event.type === "sourcedata" && event.sourceId === this._options.source) {
1332
- loaded = event.isSourceLoaded;
1333
- } else if (event.type === "idle") {
1334
- loaded = true;
1335
- }
1336
- if (this._sourceLoaded !== loaded) {
1337
- this._sourceLoaded = loaded;
1338
- if (loaded) {
1339
- mobx.runInAction(() => {
1340
- this._sourceLoadCount++;
1341
- });
1342
- }
1343
- }
1344
- }
1345
- handleSourceFeatureState(event) {
1346
- if (event.type === "sourceFeatureState" && event.source === this._options.source) {
1347
- mobx.runInAction(() => {
1348
- this._sourceLoadCount++;
1349
- });
1350
- }
1351
- }
1352
- queryFeatureData(featureIDs) {
1353
- if (featureIDs.length === 0) {
1354
- return {};
1355
- }
1356
- const featureIdProp = this._options.map.getSource(this._options.source).featureId;
1357
- let features = this._options.map.maplibreMap.querySourceFeatures(this._options.source, {
1358
- sourceLayer: this._options.sourceLayer,
1359
- filter: ["in", ["get", featureIdProp], ["literal", featureIDs]]
1360
- });
1361
- const ids = /* @__PURE__ */ new Set();
1362
- features = features.filter((feature) => ids.has(feature.id) ? false : ids.add(feature.id) && true);
1363
- const featureData = features.reduce((accum, f) => {
1364
- accum[f.id] = this.featureFromMaplibreFeature(f);
1365
- return accum;
1366
- }, {});
1367
- return featureData;
1368
- }
1369
- resume() {
1370
- this._options.map.maplibreMap.on("sourcedata", this._boundHandleLoading);
1371
- this._options.map.maplibreMap.on("idle", this._boundHandleLoading);
1372
- this._options.map.on("sourceFeatureState", this._boundHandleSourceFeatureState);
1373
- }
1374
- suspend() {
1375
- this._options.map.maplibreMap.off("sourcedata", this._boundHandleLoading);
1376
- this._options.map.maplibreMap.off("idle", this._boundHandleLoading);
1377
- this._options.map.off("sourceFeatureState", this._boundHandleSourceFeatureState);
1378
- }
1379
- }
1380
-
1381
- exports.FlowError = FlowError;
1382
- exports.FlowMapError = FlowMapError;
1383
- exports.MapDataSource = MapDataSource;
1384
- exports.MapEvent = MapEvent;
1385
- exports.MapFeatureStream = MapFeatureStream;
1386
- exports.MapLayer = MapLayer;
1387
- exports.MapLoadingEvent = MapLoadingEvent;
1388
- exports.MapMouseEvent = MapMouseEvent;
1389
- exports.MapSourceEvent = MapSourceEvent;
1390
- exports.MapStyleChangeEvent = MapStyleChangeEvent;
1391
- exports.PluginManager = PluginManager;
1392
- exports.ReactiveExpression = ReactiveExpression;
1393
- exports.assert = assert;
1394
- exports.die = die;