@classic-homes/maps-core 0.1.1

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.
package/dist/index.cjs ADDED
@@ -0,0 +1,3284 @@
1
+ 'use strict';
2
+
3
+ var themeTokens = require('@classic-homes/theme-tokens');
4
+ var RBush = require('rbush');
5
+
6
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
+
8
+ var RBush__default = /*#__PURE__*/_interopDefault(RBush);
9
+
10
+ // src/theme/generator.ts
11
+ var THEME_LIGHT = "classic-light";
12
+ var THEME_DARK = "classic-dark";
13
+ function generateLightColors() {
14
+ return {
15
+ background: themeTokens.colors.white,
16
+ water: themeTokens.colors.sky[200],
17
+ land: themeTokens.colors.sage[50],
18
+ park: themeTokens.colors.forest[100],
19
+ building: themeTokens.colors.gray[200],
20
+ buildingOutline: themeTokens.colors.gray[300],
21
+ roadPrimary: themeTokens.colors.white,
22
+ roadSecondary: themeTokens.colors.gray[100],
23
+ roadCasing: themeTokens.colors.gray[300],
24
+ rail: themeTokens.colors.gray[400],
25
+ boundary: themeTokens.colors.gray[400],
26
+ adminBoundary: themeTokens.colors.plum[300],
27
+ residential: themeTokens.colors.sage[100],
28
+ commercial: themeTokens.colors.stone[100],
29
+ industrial: themeTokens.colors.gray[200],
30
+ highlight: themeTokens.colors.teal[500],
31
+ // Core 1 - brand teal
32
+ highlightSecondary: themeTokens.colors.teal[300],
33
+ selection: themeTokens.colors.red[500],
34
+ // Brand red
35
+ textPrimary: themeTokens.semanticColors.light.foreground,
36
+ textSecondary: themeTokens.semanticColors.light.mutedForeground,
37
+ textHalo: themeTokens.colors.white,
38
+ poi: themeTokens.colors.navy[700],
39
+ // Core 2 - brand navy
40
+ labelBackground: "rgba(255, 255, 255, 0.85)"
41
+ };
42
+ }
43
+ function generateDarkColors() {
44
+ return {
45
+ background: themeTokens.colors.charcoal[900],
46
+ water: themeTokens.colors.navy[800],
47
+ land: themeTokens.colors.charcoal[800],
48
+ park: themeTokens.colors.forest[900],
49
+ building: themeTokens.colors.charcoal[700],
50
+ buildingOutline: themeTokens.colors.charcoal[600],
51
+ roadPrimary: themeTokens.colors.charcoal[600],
52
+ roadSecondary: themeTokens.colors.charcoal[700],
53
+ roadCasing: themeTokens.colors.charcoal[500],
54
+ rail: themeTokens.colors.gray[600],
55
+ boundary: themeTokens.colors.gray[600],
56
+ adminBoundary: themeTokens.colors.plum[400],
57
+ residential: themeTokens.colors.charcoal[700],
58
+ commercial: themeTokens.colors.stone[800],
59
+ industrial: themeTokens.colors.charcoal[700],
60
+ highlight: themeTokens.colors.teal[400],
61
+ // Lighter for dark mode
62
+ highlightSecondary: themeTokens.colors.teal[500],
63
+ selection: themeTokens.colors.red[400],
64
+ // Lighter for dark mode
65
+ textPrimary: themeTokens.semanticColors.dark.foreground,
66
+ textSecondary: themeTokens.semanticColors.dark.mutedForeground,
67
+ textHalo: themeTokens.colors.charcoal[900],
68
+ poi: themeTokens.colors.navy[400],
69
+ // Lighter for dark mode
70
+ labelBackground: "rgba(41, 36, 36, 0.85)"
71
+ };
72
+ }
73
+ function generateLightDataColors() {
74
+ return {
75
+ sequence: [
76
+ themeTokens.colors.teal[500],
77
+ // chart.1
78
+ themeTokens.colors.navy[700],
79
+ // chart.2
80
+ themeTokens.colors.plum[700],
81
+ // chart.3
82
+ themeTokens.colors.forest[500],
83
+ // chart.4
84
+ themeTokens.colors.sky[600]
85
+ // chart.5
86
+ ],
87
+ positive: themeTokens.colors.forest[500],
88
+ negative: themeTokens.colors.red[500],
89
+ neutral: themeTokens.colors.gray[500],
90
+ heatmapRamp: [
91
+ "rgba(59, 164, 167, 0)",
92
+ // teal transparent
93
+ themeTokens.colors.teal[200],
94
+ themeTokens.colors.teal[400],
95
+ themeTokens.colors.teal[500],
96
+ themeTokens.colors.red[400],
97
+ themeTokens.colors.red[500],
98
+ themeTokens.colors.red[600]
99
+ ]
100
+ };
101
+ }
102
+ function generateDarkDataColors() {
103
+ return {
104
+ sequence: [
105
+ themeTokens.colors.teal[400],
106
+ // chart.1
107
+ themeTokens.colors.navy[400],
108
+ // chart.2
109
+ themeTokens.colors.plum[400],
110
+ // chart.3
111
+ themeTokens.colors.forest[400],
112
+ // chart.4
113
+ themeTokens.colors.sky[400]
114
+ // chart.5
115
+ ],
116
+ positive: themeTokens.colors.forest[400],
117
+ negative: themeTokens.colors.red[400],
118
+ neutral: themeTokens.colors.gray[400],
119
+ heatmapRamp: [
120
+ "rgba(103, 204, 207, 0)",
121
+ // teal transparent
122
+ themeTokens.colors.teal[300],
123
+ themeTokens.colors.teal[400],
124
+ themeTokens.colors.teal[500],
125
+ themeTokens.colors.red[400],
126
+ themeTokens.colors.red[500],
127
+ themeTokens.colors.red[600]
128
+ ]
129
+ };
130
+ }
131
+ function getTypography() {
132
+ return {
133
+ fontFamily: themeTokens.fontFamily.sans.join(", "),
134
+ fontFamilySerif: themeTokens.fontFamily.serif.join(", "),
135
+ fontFamilyMono: themeTokens.fontFamily.mono.join(", ")
136
+ };
137
+ }
138
+ function generateLightTheme() {
139
+ return {
140
+ name: THEME_LIGHT,
141
+ colors: generateLightColors(),
142
+ dataColors: generateLightDataColors(),
143
+ typography: getTypography()
144
+ };
145
+ }
146
+ function generateDarkTheme() {
147
+ return {
148
+ name: THEME_DARK,
149
+ colors: generateDarkColors(),
150
+ dataColors: generateDarkDataColors(),
151
+ typography: getTypography()
152
+ };
153
+ }
154
+ var lightTheme = generateLightTheme();
155
+ var darkTheme = generateDarkTheme();
156
+ function getTheme(name) {
157
+ if (name === "dark" || name === THEME_DARK) {
158
+ return darkTheme;
159
+ }
160
+ return lightTheme;
161
+ }
162
+
163
+ // src/theme/style.ts
164
+ var DEFAULT_TILE_SOURCE = {
165
+ type: "vector",
166
+ url: "https://api.maptiler.com/tiles/v3/tiles.json?key=get_your_own_key"
167
+ };
168
+ var OSM_RASTER_SOURCE = {
169
+ type: "raster",
170
+ tiles: ["https://tile.openstreetmap.org/{z}/{x}/{y}.png"],
171
+ tileSize: 256,
172
+ attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
173
+ };
174
+ function generateBasicStyle(theme = lightTheme) {
175
+ const colors2 = theme.colors;
176
+ return {
177
+ version: 8,
178
+ name: `Classic Theme - ${theme.name}`,
179
+ sources: {
180
+ osm: OSM_RASTER_SOURCE
181
+ },
182
+ layers: [
183
+ {
184
+ id: "background",
185
+ type: "background",
186
+ paint: {
187
+ "background-color": colors2.background
188
+ }
189
+ },
190
+ {
191
+ id: "osm-tiles",
192
+ type: "raster",
193
+ source: "osm",
194
+ minzoom: 0,
195
+ maxzoom: 19,
196
+ paint: {
197
+ "raster-opacity": theme.name === THEME_DARK ? 0.6 : 1,
198
+ "raster-saturation": theme.name === THEME_DARK ? -0.3 : 0
199
+ }
200
+ }
201
+ ],
202
+ metadata: {
203
+ "classic-theme": theme.name
204
+ }
205
+ };
206
+ }
207
+ function createWaterLayer(colors2) {
208
+ return {
209
+ id: "water",
210
+ type: "fill",
211
+ source: "openmaptiles",
212
+ "source-layer": "water",
213
+ paint: {
214
+ "fill-color": colors2.water,
215
+ "fill-opacity": 1
216
+ }
217
+ };
218
+ }
219
+ function createLanduseLayers(colors2) {
220
+ return [
221
+ {
222
+ id: "landuse-residential",
223
+ type: "fill",
224
+ source: "openmaptiles",
225
+ "source-layer": "landuse",
226
+ filter: ["==", "class", "residential"],
227
+ paint: {
228
+ "fill-color": colors2.residential,
229
+ "fill-opacity": 0.6
230
+ }
231
+ },
232
+ {
233
+ id: "landuse-commercial",
234
+ type: "fill",
235
+ source: "openmaptiles",
236
+ "source-layer": "landuse",
237
+ filter: ["==", "class", "commercial"],
238
+ paint: {
239
+ "fill-color": colors2.commercial,
240
+ "fill-opacity": 0.6
241
+ }
242
+ },
243
+ {
244
+ id: "landuse-industrial",
245
+ type: "fill",
246
+ source: "openmaptiles",
247
+ "source-layer": "landuse",
248
+ filter: ["==", "class", "industrial"],
249
+ paint: {
250
+ "fill-color": colors2.industrial,
251
+ "fill-opacity": 0.6
252
+ }
253
+ },
254
+ {
255
+ id: "landuse-park",
256
+ type: "fill",
257
+ source: "openmaptiles",
258
+ "source-layer": "landuse",
259
+ filter: ["in", "class", "park", "grass", "cemetery"],
260
+ paint: {
261
+ "fill-color": colors2.park,
262
+ "fill-opacity": 0.8
263
+ }
264
+ }
265
+ ];
266
+ }
267
+ function createBuildingLayers(colors2) {
268
+ return [
269
+ {
270
+ id: "building",
271
+ type: "fill",
272
+ source: "openmaptiles",
273
+ "source-layer": "building",
274
+ minzoom: 13,
275
+ paint: {
276
+ "fill-color": colors2.building,
277
+ "fill-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 15, 1]
278
+ }
279
+ },
280
+ {
281
+ id: "building-outline",
282
+ type: "line",
283
+ source: "openmaptiles",
284
+ "source-layer": "building",
285
+ minzoom: 13,
286
+ paint: {
287
+ "line-color": colors2.buildingOutline,
288
+ "line-width": 1,
289
+ "line-opacity": ["interpolate", ["linear"], ["zoom"], 13, 0, 15, 1]
290
+ }
291
+ }
292
+ ];
293
+ }
294
+ function createRoadLayers(colors2) {
295
+ return [
296
+ // Road casings (outlines)
297
+ {
298
+ id: "road-casing-primary",
299
+ type: "line",
300
+ source: "openmaptiles",
301
+ "source-layer": "transportation",
302
+ filter: ["in", "class", "primary", "trunk", "motorway"],
303
+ paint: {
304
+ "line-color": colors2.roadCasing,
305
+ "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0.5, 12, 4, 18, 20]
306
+ },
307
+ layout: {
308
+ "line-cap": "round",
309
+ "line-join": "round"
310
+ }
311
+ },
312
+ {
313
+ id: "road-casing-secondary",
314
+ type: "line",
315
+ source: "openmaptiles",
316
+ "source-layer": "transportation",
317
+ filter: ["in", "class", "secondary", "tertiary"],
318
+ paint: {
319
+ "line-color": colors2.roadCasing,
320
+ "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0.5, 12, 2, 18, 12]
321
+ },
322
+ layout: {
323
+ "line-cap": "round",
324
+ "line-join": "round"
325
+ }
326
+ },
327
+ // Road fills
328
+ {
329
+ id: "road-primary",
330
+ type: "line",
331
+ source: "openmaptiles",
332
+ "source-layer": "transportation",
333
+ filter: ["in", "class", "primary", "trunk", "motorway"],
334
+ paint: {
335
+ "line-color": colors2.roadPrimary,
336
+ "line-width": ["interpolate", ["linear"], ["zoom"], 5, 0.25, 12, 3, 18, 18]
337
+ },
338
+ layout: {
339
+ "line-cap": "round",
340
+ "line-join": "round"
341
+ }
342
+ },
343
+ {
344
+ id: "road-secondary",
345
+ type: "line",
346
+ source: "openmaptiles",
347
+ "source-layer": "transportation",
348
+ filter: ["in", "class", "secondary", "tertiary"],
349
+ paint: {
350
+ "line-color": colors2.roadSecondary,
351
+ "line-width": ["interpolate", ["linear"], ["zoom"], 8, 0.25, 12, 1.5, 18, 10]
352
+ },
353
+ layout: {
354
+ "line-cap": "round",
355
+ "line-join": "round"
356
+ }
357
+ },
358
+ {
359
+ id: "road-minor",
360
+ type: "line",
361
+ source: "openmaptiles",
362
+ "source-layer": "transportation",
363
+ filter: ["in", "class", "minor", "service", "path"],
364
+ minzoom: 13,
365
+ paint: {
366
+ "line-color": colors2.roadSecondary,
367
+ "line-width": ["interpolate", ["linear"], ["zoom"], 13, 0.5, 18, 6]
368
+ },
369
+ layout: {
370
+ "line-cap": "round",
371
+ "line-join": "round"
372
+ }
373
+ },
374
+ // Rail
375
+ {
376
+ id: "rail",
377
+ type: "line",
378
+ source: "openmaptiles",
379
+ "source-layer": "transportation",
380
+ filter: ["==", "class", "rail"],
381
+ minzoom: 10,
382
+ paint: {
383
+ "line-color": colors2.rail,
384
+ "line-width": ["interpolate", ["linear"], ["zoom"], 10, 0.5, 18, 2],
385
+ "line-dasharray": [2, 2]
386
+ }
387
+ }
388
+ ];
389
+ }
390
+ function createBoundaryLayers(colors2) {
391
+ return [
392
+ {
393
+ id: "boundary-country",
394
+ type: "line",
395
+ source: "openmaptiles",
396
+ "source-layer": "boundary",
397
+ filter: ["==", "admin_level", 2],
398
+ paint: {
399
+ "line-color": colors2.adminBoundary,
400
+ "line-width": ["interpolate", ["linear"], ["zoom"], 2, 0.5, 10, 2],
401
+ "line-dasharray": [3, 2]
402
+ }
403
+ },
404
+ {
405
+ id: "boundary-state",
406
+ type: "line",
407
+ source: "openmaptiles",
408
+ "source-layer": "boundary",
409
+ filter: ["==", "admin_level", 4],
410
+ minzoom: 4,
411
+ paint: {
412
+ "line-color": colors2.boundary,
413
+ "line-width": ["interpolate", ["linear"], ["zoom"], 4, 0.5, 10, 1.5],
414
+ "line-dasharray": [2, 2]
415
+ }
416
+ }
417
+ ];
418
+ }
419
+ function createLabelLayers(colors2, typography) {
420
+ return [
421
+ {
422
+ id: "place-labels-city",
423
+ type: "symbol",
424
+ source: "openmaptiles",
425
+ "source-layer": "place",
426
+ filter: ["in", "class", "city", "town"],
427
+ paint: {
428
+ "text-color": colors2.textPrimary,
429
+ "text-halo-color": colors2.textHalo,
430
+ "text-halo-width": 1.5
431
+ },
432
+ layout: {
433
+ "text-field": ["get", "name"],
434
+ "text-font": [typography.fontFamily.split(",")[0].trim()],
435
+ "text-size": ["interpolate", ["linear"], ["zoom"], 6, 10, 14, 18],
436
+ "text-anchor": "center",
437
+ "text-max-width": 10
438
+ }
439
+ },
440
+ {
441
+ id: "place-labels-neighborhood",
442
+ type: "symbol",
443
+ source: "openmaptiles",
444
+ "source-layer": "place",
445
+ filter: ["in", "class", "suburb", "neighbourhood", "quarter"],
446
+ minzoom: 12,
447
+ paint: {
448
+ "text-color": colors2.textSecondary,
449
+ "text-halo-color": colors2.textHalo,
450
+ "text-halo-width": 1
451
+ },
452
+ layout: {
453
+ "text-field": ["get", "name"],
454
+ "text-font": [typography.fontFamily.split(",")[0].trim()],
455
+ "text-size": ["interpolate", ["linear"], ["zoom"], 12, 10, 16, 14],
456
+ "text-anchor": "center",
457
+ "text-max-width": 8
458
+ }
459
+ },
460
+ {
461
+ id: "road-labels",
462
+ type: "symbol",
463
+ source: "openmaptiles",
464
+ "source-layer": "transportation_name",
465
+ minzoom: 13,
466
+ paint: {
467
+ "text-color": colors2.textPrimary,
468
+ "text-halo-color": colors2.textHalo,
469
+ "text-halo-width": 1
470
+ },
471
+ layout: {
472
+ "text-field": ["get", "name"],
473
+ "text-font": [typography.fontFamily.split(",")[0].trim()],
474
+ "text-size": ["interpolate", ["linear"], ["zoom"], 13, 9, 18, 14],
475
+ "symbol-placement": "line",
476
+ "text-rotation-alignment": "map",
477
+ "text-max-angle": 30
478
+ }
479
+ },
480
+ {
481
+ id: "poi-labels",
482
+ type: "symbol",
483
+ source: "openmaptiles",
484
+ "source-layer": "poi",
485
+ minzoom: 14,
486
+ paint: {
487
+ "text-color": colors2.poi,
488
+ "text-halo-color": colors2.textHalo,
489
+ "text-halo-width": 1
490
+ },
491
+ layout: {
492
+ "text-field": ["get", "name"],
493
+ "text-font": [typography.fontFamily.split(",")[0].trim()],
494
+ "text-size": 11,
495
+ "text-anchor": "top",
496
+ "text-offset": [0, 0.5],
497
+ "text-max-width": 8
498
+ }
499
+ }
500
+ ];
501
+ }
502
+ function generateVectorStyle(theme = lightTheme, tileSource, glyphsUrl, spriteUrl) {
503
+ const colors2 = theme.colors;
504
+ return {
505
+ version: 8,
506
+ name: `Classic Theme Vector - ${theme.name}`,
507
+ sources: {
508
+ openmaptiles: tileSource || DEFAULT_TILE_SOURCE
509
+ },
510
+ glyphs: glyphsUrl || "https://fonts.openmaptiles.org/{fontstack}/{range}.pbf",
511
+ sprite: spriteUrl,
512
+ layers: [
513
+ {
514
+ id: "background",
515
+ type: "background",
516
+ paint: {
517
+ "background-color": colors2.land
518
+ }
519
+ },
520
+ createWaterLayer(colors2),
521
+ ...createLanduseLayers(colors2),
522
+ ...createBuildingLayers(colors2),
523
+ ...createRoadLayers(colors2),
524
+ ...createBoundaryLayers(colors2),
525
+ ...createLabelLayers(colors2, theme.typography)
526
+ ],
527
+ metadata: {
528
+ "classic-theme": theme.name
529
+ }
530
+ };
531
+ }
532
+ var lightBasicStyle = generateBasicStyle(lightTheme);
533
+ var darkBasicStyle = generateBasicStyle(darkTheme);
534
+ function getBasicStyle(themeName) {
535
+ if (themeName === "dark" || themeName === THEME_DARK) {
536
+ return darkBasicStyle;
537
+ }
538
+ return lightBasicStyle;
539
+ }
540
+
541
+ // src/utils/accessibility.ts
542
+ var KEYBOARD_CONTROLS = {
543
+ pan: {
544
+ up: "Arrow Up",
545
+ down: "Arrow Down",
546
+ left: "Arrow Left",
547
+ right: "Arrow Right"
548
+ },
549
+ zoom: {
550
+ in: "Plus (+) or Equals (=)",
551
+ out: "Minus (-)"
552
+ },
553
+ rotate: {
554
+ left: "Shift + Arrow Left",
555
+ right: "Shift + Arrow Right"
556
+ },
557
+ pitch: {
558
+ increase: "Shift + Arrow Up",
559
+ decrease: "Shift + Arrow Down"
560
+ },
561
+ reset: {
562
+ bearing: "N key (reset north)",
563
+ view: "R key (reset view)"
564
+ }
565
+ };
566
+ function generateKeyboardControlsDescription() {
567
+ return `
568
+ Map keyboard controls:
569
+ Pan: Use arrow keys to move the map.
570
+ Zoom: Press plus to zoom in, minus to zoom out.
571
+ Rotate: Hold Shift and press left or right arrows.
572
+ Tilt: Hold Shift and press up or down arrows.
573
+ Press N to reset north orientation.
574
+ `.trim().replace(/\s+/g, " ");
575
+ }
576
+ function generateMapDescription(title, options) {
577
+ let description = `${title}. Interactive map`;
578
+ if (options?.center) {
579
+ const [lng, lat] = options.center;
580
+ const latDir = lat >= 0 ? "N" : "S";
581
+ const lngDir = lng >= 0 ? "E" : "W";
582
+ description += ` centered at ${Math.abs(lat).toFixed(2)} degrees ${latDir}, ${Math.abs(lng).toFixed(2)} degrees ${lngDir}`;
583
+ }
584
+ if (options?.zoom !== void 0) {
585
+ description += ` at zoom level ${options.zoom}`;
586
+ }
587
+ if (options?.featureCount !== void 0 && options.featureCount > 0) {
588
+ description += `. Contains ${options.featureCount} ${options.featureCount === 1 ? "feature" : "features"}`;
589
+ }
590
+ if (options?.markerCount !== void 0 && options.markerCount > 0) {
591
+ description += options.featureCount ? ` and ` : `. Contains `;
592
+ description += `${options.markerCount} ${options.markerCount === 1 ? "marker" : "markers"}`;
593
+ }
594
+ if (options?.layerTypes && options.layerTypes.length > 0) {
595
+ description += `. Showing ${options.layerTypes.join(", ")} layers`;
596
+ }
597
+ description += ". Use keyboard to navigate.";
598
+ return description;
599
+ }
600
+ function generateFeatureCollectionDescription(title, data) {
601
+ const featureCount = data.features.length;
602
+ if (featureCount === 0) {
603
+ return `${title}. Map layer with no features.`;
604
+ }
605
+ const geometryTypes = {};
606
+ data.features.forEach((feature) => {
607
+ const type = feature.geometry.type;
608
+ geometryTypes[type] = (geometryTypes[type] || 0) + 1;
609
+ });
610
+ const typeDescriptions = Object.entries(geometryTypes).map(([type, count]) => `${count} ${formatGeometryType(type, count)}`).join(", ");
611
+ return `${title}. Map layer with ${featureCount} features: ${typeDescriptions}.`;
612
+ }
613
+ function formatGeometryType(type, count) {
614
+ const singular = {
615
+ Point: "point",
616
+ MultiPoint: "multi-point",
617
+ LineString: "line",
618
+ MultiLineString: "multi-line",
619
+ Polygon: "polygon",
620
+ MultiPolygon: "multi-polygon"
621
+ };
622
+ const plural = {
623
+ Point: "points",
624
+ MultiPoint: "multi-points",
625
+ LineString: "lines",
626
+ MultiLineString: "multi-lines",
627
+ Polygon: "polygons",
628
+ MultiPolygon: "multi-polygons"
629
+ };
630
+ return count === 1 ? singular[type] || type.toLowerCase() : plural[type] || `${type.toLowerCase()}s`;
631
+ }
632
+ function generateMarkersDescription(title, markers) {
633
+ const count = markers.length;
634
+ if (count === 0) {
635
+ return `${title}. No markers on the map.`;
636
+ }
637
+ let description = `${title}. Map with ${count} ${count === 1 ? "marker" : "markers"}`;
638
+ const labeledMarkers = markers.filter((m) => m.label).slice(0, 3);
639
+ if (labeledMarkers.length > 0) {
640
+ const labels = labeledMarkers.map((m) => m.label).join(", ");
641
+ description += ` including ${labels}`;
642
+ if (count > labeledMarkers.length) {
643
+ description += ` and ${count - labeledMarkers.length} more`;
644
+ }
645
+ }
646
+ return description + ".";
647
+ }
648
+ function generateFeatureTable(features, propertyKeys) {
649
+ if (features.features.length === 0) {
650
+ return "";
651
+ }
652
+ const headers = ["Type", ...propertyKeys];
653
+ const headerRow = headers.map((h) => `<th scope="col">${escapeHtml(h)}</th>`).join("");
654
+ const bodyRows = features.features.slice(0, 100).map((feature) => {
655
+ const type = feature.geometry.type;
656
+ const cells = propertyKeys.map((key) => {
657
+ const value = feature.properties?.[key];
658
+ return `<td>${escapeHtml(String(value ?? ""))}</td>`;
659
+ });
660
+ return `<tr><td>${escapeHtml(type)}</td>${cells.join("")}</tr>`;
661
+ }).join("");
662
+ return `
663
+ <table class="sr-only" role="table" aria-label="Map feature data">
664
+ <thead><tr>${headerRow}</tr></thead>
665
+ <tbody>${bodyRows}</tbody>
666
+ </table>
667
+ `.trim();
668
+ }
669
+ function generateMarkerList(markers) {
670
+ if (markers.length === 0) {
671
+ return "";
672
+ }
673
+ const items = markers.slice(0, 50).map((marker) => {
674
+ const label = marker.label || "Marker";
675
+ const [lng, lat] = marker.coordinates;
676
+ return `<li>${escapeHtml(label)} at ${lat.toFixed(4)}, ${lng.toFixed(4)}</li>`;
677
+ }).join("");
678
+ return `
679
+ <ul class="sr-only" role="list" aria-label="Map markers">
680
+ ${items}
681
+ </ul>
682
+ `.trim();
683
+ }
684
+ function generateMoveAnnouncement(center, zoom, action) {
685
+ const [lng, lat] = center;
686
+ const latDir = lat >= 0 ? "north" : "south";
687
+ const lngDir = lng >= 0 ? "east" : "west";
688
+ switch (action) {
689
+ case "pan":
690
+ return `Panned to ${Math.abs(lat).toFixed(2)} ${latDir}, ${Math.abs(lng).toFixed(2)} ${lngDir}`;
691
+ case "zoom":
692
+ return `Zoom level ${zoom.toFixed(1)}`;
693
+ case "move":
694
+ default:
695
+ return `Map moved to ${Math.abs(lat).toFixed(2)} ${latDir}, ${Math.abs(lng).toFixed(2)} ${lngDir} at zoom ${zoom.toFixed(1)}`;
696
+ }
697
+ }
698
+ function escapeHtml(str) {
699
+ const htmlEntities = {
700
+ "&": "&amp;",
701
+ "<": "&lt;",
702
+ ">": "&gt;",
703
+ '"': "&quot;",
704
+ "'": "&#39;"
705
+ };
706
+ return str.replace(/[&<>"']/g, (char) => htmlEntities[char] || char);
707
+ }
708
+
709
+ // src/utils/styles.ts
710
+ function createFillStyle(options) {
711
+ const paint = {
712
+ "fill-color": options.color
713
+ };
714
+ if (options.opacity !== void 0) {
715
+ paint["fill-opacity"] = options.opacity;
716
+ }
717
+ if (options.outlineColor !== void 0) {
718
+ paint["fill-outline-color"] = options.outlineColor;
719
+ }
720
+ return { paint };
721
+ }
722
+ function createLineStyle(options) {
723
+ const paint = {
724
+ "line-color": options.color,
725
+ "line-width": options.width
726
+ };
727
+ const layout = {};
728
+ if (options.opacity !== void 0) {
729
+ paint["line-opacity"] = options.opacity;
730
+ }
731
+ if (options.dashArray) {
732
+ paint["line-dasharray"] = options.dashArray;
733
+ }
734
+ if (options.cap) {
735
+ layout["line-cap"] = options.cap;
736
+ }
737
+ if (options.join) {
738
+ layout["line-join"] = options.join;
739
+ }
740
+ return { paint, layout };
741
+ }
742
+ function createCircleStyle(options) {
743
+ const paint = {
744
+ "circle-radius": options.radius,
745
+ "circle-color": options.color
746
+ };
747
+ if (options.opacity !== void 0) {
748
+ paint["circle-opacity"] = options.opacity;
749
+ }
750
+ if (options.strokeWidth !== void 0) {
751
+ paint["circle-stroke-width"] = options.strokeWidth;
752
+ }
753
+ if (options.strokeColor !== void 0) {
754
+ paint["circle-stroke-color"] = options.strokeColor;
755
+ }
756
+ if (options.blur !== void 0) {
757
+ paint["circle-blur"] = options.blur;
758
+ }
759
+ return { paint };
760
+ }
761
+ function createExtrusionStyle(options) {
762
+ const paint = {
763
+ "fill-extrusion-height": options.height,
764
+ "fill-extrusion-color": options.color
765
+ };
766
+ if (options.baseHeight !== void 0) {
767
+ paint["fill-extrusion-base"] = options.baseHeight;
768
+ }
769
+ if (options.opacity !== void 0) {
770
+ paint["fill-extrusion-opacity"] = options.opacity;
771
+ }
772
+ if (options.verticalGradient !== void 0) {
773
+ paint["fill-extrusion-vertical-gradient"] = options.verticalGradient;
774
+ }
775
+ return { paint };
776
+ }
777
+ function createHeatmapStyle(options) {
778
+ const paint = {};
779
+ if (options.weight !== void 0) {
780
+ paint["heatmap-weight"] = options.weight;
781
+ }
782
+ if (options.intensity !== void 0) {
783
+ paint["heatmap-intensity"] = options.intensity;
784
+ }
785
+ if (options.radius !== void 0) {
786
+ paint["heatmap-radius"] = options.radius;
787
+ }
788
+ if (options.opacity !== void 0) {
789
+ paint["heatmap-opacity"] = options.opacity;
790
+ }
791
+ if (options.colorRamp) {
792
+ const stops = ["interpolate", ["linear"], ["heatmap-density"]];
793
+ options.colorRamp.forEach((color, index) => {
794
+ stops.push(index / (options.colorRamp.length - 1));
795
+ stops.push(color);
796
+ });
797
+ paint["heatmap-color"] = stops;
798
+ }
799
+ return { paint };
800
+ }
801
+ function createHoverExpression(baseValue, hoverValue, featureStateName = "hover") {
802
+ return ["case", ["boolean", ["feature-state", featureStateName], false], hoverValue, baseValue];
803
+ }
804
+ function createSelectionExpression(baseValue, selectedValue, featureStateName = "selected") {
805
+ return [
806
+ "case",
807
+ ["boolean", ["feature-state", featureStateName], false],
808
+ selectedValue,
809
+ baseValue
810
+ ];
811
+ }
812
+ function createInteractiveExpression(baseValue, hoverValue, selectedValue) {
813
+ return [
814
+ "case",
815
+ ["boolean", ["feature-state", "selected"], false],
816
+ selectedValue,
817
+ ["boolean", ["feature-state", "hover"], false],
818
+ hoverValue,
819
+ baseValue
820
+ ];
821
+ }
822
+ function createCategoricalColorExpression(property, colorMap, defaultColor) {
823
+ const expression = ["match", ["get", property]];
824
+ Object.entries(colorMap).forEach(([value, color]) => {
825
+ expression.push(value, color);
826
+ });
827
+ expression.push(defaultColor);
828
+ return expression;
829
+ }
830
+ function createContinuousColorExpression(property, stops, interpolation = "linear") {
831
+ const expression = ["interpolate"];
832
+ if (interpolation === "linear") {
833
+ expression.push(["linear"]);
834
+ } else if (interpolation === "exponential") {
835
+ expression.push(["exponential", 1]);
836
+ } else {
837
+ expression.push(interpolation);
838
+ }
839
+ expression.push(["get", property]);
840
+ stops.forEach(([value, color]) => {
841
+ expression.push(value, color);
842
+ });
843
+ return expression;
844
+ }
845
+ function createZoomExpression(stops) {
846
+ const expression = ["interpolate", ["linear"], ["zoom"]];
847
+ stops.forEach(([zoom, value]) => {
848
+ expression.push(zoom, value);
849
+ });
850
+ return expression;
851
+ }
852
+ function getHighlightStyle(theme = lightTheme) {
853
+ const { highlight, highlightSecondary } = theme.colors;
854
+ return {
855
+ fill: {
856
+ "fill-color": createHoverExpression(highlightSecondary, highlight),
857
+ "fill-opacity": createHoverExpression(0.3, 0.5),
858
+ "fill-outline-color": highlight
859
+ },
860
+ line: {
861
+ "line-color": createHoverExpression(highlightSecondary, highlight),
862
+ "line-width": createHoverExpression(2, 3)
863
+ },
864
+ circle: {
865
+ "circle-color": createHoverExpression(highlightSecondary, highlight),
866
+ "circle-radius": createHoverExpression(6, 8),
867
+ "circle-stroke-color": highlight,
868
+ "circle-stroke-width": 2
869
+ }
870
+ };
871
+ }
872
+ function getSelectionStyle(theme = lightTheme) {
873
+ const { selection, highlight } = theme.colors;
874
+ return {
875
+ fill: {
876
+ "fill-color": createInteractiveExpression(highlight, highlight, selection),
877
+ "fill-opacity": createInteractiveExpression(0.2, 0.4, 0.6),
878
+ "fill-outline-color": createInteractiveExpression(highlight, highlight, selection)
879
+ },
880
+ line: {
881
+ "line-color": createInteractiveExpression(highlight, highlight, selection),
882
+ "line-width": createInteractiveExpression(2, 3, 4)
883
+ },
884
+ circle: {
885
+ "circle-color": createInteractiveExpression(highlight, highlight, selection),
886
+ "circle-radius": createInteractiveExpression(6, 8, 10),
887
+ "circle-stroke-color": createInteractiveExpression(highlight, highlight, selection),
888
+ "circle-stroke-width": 2
889
+ }
890
+ };
891
+ }
892
+ function createLotFillStyle(options) {
893
+ const { defaultColor, hoverColor, selectedColor, opacity = 0.7 } = options;
894
+ const fillColor = selectedColor ? createInteractiveExpression(defaultColor, hoverColor, selectedColor) : createHoverExpression(defaultColor, hoverColor);
895
+ return {
896
+ "fill-color": fillColor,
897
+ "fill-opacity": opacity
898
+ };
899
+ }
900
+ function createLotOutlineStyle(options) {
901
+ const {
902
+ defaultColor,
903
+ hoverColor,
904
+ selectedColor,
905
+ defaultWidth = 1,
906
+ hoverWidth = 2,
907
+ selectedWidth = 3
908
+ } = options;
909
+ const lineColor = selectedColor ? createInteractiveExpression(defaultColor, hoverColor, selectedColor) : createHoverExpression(defaultColor, hoverColor);
910
+ const lineWidth = selectedColor ? createInteractiveExpression(defaultWidth, hoverWidth, selectedWidth) : createHoverExpression(defaultWidth, hoverWidth);
911
+ return {
912
+ "line-color": lineColor,
913
+ "line-width": lineWidth
914
+ };
915
+ }
916
+ function createExtrusionHeightExpression(property, options = {}) {
917
+ const { scale = 1, minHeight = 0, maxHeight, defaultHeight = 0 } = options;
918
+ let heightExpr = ["coalesce", ["get", property], defaultHeight];
919
+ if (scale !== 1) {
920
+ heightExpr = ["*", heightExpr, scale];
921
+ }
922
+ if (minHeight > 0) {
923
+ heightExpr = ["max", heightExpr, minHeight];
924
+ }
925
+ if (maxHeight !== void 0) {
926
+ heightExpr = ["min", heightExpr, maxHeight];
927
+ }
928
+ return heightExpr;
929
+ }
930
+ function createStatusColorExpression(statusColors, defaultColor = "#888888") {
931
+ return createCategoricalColorExpression("status", statusColors, defaultColor);
932
+ }
933
+ function createInteractiveStatusColorExpression(statusColors, options) {
934
+ const { hoverColor, selectedColor, defaultColor = "#888888" } = options;
935
+ const baseExpr = createCategoricalColorExpression("status", statusColors, defaultColor);
936
+ if (selectedColor) {
937
+ return [
938
+ "case",
939
+ ["boolean", ["feature-state", "selected"], false],
940
+ selectedColor,
941
+ ["boolean", ["feature-state", "hover"], false],
942
+ hoverColor,
943
+ baseExpr
944
+ ];
945
+ }
946
+ return ["case", ["boolean", ["feature-state", "hover"], false], hoverColor, baseExpr];
947
+ }
948
+
949
+ // src/utils/format.ts
950
+ function formatCoordinates(coordinates, precision = 6, format = "decimal") {
951
+ const [lng, lat] = coordinates;
952
+ switch (format) {
953
+ case "dms":
954
+ return `${decimalToDMS(lat, "lat")}, ${decimalToDMS(lng, "lng")}`;
955
+ case "dd":
956
+ return `${lat.toFixed(precision)}, ${lng.toFixed(precision)}`;
957
+ case "decimal":
958
+ default:
959
+ return `${lng.toFixed(precision)}, ${lat.toFixed(precision)}`;
960
+ }
961
+ }
962
+ function decimalToDMS(decimal, type) {
963
+ const absolute = Math.abs(decimal);
964
+ const degrees = Math.floor(absolute);
965
+ const minutesDecimal = (absolute - degrees) * 60;
966
+ const minutes = Math.floor(minutesDecimal);
967
+ const seconds = ((minutesDecimal - minutes) * 60).toFixed(1);
968
+ let direction;
969
+ if (type === "lat") {
970
+ direction = decimal >= 0 ? "N" : "S";
971
+ } else {
972
+ direction = decimal >= 0 ? "E" : "W";
973
+ }
974
+ return `${degrees}\xB0 ${minutes}' ${seconds}" ${direction}`;
975
+ }
976
+ function formatDistance(meters, unit = "metric") {
977
+ if (unit === "imperial") {
978
+ const feet = meters * 3.28084;
979
+ if (feet < 1e3) {
980
+ return `${Math.round(feet)} ft`;
981
+ }
982
+ const miles = feet / 5280;
983
+ if (miles < 10) {
984
+ return `${miles.toFixed(1)} mi`;
985
+ }
986
+ return `${Math.round(miles)} mi`;
987
+ }
988
+ if (meters < 1e3) {
989
+ return `${Math.round(meters)} m`;
990
+ }
991
+ const km = meters / 1e3;
992
+ if (km < 10) {
993
+ return `${km.toFixed(1)} km`;
994
+ }
995
+ return `${Math.round(km)} km`;
996
+ }
997
+ function formatArea(sqMeters, unit = "metric") {
998
+ if (unit === "imperial") {
999
+ const sqFeet = sqMeters * 10.7639;
1000
+ if (sqFeet < 43560) {
1001
+ return `${Math.round(sqFeet).toLocaleString()} sq ft`;
1002
+ }
1003
+ const acres = sqFeet / 43560;
1004
+ if (acres < 640) {
1005
+ return `${acres.toFixed(2)} acres`;
1006
+ }
1007
+ const sqMiles = acres / 640;
1008
+ return `${sqMiles.toFixed(2)} sq mi`;
1009
+ }
1010
+ if (sqMeters < 1e4) {
1011
+ return `${Math.round(sqMeters).toLocaleString()} m\xB2`;
1012
+ }
1013
+ const hectares = sqMeters / 1e4;
1014
+ if (hectares < 100) {
1015
+ return `${hectares.toFixed(2)} ha`;
1016
+ }
1017
+ const sqKm = sqMeters / 1e6;
1018
+ return `${sqKm.toFixed(2)} km\xB2`;
1019
+ }
1020
+ function formatBounds(bounds) {
1021
+ let sw;
1022
+ let ne;
1023
+ if (Array.isArray(bounds) && Array.isArray(bounds[0])) {
1024
+ const arr = bounds;
1025
+ sw = arr[0];
1026
+ ne = arr[1];
1027
+ } else {
1028
+ const b = bounds;
1029
+ sw = b.southwest;
1030
+ ne = b.northeast;
1031
+ }
1032
+ return `SW: ${formatCoordinates(sw, 4)}, NE: ${formatCoordinates(ne, 4)}`;
1033
+ }
1034
+ function formatZoom(zoom) {
1035
+ return `Zoom: ${zoom.toFixed(1)}`;
1036
+ }
1037
+ function formatBearing(bearing) {
1038
+ const normalized = (bearing % 360 + 360) % 360;
1039
+ let direction;
1040
+ if (normalized >= 337.5 || normalized < 22.5) {
1041
+ direction = "N";
1042
+ } else if (normalized >= 22.5 && normalized < 67.5) {
1043
+ direction = "NE";
1044
+ } else if (normalized >= 67.5 && normalized < 112.5) {
1045
+ direction = "E";
1046
+ } else if (normalized >= 112.5 && normalized < 157.5) {
1047
+ direction = "SE";
1048
+ } else if (normalized >= 157.5 && normalized < 202.5) {
1049
+ direction = "S";
1050
+ } else if (normalized >= 202.5 && normalized < 247.5) {
1051
+ direction = "SW";
1052
+ } else if (normalized >= 247.5 && normalized < 292.5) {
1053
+ direction = "W";
1054
+ } else {
1055
+ direction = "NW";
1056
+ }
1057
+ return `${Math.round(normalized)}\xB0 ${direction}`;
1058
+ }
1059
+ function formatPitch(pitch) {
1060
+ return `${Math.round(pitch)}\xB0 tilt`;
1061
+ }
1062
+ function formatScale(scale) {
1063
+ if (scale >= 1e6) {
1064
+ return `1:${(scale / 1e6).toFixed(1)}M`;
1065
+ }
1066
+ if (scale >= 1e3) {
1067
+ return `1:${Math.round(scale / 1e3)}K`;
1068
+ }
1069
+ return `1:${Math.round(scale)}`;
1070
+ }
1071
+ function zoomToScale(zoom, latitude = 0) {
1072
+ const metersPerPixel = 40075e3 * Math.cos(latitude * Math.PI / 180) / (256 * Math.pow(2, zoom));
1073
+ const screenMetersPerPixel = 264583e-9;
1074
+ return Math.round(metersPerPixel / screenMetersPerPixel);
1075
+ }
1076
+ function formatPropertyValue(value) {
1077
+ if (value === null || value === void 0) {
1078
+ return "-";
1079
+ }
1080
+ if (typeof value === "number") {
1081
+ if (Math.abs(value) <= 180 && value !== Math.floor(value)) {
1082
+ return value.toFixed(6);
1083
+ }
1084
+ if (Math.abs(value) >= 1e3) {
1085
+ return value.toLocaleString();
1086
+ }
1087
+ if (value !== Math.floor(value)) {
1088
+ return value.toFixed(2);
1089
+ }
1090
+ return String(value);
1091
+ }
1092
+ if (typeof value === "boolean") {
1093
+ return value ? "Yes" : "No";
1094
+ }
1095
+ if (Array.isArray(value)) {
1096
+ return value.map(formatPropertyValue).join(", ");
1097
+ }
1098
+ if (typeof value === "object") {
1099
+ return JSON.stringify(value);
1100
+ }
1101
+ return String(value);
1102
+ }
1103
+ function formatFeatureProperties(properties, options) {
1104
+ const exclude = options?.exclude || ["id", "_id", "fid", "ogc_fid"];
1105
+ const include = options?.include;
1106
+ const labelMap = options?.labelMap || {};
1107
+ const entries = Object.entries(properties).filter(([key]) => {
1108
+ if (include) {
1109
+ return include.includes(key);
1110
+ }
1111
+ return !exclude.includes(key) && !key.startsWith("_");
1112
+ }).map(([key, value]) => {
1113
+ const label = labelMap[key] || formatLabel(key);
1114
+ return `<strong>${label}:</strong> ${formatPropertyValue(value)}`;
1115
+ });
1116
+ return entries.join("<br>");
1117
+ }
1118
+ function formatLabel(key) {
1119
+ return key.replace(/_/g, " ").replace(/([a-z])([A-Z])/g, "$1 $2").replace(/\b\w/g, (char) => char.toUpperCase());
1120
+ }
1121
+
1122
+ // src/utils/bounds.ts
1123
+ function calculateBounds(geojson) {
1124
+ let minLng = Infinity;
1125
+ let maxLng = -Infinity;
1126
+ let minLat = Infinity;
1127
+ let maxLat = -Infinity;
1128
+ let hasCoordinates = false;
1129
+ function processCoordinate(coord) {
1130
+ const [lng, lat] = coord;
1131
+ if (typeof lng === "number" && typeof lat === "number" && isFinite(lng) && isFinite(lat)) {
1132
+ minLng = Math.min(minLng, lng);
1133
+ maxLng = Math.max(maxLng, lng);
1134
+ minLat = Math.min(minLat, lat);
1135
+ maxLat = Math.max(maxLat, lat);
1136
+ hasCoordinates = true;
1137
+ }
1138
+ }
1139
+ function processGeometry(geometry) {
1140
+ if (!geometry) return;
1141
+ switch (geometry.type) {
1142
+ case "Point":
1143
+ processCoordinate(geometry.coordinates);
1144
+ break;
1145
+ case "MultiPoint":
1146
+ case "LineString":
1147
+ geometry.coordinates.forEach(processCoordinate);
1148
+ break;
1149
+ case "MultiLineString":
1150
+ case "Polygon":
1151
+ geometry.coordinates.forEach((ring) => ring.forEach(processCoordinate));
1152
+ break;
1153
+ case "MultiPolygon":
1154
+ geometry.coordinates.forEach(
1155
+ (polygon) => polygon.forEach((ring) => ring.forEach(processCoordinate))
1156
+ );
1157
+ break;
1158
+ }
1159
+ }
1160
+ if (geojson.type === "FeatureCollection") {
1161
+ geojson.features.forEach((feature) => processGeometry(feature.geometry));
1162
+ } else if (geojson.type === "Feature") {
1163
+ processGeometry(geojson.geometry);
1164
+ }
1165
+ if (!hasCoordinates) {
1166
+ return null;
1167
+ }
1168
+ return [
1169
+ [minLng, minLat],
1170
+ // Southwest
1171
+ [maxLng, maxLat]
1172
+ // Northeast
1173
+ ];
1174
+ }
1175
+ function extendBounds(bounds, point) {
1176
+ const [[swLng, swLat], [neLng, neLat]] = bounds;
1177
+ const [lng, lat] = point;
1178
+ return [
1179
+ [Math.min(swLng, lng), Math.min(swLat, lat)],
1180
+ [Math.max(neLng, lng), Math.max(neLat, lat)]
1181
+ ];
1182
+ }
1183
+ function combineBounds(bounds1, bounds2) {
1184
+ const [[sw1Lng, sw1Lat], [ne1Lng, ne1Lat]] = bounds1;
1185
+ const [[sw2Lng, sw2Lat], [ne2Lng, ne2Lat]] = bounds2;
1186
+ return [
1187
+ [Math.min(sw1Lng, sw2Lng), Math.min(sw1Lat, sw2Lat)],
1188
+ [Math.max(ne1Lng, ne2Lng), Math.max(ne1Lat, ne2Lat)]
1189
+ ];
1190
+ }
1191
+ function isValidBounds(bounds) {
1192
+ if (!Array.isArray(bounds) || bounds.length !== 2) {
1193
+ return false;
1194
+ }
1195
+ const [sw, ne] = bounds;
1196
+ if (!Array.isArray(sw) || sw.length !== 2 || !Array.isArray(ne) || ne.length !== 2) {
1197
+ return false;
1198
+ }
1199
+ const [swLng, swLat] = sw;
1200
+ const [neLng, neLat] = ne;
1201
+ if (typeof swLng !== "number" || typeof swLat !== "number" || typeof neLng !== "number" || typeof neLat !== "number" || !isFinite(swLng) || !isFinite(swLat) || !isFinite(neLng) || !isFinite(neLat)) {
1202
+ return false;
1203
+ }
1204
+ if (swLat > neLat) {
1205
+ return false;
1206
+ }
1207
+ if (swLat < -90 || swLat > 90 || neLat < -90 || neLat > 90) {
1208
+ return false;
1209
+ }
1210
+ if (swLng < -180 || swLng > 180 || neLng < -180 || neLng > 180) {
1211
+ return false;
1212
+ }
1213
+ return true;
1214
+ }
1215
+
1216
+ // src/utils/data.ts
1217
+ async function loadGeoJSON(url, options = {}) {
1218
+ const { timeout = 3e4, fetchOptions = {}, validate = true } = options;
1219
+ try {
1220
+ const controller = new AbortController();
1221
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1222
+ const response = await fetch(url, {
1223
+ ...fetchOptions,
1224
+ signal: controller.signal,
1225
+ headers: {
1226
+ Accept: "application/geo+json, application/json",
1227
+ ...fetchOptions.headers
1228
+ }
1229
+ });
1230
+ clearTimeout(timeoutId);
1231
+ if (!response.ok) {
1232
+ return {
1233
+ data: null,
1234
+ error: `HTTP ${response.status}: ${response.statusText}`,
1235
+ success: false
1236
+ };
1237
+ }
1238
+ const data = await response.json();
1239
+ if (validate) {
1240
+ const validation = validateGeoJSON(data);
1241
+ if (!validation.valid) {
1242
+ return {
1243
+ data: null,
1244
+ error: `Invalid GeoJSON: ${validation.errors.join(", ")}`,
1245
+ success: false
1246
+ };
1247
+ }
1248
+ }
1249
+ return {
1250
+ data,
1251
+ error: null,
1252
+ success: true
1253
+ };
1254
+ } catch (err) {
1255
+ if (err instanceof Error) {
1256
+ if (err.name === "AbortError") {
1257
+ return {
1258
+ data: null,
1259
+ error: `Request timeout after ${timeout}ms`,
1260
+ success: false
1261
+ };
1262
+ }
1263
+ return {
1264
+ data: null,
1265
+ error: err.message,
1266
+ success: false
1267
+ };
1268
+ }
1269
+ return {
1270
+ data: null,
1271
+ error: "Unknown error loading GeoJSON",
1272
+ success: false
1273
+ };
1274
+ }
1275
+ }
1276
+ function validateGeoJSON(data) {
1277
+ const errors = [];
1278
+ const geometryTypes = /* @__PURE__ */ new Set();
1279
+ let featureCount = 0;
1280
+ if (!data || typeof data !== "object") {
1281
+ return {
1282
+ valid: false,
1283
+ errors: ["Data must be an object"]
1284
+ };
1285
+ }
1286
+ const obj = data;
1287
+ if (!obj.type) {
1288
+ errors.push('Missing "type" property');
1289
+ return { valid: false, errors };
1290
+ }
1291
+ if (obj.type === "FeatureCollection") {
1292
+ if (!Array.isArray(obj.features)) {
1293
+ errors.push('"features" must be an array');
1294
+ return { valid: false, errors };
1295
+ }
1296
+ featureCount = obj.features.length;
1297
+ for (let i = 0; i < obj.features.length; i++) {
1298
+ const feature = obj.features[i];
1299
+ const featureErrors = validateFeature(feature, i);
1300
+ errors.push(...featureErrors.errors);
1301
+ if (feature && typeof feature === "object" && feature.geometry) {
1302
+ const geom = feature.geometry;
1303
+ if (geom && geom.type) {
1304
+ geometryTypes.add(geom.type);
1305
+ }
1306
+ }
1307
+ }
1308
+ } else if (obj.type === "Feature") {
1309
+ const featureErrors = validateFeature(obj, 0);
1310
+ errors.push(...featureErrors.errors);
1311
+ featureCount = 1;
1312
+ if (obj.geometry && typeof obj.geometry === "object") {
1313
+ const geom = obj.geometry;
1314
+ if (geom.type) {
1315
+ geometryTypes.add(geom.type);
1316
+ }
1317
+ }
1318
+ } else if (isGeometryType(obj.type)) {
1319
+ const geomErrors = validateGeometry(obj);
1320
+ errors.push(...geomErrors);
1321
+ geometryTypes.add(obj.type);
1322
+ } else {
1323
+ errors.push(`Unknown GeoJSON type: "${obj.type}"`);
1324
+ }
1325
+ return {
1326
+ valid: errors.length === 0,
1327
+ errors,
1328
+ featureCount,
1329
+ geometryTypes: Array.from(geometryTypes)
1330
+ };
1331
+ }
1332
+ function validateFeature(feature, index) {
1333
+ const errors = [];
1334
+ const prefix = `Feature[${index}]`;
1335
+ if (!feature || typeof feature !== "object") {
1336
+ errors.push(`${prefix}: must be an object`);
1337
+ return { valid: false, errors };
1338
+ }
1339
+ const f = feature;
1340
+ if (f.type !== "Feature") {
1341
+ errors.push(`${prefix}: type must be "Feature"`);
1342
+ }
1343
+ if (f.geometry !== null && f.geometry !== void 0) {
1344
+ if (typeof f.geometry !== "object") {
1345
+ errors.push(`${prefix}: geometry must be an object or null`);
1346
+ } else {
1347
+ const geomErrors = validateGeometry(f.geometry, prefix);
1348
+ errors.push(...geomErrors);
1349
+ }
1350
+ }
1351
+ if (f.properties !== null && f.properties !== void 0) {
1352
+ if (typeof f.properties !== "object") {
1353
+ errors.push(`${prefix}: properties must be an object or null`);
1354
+ }
1355
+ }
1356
+ return { valid: errors.length === 0, errors };
1357
+ }
1358
+ function validateGeometry(geometry, prefix = "") {
1359
+ const errors = [];
1360
+ const p = prefix ? `${prefix}.geometry` : "Geometry";
1361
+ if (!geometry || typeof geometry !== "object") {
1362
+ errors.push(`${p}: must be an object`);
1363
+ return errors;
1364
+ }
1365
+ if (!geometry.type) {
1366
+ errors.push(`${p}: missing type`);
1367
+ return errors;
1368
+ }
1369
+ if (!isGeometryType(geometry.type)) {
1370
+ errors.push(`${p}: unknown geometry type "${geometry.type}"`);
1371
+ return errors;
1372
+ }
1373
+ if (!geometry.coordinates) {
1374
+ errors.push(`${p}: missing coordinates`);
1375
+ return errors;
1376
+ }
1377
+ if (!Array.isArray(geometry.coordinates)) {
1378
+ errors.push(`${p}: coordinates must be an array`);
1379
+ return errors;
1380
+ }
1381
+ switch (geometry.type) {
1382
+ case "Point":
1383
+ if (!isValidPosition(geometry.coordinates)) {
1384
+ errors.push(`${p}: invalid Point coordinates`);
1385
+ }
1386
+ break;
1387
+ case "MultiPoint":
1388
+ case "LineString":
1389
+ if (!Array.isArray(geometry.coordinates) || geometry.coordinates.length === 0) {
1390
+ errors.push(`${p}: ${geometry.type} must have at least one position`);
1391
+ }
1392
+ break;
1393
+ case "Polygon":
1394
+ case "MultiLineString":
1395
+ if (!Array.isArray(geometry.coordinates) || geometry.coordinates.length === 0) {
1396
+ errors.push(`${p}: ${geometry.type} must have at least one ring/line`);
1397
+ }
1398
+ break;
1399
+ case "MultiPolygon":
1400
+ if (!Array.isArray(geometry.coordinates) || geometry.coordinates.length === 0) {
1401
+ errors.push(`${p}: MultiPolygon must have at least one polygon`);
1402
+ }
1403
+ break;
1404
+ }
1405
+ return errors;
1406
+ }
1407
+ function isGeometryType(type) {
1408
+ return [
1409
+ "Point",
1410
+ "MultiPoint",
1411
+ "LineString",
1412
+ "MultiLineString",
1413
+ "Polygon",
1414
+ "MultiPolygon",
1415
+ "GeometryCollection"
1416
+ ].includes(type);
1417
+ }
1418
+ function isValidPosition(position) {
1419
+ if (!Array.isArray(position)) return false;
1420
+ if (position.length < 2 || position.length > 3) return false;
1421
+ return position.every((coord) => typeof coord === "number" && isFinite(coord));
1422
+ }
1423
+ function calculateCentroid(geojson) {
1424
+ const coords = [];
1425
+ function collectCoordinates(geometry) {
1426
+ if (!geometry) return;
1427
+ switch (geometry.type) {
1428
+ case "Point":
1429
+ coords.push(geometry.coordinates);
1430
+ break;
1431
+ case "MultiPoint":
1432
+ case "LineString":
1433
+ geometry.coordinates.forEach((c) => coords.push(c));
1434
+ break;
1435
+ case "MultiLineString":
1436
+ case "Polygon":
1437
+ geometry.coordinates.forEach(
1438
+ (ring) => ring.forEach((c) => coords.push(c))
1439
+ );
1440
+ break;
1441
+ case "MultiPolygon":
1442
+ geometry.coordinates.forEach(
1443
+ (polygon) => polygon.forEach((ring) => ring.forEach((c) => coords.push(c)))
1444
+ );
1445
+ break;
1446
+ }
1447
+ }
1448
+ if (geojson.type === "FeatureCollection") {
1449
+ geojson.features.forEach((f) => collectCoordinates(f.geometry));
1450
+ } else if (geojson.type === "Feature") {
1451
+ collectCoordinates(geojson.geometry);
1452
+ }
1453
+ if (coords.length === 0) return null;
1454
+ const sum = coords.reduce((acc, [lng, lat]) => [acc[0] + lng, acc[1] + lat], [0, 0]);
1455
+ return [sum[0] / coords.length, sum[1] / coords.length];
1456
+ }
1457
+ function countFeaturesByType(geojson) {
1458
+ const counts = {};
1459
+ geojson.features.forEach((feature) => {
1460
+ const type = feature.geometry?.type || "null";
1461
+ counts[type] = (counts[type] || 0) + 1;
1462
+ });
1463
+ return counts;
1464
+ }
1465
+ function filterByGeometryType(geojson, types) {
1466
+ return {
1467
+ type: "FeatureCollection",
1468
+ features: geojson.features.filter((f) => f.geometry && types.includes(f.geometry.type))
1469
+ };
1470
+ }
1471
+
1472
+ // src/utils/positioning.ts
1473
+ var BASE_OFFSET = 8;
1474
+ var POSITION_CLASSES = {
1475
+ "top-left": "top-2 left-2",
1476
+ "top-right": "top-2 right-2",
1477
+ "bottom-left": "bottom-2 left-2",
1478
+ "bottom-right": "bottom-2 right-2"
1479
+ };
1480
+ var OFFSET_CLASSES = {
1481
+ "top-left": "left-14",
1482
+ // Offset right (toward center)
1483
+ "top-right": "right-14",
1484
+ // Offset left (toward center)
1485
+ "bottom-left": "left-14",
1486
+ // Offset right (toward center)
1487
+ "bottom-right": "right-14"
1488
+ // Offset left (toward center)
1489
+ };
1490
+ function computePositionClasses(position, hasControlsAtPosition) {
1491
+ const base = POSITION_CLASSES[position];
1492
+ if (!hasControlsAtPosition) {
1493
+ return base;
1494
+ }
1495
+ const offset = OFFSET_CLASSES[position];
1496
+ if (position.includes("left")) {
1497
+ return base.replace("left-2", offset);
1498
+ }
1499
+ if (position.includes("right")) {
1500
+ return base.replace("right-2", offset);
1501
+ }
1502
+ return base;
1503
+ }
1504
+ function computeVerticalOffsetStyle(position, customControlOffset, baseOffset = BASE_OFFSET) {
1505
+ if (customControlOffset <= 0) {
1506
+ return {};
1507
+ }
1508
+ const totalOffset = `${baseOffset + customControlOffset}px`;
1509
+ if (position.includes("top")) {
1510
+ return { top: totalOffset };
1511
+ }
1512
+ return { bottom: totalOffset };
1513
+ }
1514
+
1515
+ // src/utils/cluster.ts
1516
+ function isClusterFeature(feature) {
1517
+ return feature.properties !== null && feature.properties !== void 0 && typeof feature.properties === "object" && "cluster_id" in feature.properties && "point_count" in feature.properties;
1518
+ }
1519
+ async function getClusterExpansionZoom(map, sourceId, clusterId) {
1520
+ const source = map.getSource(sourceId);
1521
+ if (!source) {
1522
+ throw new Error(`Source "${sourceId}" not found`);
1523
+ }
1524
+ if (typeof source.getClusterExpansionZoom !== "function") {
1525
+ throw new Error(`Source "${sourceId}" does not support clustering`);
1526
+ }
1527
+ return source.getClusterExpansionZoom(clusterId);
1528
+ }
1529
+ async function getClusterChildren(map, sourceId, clusterId) {
1530
+ const source = map.getSource(sourceId);
1531
+ if (!source) {
1532
+ throw new Error(`Source "${sourceId}" not found`);
1533
+ }
1534
+ if (typeof source.getClusterChildren !== "function") {
1535
+ throw new Error(`Source "${sourceId}" does not support clustering`);
1536
+ }
1537
+ return source.getClusterChildren(clusterId);
1538
+ }
1539
+ async function getClusterLeaves(map, sourceId, clusterId, limit = 100, offset = 0) {
1540
+ const source = map.getSource(sourceId);
1541
+ if (!source) {
1542
+ throw new Error(`Source "${sourceId}" not found`);
1543
+ }
1544
+ if (typeof source.getClusterLeaves !== "function") {
1545
+ throw new Error(`Source "${sourceId}" does not support clustering`);
1546
+ }
1547
+ return source.getClusterLeaves(clusterId, limit, offset);
1548
+ }
1549
+ async function expandCluster(map, sourceId, clusterId, center, options = {}) {
1550
+ const { duration = 500, animate = true, padding, maxZoom } = options;
1551
+ const expansionZoom = await getClusterExpansionZoom(map, sourceId, clusterId);
1552
+ const targetZoom = maxZoom !== void 0 ? Math.min(expansionZoom, maxZoom) : expansionZoom;
1553
+ if (map.getZoom() < targetZoom) {
1554
+ map.easeTo({
1555
+ center,
1556
+ zoom: targetZoom,
1557
+ duration: animate ? duration : 0,
1558
+ animate,
1559
+ ...padding !== void 0 && { padding }
1560
+ });
1561
+ }
1562
+ }
1563
+ async function getClusterBounds(map, sourceId, clusterId, limit = 1e3) {
1564
+ const leaves = await getClusterLeaves(map, sourceId, clusterId, limit);
1565
+ if (leaves.length === 0) {
1566
+ throw new Error("Cluster has no leaves");
1567
+ }
1568
+ let minLng = Infinity;
1569
+ let minLat = Infinity;
1570
+ let maxLng = -Infinity;
1571
+ let maxLat = -Infinity;
1572
+ for (const leaf of leaves) {
1573
+ if (leaf.geometry.type === "Point") {
1574
+ const [lng, lat] = leaf.geometry.coordinates;
1575
+ minLng = Math.min(minLng, lng);
1576
+ minLat = Math.min(minLat, lat);
1577
+ maxLng = Math.max(maxLng, lng);
1578
+ maxLat = Math.max(maxLat, lat);
1579
+ }
1580
+ }
1581
+ return [
1582
+ [minLng, minLat],
1583
+ [maxLng, maxLat]
1584
+ ];
1585
+ }
1586
+ async function expandClusterToBounds(map, sourceId, clusterId, options = {}) {
1587
+ const { duration = 500, animate = true, padding = 50, maxZoom } = options;
1588
+ const bounds = await getClusterBounds(map, sourceId, clusterId);
1589
+ map.fitBounds(bounds, {
1590
+ padding,
1591
+ duration: animate ? duration : 0,
1592
+ animate,
1593
+ ...maxZoom !== void 0 && { maxZoom }
1594
+ });
1595
+ }
1596
+
1597
+ // src/utils/lod.ts
1598
+ function groupFeaturesByProperty(geojson, options) {
1599
+ const { groupBy, subGroupBy } = options;
1600
+ const groups = /* @__PURE__ */ new Map();
1601
+ for (const feature of geojson.features) {
1602
+ const groupValue = String(feature.properties?.[groupBy] ?? "unknown");
1603
+ if (!groups.has(groupValue)) {
1604
+ groups.set(groupValue, {
1605
+ id: groupValue,
1606
+ features: [],
1607
+ bounds: null,
1608
+ centroid: null,
1609
+ count: 0,
1610
+ subGroups: subGroupBy ? /* @__PURE__ */ new Map() : void 0
1611
+ });
1612
+ }
1613
+ const group = groups.get(groupValue);
1614
+ group.features.push(feature);
1615
+ group.count++;
1616
+ if (subGroupBy && group.subGroups) {
1617
+ const subGroupValue = String(feature.properties?.[subGroupBy] ?? "unknown");
1618
+ if (!group.subGroups.has(subGroupValue)) {
1619
+ group.subGroups.set(subGroupValue, {
1620
+ id: subGroupValue,
1621
+ features: [],
1622
+ bounds: null,
1623
+ centroid: null,
1624
+ count: 0
1625
+ });
1626
+ }
1627
+ const subGroup = group.subGroups.get(subGroupValue);
1628
+ subGroup.features.push(feature);
1629
+ subGroup.count++;
1630
+ }
1631
+ }
1632
+ for (const group of groups.values()) {
1633
+ const groupCollection = {
1634
+ type: "FeatureCollection",
1635
+ features: group.features
1636
+ };
1637
+ group.bounds = calculateBounds(groupCollection);
1638
+ group.centroid = group.bounds ? calculateCentroidFromBounds(group.bounds) : null;
1639
+ if (group.subGroups) {
1640
+ for (const subGroup of group.subGroups.values()) {
1641
+ const subGroupCollection = {
1642
+ type: "FeatureCollection",
1643
+ features: subGroup.features
1644
+ };
1645
+ subGroup.bounds = calculateBounds(subGroupCollection);
1646
+ subGroup.centroid = subGroup.bounds ? calculateCentroidFromBounds(subGroup.bounds) : null;
1647
+ }
1648
+ }
1649
+ }
1650
+ return groups;
1651
+ }
1652
+ function calculateCentroidFromBounds(bounds) {
1653
+ const [[swLng, swLat], [neLng, neLat]] = bounds;
1654
+ return [(swLng + neLng) / 2, (swLat + neLat) / 2];
1655
+ }
1656
+ function generateConvexHull(features) {
1657
+ const points = [];
1658
+ for (const feature of features) {
1659
+ if (feature.geometry?.type === "Polygon") {
1660
+ const exteriorRing = feature.geometry.coordinates[0];
1661
+ points.push(...exteriorRing);
1662
+ } else if (feature.geometry?.type === "MultiPolygon") {
1663
+ for (const polygon of feature.geometry.coordinates) {
1664
+ points.push(...polygon[0]);
1665
+ }
1666
+ } else if (feature.geometry?.type === "Point") {
1667
+ points.push(feature.geometry.coordinates);
1668
+ }
1669
+ }
1670
+ if (points.length < 3) {
1671
+ return null;
1672
+ }
1673
+ const hull = convexHull(points);
1674
+ if (hull.length < 3) {
1675
+ return null;
1676
+ }
1677
+ const closedHull = [...hull, hull[0]];
1678
+ return {
1679
+ type: "Polygon",
1680
+ coordinates: [closedHull]
1681
+ };
1682
+ }
1683
+ function convexHull(points) {
1684
+ if (points.length < 3) return points;
1685
+ let leftmost = 0;
1686
+ for (let i = 1; i < points.length; i++) {
1687
+ if (points[i][0] < points[leftmost][0]) {
1688
+ leftmost = i;
1689
+ }
1690
+ }
1691
+ const hull = [];
1692
+ let current = leftmost;
1693
+ let iterations = 0;
1694
+ const maxIterations = points.length * 2;
1695
+ do {
1696
+ hull.push(points[current]);
1697
+ let next = 0;
1698
+ for (let i = 1; i < points.length; i++) {
1699
+ if (next === current || crossProduct(points[current], points[next], points[i]) < 0) {
1700
+ next = i;
1701
+ }
1702
+ }
1703
+ current = next;
1704
+ iterations++;
1705
+ } while (current !== leftmost && iterations < maxIterations);
1706
+ return hull;
1707
+ }
1708
+ function crossProduct(o, a, b) {
1709
+ return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
1710
+ }
1711
+ function generateBoundingPolygon(features, padding = 0) {
1712
+ const collection = {
1713
+ type: "FeatureCollection",
1714
+ features
1715
+ };
1716
+ const bounds = calculateBounds(collection);
1717
+ if (!bounds) return null;
1718
+ return boundsToPolygon(bounds, padding);
1719
+ }
1720
+ function boundsToPolygon(bounds, padding = 0) {
1721
+ const [[swLng, swLat], [neLng, neLat]] = bounds;
1722
+ const minLng = swLng - padding;
1723
+ const minLat = swLat - padding;
1724
+ const maxLng = neLng + padding;
1725
+ const maxLat = neLat + padding;
1726
+ return {
1727
+ type: "Polygon",
1728
+ coordinates: [
1729
+ [
1730
+ [minLng, minLat],
1731
+ // SW
1732
+ [maxLng, minLat],
1733
+ // SE
1734
+ [maxLng, maxLat],
1735
+ // NE
1736
+ [minLng, maxLat],
1737
+ // NW
1738
+ [minLng, minLat]
1739
+ // Close
1740
+ ]
1741
+ ]
1742
+ };
1743
+ }
1744
+ function perpendicularDistance(point, lineStart, lineEnd) {
1745
+ const dx = lineEnd[0] - lineStart[0];
1746
+ const dy = lineEnd[1] - lineStart[1];
1747
+ const lineLengthSquared = dx * dx + dy * dy;
1748
+ if (lineLengthSquared === 0) {
1749
+ const pdx = point[0] - lineStart[0];
1750
+ const pdy = point[1] - lineStart[1];
1751
+ return Math.sqrt(pdx * pdx + pdy * pdy);
1752
+ }
1753
+ const numerator = Math.abs(
1754
+ dy * point[0] - dx * point[1] + lineEnd[0] * lineStart[1] - lineEnd[1] * lineStart[0]
1755
+ );
1756
+ const denominator = Math.sqrt(lineLengthSquared);
1757
+ return numerator / denominator;
1758
+ }
1759
+ function douglasPeuckerSimplify(points, tolerance) {
1760
+ if (points.length <= 2) {
1761
+ return points;
1762
+ }
1763
+ let maxDistance = 0;
1764
+ let maxIndex = 0;
1765
+ const first = points[0];
1766
+ const last = points[points.length - 1];
1767
+ for (let i = 1; i < points.length - 1; i++) {
1768
+ const distance = perpendicularDistance(points[i], first, last);
1769
+ if (distance > maxDistance) {
1770
+ maxDistance = distance;
1771
+ maxIndex = i;
1772
+ }
1773
+ }
1774
+ if (maxDistance > tolerance) {
1775
+ const leftPoints = douglasPeuckerSimplify(points.slice(0, maxIndex + 1), tolerance);
1776
+ const rightPoints = douglasPeuckerSimplify(points.slice(maxIndex), tolerance);
1777
+ return leftPoints.slice(0, -1).concat(rightPoints);
1778
+ } else {
1779
+ return [first, last];
1780
+ }
1781
+ }
1782
+ function simplifyRing(ring, tolerance) {
1783
+ if (ring.length < 4) {
1784
+ return ring;
1785
+ }
1786
+ const openRing = ring.slice(0, -1);
1787
+ const simplified = douglasPeuckerSimplify(openRing, tolerance);
1788
+ if (simplified.length < 3) {
1789
+ return ring;
1790
+ }
1791
+ return [...simplified, simplified[0]];
1792
+ }
1793
+ function simplifyPolygon(polygon, tolerance) {
1794
+ const simplifiedCoords = polygon.coordinates.map((ring) => simplifyRing(ring, tolerance));
1795
+ return {
1796
+ type: "Polygon",
1797
+ coordinates: simplifiedCoords
1798
+ };
1799
+ }
1800
+ function simplifyFeature(feature, tolerance) {
1801
+ if (!feature.geometry) {
1802
+ return feature;
1803
+ }
1804
+ switch (feature.geometry.type) {
1805
+ case "Point":
1806
+ case "MultiPoint":
1807
+ case "LineString":
1808
+ case "MultiLineString":
1809
+ return feature;
1810
+ case "Polygon":
1811
+ return {
1812
+ ...feature,
1813
+ geometry: simplifyPolygon(feature.geometry, tolerance)
1814
+ };
1815
+ case "MultiPolygon": {
1816
+ const multiPolygon = feature.geometry;
1817
+ const simplifiedPolygons = multiPolygon.coordinates.map((polygonCoords) => {
1818
+ return polygonCoords.map((ring) => simplifyRing(ring, tolerance));
1819
+ });
1820
+ return {
1821
+ ...feature,
1822
+ geometry: {
1823
+ type: "MultiPolygon",
1824
+ coordinates: simplifiedPolygons
1825
+ }
1826
+ };
1827
+ }
1828
+ default:
1829
+ return feature;
1830
+ }
1831
+ }
1832
+ function simplifyFeatureCollection(collection, tolerance) {
1833
+ return {
1834
+ type: "FeatureCollection",
1835
+ features: collection.features.map((f) => simplifyFeature(f, tolerance))
1836
+ };
1837
+ }
1838
+ function countVertices(collection) {
1839
+ let count = 0;
1840
+ for (const feature of collection.features) {
1841
+ if (!feature.geometry) continue;
1842
+ switch (feature.geometry.type) {
1843
+ case "Point":
1844
+ count += 1;
1845
+ break;
1846
+ case "MultiPoint":
1847
+ case "LineString":
1848
+ count += feature.geometry.coordinates.length;
1849
+ break;
1850
+ case "MultiLineString":
1851
+ case "Polygon":
1852
+ for (const ring of feature.geometry.coordinates) {
1853
+ count += ring.length;
1854
+ }
1855
+ break;
1856
+ case "MultiPolygon":
1857
+ for (const polygon of feature.geometry.coordinates) {
1858
+ for (const ring of polygon) {
1859
+ count += ring.length;
1860
+ }
1861
+ }
1862
+ break;
1863
+ }
1864
+ }
1865
+ return count;
1866
+ }
1867
+ function simplifyFeatureCollectionWithStats(collection, tolerance) {
1868
+ const originalVertices = countVertices(collection);
1869
+ const simplified = simplifyFeatureCollection(collection, tolerance);
1870
+ const simplifiedVertices = countVertices(simplified);
1871
+ const reductionPercent = originalVertices > 0 ? (originalVertices - simplifiedVertices) / originalVertices * 100 : 0;
1872
+ return {
1873
+ data: simplified,
1874
+ stats: {
1875
+ originalVertices,
1876
+ simplifiedVertices,
1877
+ reductionPercent,
1878
+ featureCount: collection.features.length
1879
+ }
1880
+ };
1881
+ }
1882
+ function generateLODData(geojson, options) {
1883
+ const {
1884
+ groupBy,
1885
+ subGroupBy,
1886
+ groupBoundaries: providedGroupBoundaries,
1887
+ subGroupBoundaries: providedSubGroupBoundaries,
1888
+ useConvexHull = true,
1889
+ boundaryPadding = 1e-4,
1890
+ aggregateProperties = []
1891
+ } = options;
1892
+ const groups = groupFeaturesByProperty(geojson, { groupBy, subGroupBy });
1893
+ const groupBoundaryFeatures = [];
1894
+ for (const [groupId, group] of groups) {
1895
+ let geometry = providedGroupBoundaries?.get(groupId) ?? null;
1896
+ if (!geometry) {
1897
+ geometry = useConvexHull ? generateConvexHull(group.features) : generateBoundingPolygon(group.features, boundaryPadding);
1898
+ }
1899
+ if (geometry) {
1900
+ const aggregated = {};
1901
+ for (const prop of aggregateProperties) {
1902
+ const values = group.features.map((f) => f.properties?.[prop]).filter((v) => v !== void 0);
1903
+ if (values.length > 0) {
1904
+ if (typeof values[0] === "number") {
1905
+ aggregated[prop] = values.reduce((a, b) => a + b, 0);
1906
+ } else {
1907
+ aggregated[`${prop}Count`] = new Set(values).size;
1908
+ }
1909
+ }
1910
+ }
1911
+ groupBoundaryFeatures.push({
1912
+ type: "Feature",
1913
+ properties: {
1914
+ [groupBy]: groupId,
1915
+ lotCount: group.count,
1916
+ ...aggregated
1917
+ },
1918
+ geometry
1919
+ });
1920
+ }
1921
+ }
1922
+ let subGroupBoundaryFeatures = null;
1923
+ if (subGroupBy) {
1924
+ subGroupBoundaryFeatures = [];
1925
+ for (const [groupId, group] of groups) {
1926
+ if (group.subGroups) {
1927
+ for (const [subGroupId, subGroup] of group.subGroups) {
1928
+ const boundaryKey = `${groupId}:${subGroupId}`;
1929
+ let geometry = providedSubGroupBoundaries?.get(boundaryKey) ?? null;
1930
+ if (!geometry) {
1931
+ geometry = useConvexHull ? generateConvexHull(subGroup.features) : generateBoundingPolygon(subGroup.features, boundaryPadding);
1932
+ }
1933
+ if (geometry) {
1934
+ const aggregated = {};
1935
+ for (const prop of aggregateProperties) {
1936
+ const values = subGroup.features.map((f) => f.properties?.[prop]).filter((v) => v !== void 0);
1937
+ if (values.length > 0) {
1938
+ if (typeof values[0] === "number") {
1939
+ aggregated[prop] = values.reduce((a, b) => a + b, 0);
1940
+ } else {
1941
+ aggregated[`${prop}Count`] = new Set(values).size;
1942
+ }
1943
+ }
1944
+ }
1945
+ subGroupBoundaryFeatures.push({
1946
+ type: "Feature",
1947
+ properties: {
1948
+ [groupBy]: groupId,
1949
+ [subGroupBy]: subGroupId,
1950
+ lotCount: subGroup.count,
1951
+ ...aggregated
1952
+ },
1953
+ geometry
1954
+ });
1955
+ }
1956
+ }
1957
+ }
1958
+ }
1959
+ }
1960
+ return {
1961
+ groupBoundaries: {
1962
+ type: "FeatureCollection",
1963
+ features: groupBoundaryFeatures
1964
+ },
1965
+ subGroupBoundaries: subGroupBoundaryFeatures ? {
1966
+ type: "FeatureCollection",
1967
+ features: subGroupBoundaryFeatures
1968
+ } : null,
1969
+ features: geojson,
1970
+ zoomThresholds: {
1971
+ groupMaxZoom: 12,
1972
+ subGroupMaxZoom: 14
1973
+ }
1974
+ };
1975
+ }
1976
+ function generateLODDataWithSimplification(geojson, options) {
1977
+ const baseLOD = generateLODData(geojson, options);
1978
+ const { simplificationThresholds } = options;
1979
+ if (!simplificationThresholds || simplificationThresholds.length === 0) {
1980
+ return baseLOD;
1981
+ }
1982
+ const sortedThresholds = [...simplificationThresholds].sort((a, b) => b.maxZoom - a.maxZoom);
1983
+ const simplifiedFeatures = /* @__PURE__ */ new Map();
1984
+ const simplificationStats = /* @__PURE__ */ new Map();
1985
+ for (const threshold of sortedThresholds) {
1986
+ const { data, stats } = simplifyFeatureCollectionWithStats(geojson, threshold.tolerance);
1987
+ simplifiedFeatures.set(threshold.maxZoom, data);
1988
+ simplificationStats.set(threshold.maxZoom, stats);
1989
+ }
1990
+ return {
1991
+ ...baseLOD,
1992
+ simplifiedFeatures,
1993
+ simplificationStats
1994
+ };
1995
+ }
1996
+ function getSimplifiedFeaturesForZoom(lodData, zoom) {
1997
+ if (!lodData.simplifiedFeatures || lodData.simplifiedFeatures.size === 0) {
1998
+ return lodData.features;
1999
+ }
2000
+ let bestMatch = null;
2001
+ for (const [maxZoom, features] of lodData.simplifiedFeatures) {
2002
+ if (zoom < maxZoom) {
2003
+ if (!bestMatch) {
2004
+ bestMatch = features;
2005
+ }
2006
+ }
2007
+ }
2008
+ return bestMatch ?? lodData.features;
2009
+ }
2010
+ function calculateZoomThresholds(groups, options = {}) {
2011
+ const { minZoomGap = 2 } = options;
2012
+ const groupCount = groups.size;
2013
+ let subGroupCount = 0;
2014
+ for (const group of groups.values()) {
2015
+ if (group.subGroups) {
2016
+ subGroupCount += group.subGroups.size;
2017
+ }
2018
+ }
2019
+ const groupMaxZoom = Math.max(10, Math.min(14, 10 + Math.log2(groupCount)));
2020
+ const subGroupMaxZoom = Math.max(
2021
+ groupMaxZoom + minZoomGap,
2022
+ Math.min(16, groupMaxZoom + Math.log2(Math.max(1, subGroupCount / groupCount)))
2023
+ );
2024
+ return {
2025
+ groupMaxZoom: Math.round(groupMaxZoom),
2026
+ subGroupMaxZoom: Math.round(subGroupMaxZoom)
2027
+ };
2028
+ }
2029
+ function createDynamicLODManager(options) {
2030
+ const {
2031
+ baseThresholds,
2032
+ targetFps = 50,
2033
+ adjustBelowFps = 40,
2034
+ maxAdjustment = 3,
2035
+ adjustmentStep = 0.5,
2036
+ smoothingFactor = 0.3,
2037
+ adjustmentCooldown = 1e3
2038
+ } = options;
2039
+ let averageFps = targetFps;
2040
+ let adjustment = 0;
2041
+ let lastAdjustmentTime = 0;
2042
+ function getState() {
2043
+ return {
2044
+ thresholds: {
2045
+ groupMaxZoom: baseThresholds.groupMaxZoom + adjustment,
2046
+ subGroupMaxZoom: baseThresholds.subGroupMaxZoom + adjustment
2047
+ },
2048
+ averageFps,
2049
+ adjustment,
2050
+ isAdjusted: adjustment > 0
2051
+ };
2052
+ }
2053
+ return {
2054
+ update(currentFps) {
2055
+ const now = performance.now();
2056
+ averageFps = smoothingFactor * currentFps + (1 - smoothingFactor) * averageFps;
2057
+ if (now - lastAdjustmentTime < adjustmentCooldown) {
2058
+ return getState();
2059
+ }
2060
+ if (averageFps < adjustBelowFps && adjustment < maxAdjustment) {
2061
+ const deficit = adjustBelowFps - averageFps;
2062
+ const newAdjustment = Math.min(
2063
+ maxAdjustment,
2064
+ adjustment + adjustmentStep * Math.ceil(deficit / 10)
2065
+ );
2066
+ if (newAdjustment !== adjustment) {
2067
+ adjustment = newAdjustment;
2068
+ lastAdjustmentTime = now;
2069
+ }
2070
+ } else if (averageFps >= targetFps && adjustment > 0) {
2071
+ const newAdjustment = Math.max(0, adjustment - adjustmentStep);
2072
+ if (newAdjustment !== adjustment) {
2073
+ adjustment = newAdjustment;
2074
+ lastAdjustmentTime = now;
2075
+ }
2076
+ }
2077
+ return getState();
2078
+ },
2079
+ reset() {
2080
+ averageFps = targetFps;
2081
+ adjustment = 0;
2082
+ lastAdjustmentTime = 0;
2083
+ return getState();
2084
+ },
2085
+ getState
2086
+ };
2087
+ }
2088
+ function getSimplificationToleranceForZoom(zoom, baseToleranceAtZoom14 = 2e-5) {
2089
+ const zoomDiff = Math.max(0, 14 - zoom);
2090
+ const multiplier = Math.pow(2, zoomDiff / 2);
2091
+ return baseToleranceAtZoom14 * multiplier;
2092
+ }
2093
+ var DEFAULT_SIMPLIFICATION_THRESHOLDS = [
2094
+ { maxZoom: 14, tolerance: 2e-5 },
2095
+ // Light: ~2m
2096
+ { maxZoom: 13, tolerance: 5e-5 },
2097
+ // Medium-light: ~5m
2098
+ { maxZoom: 12, tolerance: 1e-4 },
2099
+ // Medium: ~11m
2100
+ { maxZoom: 11, tolerance: 2e-4 },
2101
+ // Medium-heavy: ~22m
2102
+ { maxZoom: 10, tolerance: 5e-4 }
2103
+ // Heavy: ~55m
2104
+ ];
2105
+ function buildSpatialIndex(geojson, options = {}) {
2106
+ const { targetCells = 100, minCellSize = 1e-3 } = options;
2107
+ const bounds = calculateBounds(geojson);
2108
+ if (!bounds) {
2109
+ return {
2110
+ grid: /* @__PURE__ */ new Map(),
2111
+ cols: 0,
2112
+ rows: 0,
2113
+ bounds: [
2114
+ [0, 0],
2115
+ [0, 0]
2116
+ ],
2117
+ cellWidth: 0,
2118
+ cellHeight: 0,
2119
+ featureCount: 0
2120
+ };
2121
+ }
2122
+ const [[minLng, minLat], [maxLng, maxLat]] = bounds;
2123
+ const width = maxLng - minLng;
2124
+ const height = maxLat - minLat;
2125
+ const aspectRatio = width / height;
2126
+ let cols = Math.ceil(Math.sqrt(targetCells * aspectRatio));
2127
+ let rows = Math.ceil(targetCells / cols);
2128
+ const cellWidth = Math.max(width / cols, minCellSize);
2129
+ const cellHeight = Math.max(height / rows, minCellSize);
2130
+ cols = Math.ceil(width / cellWidth);
2131
+ rows = Math.ceil(height / cellHeight);
2132
+ const grid = /* @__PURE__ */ new Map();
2133
+ for (const feature of geojson.features) {
2134
+ const featureBounds = getFeatureBounds(feature);
2135
+ if (!featureBounds) continue;
2136
+ const [[fMinLng, fMinLat], [fMaxLng, fMaxLat]] = featureBounds;
2137
+ const minCol = Math.max(0, Math.floor((fMinLng - minLng) / cellWidth));
2138
+ const maxCol = Math.min(cols - 1, Math.floor((fMaxLng - minLng) / cellWidth));
2139
+ const minRow = Math.max(0, Math.floor((fMinLat - minLat) / cellHeight));
2140
+ const maxRow = Math.min(rows - 1, Math.floor((fMaxLat - minLat) / cellHeight));
2141
+ for (let col = minCol; col <= maxCol; col++) {
2142
+ for (let row = minRow; row <= maxRow; row++) {
2143
+ const key = `${col},${row}`;
2144
+ if (!grid.has(key)) {
2145
+ grid.set(key, { features: [] });
2146
+ }
2147
+ grid.get(key).features.push(feature);
2148
+ }
2149
+ }
2150
+ }
2151
+ return {
2152
+ grid,
2153
+ cols,
2154
+ rows,
2155
+ bounds,
2156
+ cellWidth,
2157
+ cellHeight,
2158
+ featureCount: geojson.features.length
2159
+ };
2160
+ }
2161
+ function getFeatureBounds(feature) {
2162
+ const geometry = feature.geometry;
2163
+ if (!geometry) return null;
2164
+ let minLng = Infinity;
2165
+ let minLat = Infinity;
2166
+ let maxLng = -Infinity;
2167
+ let maxLat = -Infinity;
2168
+ function processCoord(coord) {
2169
+ minLng = Math.min(minLng, coord[0]);
2170
+ minLat = Math.min(minLat, coord[1]);
2171
+ maxLng = Math.max(maxLng, coord[0]);
2172
+ maxLat = Math.max(maxLat, coord[1]);
2173
+ }
2174
+ function processRing(ring) {
2175
+ ring.forEach(processCoord);
2176
+ }
2177
+ switch (geometry.type) {
2178
+ case "Point":
2179
+ processCoord(geometry.coordinates);
2180
+ break;
2181
+ case "MultiPoint":
2182
+ case "LineString":
2183
+ geometry.coordinates.forEach(processCoord);
2184
+ break;
2185
+ case "MultiLineString":
2186
+ case "Polygon":
2187
+ geometry.coordinates.forEach(processRing);
2188
+ break;
2189
+ case "MultiPolygon":
2190
+ geometry.coordinates.forEach(
2191
+ (polygon) => polygon.forEach(processRing)
2192
+ );
2193
+ break;
2194
+ }
2195
+ if (minLng === Infinity) return null;
2196
+ return [
2197
+ [minLng, minLat],
2198
+ [maxLng, maxLat]
2199
+ ];
2200
+ }
2201
+ function queryByBounds(index, queryBounds, options = {}) {
2202
+ const { buffer = 0.01, bufferFraction } = options;
2203
+ if (index.featureCount === 0) {
2204
+ return { type: "FeatureCollection", features: [] };
2205
+ }
2206
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBounds(queryBounds);
2207
+ const viewWidth = maxLng - minLng;
2208
+ const viewHeight = maxLat - minLat;
2209
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
2210
+ minLng -= actualBuffer;
2211
+ minLat -= actualBuffer;
2212
+ maxLng += actualBuffer;
2213
+ maxLat += actualBuffer;
2214
+ const [[idxMinLng, idxMinLat]] = index.bounds;
2215
+ const minCol = Math.max(0, Math.floor((minLng - idxMinLng) / index.cellWidth));
2216
+ const maxCol = Math.min(index.cols - 1, Math.floor((maxLng - idxMinLng) / index.cellWidth));
2217
+ const minRow = Math.max(0, Math.floor((minLat - idxMinLat) / index.cellHeight));
2218
+ const maxRow = Math.min(index.rows - 1, Math.floor((maxLat - idxMinLat) / index.cellHeight));
2219
+ const seen = /* @__PURE__ */ new Set();
2220
+ const features = [];
2221
+ for (let col = minCol; col <= maxCol; col++) {
2222
+ for (let row = minRow; row <= maxRow; row++) {
2223
+ const cell = index.grid.get(`${col},${row}`);
2224
+ if (cell) {
2225
+ for (const feature of cell.features) {
2226
+ if (!seen.has(feature)) {
2227
+ const featureBounds = getFeatureBounds(feature);
2228
+ if (featureBounds && boundsIntersect(featureBounds, [
2229
+ [minLng, minLat],
2230
+ [maxLng, maxLat]
2231
+ ])) {
2232
+ seen.add(feature);
2233
+ features.push(feature);
2234
+ }
2235
+ }
2236
+ }
2237
+ }
2238
+ }
2239
+ }
2240
+ return { type: "FeatureCollection", features };
2241
+ }
2242
+ function boundsIntersect(a, b) {
2243
+ return !(a[1][0] < b[0][0] || // a is left of b
2244
+ a[0][0] > b[1][0] || // a is right of b
2245
+ a[1][1] < b[0][1] || // a is below b
2246
+ a[0][1] > b[1][1]);
2247
+ }
2248
+ function normalizeBounds(bounds) {
2249
+ if (Array.isArray(bounds) && Array.isArray(bounds[0])) {
2250
+ return bounds;
2251
+ }
2252
+ const mapBounds = bounds;
2253
+ return [mapBounds.southwest, mapBounds.northeast];
2254
+ }
2255
+ function queryByBoundsWithStats(index, queryBounds, options = {}) {
2256
+ const { buffer = 0.01, bufferFraction } = options;
2257
+ if (index.featureCount === 0) {
2258
+ return {
2259
+ data: { type: "FeatureCollection", features: [] },
2260
+ stats: {
2261
+ totalFeatures: 0,
2262
+ visibleFeatures: 0,
2263
+ culledPercent: 0,
2264
+ cellsChecked: 0,
2265
+ totalCells: 0
2266
+ }
2267
+ };
2268
+ }
2269
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBounds(queryBounds);
2270
+ const viewWidth = maxLng - minLng;
2271
+ const viewHeight = maxLat - minLat;
2272
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
2273
+ minLng -= actualBuffer;
2274
+ minLat -= actualBuffer;
2275
+ maxLng += actualBuffer;
2276
+ maxLat += actualBuffer;
2277
+ const [[idxMinLng, idxMinLat]] = index.bounds;
2278
+ const minCol = Math.max(0, Math.floor((minLng - idxMinLng) / index.cellWidth));
2279
+ const maxCol = Math.min(index.cols - 1, Math.floor((maxLng - idxMinLng) / index.cellWidth));
2280
+ const minRow = Math.max(0, Math.floor((minLat - idxMinLat) / index.cellHeight));
2281
+ const maxRow = Math.min(index.rows - 1, Math.floor((maxLat - idxMinLat) / index.cellHeight));
2282
+ const seen = /* @__PURE__ */ new Set();
2283
+ const features = [];
2284
+ let cellsChecked = 0;
2285
+ for (let col = minCol; col <= maxCol; col++) {
2286
+ for (let row = minRow; row <= maxRow; row++) {
2287
+ cellsChecked++;
2288
+ const cell = index.grid.get(`${col},${row}`);
2289
+ if (cell) {
2290
+ for (const feature of cell.features) {
2291
+ if (!seen.has(feature)) {
2292
+ const featureBounds = getFeatureBounds(feature);
2293
+ if (featureBounds && boundsIntersect(featureBounds, [
2294
+ [minLng, minLat],
2295
+ [maxLng, maxLat]
2296
+ ])) {
2297
+ seen.add(feature);
2298
+ features.push(feature);
2299
+ }
2300
+ }
2301
+ }
2302
+ }
2303
+ }
2304
+ }
2305
+ const visibleFeatures = features.length;
2306
+ const culledPercent = index.featureCount > 0 ? (index.featureCount - visibleFeatures) / index.featureCount * 100 : 0;
2307
+ return {
2308
+ data: { type: "FeatureCollection", features },
2309
+ stats: {
2310
+ totalFeatures: index.featureCount,
2311
+ visibleFeatures,
2312
+ culledPercent,
2313
+ cellsChecked,
2314
+ totalCells: index.cols * index.rows
2315
+ }
2316
+ };
2317
+ }
2318
+ function createViewportQuery(index, options) {
2319
+ const { debounceMs = 50, bufferFraction = 0.2, onUpdate } = options;
2320
+ let timeoutId = null;
2321
+ let lastBounds = null;
2322
+ return (bounds) => {
2323
+ lastBounds = bounds;
2324
+ if (timeoutId) {
2325
+ clearTimeout(timeoutId);
2326
+ }
2327
+ timeoutId = setTimeout(() => {
2328
+ if (lastBounds) {
2329
+ const { data, stats } = queryByBoundsWithStats(index, lastBounds, {
2330
+ bufferFraction
2331
+ });
2332
+ onUpdate(data, stats);
2333
+ }
2334
+ timeoutId = null;
2335
+ }, debounceMs);
2336
+ };
2337
+ }
2338
+ function createViewportManager(index, options = {}) {
2339
+ const { bufferFraction = 0.25, minMovement = 0.1 } = options;
2340
+ let lastBounds = null;
2341
+ let lastData = null;
2342
+ let lastStats = null;
2343
+ function shouldUpdate(newBounds) {
2344
+ if (!lastBounds) return true;
2345
+ const lastWidth = lastBounds[1][0] - lastBounds[0][0];
2346
+ const lastHeight = lastBounds[1][1] - lastBounds[0][1];
2347
+ const movementLng = Math.abs(
2348
+ (newBounds[0][0] + newBounds[1][0]) / 2 - (lastBounds[0][0] + lastBounds[1][0]) / 2
2349
+ );
2350
+ const movementLat = Math.abs(
2351
+ (newBounds[0][1] + newBounds[1][1]) / 2 - (lastBounds[0][1] + lastBounds[1][1]) / 2
2352
+ );
2353
+ const movement = Math.max(movementLng / lastWidth, movementLat / lastHeight);
2354
+ const newWidth = newBounds[1][0] - newBounds[0][0];
2355
+ const zoomChange = Math.abs(newWidth / lastWidth - 1);
2356
+ return movement > minMovement || zoomChange > 0.2;
2357
+ }
2358
+ return {
2359
+ update(bounds) {
2360
+ const normalizedBounds = normalizeBounds(bounds);
2361
+ if (lastData && !shouldUpdate(normalizedBounds)) {
2362
+ return {
2363
+ data: lastData,
2364
+ stats: lastStats,
2365
+ updated: false
2366
+ };
2367
+ }
2368
+ const { data, stats } = queryByBoundsWithStats(index, normalizedBounds, {
2369
+ bufferFraction
2370
+ });
2371
+ lastBounds = normalizedBounds;
2372
+ lastData = data;
2373
+ lastStats = stats;
2374
+ return {
2375
+ data,
2376
+ stats,
2377
+ updated: true
2378
+ };
2379
+ },
2380
+ reset() {
2381
+ lastBounds = null;
2382
+ lastData = null;
2383
+ lastStats = null;
2384
+ },
2385
+ getStats() {
2386
+ return lastStats;
2387
+ }
2388
+ };
2389
+ }
2390
+ var requestIdleCallbackPolyfill = typeof requestIdleCallback !== "undefined" ? requestIdleCallback : (cb, options) => {
2391
+ const start = Date.now();
2392
+ return setTimeout(() => {
2393
+ cb({
2394
+ didTimeout: true,
2395
+ timeRemaining: () => Math.max(0, 50 - (Date.now() - start))
2396
+ });
2397
+ }, options?.timeout ?? 1);
2398
+ };
2399
+ var cancelIdleCallbackPolyfill = typeof cancelIdleCallback !== "undefined" ? cancelIdleCallback : (id) => clearTimeout(id);
2400
+ function createIdleViewportManager(index, options = {}) {
2401
+ const {
2402
+ bufferFraction = 0.25,
2403
+ minMovement = 0.1,
2404
+ maxUpdatesPerSecond = 12,
2405
+ idleDelay = 100,
2406
+ predictivePan = true,
2407
+ predictiveMultiplier = 2,
2408
+ velocitySamples = 5,
2409
+ maxPanDistance = 0.5
2410
+ } = options;
2411
+ const minUpdateInterval = 1e3 / maxUpdatesPerSecond;
2412
+ let lastBounds = null;
2413
+ let lastDataFetchBounds = null;
2414
+ let lastData = null;
2415
+ let lastStats = null;
2416
+ let pendingIdleId = null;
2417
+ let pendingBounds = null;
2418
+ let lastUpdateTime = 0;
2419
+ let viewportSamples = [];
2420
+ let currentVelocity = { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2421
+ let dataReadyCallback = null;
2422
+ const isRTree = "tree" in index;
2423
+ function getCumulativeDistance(newBounds) {
2424
+ if (!lastDataFetchBounds) return Infinity;
2425
+ const viewWidth = newBounds[1][0] - newBounds[0][0];
2426
+ const viewHeight = newBounds[1][1] - newBounds[0][1];
2427
+ const fetchCenterLng = (lastDataFetchBounds[0][0] + lastDataFetchBounds[1][0]) / 2;
2428
+ const fetchCenterLat = (lastDataFetchBounds[0][1] + lastDataFetchBounds[1][1]) / 2;
2429
+ const newCenterLng = (newBounds[0][0] + newBounds[1][0]) / 2;
2430
+ const newCenterLat = (newBounds[0][1] + newBounds[1][1]) / 2;
2431
+ const distLng = Math.abs(newCenterLng - fetchCenterLng) / viewWidth;
2432
+ const distLat = Math.abs(newCenterLat - fetchCenterLat) / viewHeight;
2433
+ return Math.max(distLng, distLat);
2434
+ }
2435
+ function shouldUpdate(newBounds) {
2436
+ if (!lastBounds) return true;
2437
+ const lastWidth = lastBounds[1][0] - lastBounds[0][0];
2438
+ const lastHeight = lastBounds[1][1] - lastBounds[0][1];
2439
+ const movementLng = Math.abs(
2440
+ (newBounds[0][0] + newBounds[1][0]) / 2 - (lastBounds[0][0] + lastBounds[1][0]) / 2
2441
+ );
2442
+ const movementLat = Math.abs(
2443
+ (newBounds[0][1] + newBounds[1][1]) / 2 - (lastBounds[0][1] + lastBounds[1][1]) / 2
2444
+ );
2445
+ const movement = Math.max(movementLng / lastWidth, movementLat / lastHeight);
2446
+ const newWidth = newBounds[1][0] - newBounds[0][0];
2447
+ const zoomChange = Math.abs(newWidth / lastWidth - 1);
2448
+ const cumulativeDistance = getCumulativeDistance(newBounds);
2449
+ return movement > minMovement || zoomChange > 0.2 || cumulativeDistance > maxPanDistance;
2450
+ }
2451
+ function trackVelocity(normalizedBounds) {
2452
+ const now = performance.now();
2453
+ const center = [
2454
+ (normalizedBounds[0][0] + normalizedBounds[1][0]) / 2,
2455
+ (normalizedBounds[0][1] + normalizedBounds[1][1]) / 2
2456
+ ];
2457
+ viewportSamples.push({ center, timestamp: now });
2458
+ while (viewportSamples.length > velocitySamples) {
2459
+ viewportSamples.shift();
2460
+ }
2461
+ currentVelocity = calculatePanVelocityInternal(viewportSamples);
2462
+ }
2463
+ function executeQuery(normalizedBounds) {
2464
+ const viewWidth = normalizedBounds[1][0] - normalizedBounds[0][0];
2465
+ const viewHeight = normalizedBounds[1][1] - normalizedBounds[0][1];
2466
+ const baseBuffer = Math.max(viewWidth, viewHeight) * bufferFraction;
2467
+ let queryBounds = normalizedBounds;
2468
+ if (predictivePan && currentVelocity.magnitude > 1e-5) {
2469
+ queryBounds = applyPredictiveBufferInternal(
2470
+ normalizedBounds,
2471
+ currentVelocity,
2472
+ baseBuffer,
2473
+ predictiveMultiplier
2474
+ );
2475
+ } else {
2476
+ queryBounds = [
2477
+ [normalizedBounds[0][0] - baseBuffer, normalizedBounds[0][1] - baseBuffer],
2478
+ [normalizedBounds[1][0] + baseBuffer, normalizedBounds[1][1] + baseBuffer]
2479
+ ];
2480
+ }
2481
+ let data;
2482
+ let stats;
2483
+ if (isRTree) {
2484
+ const rtreeIndex = index;
2485
+ const result = queryRTreeByBoundsWithStats(rtreeIndex, queryBounds, {
2486
+ buffer: 0
2487
+ // Buffer already applied
2488
+ });
2489
+ data = result.data;
2490
+ stats = {
2491
+ totalFeatures: result.stats.totalFeatures,
2492
+ visibleFeatures: result.stats.visibleFeatures,
2493
+ culledPercent: result.stats.culledPercent,
2494
+ cellsChecked: 0,
2495
+ totalCells: 0
2496
+ };
2497
+ } else {
2498
+ const gridIndex = index;
2499
+ const result = queryByBoundsWithStats(gridIndex, queryBounds, {
2500
+ buffer: 0
2501
+ // Buffer already applied
2502
+ });
2503
+ data = result.data;
2504
+ stats = result.stats;
2505
+ }
2506
+ lastBounds = normalizedBounds;
2507
+ lastDataFetchBounds = normalizedBounds;
2508
+ lastData = data;
2509
+ lastStats = stats;
2510
+ lastUpdateTime = performance.now();
2511
+ return {
2512
+ data,
2513
+ stats,
2514
+ updated: true,
2515
+ velocity: currentVelocity
2516
+ };
2517
+ }
2518
+ function cancelPending() {
2519
+ if (pendingIdleId !== null) {
2520
+ cancelIdleCallbackPolyfill(pendingIdleId);
2521
+ pendingIdleId = null;
2522
+ }
2523
+ pendingBounds = null;
2524
+ }
2525
+ return {
2526
+ queueUpdate(bounds, trackOnly = false) {
2527
+ const normalizedBounds = normalizeBoundsInternal(bounds);
2528
+ trackVelocity(normalizedBounds);
2529
+ const cumulativeDistance = getCumulativeDistance(normalizedBounds);
2530
+ const mustUpdate = cumulativeDistance > maxPanDistance;
2531
+ if (trackOnly) {
2532
+ if (mustUpdate) {
2533
+ const result = executeQuery(normalizedBounds);
2534
+ result.chunkLoadTriggered = true;
2535
+ if (dataReadyCallback) {
2536
+ dataReadyCallback(result);
2537
+ }
2538
+ }
2539
+ return;
2540
+ }
2541
+ if (lastData && !shouldUpdate(normalizedBounds) && !mustUpdate) {
2542
+ return;
2543
+ }
2544
+ const now = performance.now();
2545
+ if (!mustUpdate && now - lastUpdateTime < minUpdateInterval) {
2546
+ pendingBounds = normalizedBounds;
2547
+ if (pendingIdleId === null) {
2548
+ pendingIdleId = requestIdleCallbackPolyfill(
2549
+ () => {
2550
+ pendingIdleId = null;
2551
+ if (pendingBounds) {
2552
+ const result = executeQuery(pendingBounds);
2553
+ pendingBounds = null;
2554
+ if (dataReadyCallback) {
2555
+ dataReadyCallback(result);
2556
+ }
2557
+ }
2558
+ },
2559
+ { timeout: idleDelay }
2560
+ );
2561
+ }
2562
+ return;
2563
+ }
2564
+ cancelPending();
2565
+ if (mustUpdate) {
2566
+ const result = executeQuery(normalizedBounds);
2567
+ result.chunkLoadTriggered = true;
2568
+ if (dataReadyCallback) {
2569
+ dataReadyCallback(result);
2570
+ }
2571
+ return;
2572
+ }
2573
+ pendingBounds = normalizedBounds;
2574
+ pendingIdleId = requestIdleCallbackPolyfill(
2575
+ () => {
2576
+ pendingIdleId = null;
2577
+ if (pendingBounds) {
2578
+ const result = executeQuery(pendingBounds);
2579
+ pendingBounds = null;
2580
+ if (dataReadyCallback) {
2581
+ dataReadyCallback(result);
2582
+ }
2583
+ }
2584
+ },
2585
+ { timeout: idleDelay }
2586
+ );
2587
+ },
2588
+ forceUpdate(bounds) {
2589
+ const normalizedBounds = normalizeBoundsInternal(bounds);
2590
+ cancelPending();
2591
+ trackVelocity(normalizedBounds);
2592
+ if (lastData && !shouldUpdate(normalizedBounds)) {
2593
+ return {
2594
+ data: lastData,
2595
+ stats: lastStats,
2596
+ updated: false,
2597
+ velocity: currentVelocity
2598
+ };
2599
+ }
2600
+ return executeQuery(normalizedBounds);
2601
+ },
2602
+ onDataReady(callback) {
2603
+ dataReadyCallback = callback;
2604
+ },
2605
+ reset() {
2606
+ cancelPending();
2607
+ lastBounds = null;
2608
+ lastDataFetchBounds = null;
2609
+ lastData = null;
2610
+ lastStats = null;
2611
+ lastUpdateTime = 0;
2612
+ viewportSamples = [];
2613
+ currentVelocity = { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2614
+ },
2615
+ getStats() {
2616
+ return lastStats;
2617
+ },
2618
+ getVelocity() {
2619
+ return currentVelocity;
2620
+ },
2621
+ getCumulativeDistance(bounds) {
2622
+ return getCumulativeDistance(normalizeBoundsInternal(bounds));
2623
+ }
2624
+ };
2625
+ }
2626
+ function calculatePanVelocityInternal(samples) {
2627
+ if (samples.length < 2) {
2628
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2629
+ }
2630
+ let totalLngDelta = 0;
2631
+ let totalLatDelta = 0;
2632
+ let totalTime = 0;
2633
+ let weight = 1;
2634
+ for (let i = samples.length - 1; i > 0; i--) {
2635
+ const current = samples[i];
2636
+ const previous = samples[i - 1];
2637
+ const dt = (current.timestamp - previous.timestamp) / 1e3;
2638
+ if (dt > 0 && dt < 1) {
2639
+ totalLngDelta += (current.center[0] - previous.center[0]) * weight;
2640
+ totalLatDelta += (current.center[1] - previous.center[1]) * weight;
2641
+ totalTime += dt * weight;
2642
+ }
2643
+ weight *= 0.7;
2644
+ }
2645
+ if (totalTime === 0) {
2646
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2647
+ }
2648
+ const lngPerSec = totalLngDelta / totalTime;
2649
+ const latPerSec = totalLatDelta / totalTime;
2650
+ const magnitude = Math.sqrt(lngPerSec * lngPerSec + latPerSec * latPerSec);
2651
+ return { lngPerSec, latPerSec, magnitude };
2652
+ }
2653
+ function applyPredictiveBufferInternal(bounds, velocity, baseBuffer, multiplier) {
2654
+ const [[minLng, minLat], [maxLng, maxLat]] = bounds;
2655
+ let bufferMinLng = baseBuffer;
2656
+ let bufferMaxLng = baseBuffer;
2657
+ let bufferMinLat = baseBuffer;
2658
+ let bufferMaxLat = baseBuffer;
2659
+ if (velocity.magnitude > 1e-5) {
2660
+ const extraBuffer = baseBuffer * (multiplier - 1);
2661
+ if (velocity.lngPerSec > 0) {
2662
+ bufferMaxLng += extraBuffer * Math.min(1, velocity.lngPerSec / velocity.magnitude);
2663
+ } else if (velocity.lngPerSec < 0) {
2664
+ bufferMinLng += extraBuffer * Math.min(1, -velocity.lngPerSec / velocity.magnitude);
2665
+ }
2666
+ if (velocity.latPerSec > 0) {
2667
+ bufferMaxLat += extraBuffer * Math.min(1, velocity.latPerSec / velocity.magnitude);
2668
+ } else if (velocity.latPerSec < 0) {
2669
+ bufferMinLat += extraBuffer * Math.min(1, -velocity.latPerSec / velocity.magnitude);
2670
+ }
2671
+ }
2672
+ return [
2673
+ [minLng - bufferMinLng, minLat - bufferMinLat],
2674
+ [maxLng + bufferMaxLng, maxLat + bufferMaxLat]
2675
+ ];
2676
+ }
2677
+ function calculatePanVelocity(samples) {
2678
+ if (samples.length < 2) {
2679
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2680
+ }
2681
+ let totalLngDelta = 0;
2682
+ let totalLatDelta = 0;
2683
+ let totalTime = 0;
2684
+ let weight = 1;
2685
+ for (let i = samples.length - 1; i > 0; i--) {
2686
+ const current = samples[i];
2687
+ const previous = samples[i - 1];
2688
+ const dt = (current.timestamp - previous.timestamp) / 1e3;
2689
+ if (dt > 0 && dt < 1) {
2690
+ totalLngDelta += (current.center[0] - previous.center[0]) * weight;
2691
+ totalLatDelta += (current.center[1] - previous.center[1]) * weight;
2692
+ totalTime += dt * weight;
2693
+ }
2694
+ weight *= 0.7;
2695
+ }
2696
+ if (totalTime === 0) {
2697
+ return { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2698
+ }
2699
+ const lngPerSec = totalLngDelta / totalTime;
2700
+ const latPerSec = totalLatDelta / totalTime;
2701
+ const magnitude = Math.sqrt(lngPerSec * lngPerSec + latPerSec * latPerSec);
2702
+ return { lngPerSec, latPerSec, magnitude };
2703
+ }
2704
+ function applyPredictiveBuffer(bounds, velocity, baseBuffer, multiplier) {
2705
+ const [[minLng, minLat], [maxLng, maxLat]] = bounds;
2706
+ let bufferMinLng = baseBuffer;
2707
+ let bufferMaxLng = baseBuffer;
2708
+ let bufferMinLat = baseBuffer;
2709
+ let bufferMaxLat = baseBuffer;
2710
+ if (velocity.magnitude > 1e-5) {
2711
+ const extraBuffer = baseBuffer * (multiplier - 1);
2712
+ if (velocity.lngPerSec > 0) {
2713
+ bufferMaxLng += extraBuffer * Math.min(1, velocity.lngPerSec / velocity.magnitude);
2714
+ } else if (velocity.lngPerSec < 0) {
2715
+ bufferMinLng += extraBuffer * Math.min(1, -velocity.lngPerSec / velocity.magnitude);
2716
+ }
2717
+ if (velocity.latPerSec > 0) {
2718
+ bufferMaxLat += extraBuffer * Math.min(1, velocity.latPerSec / velocity.magnitude);
2719
+ } else if (velocity.latPerSec < 0) {
2720
+ bufferMinLat += extraBuffer * Math.min(1, -velocity.latPerSec / velocity.magnitude);
2721
+ }
2722
+ }
2723
+ return [
2724
+ [minLng - bufferMinLng, minLat - bufferMinLat],
2725
+ [maxLng + bufferMaxLng, maxLat + bufferMaxLat]
2726
+ ];
2727
+ }
2728
+ function createPredictiveViewportManager(index, options = {}) {
2729
+ const {
2730
+ bufferFraction = 0.25,
2731
+ minMovement = 0.1,
2732
+ predictiveMultiplier = 2,
2733
+ velocitySamples = 5
2734
+ } = options;
2735
+ let lastBounds = null;
2736
+ let lastData = null;
2737
+ let lastStats = null;
2738
+ let viewportSamples = [];
2739
+ let currentVelocity = { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2740
+ const isRTree = "tree" in index;
2741
+ function shouldUpdate(newBounds) {
2742
+ if (!lastBounds) return true;
2743
+ const lastWidth = lastBounds[1][0] - lastBounds[0][0];
2744
+ const lastHeight = lastBounds[1][1] - lastBounds[0][1];
2745
+ const movementLng = Math.abs(
2746
+ (newBounds[0][0] + newBounds[1][0]) / 2 - (lastBounds[0][0] + lastBounds[1][0]) / 2
2747
+ );
2748
+ const movementLat = Math.abs(
2749
+ (newBounds[0][1] + newBounds[1][1]) / 2 - (lastBounds[0][1] + lastBounds[1][1]) / 2
2750
+ );
2751
+ const movement = Math.max(movementLng / lastWidth, movementLat / lastHeight);
2752
+ const newWidth = newBounds[1][0] - newBounds[0][0];
2753
+ const zoomChange = Math.abs(newWidth / lastWidth - 1);
2754
+ return movement > minMovement || zoomChange > 0.2;
2755
+ }
2756
+ return {
2757
+ update(bounds) {
2758
+ const normalizedBounds = normalizeBounds(bounds);
2759
+ const now = performance.now();
2760
+ const center = [
2761
+ (normalizedBounds[0][0] + normalizedBounds[1][0]) / 2,
2762
+ (normalizedBounds[0][1] + normalizedBounds[1][1]) / 2
2763
+ ];
2764
+ viewportSamples.push({ center, timestamp: now });
2765
+ while (viewportSamples.length > velocitySamples) {
2766
+ viewportSamples.shift();
2767
+ }
2768
+ currentVelocity = calculatePanVelocity(viewportSamples);
2769
+ if (lastData && !shouldUpdate(normalizedBounds)) {
2770
+ return {
2771
+ data: lastData,
2772
+ stats: lastStats,
2773
+ updated: false,
2774
+ velocity: currentVelocity
2775
+ };
2776
+ }
2777
+ const viewWidth = normalizedBounds[1][0] - normalizedBounds[0][0];
2778
+ const viewHeight = normalizedBounds[1][1] - normalizedBounds[0][1];
2779
+ const baseBuffer = Math.max(viewWidth, viewHeight) * bufferFraction;
2780
+ const predictiveBounds = applyPredictiveBuffer(
2781
+ normalizedBounds,
2782
+ currentVelocity,
2783
+ baseBuffer,
2784
+ predictiveMultiplier
2785
+ );
2786
+ let data;
2787
+ let stats;
2788
+ if (isRTree) {
2789
+ const rtreeIndex = index;
2790
+ const result = queryRTreeByBoundsWithStats(rtreeIndex, predictiveBounds, {
2791
+ buffer: 0
2792
+ // Buffer already applied
2793
+ });
2794
+ data = result.data;
2795
+ stats = {
2796
+ totalFeatures: result.stats.totalFeatures,
2797
+ visibleFeatures: result.stats.visibleFeatures,
2798
+ culledPercent: result.stats.culledPercent,
2799
+ cellsChecked: 0,
2800
+ totalCells: 0
2801
+ };
2802
+ } else {
2803
+ const gridIndex = index;
2804
+ const result = queryByBoundsWithStats(gridIndex, predictiveBounds, {
2805
+ buffer: 0
2806
+ // Buffer already applied
2807
+ });
2808
+ data = result.data;
2809
+ stats = result.stats;
2810
+ }
2811
+ lastBounds = normalizedBounds;
2812
+ lastData = data;
2813
+ lastStats = stats;
2814
+ return {
2815
+ data,
2816
+ stats,
2817
+ updated: true,
2818
+ velocity: currentVelocity
2819
+ };
2820
+ },
2821
+ reset() {
2822
+ lastBounds = null;
2823
+ lastData = null;
2824
+ lastStats = null;
2825
+ viewportSamples = [];
2826
+ currentVelocity = { lngPerSec: 0, latPerSec: 0, magnitude: 0 };
2827
+ },
2828
+ getStats() {
2829
+ return lastStats;
2830
+ },
2831
+ getVelocity() {
2832
+ return currentVelocity;
2833
+ }
2834
+ };
2835
+ }
2836
+ function buildRTreeIndex(geojson, options = {}) {
2837
+ const { maxEntries = 9 } = options;
2838
+ const tree = new RBush__default.default(maxEntries);
2839
+ const items = [];
2840
+ let minLngAll = Infinity;
2841
+ let minLatAll = Infinity;
2842
+ let maxLngAll = -Infinity;
2843
+ let maxLatAll = -Infinity;
2844
+ for (const feature of geojson.features) {
2845
+ const featureBounds = getFeatureBoundsInternal(feature);
2846
+ if (!featureBounds) continue;
2847
+ const [[minLng, minLat], [maxLng, maxLat]] = featureBounds;
2848
+ items.push({
2849
+ minX: minLng,
2850
+ minY: minLat,
2851
+ maxX: maxLng,
2852
+ maxY: maxLat,
2853
+ feature
2854
+ });
2855
+ minLngAll = Math.min(minLngAll, minLng);
2856
+ minLatAll = Math.min(minLatAll, minLat);
2857
+ maxLngAll = Math.max(maxLngAll, maxLng);
2858
+ maxLatAll = Math.max(maxLatAll, maxLat);
2859
+ }
2860
+ tree.load(items);
2861
+ const bounds = minLngAll === Infinity ? [
2862
+ [0, 0],
2863
+ [0, 0]
2864
+ ] : [
2865
+ [minLngAll, minLatAll],
2866
+ [maxLngAll, maxLatAll]
2867
+ ];
2868
+ return {
2869
+ tree,
2870
+ bounds,
2871
+ featureCount: items.length
2872
+ };
2873
+ }
2874
+ function getFeatureBoundsInternal(feature) {
2875
+ const geometry = feature.geometry;
2876
+ if (!geometry) return null;
2877
+ let minLng = Infinity;
2878
+ let minLat = Infinity;
2879
+ let maxLng = -Infinity;
2880
+ let maxLat = -Infinity;
2881
+ function processCoord(coord) {
2882
+ minLng = Math.min(minLng, coord[0]);
2883
+ minLat = Math.min(minLat, coord[1]);
2884
+ maxLng = Math.max(maxLng, coord[0]);
2885
+ maxLat = Math.max(maxLat, coord[1]);
2886
+ }
2887
+ function processRing(ring) {
2888
+ ring.forEach(processCoord);
2889
+ }
2890
+ switch (geometry.type) {
2891
+ case "Point":
2892
+ processCoord(geometry.coordinates);
2893
+ break;
2894
+ case "MultiPoint":
2895
+ case "LineString":
2896
+ geometry.coordinates.forEach(processCoord);
2897
+ break;
2898
+ case "MultiLineString":
2899
+ case "Polygon":
2900
+ geometry.coordinates.forEach(processRing);
2901
+ break;
2902
+ case "MultiPolygon":
2903
+ geometry.coordinates.forEach(
2904
+ (polygon) => polygon.forEach(processRing)
2905
+ );
2906
+ break;
2907
+ }
2908
+ if (minLng === Infinity) return null;
2909
+ return [
2910
+ [minLng, minLat],
2911
+ [maxLng, maxLat]
2912
+ ];
2913
+ }
2914
+ function queryRTreeByBounds(index, queryBounds, options = {}) {
2915
+ const { buffer = 0.01, bufferFraction } = options;
2916
+ if (index.featureCount === 0) {
2917
+ return { type: "FeatureCollection", features: [] };
2918
+ }
2919
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBoundsInternal(queryBounds);
2920
+ const viewWidth = maxLng - minLng;
2921
+ const viewHeight = maxLat - minLat;
2922
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
2923
+ minLng -= actualBuffer;
2924
+ minLat -= actualBuffer;
2925
+ maxLng += actualBuffer;
2926
+ maxLat += actualBuffer;
2927
+ const results = index.tree.search({
2928
+ minX: minLng,
2929
+ minY: minLat,
2930
+ maxX: maxLng,
2931
+ maxY: maxLat
2932
+ });
2933
+ return {
2934
+ type: "FeatureCollection",
2935
+ features: results.map((item) => item.feature)
2936
+ };
2937
+ }
2938
+ function queryRTreeByBoundsWithStats(index, queryBounds, options = {}) {
2939
+ const { buffer = 0.01, bufferFraction } = options;
2940
+ if (index.featureCount === 0) {
2941
+ return {
2942
+ data: { type: "FeatureCollection", features: [] },
2943
+ stats: {
2944
+ totalFeatures: 0,
2945
+ visibleFeatures: 0,
2946
+ culledPercent: 0,
2947
+ queryTimeMs: 0
2948
+ }
2949
+ };
2950
+ }
2951
+ const startTime = performance.now();
2952
+ let [[minLng, minLat], [maxLng, maxLat]] = normalizeBoundsInternal(queryBounds);
2953
+ const viewWidth = maxLng - minLng;
2954
+ const viewHeight = maxLat - minLat;
2955
+ const actualBuffer = bufferFraction ? Math.max(viewWidth, viewHeight) * bufferFraction : buffer;
2956
+ minLng -= actualBuffer;
2957
+ minLat -= actualBuffer;
2958
+ maxLng += actualBuffer;
2959
+ maxLat += actualBuffer;
2960
+ const results = index.tree.search({
2961
+ minX: minLng,
2962
+ minY: minLat,
2963
+ maxX: maxLng,
2964
+ maxY: maxLat
2965
+ });
2966
+ const queryTimeMs = performance.now() - startTime;
2967
+ const visibleFeatures = results.length;
2968
+ const culledPercent = index.featureCount > 0 ? (index.featureCount - visibleFeatures) / index.featureCount * 100 : 0;
2969
+ return {
2970
+ data: {
2971
+ type: "FeatureCollection",
2972
+ features: results.map((item) => item.feature)
2973
+ },
2974
+ stats: {
2975
+ totalFeatures: index.featureCount,
2976
+ visibleFeatures,
2977
+ culledPercent,
2978
+ queryTimeMs
2979
+ }
2980
+ };
2981
+ }
2982
+ function normalizeBoundsInternal(bounds) {
2983
+ if (Array.isArray(bounds) && Array.isArray(bounds[0])) {
2984
+ return bounds;
2985
+ }
2986
+ const mapBounds = bounds;
2987
+ return [mapBounds.southwest, mapBounds.northeast];
2988
+ }
2989
+ function createRTreeViewportManager(index, options = {}) {
2990
+ const { bufferFraction = 0.25, minMovement = 0.1 } = options;
2991
+ let lastBounds = null;
2992
+ let lastData = null;
2993
+ let lastStats = null;
2994
+ function shouldUpdate(newBounds) {
2995
+ if (!lastBounds) return true;
2996
+ const lastWidth = lastBounds[1][0] - lastBounds[0][0];
2997
+ const lastHeight = lastBounds[1][1] - lastBounds[0][1];
2998
+ const movementLng = Math.abs(
2999
+ (newBounds[0][0] + newBounds[1][0]) / 2 - (lastBounds[0][0] + lastBounds[1][0]) / 2
3000
+ );
3001
+ const movementLat = Math.abs(
3002
+ (newBounds[0][1] + newBounds[1][1]) / 2 - (lastBounds[0][1] + lastBounds[1][1]) / 2
3003
+ );
3004
+ const movement = Math.max(movementLng / lastWidth, movementLat / lastHeight);
3005
+ const newWidth = newBounds[1][0] - newBounds[0][0];
3006
+ const zoomChange = Math.abs(newWidth / lastWidth - 1);
3007
+ return movement > minMovement || zoomChange > 0.2;
3008
+ }
3009
+ return {
3010
+ update(bounds) {
3011
+ const normalizedBounds = normalizeBoundsInternal(bounds);
3012
+ if (lastData && !shouldUpdate(normalizedBounds)) {
3013
+ return {
3014
+ data: lastData,
3015
+ stats: lastStats,
3016
+ updated: false,
3017
+ queryTimeMs: lastStats?.queryTimeMs
3018
+ };
3019
+ }
3020
+ const { data, stats } = queryRTreeByBoundsWithStats(index, normalizedBounds, {
3021
+ bufferFraction
3022
+ });
3023
+ lastBounds = normalizedBounds;
3024
+ lastData = data;
3025
+ lastStats = {
3026
+ totalFeatures: stats.totalFeatures,
3027
+ visibleFeatures: stats.visibleFeatures,
3028
+ culledPercent: stats.culledPercent,
3029
+ cellsChecked: 0,
3030
+ // R-tree doesn't use cells
3031
+ totalCells: 0,
3032
+ queryTimeMs: stats.queryTimeMs
3033
+ };
3034
+ return {
3035
+ data,
3036
+ stats: lastStats,
3037
+ updated: true,
3038
+ queryTimeMs: stats.queryTimeMs
3039
+ };
3040
+ },
3041
+ reset() {
3042
+ lastBounds = null;
3043
+ lastData = null;
3044
+ lastStats = null;
3045
+ },
3046
+ getStats() {
3047
+ return lastStats;
3048
+ }
3049
+ };
3050
+ }
3051
+
3052
+ // src/utils/fingerprint.ts
3053
+ function createGeoJSONFingerprint(data) {
3054
+ if (!data) return null;
3055
+ if (typeof data === "string") return null;
3056
+ if (data.type !== "FeatureCollection") return null;
3057
+ const features = data.features;
3058
+ if (!features || !Array.isArray(features)) {
3059
+ return { count: 0, firstId: void 0, lastId: void 0 };
3060
+ }
3061
+ const count = features.length;
3062
+ if (count === 0) {
3063
+ return { count: 0, firstId: void 0, lastId: void 0 };
3064
+ }
3065
+ const firstFeature = features[0];
3066
+ const lastFeature = features[count - 1];
3067
+ return {
3068
+ count,
3069
+ firstId: firstFeature?.id,
3070
+ lastId: lastFeature?.id
3071
+ };
3072
+ }
3073
+ function fingerprintEqual(a, b) {
3074
+ if (a === null && b === null) return true;
3075
+ if (a === null || b === null) return false;
3076
+ return a.count === b.count && a.firstId === b.firstId && a.lastId === b.lastId;
3077
+ }
3078
+ function geoJSONEqual(a, b) {
3079
+ if (typeof a === "string" || typeof b === "string") {
3080
+ return a === b;
3081
+ }
3082
+ if (!a && !b) return true;
3083
+ if (!a || !b) return false;
3084
+ const fpA = createGeoJSONFingerprint(a);
3085
+ const fpB = createGeoJSONFingerprint(b);
3086
+ return fingerprintEqual(fpA, fpB);
3087
+ }
3088
+
3089
+ // src/utils/equality.ts
3090
+ function deepEqual(a, b) {
3091
+ if (a === b) return true;
3092
+ if (a == null || b == null) return a === b;
3093
+ if (typeof a !== typeof b) return false;
3094
+ if (Array.isArray(a) && Array.isArray(b)) {
3095
+ if (a.length !== b.length) return false;
3096
+ for (let i = 0; i < a.length; i++) {
3097
+ if (!deepEqual(a[i], b[i])) return false;
3098
+ }
3099
+ return true;
3100
+ }
3101
+ if (typeof a === "object" && typeof b === "object") {
3102
+ const aKeys = Object.keys(a);
3103
+ const bKeys = Object.keys(b);
3104
+ if (aKeys.length !== bKeys.length) return false;
3105
+ for (const key of aKeys) {
3106
+ if (!Object.prototype.hasOwnProperty.call(b, key) || !deepEqual(a[key], b[key])) {
3107
+ return false;
3108
+ }
3109
+ }
3110
+ return true;
3111
+ }
3112
+ return false;
3113
+ }
3114
+ function paintPropsEqual(prev, next) {
3115
+ if (prev === next) return true;
3116
+ if (!prev && !next) return true;
3117
+ if (!prev || !next) return false;
3118
+ const prevKeys = Object.keys(prev);
3119
+ const nextKeys = Object.keys(next);
3120
+ if (prevKeys.length !== nextKeys.length) return false;
3121
+ for (const key of prevKeys) {
3122
+ if (!Object.prototype.hasOwnProperty.call(next, key)) return false;
3123
+ if (!deepEqual(prev[key], next[key])) return false;
3124
+ }
3125
+ return true;
3126
+ }
3127
+ function getChangedPaintProps(prev, next) {
3128
+ const changed = {};
3129
+ const removed = [];
3130
+ if (!prev) {
3131
+ return {
3132
+ changed: next || {},
3133
+ removed: [],
3134
+ hasChanges: !!next && Object.keys(next).length > 0
3135
+ };
3136
+ }
3137
+ if (!next) {
3138
+ return {
3139
+ changed: {},
3140
+ removed: Object.keys(prev),
3141
+ hasChanges: Object.keys(prev).length > 0
3142
+ };
3143
+ }
3144
+ for (const key of Object.keys(next)) {
3145
+ if (!deepEqual(prev[key], next[key])) {
3146
+ changed[key] = next[key];
3147
+ }
3148
+ }
3149
+ for (const key of Object.keys(prev)) {
3150
+ if (!Object.prototype.hasOwnProperty.call(next, key)) {
3151
+ removed.push(key);
3152
+ }
3153
+ }
3154
+ return {
3155
+ changed,
3156
+ removed,
3157
+ hasChanges: Object.keys(changed).length > 0 || removed.length > 0
3158
+ };
3159
+ }
3160
+ function filterEqual(prev, next) {
3161
+ if (!prev && !next) return true;
3162
+ if (!prev || !next) return false;
3163
+ return deepEqual(prev, next);
3164
+ }
3165
+ function serializeFilter(filter) {
3166
+ if (!filter) return "";
3167
+ try {
3168
+ return JSON.stringify(filter);
3169
+ } catch {
3170
+ return "";
3171
+ }
3172
+ }
3173
+
3174
+ exports.BASE_OFFSET = BASE_OFFSET;
3175
+ exports.DEFAULT_SIMPLIFICATION_THRESHOLDS = DEFAULT_SIMPLIFICATION_THRESHOLDS;
3176
+ exports.KEYBOARD_CONTROLS = KEYBOARD_CONTROLS;
3177
+ exports.OFFSET_CLASSES = OFFSET_CLASSES;
3178
+ exports.POSITION_CLASSES = POSITION_CLASSES;
3179
+ exports.THEME_DARK = THEME_DARK;
3180
+ exports.THEME_LIGHT = THEME_LIGHT;
3181
+ exports.boundsToPolygon = boundsToPolygon;
3182
+ exports.buildRTreeIndex = buildRTreeIndex;
3183
+ exports.buildSpatialIndex = buildSpatialIndex;
3184
+ exports.calculateBounds = calculateBounds;
3185
+ exports.calculateCentroid = calculateCentroid;
3186
+ exports.calculateZoomThresholds = calculateZoomThresholds;
3187
+ exports.combineBounds = combineBounds;
3188
+ exports.computePositionClasses = computePositionClasses;
3189
+ exports.computeVerticalOffsetStyle = computeVerticalOffsetStyle;
3190
+ exports.countFeaturesByType = countFeaturesByType;
3191
+ exports.createCategoricalColorExpression = createCategoricalColorExpression;
3192
+ exports.createCircleStyle = createCircleStyle;
3193
+ exports.createContinuousColorExpression = createContinuousColorExpression;
3194
+ exports.createDynamicLODManager = createDynamicLODManager;
3195
+ exports.createExtrusionHeightExpression = createExtrusionHeightExpression;
3196
+ exports.createExtrusionStyle = createExtrusionStyle;
3197
+ exports.createFillStyle = createFillStyle;
3198
+ exports.createGeoJSONFingerprint = createGeoJSONFingerprint;
3199
+ exports.createHeatmapStyle = createHeatmapStyle;
3200
+ exports.createHoverExpression = createHoverExpression;
3201
+ exports.createIdleViewportManager = createIdleViewportManager;
3202
+ exports.createInteractiveExpression = createInteractiveExpression;
3203
+ exports.createInteractiveStatusColorExpression = createInteractiveStatusColorExpression;
3204
+ exports.createLineStyle = createLineStyle;
3205
+ exports.createLotFillStyle = createLotFillStyle;
3206
+ exports.createLotOutlineStyle = createLotOutlineStyle;
3207
+ exports.createPredictiveViewportManager = createPredictiveViewportManager;
3208
+ exports.createRTreeViewportManager = createRTreeViewportManager;
3209
+ exports.createSelectionExpression = createSelectionExpression;
3210
+ exports.createStatusColorExpression = createStatusColorExpression;
3211
+ exports.createViewportManager = createViewportManager;
3212
+ exports.createViewportQuery = createViewportQuery;
3213
+ exports.createZoomExpression = createZoomExpression;
3214
+ exports.darkBasicStyle = darkBasicStyle;
3215
+ exports.darkTheme = darkTheme;
3216
+ exports.decimalToDMS = decimalToDMS;
3217
+ exports.deepEqual = deepEqual;
3218
+ exports.expandCluster = expandCluster;
3219
+ exports.expandClusterToBounds = expandClusterToBounds;
3220
+ exports.extendBounds = extendBounds;
3221
+ exports.filterByGeometryType = filterByGeometryType;
3222
+ exports.filterEqual = filterEqual;
3223
+ exports.fingerprintEqual = fingerprintEqual;
3224
+ exports.formatArea = formatArea;
3225
+ exports.formatBearing = formatBearing;
3226
+ exports.formatBounds = formatBounds;
3227
+ exports.formatCoordinates = formatCoordinates;
3228
+ exports.formatDistance = formatDistance;
3229
+ exports.formatFeatureProperties = formatFeatureProperties;
3230
+ exports.formatLabel = formatLabel;
3231
+ exports.formatPitch = formatPitch;
3232
+ exports.formatPropertyValue = formatPropertyValue;
3233
+ exports.formatScale = formatScale;
3234
+ exports.formatZoom = formatZoom;
3235
+ exports.generateBasicStyle = generateBasicStyle;
3236
+ exports.generateBoundingPolygon = generateBoundingPolygon;
3237
+ exports.generateConvexHull = generateConvexHull;
3238
+ exports.generateDarkColors = generateDarkColors;
3239
+ exports.generateDarkDataColors = generateDarkDataColors;
3240
+ exports.generateDarkTheme = generateDarkTheme;
3241
+ exports.generateFeatureCollectionDescription = generateFeatureCollectionDescription;
3242
+ exports.generateFeatureTable = generateFeatureTable;
3243
+ exports.generateKeyboardControlsDescription = generateKeyboardControlsDescription;
3244
+ exports.generateLODData = generateLODData;
3245
+ exports.generateLODDataWithSimplification = generateLODDataWithSimplification;
3246
+ exports.generateLightColors = generateLightColors;
3247
+ exports.generateLightDataColors = generateLightDataColors;
3248
+ exports.generateLightTheme = generateLightTheme;
3249
+ exports.generateMapDescription = generateMapDescription;
3250
+ exports.generateMarkerList = generateMarkerList;
3251
+ exports.generateMarkersDescription = generateMarkersDescription;
3252
+ exports.generateMoveAnnouncement = generateMoveAnnouncement;
3253
+ exports.generateVectorStyle = generateVectorStyle;
3254
+ exports.geoJSONEqual = geoJSONEqual;
3255
+ exports.getBasicStyle = getBasicStyle;
3256
+ exports.getChangedPaintProps = getChangedPaintProps;
3257
+ exports.getClusterBounds = getClusterBounds;
3258
+ exports.getClusterChildren = getClusterChildren;
3259
+ exports.getClusterExpansionZoom = getClusterExpansionZoom;
3260
+ exports.getClusterLeaves = getClusterLeaves;
3261
+ exports.getHighlightStyle = getHighlightStyle;
3262
+ exports.getSelectionStyle = getSelectionStyle;
3263
+ exports.getSimplificationToleranceForZoom = getSimplificationToleranceForZoom;
3264
+ exports.getSimplifiedFeaturesForZoom = getSimplifiedFeaturesForZoom;
3265
+ exports.getTheme = getTheme;
3266
+ exports.getTypography = getTypography;
3267
+ exports.groupFeaturesByProperty = groupFeaturesByProperty;
3268
+ exports.isClusterFeature = isClusterFeature;
3269
+ exports.isValidBounds = isValidBounds;
3270
+ exports.lightBasicStyle = lightBasicStyle;
3271
+ exports.lightTheme = lightTheme;
3272
+ exports.loadGeoJSON = loadGeoJSON;
3273
+ exports.paintPropsEqual = paintPropsEqual;
3274
+ exports.queryByBounds = queryByBounds;
3275
+ exports.queryByBoundsWithStats = queryByBoundsWithStats;
3276
+ exports.queryRTreeByBounds = queryRTreeByBounds;
3277
+ exports.queryRTreeByBoundsWithStats = queryRTreeByBoundsWithStats;
3278
+ exports.serializeFilter = serializeFilter;
3279
+ exports.simplifyFeature = simplifyFeature;
3280
+ exports.simplifyFeatureCollection = simplifyFeatureCollection;
3281
+ exports.simplifyFeatureCollectionWithStats = simplifyFeatureCollectionWithStats;
3282
+ exports.simplifyPolygon = simplifyPolygon;
3283
+ exports.validateGeoJSON = validateGeoJSON;
3284
+ exports.zoomToScale = zoomToScale;