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