@octostar/map-component 0.2.11 → 0.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/index.cjs +1515 -819
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +1516 -820
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/styles.css +1 -0
  6. package/dist/types/components/cursor-coordinates-overlay.d.ts +13 -0
  7. package/dist/types/components/cursor-coordinates-overlay.d.ts.map +1 -0
  8. package/dist/types/components/debug-sidebar.d.ts.map +1 -1
  9. package/dist/types/components/map-drop-zone.d.ts +7 -1
  10. package/dist/types/components/map-drop-zone.d.ts.map +1 -1
  11. package/dist/types/components/map-editor-canvas.d.ts.map +1 -1
  12. package/dist/types/lib/deep-clone.d.ts +22 -0
  13. package/dist/types/lib/deep-clone.d.ts.map +1 -0
  14. package/dist/types/lib/draw-render-gate.d.ts +10 -0
  15. package/dist/types/lib/draw-render-gate.d.ts.map +1 -0
  16. package/dist/types/lib/geojson-crs.d.ts +10 -0
  17. package/dist/types/lib/geojson-crs.d.ts.map +1 -0
  18. package/dist/types/lib/geojson-reproject.d.ts +15 -0
  19. package/dist/types/lib/geojson-reproject.d.ts.map +1 -0
  20. package/dist/types/lib/geojson-serialize.d.ts +21 -0
  21. package/dist/types/lib/geojson-serialize.d.ts.map +1 -0
  22. package/dist/types/lib/geometry-equals.d.ts +15 -0
  23. package/dist/types/lib/geometry-equals.d.ts.map +1 -0
  24. package/dist/types/lib/ingest-client.d.ts +25 -0
  25. package/dist/types/lib/ingest-client.d.ts.map +1 -0
  26. package/dist/types/lib/ingest-pipeline.d.ts +74 -0
  27. package/dist/types/lib/ingest-pipeline.d.ts.map +1 -0
  28. package/dist/types/lib/ingest.worker.d.ts +2 -0
  29. package/dist/types/lib/ingest.worker.d.ts.map +1 -0
  30. package/dist/types/lib/map-editor-api.d.ts +5 -0
  31. package/dist/types/lib/map-editor-api.d.ts.map +1 -1
  32. package/dist/types/lib/perf-log.d.ts +3 -0
  33. package/dist/types/lib/perf-log.d.ts.map +1 -0
  34. package/dist/types/lib/raf-coalescer.d.ts +29 -0
  35. package/dist/types/lib/raf-coalescer.d.ts.map +1 -0
  36. package/dist/types/lib/selection-diff.d.ts +91 -0
  37. package/dist/types/lib/selection-diff.d.ts.map +1 -0
  38. package/dist/types/lib/selection-hit-test.d.ts +55 -0
  39. package/dist/types/lib/selection-hit-test.d.ts.map +1 -0
  40. package/dist/types/lib/selection-spatial-index.d.ts +63 -0
  41. package/dist/types/lib/selection-spatial-index.d.ts.map +1 -0
  42. package/dist/types/lib/temporal-ingest.d.ts +53 -0
  43. package/dist/types/lib/temporal-ingest.d.ts.map +1 -0
  44. package/dist/types/lib/temporal-normalize.d.ts +11 -0
  45. package/dist/types/lib/temporal-normalize.d.ts.map +1 -0
  46. package/dist/types/lib/timeline-diff.d.ts +43 -0
  47. package/dist/types/lib/timeline-diff.d.ts.map +1 -0
  48. package/dist/types/lib/timeline-store.d.ts +1 -9
  49. package/dist/types/lib/timeline-store.d.ts.map +1 -1
  50. package/package.json +5 -4
package/dist/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  import { jsxs, Fragment, jsx } from "react/jsx-runtime";
2
- import { useState, useCallback, useMemo, createContext, useContext, useRef, useEffect, forwardRef, useImperativeHandle } from "react";
2
+ import { useState, useEffect, useCallback, useMemo, createContext, useContext, useRef, forwardRef, useImperativeHandle } from "react";
3
3
  import maplibregl from "maplibre-gl";
4
4
  import MapboxDraw from "@mapbox/mapbox-gl-draw";
5
5
  import * as turf from "@turf/turf";
6
- import proj4 from "proj4";
7
6
  import * as THREE from "three";
7
+ import proj4 from "proj4";
8
8
  import { Button, Modal, Input, App, message, Tooltip, Dropdown, Divider, Popover, Switch, Slider, Tag, Select, Collapse, ColorPicker, Tabs, Card, Table, DatePicker } from "antd";
9
9
  import { clsx } from "clsx";
10
10
  import { twMerge } from "tailwind-merge";
@@ -12,8 +12,475 @@ import { MousePointer2, Square, Hexagon, Circle, MoreVertical, ChevronDown, Filt
12
12
  import { createPortal } from "react-dom";
13
13
  import { format } from "date-fns";
14
14
  import { useStore, createStore } from "zustand";
15
+ import Flatbush from "flatbush";
15
16
  import dayjs from "dayjs";
16
17
  import * as toGeoJSON from "@mapbox/togeojson";
18
+ function detectSourceCRS(geojson) {
19
+ var _a, _b;
20
+ const crsName = (_b = (_a = geojson.crs) == null ? void 0 : _a.properties) == null ? void 0 : _b.name;
21
+ let sourceCRS = null;
22
+ if (crsName) {
23
+ const epsgMatch = crsName.match(/EPSG::?(\d+)/i);
24
+ if (epsgMatch) sourceCRS = `EPSG:${epsgMatch[1]}`;
25
+ }
26
+ if (!sourceCRS && geojson.features.length > 0) {
27
+ const firstCoord = getFirstCoordinate(geojson.features[0].geometry);
28
+ if (firstCoord) {
29
+ const [x, y] = firstCoord;
30
+ if (Math.abs(x) <= 180 && Math.abs(y) <= 90) {
31
+ return { sourceCRS: "EPSG:4326", needsReprojection: false };
32
+ }
33
+ }
34
+ return { sourceCRS: null, needsReprojection: false };
35
+ }
36
+ return { sourceCRS, needsReprojection: sourceCRS !== null && sourceCRS !== "EPSG:4326" };
37
+ }
38
+ function getFirstCoordinate(geometry) {
39
+ var _a, _b, _c;
40
+ if (!geometry) return null;
41
+ switch (geometry.type) {
42
+ case "Point":
43
+ return geometry.coordinates;
44
+ case "MultiPoint":
45
+ case "LineString":
46
+ return geometry.coordinates[0];
47
+ case "MultiLineString":
48
+ case "Polygon":
49
+ return (_a = geometry.coordinates[0]) == null ? void 0 : _a[0];
50
+ case "MultiPolygon":
51
+ return (_c = (_b = geometry.coordinates[0]) == null ? void 0 : _b[0]) == null ? void 0 : _c[0];
52
+ default:
53
+ return null;
54
+ }
55
+ }
56
+ function hasAltitudeData(feature) {
57
+ var _a, _b;
58
+ if (((_a = feature.geometry) == null ? void 0 : _a.type) === "LineString") {
59
+ const coords = feature.geometry.coordinates;
60
+ return coords.some((c) => c.length >= 3 && c[2] !== 0);
61
+ }
62
+ if (((_b = feature.geometry) == null ? void 0 : _b.type) === "MultiLineString") {
63
+ const coords = feature.geometry.coordinates;
64
+ return coords.some((line) => line.some((c) => c.length >= 3 && c[2] !== 0));
65
+ }
66
+ return false;
67
+ }
68
+ const PRETTY_EXPORT_MAX_FEATURES = 1e4;
69
+ const TARGET_PART_CHARS = 8 * 1024 * 1024;
70
+ function featureCollectionBlobParts(collection, options) {
71
+ const prettyMax = PRETTY_EXPORT_MAX_FEATURES;
72
+ if (collection.features.length <= prettyMax) {
73
+ return [JSON.stringify(collection, null, 2)];
74
+ }
75
+ const targetChars = TARGET_PART_CHARS;
76
+ const { features, ...rest } = collection;
77
+ const head = JSON.stringify(rest);
78
+ const parts = [];
79
+ let pending = [];
80
+ let pendingChars = 0;
81
+ const push = (piece) => {
82
+ pending.push(piece);
83
+ pendingChars += piece.length;
84
+ if (pendingChars >= targetChars) {
85
+ parts.push(pending.join(""));
86
+ pending = [];
87
+ pendingChars = 0;
88
+ }
89
+ };
90
+ push(head.slice(0, -1));
91
+ push(head.length > 2 ? ',"features":[' : '"features":[');
92
+ for (let i = 0; i < features.length; i++) {
93
+ push(i === 0 ? JSON.stringify(features[i]) : "," + JSON.stringify(features[i]));
94
+ }
95
+ push("]}");
96
+ if (pending.length > 0) parts.push(pending.join(""));
97
+ return parts;
98
+ }
99
+ const ingestWorkerSource = '"use strict";(()=>{function y(e){let n=e.crs?.properties?.name,t=null;if(n){let r=n.match(/EPSG::?(\\d+)/i);r&&(t=`EPSG:${r[1]}`)}if(!t&&e.features.length>0){let r=D(e.features[0].geometry);if(r){let[o,u]=r;if(Math.abs(o)<=180&&Math.abs(u)<=90)return{sourceCRS:"EPSG:4326",needsReprojection:!1}}return{sourceCRS:null,needsReprojection:!1}}return{sourceCRS:t,needsReprojection:t!==null&&t!=="EPSG:4326"}}function D(e){if(!e)return null;switch(e.type){case"Point":return e.coordinates;case"MultiPoint":case"LineString":return e.coordinates[0];case"MultiLineString":case"Polygon":return e.coordinates[0]?.[0];case"MultiPolygon":return e.coordinates[0]?.[0]?.[0];default:return null}}function b(e){return e.geometry?.type==="LineString"?e.geometry.coordinates.some(t=>t.length>=3&&t[2]!==0):e.geometry?.type==="MultiLineString"?e.geometry.coordinates.some(t=>t.some(r=>r.length>=3&&r[2]!==0)):!1}function a(e){if(!e)return null;if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let n=new Date(e);return isNaN(n.getTime())?null:n}return null}function p(e){return!!(e.startDate||e.startdate||e.start_date||e.start_time||e.date||e.timestamp||e.flightDate||e.time||e.datetime||e.endDate||e.enddate||e.end_date||e.end_time)}function S(e){let n=a(e.startDate)||a(e.startdate)||a(e.start_date)||a(e.start_time)||a(e.date)||a(e.timestamp)||a(e.flightDate)||a(e.time)||a(e.datetime),t=a(e.endDate)||a(e.enddate)||a(e.end_date)||a(e.end_time);return n&&t&&t<n&&([n,t]=[t,n]),{startDate:n,endDate:t}}function x(){let e=globalThis.crypto?.randomUUID?.bind(globalThis.crypto);return e?e():`f-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function G(e,n,t){switch(t.idStrategy){case"preserve":return e.id;case"layer-index":return e.id!==void 0&&e.id!==null?String(e.id):`${t.layerId}-f${n}`;case"uuid-fallback":return e.id?String(e.id):x()}}function I(e,n){if(Array.isArray(e)){if(typeof e[0]=="number"){let t=e[0],r=e[1];n[0]=Math.min(n[0],t),n[1]=Math.min(n[1],r),n[2]=Math.max(n[2],t),n[3]=Math.max(n[3],r);return}for(let t of e)I(t,n)}}function h(e,n){if(e){if(e.type==="GeometryCollection"){for(let t of e.geometries)h(t,n);return}I(e.coordinates,n)}}function O(e){let n=[1/0,1/0,-1/0,-1/0];for(let t of e)h(t.geometry,n);return n.every(t=>isFinite(t))?n:null}function k(e,n){let t;if(e.type==="text")try{t=JSON.parse(e.text)}catch(s){return{kind:"error",code:"parse-error",message:s instanceof Error?s.message:"Invalid file"}}else t=e.data;if(t&&t.type==="Feature"&&(t={type:"FeatureCollection",features:[t]}),!t||t.type!=="FeatureCollection"||!Array.isArray(t.features))return{kind:"error",code:"invalid-format",message:"Invalid GeoJSON format"};if(n.emptyIsError&&t.features.length===0)return{kind:"error",code:"empty",message:"The file contains no features"};if(t["octostar:map"])return{kind:"enriched",data:t};let{sourceCRS:r,needsReprojection:o}=y(t),u=!1,l=!1,i=[];t.features.forEach((s,C)=>{let m=G(s,C,n);!l&&b(s)&&(l=!0);let d=s.properties||{};if(!p(d)){i.push(n.idStrategy==="preserve"?s:{...s,id:m});return}let{startDate:f,endDate:g}=S(d);(f||g)&&(u=!0),i.push({...s,id:m,properties:{...d,startDate:f?.toISOString()||null,endDate:g?.toISOString()||null}})});let c=t.properties?.layerMetadata;return{kind:"features",features:i,featureCount:i.length,bbox:O(i),hasTemporal:u,hasAltitude:l,reprojected:!1,sourceCRS:r,...o&&{needsReprojection:o},...c&&{layerMetadata:c}}}var R=e=>self.postMessage(e);self.onmessage=async e=>{let{id:n,source:t,options:r}=e.data;try{let o=t.type==="blob"?{type:"text",text:await t.blob.text()}:t;R({id:n,ok:!0,result:k(o,r)})}catch(o){R({id:n,ok:!1,error:o instanceof Error?o.message:String(o)})}};})();\n';
100
+ proj4.defs("EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs");
101
+ proj4.defs("EPSG:3857", "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs");
102
+ proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
103
+ proj4.defs("EPSG:32631", "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs");
104
+ function reprojectFeatures(features, sourceCRS) {
105
+ if (!proj4.defs(sourceCRS)) return null;
106
+ try {
107
+ return features.map((feature) => ({
108
+ ...feature,
109
+ geometry: reprojectGeometry(feature.geometry, sourceCRS)
110
+ }));
111
+ } catch (e) {
112
+ console.error("Reprojection failed:", e);
113
+ return null;
114
+ }
115
+ }
116
+ function reprojectGeometry(geometry, fromCRS) {
117
+ if (!geometry) return geometry;
118
+ const transform = (coord) => {
119
+ const [x, y] = proj4(fromCRS, "EPSG:4326", [coord[0], coord[1]]);
120
+ return coord.length > 2 ? [x, y, ...coord.slice(2)] : [x, y];
121
+ };
122
+ const reprojectCoords = (coords) => {
123
+ if (typeof coords[0] === "number") {
124
+ return transform(coords);
125
+ }
126
+ return coords.map(reprojectCoords);
127
+ };
128
+ if (geometry.type === "GeometryCollection") {
129
+ return {
130
+ type: "GeometryCollection",
131
+ geometries: geometry.geometries.map((g) => reprojectGeometry(g, fromCRS))
132
+ };
133
+ }
134
+ const geomWithCoords = geometry;
135
+ return {
136
+ ...geomWithCoords,
137
+ coordinates: reprojectCoords(geomWithCoords.coordinates)
138
+ };
139
+ }
140
+ function parseDate(value) {
141
+ if (!value) return null;
142
+ if (value instanceof Date) return value;
143
+ if (typeof value === "string" || typeof value === "number") {
144
+ const date = new Date(value);
145
+ return isNaN(date.getTime()) ? null : date;
146
+ }
147
+ return null;
148
+ }
149
+ function hasAnyTemporalValue(properties) {
150
+ return !!(properties.startDate || properties.startdate || properties.start_date || properties.start_time || properties.date || properties.timestamp || properties.flightDate || properties.time || properties.datetime || properties.endDate || properties.enddate || properties.end_date || properties.end_time);
151
+ }
152
+ function normalizeTemporalProperties(properties) {
153
+ let startDate = parseDate(properties.startDate) || parseDate(properties.startdate) || parseDate(properties.start_date) || parseDate(properties.start_time) || parseDate(properties.date) || parseDate(properties.timestamp) || parseDate(properties.flightDate) || parseDate(properties.time) || parseDate(properties.datetime);
154
+ let endDate = parseDate(properties.endDate) || parseDate(properties.enddate) || parseDate(properties.end_date) || parseDate(properties.end_time);
155
+ if (startDate && endDate && endDate < startDate) {
156
+ [startDate, endDate] = [endDate, startDate];
157
+ }
158
+ return { startDate, endDate };
159
+ }
160
+ function generateUuid() {
161
+ var _a, _b;
162
+ const uuid = (_b = (_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) == null ? void 0 : _b.bind(globalThis.crypto);
163
+ return uuid ? uuid() : `f-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
164
+ }
165
+ function assignId(feature, index, options) {
166
+ switch (options.idStrategy) {
167
+ case "preserve":
168
+ return feature.id;
169
+ case "layer-index":
170
+ return feature.id !== void 0 && feature.id !== null ? String(feature.id) : `${options.layerId}-f${index}`;
171
+ case "uuid-fallback":
172
+ return feature.id ? String(feature.id) : generateUuid();
173
+ }
174
+ }
175
+ function scanCoords(coords, box) {
176
+ if (!Array.isArray(coords)) return;
177
+ if (typeof coords[0] === "number") {
178
+ const x = coords[0];
179
+ const y = coords[1];
180
+ box[0] = Math.min(box[0], x);
181
+ box[1] = Math.min(box[1], y);
182
+ box[2] = Math.max(box[2], x);
183
+ box[3] = Math.max(box[3], y);
184
+ return;
185
+ }
186
+ for (const c of coords) scanCoords(c, box);
187
+ }
188
+ function scanGeometry(geometry, box) {
189
+ if (!geometry) return;
190
+ if (geometry.type === "GeometryCollection") {
191
+ for (const g of geometry.geometries) scanGeometry(g, box);
192
+ return;
193
+ }
194
+ scanCoords(geometry.coordinates, box);
195
+ }
196
+ function computeFeatureCollectionBbox(features) {
197
+ const box = [Infinity, Infinity, -Infinity, -Infinity];
198
+ for (const f of features) scanGeometry(f.geometry, box);
199
+ return box.every((v) => isFinite(v)) ? box : null;
200
+ }
201
+ function runIngestPipeline(source, options) {
202
+ var _a;
203
+ let data;
204
+ if (source.type === "text") {
205
+ try {
206
+ data = JSON.parse(source.text);
207
+ } catch (err) {
208
+ return {
209
+ kind: "error",
210
+ code: "parse-error",
211
+ message: err instanceof Error ? err.message : "Invalid file"
212
+ };
213
+ }
214
+ } else {
215
+ data = source.data;
216
+ }
217
+ if (data && data.type === "Feature") {
218
+ data = {
219
+ type: "FeatureCollection",
220
+ features: [data]
221
+ };
222
+ }
223
+ if (!data || data.type !== "FeatureCollection" || !Array.isArray(data.features)) {
224
+ return { kind: "error", code: "invalid-format", message: "Invalid GeoJSON format" };
225
+ }
226
+ if (options.emptyIsError && data.features.length === 0) {
227
+ return { kind: "error", code: "empty", message: "The file contains no features" };
228
+ }
229
+ if (data["octostar:map"]) {
230
+ return { kind: "enriched", data };
231
+ }
232
+ const { sourceCRS, needsReprojection } = detectSourceCRS(data);
233
+ let hasTemporal = false;
234
+ let hasAltitude = false;
235
+ const features = [];
236
+ data.features.forEach((f, index) => {
237
+ const id = assignId(f, index, options);
238
+ if (!hasAltitude && hasAltitudeData(f)) hasAltitude = true;
239
+ const props = f.properties || {};
240
+ if (!hasAnyTemporalValue(props)) {
241
+ features.push(options.idStrategy === "preserve" ? f : { ...f, id });
242
+ return;
243
+ }
244
+ const { startDate, endDate } = normalizeTemporalProperties(props);
245
+ if (startDate || endDate) hasTemporal = true;
246
+ features.push({
247
+ ...f,
248
+ id,
249
+ properties: {
250
+ ...props,
251
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
252
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
253
+ }
254
+ });
255
+ });
256
+ const layerMetadata = (_a = data.properties) == null ? void 0 : _a.layerMetadata;
257
+ return {
258
+ kind: "features",
259
+ features,
260
+ featureCount: features.length,
261
+ bbox: computeFeatureCollectionBbox(features),
262
+ hasTemporal,
263
+ hasAltitude,
264
+ reprojected: false,
265
+ sourceCRS,
266
+ ...needsReprojection && { needsReprojection },
267
+ ...layerMetadata && { layerMetadata }
268
+ };
269
+ }
270
+ const fromStorage = (() => {
271
+ var _a;
272
+ try {
273
+ return ((_a = globalThis.localStorage) == null ? void 0 : _a.getItem("octostar-map-perf-log")) === "1";
274
+ } catch {
275
+ return false;
276
+ }
277
+ })();
278
+ function mapPerfLogEnabled() {
279
+ return fromStorage || globalThis.__octostarMapPerfLog === true;
280
+ }
281
+ function mapPerfLog(area, message2, data) {
282
+ if (!mapPerfLogEnabled()) return;
283
+ if (data === void 0) {
284
+ console.info(`[map-perf:${area}] ${message2}`);
285
+ } else {
286
+ console.info(`[map-perf:${area}] ${message2}`, data);
287
+ }
288
+ }
289
+ function finalizeReprojection(result) {
290
+ if (result.kind !== "features" || !result.needsReprojection || !result.sourceCRS) return result;
291
+ const reprojected = reprojectFeatures(result.features, result.sourceCRS);
292
+ if (!reprojected) {
293
+ return { ...result, needsReprojection: false };
294
+ }
295
+ return {
296
+ ...result,
297
+ features: reprojected,
298
+ reprojected: true,
299
+ needsReprojection: false,
300
+ bbox: computeFeatureCollectionBbox(reprojected)
301
+ };
302
+ }
303
+ function createWorkerPort() {
304
+ if (typeof Worker === "undefined") {
305
+ mapPerfLog("ingest", "Worker unavailable in this environment — using main-thread pipeline");
306
+ return null;
307
+ }
308
+ let url = null;
309
+ try {
310
+ url = URL.createObjectURL(new Blob([ingestWorkerSource], { type: "text/javascript" }));
311
+ const worker = new Worker(url);
312
+ let pendingUrl = url;
313
+ const revokePendingUrl = () => {
314
+ if (pendingUrl) URL.revokeObjectURL(pendingUrl);
315
+ pendingUrl = null;
316
+ };
317
+ mapPerfLog("ingest", "worker spawned");
318
+ return {
319
+ post: (msg) => worker.postMessage(msg),
320
+ onMessage: (cb) => {
321
+ worker.onmessage = (e) => {
322
+ revokePendingUrl();
323
+ cb(e.data);
324
+ };
325
+ },
326
+ onError: (cb) => {
327
+ worker.onerror = (e) => {
328
+ revokePendingUrl();
329
+ cb(e);
330
+ };
331
+ worker.onmessageerror = (e) => cb(e);
332
+ },
333
+ terminate: () => {
334
+ revokePendingUrl();
335
+ worker.terminate();
336
+ }
337
+ };
338
+ } catch (err) {
339
+ if (url) URL.revokeObjectURL(url);
340
+ console.warn(
341
+ "[map-component] Ingest worker could not be spawned (CSP may block blob: workers); file parsing will run on the main thread.",
342
+ err
343
+ );
344
+ return null;
345
+ }
346
+ }
347
+ const INGEST_TIMEOUT_MS = 12e4;
348
+ function createIngestClient(portFactory = createWorkerPort) {
349
+ let port = null;
350
+ let portUnavailable = false;
351
+ let nextId = 0;
352
+ const pending = /* @__PURE__ */ new Map();
353
+ const rejectAllPending = (reason) => {
354
+ pending.forEach((request) => {
355
+ clearTimeout(request.timeout);
356
+ request.reject(new Error(reason));
357
+ });
358
+ pending.clear();
359
+ };
360
+ const abandonPort = (reason) => {
361
+ rejectAllPending(reason);
362
+ port == null ? void 0 : port.terminate();
363
+ port = null;
364
+ };
365
+ const ensurePort = () => {
366
+ if (portUnavailable || port) return port;
367
+ try {
368
+ port = portFactory();
369
+ } catch {
370
+ port = null;
371
+ }
372
+ if (!port) {
373
+ portUnavailable = true;
374
+ return null;
375
+ }
376
+ port.onMessage((msg) => {
377
+ const request = pending.get(msg.id);
378
+ if (!request) return;
379
+ pending.delete(msg.id);
380
+ clearTimeout(request.timeout);
381
+ mapPerfLog("ingest", `worker request "${request.label}" finished`, {
382
+ ms: Math.round(performance.now() - request.startedAt),
383
+ ok: msg.ok
384
+ });
385
+ if (msg.ok) {
386
+ request.resolve(finalizeReprojection(msg.result));
387
+ } else {
388
+ request.reject(new Error(msg.error));
389
+ }
390
+ });
391
+ port.onError((err) => {
392
+ console.warn("[map-component] Ingest worker crashed; it will be respawned on next use.", err);
393
+ abandonPort("Ingest worker crashed");
394
+ });
395
+ return port;
396
+ };
397
+ const runInline = async (input, options) => {
398
+ const text = typeof input === "string" ? input : await input.text();
399
+ const startedAt = performance.now();
400
+ const result = finalizeReprojection(runIngestPipeline({ type: "text", text }, options));
401
+ mapPerfLog("ingest", "main-thread pipeline finished (no worker)", {
402
+ ms: Math.round(performance.now() - startedAt)
403
+ });
404
+ return result;
405
+ };
406
+ return {
407
+ ingest(input, options) {
408
+ if (typeof input === "object" && !(input instanceof Blob)) {
409
+ return Promise.resolve().then(
410
+ () => finalizeReprojection(runIngestPipeline({ type: "parsed", data: input }, options))
411
+ );
412
+ }
413
+ const activePort = ensurePort();
414
+ if (!activePort) return runInline(input, options);
415
+ const id = nextId++;
416
+ const label = input instanceof File ? input.name : typeof input === "string" ? "text" : "blob";
417
+ return new Promise((resolve, reject) => {
418
+ const timeout = setTimeout(() => {
419
+ console.warn(
420
+ `[map-component] Ingest worker unresponsive for "${label}" after ${INGEST_TIMEOUT_MS}ms; it will be respawned on next use.`
421
+ );
422
+ abandonPort("Ingest worker unresponsive — the file could not be parsed");
423
+ }, INGEST_TIMEOUT_MS);
424
+ pending.set(id, { resolve, reject, startedAt: performance.now(), label, timeout });
425
+ activePort.post({
426
+ id,
427
+ source: typeof input === "string" ? { type: "text", text: input } : { type: "blob", blob: input },
428
+ options
429
+ });
430
+ });
431
+ },
432
+ dispose() {
433
+ abandonPort("Ingest client disposed");
434
+ portUnavailable = false;
435
+ }
436
+ };
437
+ }
438
+ let sharedClient = null;
439
+ function getSharedIngestClient() {
440
+ if (!sharedClient) sharedClient = createIngestClient();
441
+ return sharedClient;
442
+ }
443
+ function CursorCoordinatesOverlay({ map }) {
444
+ const [coords, setCoords] = useState(null);
445
+ useEffect(() => {
446
+ if (!map) return;
447
+ let pending = null;
448
+ let frame = 0;
449
+ const flush = () => {
450
+ frame = 0;
451
+ setCoords(pending);
452
+ };
453
+ const schedule = (next) => {
454
+ pending = next;
455
+ if (!frame) frame = requestAnimationFrame(flush);
456
+ };
457
+ const onMove = (e) => schedule({ lng: e.lngLat.lng, lat: e.lngLat.lat });
458
+ const onOut = () => schedule(null);
459
+ map.on("mousemove", onMove);
460
+ map.on("mouseout", onOut);
461
+ return () => {
462
+ if (frame) cancelAnimationFrame(frame);
463
+ try {
464
+ map.off("mousemove", onMove);
465
+ map.off("mouseout", onOut);
466
+ } catch {
467
+ }
468
+ };
469
+ }, [map]);
470
+ if (!coords) return null;
471
+ return /* @__PURE__ */ jsxs(
472
+ "div",
473
+ {
474
+ className: "absolute bottom-1 right-12 z-10 pointer-events-none font-mono text-[10px] text-muted-foreground/70 select-none",
475
+ "data-testid": "cursor-coordinates",
476
+ children: [
477
+ coords.lat.toFixed(5),
478
+ ", ",
479
+ coords.lng.toFixed(5)
480
+ ]
481
+ }
482
+ );
483
+ }
17
484
  const ICONS = [
18
485
  // Location & Places
19
486
  { id: "map-pin", emoji: "📍", name: "Map Pin", category: "places" },
@@ -4503,26 +4970,6 @@ function StatusIndicator({ featureCount, selectedCount = 0 }) {
4503
4970
  }
4504
4971
  );
4505
4972
  }
4506
- function parseDate(value) {
4507
- if (!value) return null;
4508
- if (value instanceof Date) return value;
4509
- if (typeof value === "string" || typeof value === "number") {
4510
- const date = new Date(value);
4511
- return isNaN(date.getTime()) ? null : date;
4512
- }
4513
- return null;
4514
- }
4515
- function hasAnyTemporalValue(properties) {
4516
- return !!(properties.startDate || properties.startdate || properties.start_date || properties.start_time || properties.date || properties.timestamp || properties.flightDate || properties.time || properties.datetime || properties.endDate || properties.enddate || properties.end_date || properties.end_time);
4517
- }
4518
- function normalizeTemporalProperties(properties) {
4519
- let startDate = parseDate(properties.startDate) || parseDate(properties.startdate) || parseDate(properties.start_date) || parseDate(properties.start_time) || parseDate(properties.date) || parseDate(properties.timestamp) || parseDate(properties.flightDate) || parseDate(properties.time) || parseDate(properties.datetime);
4520
- let endDate = parseDate(properties.endDate) || parseDate(properties.enddate) || parseDate(properties.end_date) || parseDate(properties.end_time);
4521
- if (startDate && endDate && endDate < startDate) {
4522
- [startDate, endDate] = [endDate, startDate];
4523
- }
4524
- return { startDate, endDate };
4525
- }
4526
4973
  function isFeatureInRange(feature, rangeStart, rangeEnd) {
4527
4974
  if (!feature.startDate && !feature.endDate) return true;
4528
4975
  if (!rangeStart || !rangeEnd) return true;
@@ -4616,7 +5063,8 @@ const timelineStoreInitializer = (set, get) => ({
4616
5063
  const computedMax = maxDate;
4617
5064
  const sameFeatureIds = state.temporalFeatures.length === timedFeatures.length && timedFeatures.every((f, i) => f.id === state.temporalFeatures[i].id);
4618
5065
  const sameDates = ((_a = state.globalMinDate) == null ? void 0 : _a.getTime()) === (computedMin == null ? void 0 : computedMin.getTime()) && ((_b = state.globalMaxDate) == null ? void 0 : _b.getTime()) === (computedMax == null ? void 0 : computedMax.getTime());
4619
- if (sameFeatureIds && sameDates && state.hasTemporalData) return;
5066
+ const sameUntimed = state.untimedFeatureIds.length === untimedIds.length && untimedIds.every((id, i) => id === state.untimedFeatureIds[i]);
5067
+ if (sameFeatureIds && sameDates && sameUntimed && state.hasTemporalData) return;
4620
5068
  const histogramBins = minDate && maxDate ? computeHistogramBins(timedFeatures, minDate, maxDate) : [];
4621
5069
  set({
4622
5070
  hasTemporalData: true,
@@ -5141,7 +5589,7 @@ function Timebar({ onFilterChange, selectedFeatureIds = [], selectedFeatureColor
5141
5589
  }
5142
5590
  );
5143
5591
  }
5144
- function MapDropZone({ onDrop, children }) {
5592
+ function MapDropZone({ onDrop, onDropFile, children }) {
5145
5593
  const [isDragOver, setIsDragOver] = useState(false);
5146
5594
  const handleDragOver = useCallback((e) => {
5147
5595
  e.preventDefault();
@@ -5176,13 +5624,17 @@ function MapDropZone({ onDrop, children }) {
5176
5624
  for (let i = 0; i < files.length; i++) {
5177
5625
  const file = files[i];
5178
5626
  if (!file.name.match(/\.(geojson|json)$/i)) continue;
5627
+ const name = file.name.replace(/\.(geojson|json)$/i, "");
5628
+ if (onDropFile) {
5629
+ onDropFile(name, file);
5630
+ continue;
5631
+ }
5179
5632
  const reader = new FileReader();
5180
5633
  reader.onload = (evt) => {
5181
5634
  var _a;
5182
5635
  try {
5183
5636
  const parsed = JSON.parse((_a = evt.target) == null ? void 0 : _a.result);
5184
5637
  if (parsed.type === "FeatureCollection" && Array.isArray(parsed.features)) {
5185
- const name = file.name.replace(/\.(geojson|json)$/i, "");
5186
5638
  onDrop(name, parsed);
5187
5639
  }
5188
5640
  } catch (err) {
@@ -5192,7 +5644,7 @@ function MapDropZone({ onDrop, children }) {
5192
5644
  reader.readAsText(file);
5193
5645
  }
5194
5646
  }
5195
- }, [onDrop]);
5647
+ }, [onDrop, onDropFile]);
5196
5648
  return /* @__PURE__ */ jsxs(
5197
5649
  "div",
5198
5650
  {
@@ -5386,23 +5838,438 @@ function countFeaturesInBounds(featureGroups, bounds, options) {
5386
5838
  }
5387
5839
  return count;
5388
5840
  }
5389
- const OTHER_BUCKET_KEY = "__other__";
5390
- const OTHER_BUCKET_LABEL = "Other";
5391
- const OTHER_BUCKET_COLOR = "#9ca3af";
5392
- function toDisplayName(name) {
5393
- return name === OTHER_BUCKET_KEY ? OTHER_BUCKET_LABEL : name;
5841
+ const rafScheduler = {
5842
+ request: (cb) => requestAnimationFrame(() => cb()),
5843
+ cancel: (handle) => cancelAnimationFrame(handle)
5844
+ };
5845
+ function createRafCoalescer(run, scheduler = rafScheduler) {
5846
+ let reasons = /* @__PURE__ */ new Set();
5847
+ let handle = null;
5848
+ let running = false;
5849
+ const fire = () => {
5850
+ handle = null;
5851
+ const snapshot = reasons;
5852
+ reasons = /* @__PURE__ */ new Set();
5853
+ running = true;
5854
+ try {
5855
+ run(snapshot);
5856
+ } finally {
5857
+ running = false;
5858
+ }
5859
+ };
5860
+ return {
5861
+ schedule(reason) {
5862
+ reasons.add(reason);
5863
+ if (handle === null) {
5864
+ handle = scheduler.request(fire);
5865
+ }
5866
+ },
5867
+ isPending() {
5868
+ return handle !== null;
5869
+ },
5870
+ flush() {
5871
+ if (running || handle === null) return;
5872
+ scheduler.cancel(handle);
5873
+ fire();
5874
+ },
5875
+ cancel() {
5876
+ if (handle !== null) {
5877
+ scheduler.cancel(handle);
5878
+ handle = null;
5879
+ }
5880
+ reasons.clear();
5881
+ }
5882
+ };
5394
5883
  }
5395
- function createPieSVG(categories, total, size = 44, onSliceHover) {
5396
- const container = document.createElement("div");
5397
- container.style.width = `${size}px`;
5398
- container.style.height = `${size}px`;
5399
- container.style.cursor = "pointer";
5400
- const radius = size / 2;
5401
- const innerRadius = radius * 0.5;
5402
- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
5403
- svg.setAttribute("width", String(size));
5404
- svg.setAttribute("height", String(size));
5405
- svg.setAttribute("viewBox", `0 0 ${size} ${size}`);
5884
+ const DEFAULT_LABEL_PRIORITY = 100;
5885
+ const DEFAULT_VISIBLE_STROKE_OPACITY = 1;
5886
+ const DEFAULT_VISIBLE_FILL_OPACITY = 0.2;
5887
+ function createSelectionPaintCache() {
5888
+ return {
5889
+ presentIds: /* @__PURE__ */ new Set(),
5890
+ appliedSelectedIds: /* @__PURE__ */ new Set(),
5891
+ basePriorityById: /* @__PURE__ */ new Map(),
5892
+ appliedHiddenIds: /* @__PURE__ */ new Set(),
5893
+ visibleStrokeOpacityById: /* @__PURE__ */ new Map(),
5894
+ visibleFillOpacityById: /* @__PURE__ */ new Map(),
5895
+ updatable: true
5896
+ };
5897
+ }
5898
+ function recordPaintedFeature(cache, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
5899
+ if (cache.presentIds.has(featureId)) {
5900
+ cache.updatable = false;
5901
+ } else {
5902
+ cache.presentIds.add(featureId);
5903
+ }
5904
+ cache.basePriorityById.set(featureId, basePriority);
5905
+ if (isSelected) cache.appliedSelectedIds.add(featureId);
5906
+ if (visibleStrokeOpacity !== DEFAULT_VISIBLE_STROKE_OPACITY) {
5907
+ cache.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
5908
+ }
5909
+ if (visibleFillOpacity !== DEFAULT_VISIBLE_FILL_OPACITY) {
5910
+ cache.visibleFillOpacityById.set(featureId, visibleFillOpacity);
5911
+ }
5912
+ if (isTimelineHidden) cache.appliedHiddenIds.add(featureId);
5913
+ }
5914
+ function applySelectionFastPath(cache, nextSelectedIds, source) {
5915
+ if (!cache || !cache.updatable || !source) return false;
5916
+ const diff = buildSelectionDiff(cache, nextSelectedIds);
5917
+ if (diff) {
5918
+ try {
5919
+ source.updateData(diff);
5920
+ } catch {
5921
+ return false;
5922
+ }
5923
+ }
5924
+ const applied = /* @__PURE__ */ new Set();
5925
+ nextSelectedIds.forEach((id) => {
5926
+ if (cache.presentIds.has(id)) applied.add(id);
5927
+ });
5928
+ cache.appliedSelectedIds = applied;
5929
+ return true;
5930
+ }
5931
+ function needsDrawSelectionUpdate(input) {
5932
+ return input.editableSelectionCount > 0 || input.drawSelectedCount > 0 || input.currentMode !== input.targetMode;
5933
+ }
5934
+ function buildSelectionDiff(cache, nextSelectedIds) {
5935
+ const update = [];
5936
+ cache.appliedSelectedIds.forEach((id) => {
5937
+ if (!nextSelectedIds.has(id) && cache.presentIds.has(id)) {
5938
+ update.push({
5939
+ id,
5940
+ addOrUpdateProperties: [
5941
+ { key: "isSelected", value: 0 },
5942
+ { key: "_labelPriority", value: cache.basePriorityById.get(id) ?? DEFAULT_LABEL_PRIORITY }
5943
+ ]
5944
+ });
5945
+ }
5946
+ });
5947
+ nextSelectedIds.forEach((id) => {
5948
+ if (!cache.appliedSelectedIds.has(id) && cache.presentIds.has(id)) {
5949
+ update.push({
5950
+ id,
5951
+ addOrUpdateProperties: [
5952
+ { key: "isSelected", value: 1 },
5953
+ { key: "_labelPriority", value: 0 }
5954
+ ]
5955
+ });
5956
+ }
5957
+ });
5958
+ return update.length > 0 ? { update } : null;
5959
+ }
5960
+ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
5961
+ const update = [];
5962
+ const nextHiddenIds = /* @__PURE__ */ new Set();
5963
+ cache.presentIds.forEach((id) => {
5964
+ const nextHidden = nextVisibleSet !== null && !nextVisibleSet.has(id);
5965
+ if (nextHidden) nextHiddenIds.add(id);
5966
+ if (nextHidden === cache.appliedHiddenIds.has(id)) return;
5967
+ if (nextHidden) {
5968
+ update.push({
5969
+ id,
5970
+ addOrUpdateProperties: [
5971
+ { key: "stroke-opacity", value: 0 },
5972
+ { key: "fill-opacity", value: 0 },
5973
+ { key: "isTimelineHidden", value: 1 }
5974
+ ]
5975
+ });
5976
+ } else {
5977
+ update.push({
5978
+ id,
5979
+ addOrUpdateProperties: [
5980
+ { key: "stroke-opacity", value: cache.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
5981
+ { key: "fill-opacity", value: cache.visibleFillOpacityById.get(id) ?? DEFAULT_VISIBLE_FILL_OPACITY },
5982
+ { key: "isTimelineHidden", value: 0 }
5983
+ ]
5984
+ });
5985
+ }
5986
+ });
5987
+ return { diff: update.length > 0 ? { update } : null, nextHiddenIds };
5988
+ }
5989
+ function applyTimelineFastPath(cache, nextVisibleSet, source) {
5990
+ var _a;
5991
+ if (!cache || !cache.updatable || !source) return { applied: false, toggled: 0 };
5992
+ const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache, nextVisibleSet);
5993
+ if (diff) {
5994
+ try {
5995
+ source.updateData(diff);
5996
+ } catch {
5997
+ return { applied: false, toggled: 0 };
5998
+ }
5999
+ }
6000
+ cache.appliedHiddenIds = nextHiddenIds;
6001
+ return { applied: true, toggled: ((_a = diff == null ? void 0 : diff.update) == null ? void 0 : _a.length) ?? 0 };
6002
+ }
6003
+ function deepClone(value) {
6004
+ try {
6005
+ return structuredClone(value);
6006
+ } catch {
6007
+ return JSON.parse(JSON.stringify(value));
6008
+ }
6009
+ }
6010
+ function cloneFeatures(features) {
6011
+ try {
6012
+ return structuredClone(features);
6013
+ } catch {
6014
+ return features.map((f) => deepClone(f));
6015
+ }
6016
+ }
6017
+ function numberEquals(a, b) {
6018
+ return a === b || !Number.isFinite(a) && !Number.isFinite(b);
6019
+ }
6020
+ function coordinatesEqual(a, b) {
6021
+ if (typeof a === "number" || typeof b === "number") {
6022
+ return typeof a === "number" && typeof b === "number" && numberEquals(a, b);
6023
+ }
6024
+ if (a.length !== b.length) return false;
6025
+ for (let i = 0; i < a.length; i++) {
6026
+ if (!coordinatesEqual(a[i], b[i])) return false;
6027
+ }
6028
+ return true;
6029
+ }
6030
+ function bboxEqual(a, b) {
6031
+ if (a === void 0 || b === void 0) return a === b;
6032
+ if (a.length !== b.length) return false;
6033
+ for (let i = 0; i < a.length; i++) {
6034
+ if (!numberEquals(a[i], b[i])) return false;
6035
+ }
6036
+ return true;
6037
+ }
6038
+ function geometryEquals(a, b) {
6039
+ if (a == null || b == null) return a === b;
6040
+ if (a.type !== b.type) return false;
6041
+ if (!bboxEqual(a.bbox, b.bbox)) return false;
6042
+ if (a.type === "GeometryCollection") {
6043
+ const bGeometries = b.geometries;
6044
+ if (a.geometries.length !== bGeometries.length) return false;
6045
+ for (let i = 0; i < a.geometries.length; i++) {
6046
+ if (!geometryEquals(a.geometries[i], bGeometries[i])) return false;
6047
+ }
6048
+ return true;
6049
+ }
6050
+ return coordinatesEqual(
6051
+ a.coordinates,
6052
+ b.coordinates
6053
+ );
6054
+ }
6055
+ function prepareFeaturesForLayer(input, caller) {
6056
+ const logging = mapPerfLogEnabled();
6057
+ const started = logging ? performance.now() : 0;
6058
+ const count = input.length;
6059
+ const features = new Array(count);
6060
+ const featureIds = new Array(count);
6061
+ let hasTemporal = false;
6062
+ let temporalCount = 0;
6063
+ let reused = 0;
6064
+ for (let i = 0; i < count; i++) {
6065
+ const f = input[i];
6066
+ const props = f.properties || {};
6067
+ if (!hasAnyTemporalValue(props)) {
6068
+ if (typeof f.id === "string" && f.id) {
6069
+ features[i] = f;
6070
+ featureIds[i] = f.id;
6071
+ reused++;
6072
+ } else {
6073
+ const id2 = f.id ? String(f.id) : crypto.randomUUID();
6074
+ features[i] = { ...f, id: id2 };
6075
+ featureIds[i] = id2;
6076
+ }
6077
+ continue;
6078
+ }
6079
+ const id = f.id ? String(f.id) : crypto.randomUUID();
6080
+ featureIds[i] = id;
6081
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6082
+ if (startDate || endDate) hasTemporal = true;
6083
+ temporalCount++;
6084
+ features[i] = {
6085
+ ...f,
6086
+ id,
6087
+ properties: {
6088
+ ...props,
6089
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
6090
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
6091
+ }
6092
+ };
6093
+ }
6094
+ if (logging) {
6095
+ mapPerfLog("normalize", `${caller ?? "prepareFeaturesForLayer"} normalized ${count} features`, {
6096
+ ms: Math.round((performance.now() - started) * 10) / 10,
6097
+ withTemporalKeys: temporalCount,
6098
+ hasTemporal,
6099
+ reused,
6100
+ copied: count - reused
6101
+ });
6102
+ }
6103
+ return { features, featureIds, hasTemporal };
6104
+ }
6105
+ function scanTemporalFeatures(features, resolveLayerId, out) {
6106
+ let foundTemporal = false;
6107
+ for (let i = 0; i < features.length; i++) {
6108
+ const feature = features[i];
6109
+ const id = feature.id;
6110
+ const props = feature.properties || {};
6111
+ if (!hasAnyTemporalValue(props)) {
6112
+ out.untimedIds.push(id);
6113
+ continue;
6114
+ }
6115
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6116
+ if (startDate || endDate) {
6117
+ out.temporal.push({ id, startDate, endDate, layerId: resolveLayerId(id) });
6118
+ foundTemporal = true;
6119
+ } else {
6120
+ out.untimedIds.push(id);
6121
+ }
6122
+ }
6123
+ return foundTemporal;
6124
+ }
6125
+ function shouldDiffDrawRender({ mode, pointerDown, hasSelection }) {
6126
+ if (mode === "view_select") return false;
6127
+ if (mode === "simple_select" || mode === "direct_select") return pointerDown && hasSelection;
6128
+ return true;
6129
+ }
6130
+ function extendBounds(bounds, coords) {
6131
+ if (!Array.isArray(coords) || coords.length === 0) return;
6132
+ if (typeof coords[0] === "number") {
6133
+ const lng = coords[0];
6134
+ const lat = coords[1];
6135
+ if (lng < bounds.minLng) bounds.minLng = lng;
6136
+ if (lng > bounds.maxLng) bounds.maxLng = lng;
6137
+ if (lat < bounds.minLat) bounds.minLat = lat;
6138
+ if (lat > bounds.maxLat) bounds.maxLat = lat;
6139
+ return;
6140
+ }
6141
+ for (const nested of coords) extendBounds(bounds, nested);
6142
+ }
6143
+ function computeBounds(coords) {
6144
+ const bounds = { minLng: Infinity, minLat: Infinity, maxLng: -Infinity, maxLat: -Infinity };
6145
+ extendBounds(bounds, coords);
6146
+ return bounds;
6147
+ }
6148
+ function boundsDisjoint(a, b) {
6149
+ return a.maxLng < b.minLng || a.minLng > b.maxLng || a.maxLat < b.minLat || a.minLat > b.maxLat;
6150
+ }
6151
+ function pointInBounds(lng, lat, b) {
6152
+ return lng >= b.minLng && lng <= b.maxLng && lat >= b.minLat && lat <= b.maxLat;
6153
+ }
6154
+ function buildGroupSpatialIndex(features) {
6155
+ var _a;
6156
+ const boxes = [];
6157
+ const positions = [];
6158
+ for (let p = 0; p < features.length; p++) {
6159
+ const geom = (_a = features[p]) == null ? void 0 : _a.geometry;
6160
+ const b = computeBounds(geom == null ? void 0 : geom.coordinates);
6161
+ if (!isFinite(b.minLng) || !isFinite(b.minLat) || !isFinite(b.maxLng) || !isFinite(b.maxLat)) {
6162
+ continue;
6163
+ }
6164
+ boxes.push(b.minLng, b.minLat, b.maxLng, b.maxLat);
6165
+ positions.push(p);
6166
+ }
6167
+ if (positions.length === 0) {
6168
+ return { tree: null, positions, size: features.length };
6169
+ }
6170
+ const startedAt = performance.now();
6171
+ const tree = new Flatbush(positions.length);
6172
+ for (let i = 0; i < boxes.length; i += 4) {
6173
+ tree.add(boxes[i], boxes[i + 1], boxes[i + 2], boxes[i + 3]);
6174
+ }
6175
+ tree.finish();
6176
+ mapPerfLog("spatial-index", "built group index", {
6177
+ indexed: positions.length,
6178
+ of: features.length,
6179
+ ms: Math.round(performance.now() - startedAt)
6180
+ });
6181
+ return { tree, positions, size: features.length };
6182
+ }
6183
+ const indexCache = /* @__PURE__ */ new WeakMap();
6184
+ const failedBuilds = /* @__PURE__ */ new WeakSet();
6185
+ function getGroupSpatialIndex(features) {
6186
+ if (failedBuilds.has(features)) return void 0;
6187
+ let index = indexCache.get(features);
6188
+ if (!index) {
6189
+ try {
6190
+ index = buildGroupSpatialIndex(features);
6191
+ } catch {
6192
+ failedBuilds.add(features);
6193
+ return void 0;
6194
+ }
6195
+ indexCache.set(features, index);
6196
+ }
6197
+ return index;
6198
+ }
6199
+ function queryCandidatePositions(index, bounds) {
6200
+ if (!index.tree) return [];
6201
+ const items = index.tree.search(bounds.minLng, bounds.minLat, bounds.maxLng, bounds.maxLat);
6202
+ const positions = items.map((i) => index.positions[i]);
6203
+ positions.sort((a, b) => a - b);
6204
+ return positions;
6205
+ }
6206
+ function collectVisibleFeatureGroups(drawFeatures, readOnlyByLayer, layers) {
6207
+ const groups = [];
6208
+ if (drawFeatures) groups.push({ features: drawFeatures });
6209
+ const layerById = new Map(layers.map((l) => [l.id, l]));
6210
+ readOnlyByLayer.forEach((features, layerId) => {
6211
+ var _a;
6212
+ if ((_a = layerById.get(layerId)) == null ? void 0 : _a.visible) {
6213
+ groups.push({ features, index: getGroupSpatialIndex(features) });
6214
+ }
6215
+ });
6216
+ return groups;
6217
+ }
6218
+ function featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) {
6219
+ const geom = feature.geometry;
6220
+ if ((geom == null ? void 0 : geom.type) === "Point") {
6221
+ const lng = geom.coordinates[0];
6222
+ const lat = geom.coordinates[1];
6223
+ return typeof lng === "number" && typeof lat === "number" && pointInBounds(lng, lat, selectionBounds) && (rectExactForPoints || turf.booleanPointInPolygon(geom.coordinates, selectionPolygon));
6224
+ }
6225
+ if ((geom == null ? void 0 : geom.type) === "LineString" || (geom == null ? void 0 : geom.type) === "Polygon" || (geom == null ? void 0 : geom.type) === "MultiPoint" || (geom == null ? void 0 : geom.type) === "MultiLineString" || (geom == null ? void 0 : geom.type) === "MultiPolygon") {
6226
+ return !boundsDisjoint(computeBounds(geom.coordinates), selectionBounds) && turf.booleanIntersects(feature, selectionPolygon);
6227
+ }
6228
+ return false;
6229
+ }
6230
+ function hitTestSelection(featureGroups, selectionPolygon, options) {
6231
+ const selectionBounds = computeBounds(selectionPolygon.geometry.coordinates);
6232
+ const rectExactForPoints = (options == null ? void 0 : options.axisAlignedRectangle) === true;
6233
+ const selectedIds = [];
6234
+ let visited = 0;
6235
+ let total = 0;
6236
+ for (const group of featureGroups) {
6237
+ const { features, index } = group;
6238
+ total += features.length;
6239
+ const useIndex = index !== void 0 && index.size === features.length;
6240
+ const candidates = useIndex ? queryCandidatePositions(index, selectionBounds) : null;
6241
+ const count = candidates ? candidates.length : features.length;
6242
+ visited += count;
6243
+ for (let i = 0; i < count; i++) {
6244
+ const feature = candidates ? features[candidates[i]] : features[i];
6245
+ try {
6246
+ if (featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) && feature.id) {
6247
+ selectedIds.push(String(feature.id));
6248
+ }
6249
+ } catch {
6250
+ }
6251
+ }
6252
+ }
6253
+ mapPerfLog("hit-test", "selection gesture", { visited, total, selected: selectedIds.length });
6254
+ return selectedIds;
6255
+ }
6256
+ const OTHER_BUCKET_KEY = "__other__";
6257
+ const OTHER_BUCKET_LABEL = "Other";
6258
+ const OTHER_BUCKET_COLOR = "#9ca3af";
6259
+ function toDisplayName(name) {
6260
+ return name === OTHER_BUCKET_KEY ? OTHER_BUCKET_LABEL : name;
6261
+ }
6262
+ function createPieSVG(categories, total, size = 44, onSliceHover) {
6263
+ const container = document.createElement("div");
6264
+ container.style.width = `${size}px`;
6265
+ container.style.height = `${size}px`;
6266
+ container.style.cursor = "pointer";
6267
+ const radius = size / 2;
6268
+ const innerRadius = radius * 0.5;
6269
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
6270
+ svg.setAttribute("width", String(size));
6271
+ svg.setAttribute("height", String(size));
6272
+ svg.setAttribute("viewBox", `0 0 ${size} ${size}`);
5406
6273
  svg.style.display = "block";
5407
6274
  const bgCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
5408
6275
  bgCircle.setAttribute("cx", String(radius));
@@ -5692,92 +6559,6 @@ function ClusterPieManager(props) {
5692
6559
  }, [visible, updateMarkers]);
5693
6560
  return null;
5694
6561
  }
5695
- proj4.defs("EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs");
5696
- proj4.defs("EPSG:3857", "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs");
5697
- proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
5698
- proj4.defs("EPSG:32631", "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs");
5699
- function detectAndReprojectGeoJSON(geojson) {
5700
- var _a;
5701
- const crsProperty = geojson.crs;
5702
- let sourceCRS = null;
5703
- if ((_a = crsProperty == null ? void 0 : crsProperty.properties) == null ? void 0 : _a.name) {
5704
- const crsName = crsProperty.properties.name;
5705
- const epsgMatch = crsName.match(/EPSG::?(\d+)/i);
5706
- if (epsgMatch) {
5707
- sourceCRS = `EPSG:${epsgMatch[1]}`;
5708
- }
5709
- }
5710
- if (!sourceCRS && geojson.features.length > 0) {
5711
- const firstCoord = getFirstCoordinate(geojson.features[0].geometry);
5712
- if (firstCoord) {
5713
- const [x, y] = firstCoord;
5714
- const looksLikeWGS84 = Math.abs(x) <= 180 && Math.abs(y) <= 90;
5715
- if (looksLikeWGS84) {
5716
- return { features: geojson, reprojected: false, sourceCRS: "EPSG:4326" };
5717
- }
5718
- }
5719
- }
5720
- if (sourceCRS === "EPSG:4326") {
5721
- return { features: geojson, reprojected: false, sourceCRS };
5722
- }
5723
- if (sourceCRS && proj4.defs(sourceCRS)) {
5724
- try {
5725
- const reprojectedFeatures = geojson.features.map((feature) => ({
5726
- ...feature,
5727
- geometry: reprojectGeometry(feature.geometry, sourceCRS)
5728
- }));
5729
- return {
5730
- features: { ...geojson, type: "FeatureCollection", features: reprojectedFeatures },
5731
- reprojected: true,
5732
- sourceCRS
5733
- };
5734
- } catch (e) {
5735
- console.error("Reprojection failed:", e);
5736
- }
5737
- }
5738
- return { features: geojson, reprojected: false, sourceCRS };
5739
- }
5740
- function getFirstCoordinate(geometry) {
5741
- var _a, _b, _c;
5742
- if (!geometry) return null;
5743
- switch (geometry.type) {
5744
- case "Point":
5745
- return geometry.coordinates;
5746
- case "MultiPoint":
5747
- case "LineString":
5748
- return geometry.coordinates[0];
5749
- case "MultiLineString":
5750
- case "Polygon":
5751
- return (_a = geometry.coordinates[0]) == null ? void 0 : _a[0];
5752
- case "MultiPolygon":
5753
- return (_c = (_b = geometry.coordinates[0]) == null ? void 0 : _b[0]) == null ? void 0 : _c[0];
5754
- default:
5755
- return null;
5756
- }
5757
- }
5758
- function reprojectGeometry(geometry, fromCRS) {
5759
- const transform = (coord) => {
5760
- const [x, y] = proj4(fromCRS, "EPSG:4326", [coord[0], coord[1]]);
5761
- return coord.length > 2 ? [x, y, ...coord.slice(2)] : [x, y];
5762
- };
5763
- const reprojectCoords = (coords) => {
5764
- if (typeof coords[0] === "number") {
5765
- return transform(coords);
5766
- }
5767
- return coords.map(reprojectCoords);
5768
- };
5769
- if (geometry.type === "GeometryCollection") {
5770
- return {
5771
- type: "GeometryCollection",
5772
- geometries: geometry.geometries.map((g) => reprojectGeometry(g, fromCRS))
5773
- };
5774
- }
5775
- const geomWithCoords = geometry;
5776
- return {
5777
- ...geomWithCoords,
5778
- coordinates: reprojectCoords(geomWithCoords.coordinates)
5779
- };
5780
- }
5781
6562
  const EMOJI_CANVAS_SIZE = 48;
5782
6563
  function renderEmojiToCanvas(emoji, size = EMOJI_CANVAS_SIZE) {
5783
6564
  const ratio = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
@@ -5917,17 +6698,6 @@ function createFlightPath3DLayer(layerId, mapInstance, flightPaths) {
5917
6698
  }
5918
6699
  };
5919
6700
  }
5920
- function hasAltitudeData(feature) {
5921
- if (feature.geometry.type === "LineString") {
5922
- const coords = feature.geometry.coordinates;
5923
- return coords.some((c) => c.length >= 3 && c[2] !== 0);
5924
- }
5925
- if (feature.geometry.type === "MultiLineString") {
5926
- const coords = feature.geometry.coordinates;
5927
- return coords.some((line) => line.some((c) => c.length >= 3 && c[2] !== 0));
5928
- }
5929
- return false;
5930
- }
5931
6701
  function extract3DFlightPaths(features) {
5932
6702
  const paths = [];
5933
6703
  features.forEach((feature) => {
@@ -6193,7 +6963,6 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6193
6963
  const [visibleFeatureCount, setVisibleFeatureCount] = useState(Infinity);
6194
6964
  const lastLabelVisibility = useRef(false);
6195
6965
  const [labelsSuppressed, setLabelsSuppressed] = useState(true);
6196
- const [cursorCoords, setCursorCoords] = useState(null);
6197
6966
  const [contextMenu, setContextMenu] = useState(null);
6198
6967
  const [timelineStoreApi] = useState(createTimelineStore);
6199
6968
  const timelineStore = useStore(timelineStoreApi);
@@ -6369,14 +7138,22 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6369
7138
  return false;
6370
7139
  }
6371
7140
  });
6372
- draw.current.changeMode(mode, { featureIds: visibleEditableIds });
7141
+ const needsDrawCall = needsDrawSelectionUpdate({
7142
+ editableSelectionCount: visibleEditableIds.length,
7143
+ drawSelectedCount: draw.current.getSelectedIds().length,
7144
+ currentMode: draw.current.getMode(),
7145
+ targetMode: mode
7146
+ });
7147
+ if (needsDrawCall) {
7148
+ draw.current.changeMode(mode, { featureIds: visibleEditableIds });
7149
+ }
6373
7150
  setSelectedFeatureIds(nextIds);
6374
7151
  selectedFeatureIdsRef.current = nextIds;
6375
7152
  if (options == null ? void 0 : options.focusProperties) setShowProperties(nextIds.length > 0);
6376
7153
  if (onFeatureSelect) {
6377
7154
  onFeatureSelect(nextIds.map((id) => getFeatureById(id)).filter(Boolean));
6378
7155
  }
6379
- syncRef.current();
7156
+ scheduleSync("selection");
6380
7157
  if (readOnlyIds.length > 0) {
6381
7158
  queueMicrotask(() => {
6382
7159
  isSelectingReadOnlyRef.current = false;
@@ -6399,9 +7176,39 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6399
7176
  setFeatureCount(drawFeatureCount + hiddenCount + readOnlyCount);
6400
7177
  }, []);
6401
7178
  const timelineVisibleIdsRef = useRef(null);
6402
- const timelineSyncRafRef = useRef(null);
6403
7179
  const syncRef = useRef(() => {
6404
7180
  });
7181
+ const trySelectionFastPathRef = useRef(null);
7182
+ const tryTimelineFastPathRef = useRef(null);
7183
+ const syncCoalescerRef = useRef(null);
7184
+ if (syncCoalescerRef.current === null) {
7185
+ syncCoalescerRef.current = createRafCoalescer((reasons) => {
7186
+ var _a, _b;
7187
+ if (!reasons.has("full")) {
7188
+ let handled = true;
7189
+ if (reasons.has("timeline")) handled = ((_a = tryTimelineFastPathRef.current) == null ? void 0 : _a.call(tryTimelineFastPathRef)) ?? false;
7190
+ if (handled && reasons.has("selection")) handled = ((_b = trySelectionFastPathRef.current) == null ? void 0 : _b.call(trySelectionFastPathRef)) ?? false;
7191
+ if (handled) {
7192
+ mapPerfLog("sync", "frame handled by fast path(s)", reasons);
7193
+ return;
7194
+ }
7195
+ mapPerfLog("sync", "fast path bailed — full rebuild", reasons);
7196
+ }
7197
+ syncRef.current();
7198
+ });
7199
+ }
7200
+ const fullSyncCallersRef = useRef([]);
7201
+ const scheduleSync = useCallback((reason = "full") => {
7202
+ var _a, _b;
7203
+ if (reason === "full" && mapPerfLogEnabled() && fullSyncCallersRef.current.length < 4) {
7204
+ const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n").slice(2, 5).map((line) => line.trim()).join(" ← ");
7205
+ if (stack) fullSyncCallersRef.current.push(stack);
7206
+ }
7207
+ (_b = syncCoalescerRef.current) == null ? void 0 : _b.schedule(reason);
7208
+ }, []);
7209
+ useEffect(() => {
7210
+ scheduleSync();
7211
+ }, [layers, scheduleSync]);
6405
7212
  const hashStringToColor$1 = useCallback((str) => hashStringToColor(str), []);
6406
7213
  const selectedFeatureColors = useMemo(() => {
6407
7214
  if (selectedFeatureIds.length === 0) return /* @__PURE__ */ new Map();
@@ -6487,17 +7294,116 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6487
7294
  );
6488
7295
  }, []);
6489
7296
  const isSyncingRef = useRef(false);
7297
+ const selectionPaintCacheRef = useRef(null);
7298
+ const paintedArrowLinesRef = useRef([]);
7299
+ const renderArrowOverlays = useCallback((arrowLines) => {
7300
+ const mapInstance = map.current;
7301
+ if (!mapInstance) return;
7302
+ const arrowHeadSource = mapInstance.getSource("arrow-heads");
7303
+ if (arrowHeadSource) {
7304
+ const arrowHeadTriangles = [];
7305
+ const headLength = 16;
7306
+ const headWidth = 10;
7307
+ arrowLines.forEach((f) => {
7308
+ const coords = f.geometry.coordinates;
7309
+ if (coords.length < 2) return;
7310
+ const end = coords[coords.length - 1];
7311
+ const prev = coords[coords.length - 2];
7312
+ const endScreen = mapInstance.project(end);
7313
+ const prevScreen = mapInstance.project(prev);
7314
+ const dx = endScreen.x - prevScreen.x;
7315
+ const dy = endScreen.y - prevScreen.y;
7316
+ const len = Math.sqrt(dx * dx + dy * dy);
7317
+ if (len < 1e-3) return;
7318
+ const dirX = dx / len;
7319
+ const dirY = dy / len;
7320
+ const perpX = -dirY;
7321
+ const perpY = dirX;
7322
+ const tipScreen = { x: endScreen.x, y: endScreen.y };
7323
+ const baseLeftScreen = {
7324
+ x: endScreen.x - dirX * headLength - perpX * headWidth,
7325
+ y: endScreen.y - dirY * headLength - perpY * headWidth
7326
+ };
7327
+ const baseRightScreen = {
7328
+ x: endScreen.x - dirX * headLength + perpX * headWidth,
7329
+ y: endScreen.y - dirY * headLength + perpY * headWidth
7330
+ };
7331
+ const tipGeo = mapInstance.unproject([tipScreen.x, tipScreen.y]);
7332
+ const baseLeftGeo = mapInstance.unproject([baseLeftScreen.x, baseLeftScreen.y]);
7333
+ const baseRightGeo = mapInstance.unproject([baseRightScreen.x, baseRightScreen.y]);
7334
+ arrowHeadTriangles.push({
7335
+ type: "Feature",
7336
+ geometry: {
7337
+ type: "Polygon",
7338
+ coordinates: [[
7339
+ [tipGeo.lng, tipGeo.lat],
7340
+ [baseLeftGeo.lng, baseLeftGeo.lat],
7341
+ [baseRightGeo.lng, baseRightGeo.lat],
7342
+ [tipGeo.lng, tipGeo.lat]
7343
+ // Close the polygon
7344
+ ]]
7345
+ },
7346
+ properties: {
7347
+ ...f.properties
7348
+ }
7349
+ });
7350
+ });
7351
+ arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
7352
+ }
7353
+ const arrowLabelSource = mapInstance.getSource("arrow-labels");
7354
+ if (arrowLabelSource) {
7355
+ const arrowLabelPoints = [];
7356
+ arrowLines.forEach((f) => {
7357
+ var _a;
7358
+ const name = (_a = f.properties) == null ? void 0 : _a.name;
7359
+ if (!name) return;
7360
+ const coords = f.geometry.coordinates;
7361
+ if (coords.length < 2) return;
7362
+ const start = coords[0];
7363
+ const end = coords[coords.length - 1];
7364
+ const midPoint = [
7365
+ (start[0] + end[0]) / 2,
7366
+ (start[1] + end[1]) / 2
7367
+ ];
7368
+ const dLng = end[0] - start[0];
7369
+ const dLat = end[1] - start[1];
7370
+ const angleFromEast = Math.atan2(dLat, dLng) * (180 / Math.PI);
7371
+ let labelBearing = -angleFromEast;
7372
+ labelBearing = (labelBearing % 360 + 540) % 360 - 180;
7373
+ if (labelBearing > 90) {
7374
+ labelBearing -= 180;
7375
+ } else if (labelBearing < -90) {
7376
+ labelBearing += 180;
7377
+ }
7378
+ arrowLabelPoints.push({
7379
+ type: "Feature",
7380
+ geometry: {
7381
+ type: "Point",
7382
+ coordinates: midPoint
7383
+ },
7384
+ properties: {
7385
+ ...f.properties,
7386
+ labelBearing
7387
+ }
7388
+ });
7389
+ });
7390
+ arrowLabelSource.setData({ type: "FeatureCollection", features: arrowLabelPoints });
7391
+ }
7392
+ }, []);
6490
7393
  const syncFeaturesToCustomLayers = useCallback(() => {
6491
7394
  if (!map.current) return;
6492
7395
  if (isSyncingRef.current) return;
6493
7396
  isSyncingRef.current = true;
7397
+ const fullSyncStart = performance.now();
6494
7398
  try {
6495
7399
  const source = map.current.getSource("custom-features");
6496
7400
  if (!source) return;
6497
7401
  const drawFeatures = draw.current ? draw.current.getAll() : { type: "FeatureCollection", features: [] };
6498
7402
  const drawSelectedIds = draw.current ? draw.current.getSelectedIds() : [];
6499
7403
  const componentSelectedIds = selectedFeatureIdsRef.current;
6500
- const selectedIds = Array.from(/* @__PURE__ */ new Set([...drawSelectedIds, ...componentSelectedIds]));
7404
+ const selectedIdSet = /* @__PURE__ */ new Set();
7405
+ drawSelectedIds.forEach((id) => selectedIdSet.add(String(id)));
7406
+ componentSelectedIds.forEach((id) => selectedIdSet.add(String(id)));
6501
7407
  const visibleSet = timelineVisibleIdsRef.current;
6502
7408
  const currentLayers = layersRef.current;
6503
7409
  const isLayerVisible = (layer) => {
@@ -6602,6 +7508,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6602
7508
  }
6603
7509
  });
6604
7510
  });
7511
+ const paintCache = createSelectionPaintCache();
6605
7512
  const sourceData = {
6606
7513
  type: "FeatureCollection",
6607
7514
  features: allFeatures.map((f) => {
@@ -6610,7 +7517,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6610
7517
  const layer = featureToLayer.get(featureId);
6611
7518
  const visualConfig = layer == null ? void 0 : layer.visualConfig;
6612
7519
  const isTimelineVisible = visibleSet === null || visibleSet.has(featureId);
6613
- const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? 1;
7520
+ const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? DEFAULT_VISIBLE_STROKE_OPACITY;
6614
7521
  let strokeColor = ((_b = f.properties) == null ? void 0 : _b.stroke) || "#3b82f6";
6615
7522
  const colorConfig = visualConfig == null ? void 0 : visualConfig.color;
6616
7523
  if (colorConfig) {
@@ -6679,7 +7586,6 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6679
7586
  const isPoint = f.geometry.type === "Point";
6680
7587
  const hideByHeatmap = isPoint && ((_i = layer == null ? void 0 : layer.heatmapConfig) == null ? void 0 : _i.enabled) === true;
6681
7588
  const hideByCluster = isPoint && ((_j = layer == null ? void 0 : layer.clusterConfig) == null ? void 0 : _j.enabled) === true && !((_k = layer == null ? void 0 : layer.clusterConfig) == null ? void 0 : _k.showPointDots);
6682
- const isSelected = selectedIds.includes(featureId);
6683
7589
  const hideByTrace = false;
6684
7590
  const isLine = f.geometry.type === "LineString" || f.geometry.type === "MultiLineString";
6685
7591
  const hideFlatFor3DOnly = isLine && (layer == null ? void 0 : layer.hasAltitudeData) && (layer == null ? void 0 : layer.altitudeDisplayMode) === "3d";
@@ -6697,14 +7603,12 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6697
7603
  }
6698
7604
  });
6699
7605
  }
6700
- const isFeatureSelected = (enableSelectionRef.current || enableDrawingRef.current) && selectedIds.includes(featureId) ? 1 : 0;
6701
- let labelPriority = 100;
6702
- if (isFeatureSelected) {
6703
- labelPriority = 0;
6704
- } else if (traceLabel) {
6705
- labelPriority = 5;
7606
+ const isFeatureSelected = (enableSelectionRef.current || enableDrawingRef.current) && selectedIdSet.has(featureId) ? 1 : 0;
7607
+ let basePriority = DEFAULT_LABEL_PRIORITY;
7608
+ if (traceLabel) {
7609
+ basePriority = 5;
6706
7610
  } else if (((_l = f.properties) == null ? void 0 : _l.kind) === "text") {
6707
- labelPriority = ((_m = f.properties) == null ? void 0 : _m.fontWeight) === "bold" ? 8 : 10;
7611
+ basePriority = ((_m = f.properties) == null ? void 0 : _m.fontWeight) === "bold" ? 8 : 10;
6708
7612
  } else {
6709
7613
  const idStr = String(featureId);
6710
7614
  let h = 0;
@@ -6712,8 +7616,20 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6712
7616
  h = (h << 5) - h + idStr.charCodeAt(i);
6713
7617
  h |= 0;
6714
7618
  }
6715
- labelPriority = 100 + Math.abs(h) % 1e3;
6716
- }
7619
+ basePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
7620
+ }
7621
+ const labelPriority = isFeatureSelected ? 0 : basePriority;
7622
+ const visibleStrokeOpacity = hideFlatFor3DOnly ? 0 : baseOpacity;
7623
+ const visibleFillOpacity = hideFlatFor3DOnly ? 0 : ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? DEFAULT_VISIBLE_FILL_OPACITY;
7624
+ recordPaintedFeature(
7625
+ paintCache,
7626
+ featureId,
7627
+ basePriority,
7628
+ isFeatureSelected === 1,
7629
+ visibleStrokeOpacity,
7630
+ visibleFillOpacity,
7631
+ !isTimelineVisible
7632
+ );
6717
7633
  return {
6718
7634
  type: "Feature",
6719
7635
  id: featureId,
@@ -6734,9 +7650,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6734
7650
  iconSize: featureIconSize,
6735
7651
  stroke: strokeColor,
6736
7652
  "stroke-width": strokeWidth,
6737
- "stroke-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? baseOpacity : 0,
7653
+ "stroke-opacity": isTimelineVisible ? visibleStrokeOpacity : 0,
6738
7654
  fill: strokeColor,
6739
- "fill-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? 0.2 : 0,
7655
+ "fill-opacity": isTimelineVisible ? visibleFillOpacity : 0,
6740
7656
  pointRadius,
6741
7657
  isHiddenFor3DOnly: hideFlatFor3DOnly ? 1 : 0,
6742
7658
  isTimelineHidden: isTimelineVisible ? 0 : 1,
@@ -6746,6 +7662,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6746
7662
  })
6747
7663
  };
6748
7664
  source.setData(sourceData);
7665
+ selectionPaintCacheRef.current = paintCache;
6749
7666
  const traceSource = map.current.getSource("trace-features");
6750
7667
  if (traceSource) {
6751
7668
  const traceSegments = [];
@@ -6834,104 +7751,19 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6834
7751
  });
6835
7752
  traceSource.setData({ type: "FeatureCollection", features: traceSegments });
6836
7753
  }
6837
- const arrowHeadSource = map.current.getSource("arrow-heads");
6838
- if (arrowHeadSource && map.current) {
6839
- const arrowHeadTriangles = [];
6840
- const mapInstance = map.current;
7754
+ {
6841
7755
  let sawArrowFeature = false;
6842
- const headLength = 16;
6843
- const headWidth = 10;
7756
+ const arrowLines = [];
6844
7757
  sourceData.features.forEach((f) => {
6845
7758
  var _a;
6846
7759
  const isArrow = ((_a = f.properties) == null ? void 0 : _a.kind) === "arrow" || arrowFeatureIdsRef.current.has(String(f.id));
6847
- if (isArrow) sawArrowFeature = true;
6848
- if (f.geometry.type !== "LineString" || !isArrow) return;
6849
- const coords = f.geometry.coordinates;
6850
- if (coords.length < 2) return;
6851
- const end = coords[coords.length - 1];
6852
- const prev = coords[coords.length - 2];
6853
- const endScreen = mapInstance.project(end);
6854
- const prevScreen = mapInstance.project(prev);
6855
- const dx = endScreen.x - prevScreen.x;
6856
- const dy = endScreen.y - prevScreen.y;
6857
- const len = Math.sqrt(dx * dx + dy * dy);
6858
- if (len < 1e-3) return;
6859
- const dirX = dx / len;
6860
- const dirY = dy / len;
6861
- const perpX = -dirY;
6862
- const perpY = dirX;
6863
- const tipScreen = { x: endScreen.x, y: endScreen.y };
6864
- const baseLeftScreen = {
6865
- x: endScreen.x - dirX * headLength - perpX * headWidth,
6866
- y: endScreen.y - dirY * headLength - perpY * headWidth
6867
- };
6868
- const baseRightScreen = {
6869
- x: endScreen.x - dirX * headLength + perpX * headWidth,
6870
- y: endScreen.y - dirY * headLength + perpY * headWidth
6871
- };
6872
- const tipGeo = mapInstance.unproject([tipScreen.x, tipScreen.y]);
6873
- const baseLeftGeo = mapInstance.unproject([baseLeftScreen.x, baseLeftScreen.y]);
6874
- const baseRightGeo = mapInstance.unproject([baseRightScreen.x, baseRightScreen.y]);
6875
- arrowHeadTriangles.push({
6876
- type: "Feature",
6877
- geometry: {
6878
- type: "Polygon",
6879
- coordinates: [[
6880
- [tipGeo.lng, tipGeo.lat],
6881
- [baseLeftGeo.lng, baseLeftGeo.lat],
6882
- [baseRightGeo.lng, baseRightGeo.lat],
6883
- [tipGeo.lng, tipGeo.lat]
6884
- // Close the polygon
6885
- ]]
6886
- },
6887
- properties: {
6888
- ...f.properties
6889
- }
6890
- });
7760
+ if (!isArrow) return;
7761
+ sawArrowFeature = true;
7762
+ if (f.geometry.type === "LineString") arrowLines.push(f);
6891
7763
  });
6892
- arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
6893
7764
  hasArrowFeaturesRef.current = sawArrowFeature;
6894
- }
6895
- const arrowLabelSource = map.current.getSource("arrow-labels");
6896
- if (arrowLabelSource) {
6897
- const arrowLabelPoints = [];
6898
- sourceData.features.forEach((f) => {
6899
- var _a, _b;
6900
- const isArrow = ((_a = f.properties) == null ? void 0 : _a.kind) === "arrow" || arrowFeatureIdsRef.current.has(String(f.id));
6901
- if (f.geometry.type !== "LineString" || !isArrow) return;
6902
- const name = (_b = f.properties) == null ? void 0 : _b.name;
6903
- if (!name) return;
6904
- const coords = f.geometry.coordinates;
6905
- if (coords.length < 2) return;
6906
- const start = coords[0];
6907
- const end = coords[coords.length - 1];
6908
- const midPoint = [
6909
- (start[0] + end[0]) / 2,
6910
- (start[1] + end[1]) / 2
6911
- ];
6912
- const dLng = end[0] - start[0];
6913
- const dLat = end[1] - start[1];
6914
- const angleFromEast = Math.atan2(dLat, dLng) * (180 / Math.PI);
6915
- let labelBearing = -angleFromEast;
6916
- labelBearing = (labelBearing % 360 + 540) % 360 - 180;
6917
- if (labelBearing > 90) {
6918
- labelBearing -= 180;
6919
- } else if (labelBearing < -90) {
6920
- labelBearing += 180;
6921
- }
6922
- arrowLabelPoints.push({
6923
- type: "Feature",
6924
- geometry: {
6925
- type: "Point",
6926
- coordinates: midPoint
6927
- },
6928
- properties: {
6929
- ...f.properties,
6930
- labelBearing
6931
- }
6932
- });
6933
- });
6934
- arrowLabelSource.setData({ type: "FeatureCollection", features: arrowLabelPoints });
7765
+ paintedArrowLinesRef.current = arrowLines;
7766
+ renderArrowOverlays(arrowLines);
6935
7767
  }
6936
7768
  if (update3DFlightPathsRef == null ? void 0 : update3DFlightPathsRef.current) {
6937
7769
  update3DFlightPathsRef.current();
@@ -6941,11 +7773,18 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6941
7773
  setVisibleFeatureCount(countVisibleFeatures(threshold));
6942
7774
  setLabelsSuppressed(false);
6943
7775
  }
7776
+ const requestedBy = fullSyncCallersRef.current.splice(0);
7777
+ mapPerfLog("sync", "full rebuild", {
7778
+ features: sourceData.features.length,
7779
+ ms: Math.round(performance.now() - fullSyncStart),
7780
+ requestedBy
7781
+ });
6944
7782
  } finally {
6945
7783
  isSyncingRef.current = false;
6946
7784
  }
6947
- }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures]);
7785
+ }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures, renderArrowOverlays]);
6948
7786
  const update3DFlightPaths = useCallback(() => {
7787
+ var _a;
6949
7788
  if (!map.current || !is3DTerrainEnabled) {
6950
7789
  if (map.current && flightPath3DLayerId.current) {
6951
7790
  try {
@@ -6966,20 +7805,21 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6966
7805
  const allFeatures = [];
6967
7806
  const currentLayers = layersRef.current;
6968
7807
  if (draw.current) {
6969
- const drawFeatures = draw.current.getAll().features.filter((feature) => {
6970
- var _a;
6971
- if (!isFeatureVisibleInTimeline(feature)) return false;
6972
- const featureId = feature.id;
6973
- const layer2 = currentLayers.find((l) => l.featureIds.includes(featureId));
6974
- return ((_a = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a.enabled) === true;
6975
- });
7808
+ const traceFeatureIds = /* @__PURE__ */ new Set();
7809
+ for (const l of currentLayers) {
7810
+ if (((_a = l.traceConfig) == null ? void 0 : _a.enabled) !== true) continue;
7811
+ for (const featureId of l.featureIds) traceFeatureIds.add(featureId);
7812
+ }
7813
+ const drawFeatures = draw.current.getAll().features.filter(
7814
+ (feature) => isFeatureVisibleInTimeline(feature) && traceFeatureIds.has(feature.id)
7815
+ );
6976
7816
  pushAll(allFeatures, drawFeatures);
6977
7817
  }
6978
7818
  readOnlyFeatures.current.forEach((features, layerId2) => {
6979
- var _a;
7819
+ var _a2;
6980
7820
  const layer2 = currentLayers.find((l) => l.id === layerId2);
6981
7821
  const altitudeMode = (layer2 == null ? void 0 : layer2.altitudeDisplayMode) ?? "both";
6982
- const traceEnabled = ((_a = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a.enabled) === true;
7822
+ const traceEnabled = ((_a2 = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a2.enabled) === true;
6983
7823
  if ((layer2 == null ? void 0 : layer2.visible) && traceEnabled && (altitudeMode === "3d" || altitudeMode === "both")) {
6984
7824
  const visibleFeatures = features.filter(isFeatureVisibleInTimeline);
6985
7825
  pushAll(allFeatures, visibleFeatures);
@@ -7034,52 +7874,24 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7034
7874
  featureToLayer.set(fid, layer.id);
7035
7875
  }
7036
7876
  }
7037
- const temporalFeatures = [];
7038
- const untimedIds = [];
7039
- for (const feature of drawFeatures) {
7040
- const props = feature.properties || {};
7041
- if (!hasAnyTemporalValue(props)) {
7042
- untimedIds.push(feature.id);
7043
- continue;
7044
- }
7045
- const { startDate, endDate } = normalizeTemporalProperties(props);
7046
- if (startDate || endDate) {
7047
- temporalFeatures.push({
7048
- id: feature.id,
7049
- startDate,
7050
- endDate,
7051
- layerId: featureToLayer.get(feature.id) || "default"
7052
- });
7053
- } else {
7054
- untimedIds.push(feature.id);
7055
- }
7056
- }
7877
+ const scan = { temporal: [], untimedIds: [] };
7878
+ scanTemporalFeatures(
7879
+ drawFeatures,
7880
+ (id) => featureToLayer.get(id) || "default",
7881
+ scan
7882
+ );
7057
7883
  readOnlyFeatures.current.forEach((features, layerId) => {
7058
7884
  const layer = currentLayers.find((l) => l.id === layerId);
7059
7885
  if (!(layer == null ? void 0 : layer.visible)) return;
7060
7886
  const cached = layerTemporalCacheRef.current.get(layerId);
7061
7887
  if (cached && cached.featureCount === features.length && !cached.hasTemporal) {
7062
- for (const f of features) untimedIds.push(f.id);
7888
+ for (const f of features) scan.untimedIds.push(f.id);
7063
7889
  return;
7064
7890
  }
7065
- let layerHasTemporal = false;
7066
- for (const feature of features) {
7067
- const props = feature.properties || {};
7068
- if (!hasAnyTemporalValue(props)) {
7069
- untimedIds.push(feature.id);
7070
- continue;
7071
- }
7072
- const { startDate, endDate } = normalizeTemporalProperties(props);
7073
- if (startDate || endDate) {
7074
- temporalFeatures.push({ id: feature.id, startDate, endDate, layerId });
7075
- layerHasTemporal = true;
7076
- } else {
7077
- untimedIds.push(feature.id);
7078
- }
7079
- }
7891
+ const layerHasTemporal = scanTemporalFeatures(features, () => layerId, scan);
7080
7892
  layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: layerHasTemporal });
7081
7893
  });
7082
- timelineStoreApi.getState().setTemporalFeatures(temporalFeatures, untimedIds);
7894
+ timelineStoreApi.getState().setTemporalFeatures(scan.temporal, scan.untimedIds);
7083
7895
  }, [timelineStoreApi]);
7084
7896
  const scheduleTimelineUpdate = useCallback(() => {
7085
7897
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
@@ -7264,13 +8076,13 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7264
8076
  layerTemporalCacheRef.current.clear();
7265
8077
  updateFeatureCount();
7266
8078
  scheduleTimelineUpdate();
7267
- syncFeaturesToCustomLayers();
8079
+ scheduleSync();
7268
8080
  setFeatureUpdateCounter((c) => c + 1);
7269
8081
  queueMicrotask(() => {
7270
8082
  isSelectingReadOnlyRef.current = false;
7271
8083
  });
7272
8084
  },
7273
- [cleanupOrphanLayerSources, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers]
8085
+ [cleanupOrphanLayerSources, updateFeatureCount, scheduleTimelineUpdate, scheduleSync]
7274
8086
  );
7275
8087
  const buildDiffCommand = useCallback(
7276
8088
  (label, coalesceKey, before, after, beforeLayers, afterLayers, beforeSelectedIds, afterSelectedIds) => {
@@ -7355,6 +8167,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7355
8167
  }, [finalizeCapture]);
7356
8168
  useEffect(() => {
7357
8169
  if (!mapContainer.current || map.current) return;
8170
+ let removeDrawGateListeners;
7358
8171
  try {
7359
8172
  const baseStyle = createBaseStyle({
7360
8173
  glyphsUrl,
@@ -7413,12 +8226,6 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7413
8226
  ]
7414
8227
  });
7415
8228
  mapInstance.addControl(drawInstance);
7416
- mapInstance.on("mousemove", (e) => {
7417
- setCursorCoords({ lng: e.lngLat.lng, lat: e.lngLat.lat });
7418
- });
7419
- mapInstance.on("mouseout", () => {
7420
- setCursorCoords(null);
7421
- });
7422
8229
  requestAnimationFrame(() => {
7423
8230
  try {
7424
8231
  const container = mapInstance.getContainer();
@@ -8382,7 +9189,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8382
9189
  saveStateForUndo("draw feature", {
8383
9190
  excludeDrawIds: new Set(newFeatures.map((f) => String(f.id)))
8384
9191
  });
8385
- syncRef.current();
9192
+ scheduleSync();
8386
9193
  setTimeout(() => {
8387
9194
  setActiveMode("simple_select");
8388
9195
  if (drawInstance.getMode() !== "simple_select") {
@@ -8393,8 +9200,52 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8393
9200
  onFeatureCreate == null ? void 0 : onFeatureCreate(feature);
8394
9201
  });
8395
9202
  });
9203
+ let drawGatePointerDown = false;
9204
+ const onDrawGatePointerDown = () => {
9205
+ drawGatePointerDown = true;
9206
+ };
9207
+ const onDrawGatePointerUp = () => {
9208
+ drawGatePointerDown = false;
9209
+ };
9210
+ const drawGateCanvas = mapInstance.getCanvasContainer();
9211
+ drawGateCanvas.addEventListener("pointerdown", onDrawGatePointerDown);
9212
+ window.addEventListener("pointerup", onDrawGatePointerUp);
9213
+ window.addEventListener("pointercancel", onDrawGatePointerUp);
9214
+ window.addEventListener("blur", onDrawGatePointerUp);
9215
+ removeDrawGateListeners = () => {
9216
+ drawGateCanvas.removeEventListener("pointerdown", onDrawGatePointerDown);
9217
+ window.removeEventListener("pointerup", onDrawGatePointerUp);
9218
+ window.removeEventListener("pointercancel", onDrawGatePointerUp);
9219
+ window.removeEventListener("blur", onDrawGatePointerUp);
9220
+ };
9221
+ let lastDrawGeometries = /* @__PURE__ */ new Map();
9222
+ let drawGateSkips = 0;
8396
9223
  mapInstance.on("draw.render", () => {
8397
- syncRef.current();
9224
+ if (!shouldDiffDrawRender({
9225
+ mode: drawInstance.getMode(),
9226
+ pointerDown: drawGatePointerDown,
9227
+ hasSelection: drawInstance.getSelectedIds().length > 0
9228
+ })) {
9229
+ drawGateSkips++;
9230
+ return;
9231
+ }
9232
+ if (drawGateSkips > 0) {
9233
+ mapPerfLog("sync", "draw.render diff resumed", { skippedWhileIdle: drawGateSkips });
9234
+ drawGateSkips = 0;
9235
+ }
9236
+ const features = drawInstance.getAll().features;
9237
+ let changed = features.length !== lastDrawGeometries.size;
9238
+ const next = /* @__PURE__ */ new Map();
9239
+ features.forEach((f) => {
9240
+ const id = String(f.id);
9241
+ next.set(id, f.geometry);
9242
+ if (!changed) {
9243
+ const prev = lastDrawGeometries.get(id);
9244
+ if (!prev || !geometryEquals(prev, f.geometry)) changed = true;
9245
+ }
9246
+ });
9247
+ lastDrawGeometries = next;
9248
+ if (changed) scheduleSync();
8398
9249
  });
8399
9250
  mapInstance.on("draw.update", (e) => {
8400
9251
  const activeLayerId = activeEditingLayerIdRef.current;
@@ -8424,9 +9275,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8424
9275
  }
8425
9276
  } else {
8426
9277
  const previousGeometry = originalGeometriesRef.current.get(fid);
8427
- const geometryChanged = !previousGeometry || JSON.stringify(previousGeometry) !== JSON.stringify(feature.geometry);
9278
+ const geometryChanged = !previousGeometry || !geometryEquals(previousGeometry, feature.geometry);
8428
9279
  if (geometryChanged) {
8429
- originalGeometriesRef.current.set(fid, JSON.parse(JSON.stringify(feature.geometry)));
9280
+ originalGeometriesRef.current.set(fid, deepClone(feature.geometry));
8430
9281
  if (!externalPersistence) {
8431
9282
  drawInstance.setFeatureProperty(fid, "_unsaved", true);
8432
9283
  }
@@ -8435,8 +9286,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8435
9286
  }
8436
9287
  }
8437
9288
  });
8438
- syncRef.current();
8439
- if (e.action === "change_coordinates" && !hasRevertedFeatures) {
9289
+ scheduleSync();
9290
+ if ((e.action === "move" || e.action === "change_coordinates") && !hasRevertedFeatures) {
8440
9291
  scheduleTimelineUpdate();
8441
9292
  recordMoveFromPreDrag();
8442
9293
  }
@@ -8455,7 +9306,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8455
9306
  updateFeatureCount();
8456
9307
  scheduleTimelineUpdate();
8457
9308
  saveStateForUndo("delete feature", { addDrawFeatures: e.features });
8458
- syncRef.current();
9309
+ scheduleSync();
8459
9310
  onFeatureDelete == null ? void 0 : onFeatureDelete(deletedIds);
8460
9311
  });
8461
9312
  mapInstance.on("draw.selectionchange", (e) => {
@@ -8471,7 +9322,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8471
9322
  e.features.forEach((feature) => {
8472
9323
  const fid = feature.id;
8473
9324
  if (!originalGeometriesRef.current.has(fid)) {
8474
- originalGeometriesRef.current.set(fid, JSON.parse(JSON.stringify(feature.geometry)));
9325
+ originalGeometriesRef.current.set(fid, deepClone(feature.geometry));
8475
9326
  }
8476
9327
  });
8477
9328
  }
@@ -8488,11 +9339,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8488
9339
  if (enableProperties && (autoOpenProperties || !wasJustCreated)) {
8489
9340
  setShowProperties(ids.length > 0);
8490
9341
  }
8491
- syncRef.current();
9342
+ scheduleSync("selection");
8492
9343
  onFeatureSelect == null ? void 0 : onFeatureSelect(e.features);
8493
9344
  });
8494
9345
  mapInstance.on("draw.modechange", () => {
8495
- syncRef.current();
9346
+ scheduleSync();
8496
9347
  });
8497
9348
  mapInstance.on("click", (e) => {
8498
9349
  var _a;
@@ -8540,7 +9391,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8540
9391
  setSelectedFeatureIds(nextIds);
8541
9392
  selectedFeatureIdsRef.current = nextIds;
8542
9393
  if (enableProperties) setShowProperties(nextIds.length > 0);
8543
- syncRef.current();
9394
+ scheduleSync("selection");
8544
9395
  const selectedFeatures2 = [];
8545
9396
  for (const id of nextIds) {
8546
9397
  readOnlyFeatures.current.forEach((layerFeatures) => {
@@ -8573,7 +9424,10 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8573
9424
  setMapError(error instanceof Error ? error.message : "Failed to initialize map");
8574
9425
  }
8575
9426
  return () => {
9427
+ var _a;
8576
9428
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
9429
+ (_a = syncCoalescerRef.current) == null ? void 0 : _a.cancel();
9430
+ removeDrawGateListeners == null ? void 0 : removeDrawGateListeners();
8577
9431
  if (map.current) {
8578
9432
  map.current.remove();
8579
9433
  map.current = null;
@@ -8696,10 +9550,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8696
9550
  updateFeatureCount();
8697
9551
  scheduleTimelineUpdate();
8698
9552
  }
8699
- requestAnimationFrame(() => syncRef.current());
9553
+ scheduleSync();
8700
9554
  return true;
8701
9555
  },
8702
9556
  captureScreenshot: async (options) => {
9557
+ var _a;
8703
9558
  const m = map.current;
8704
9559
  if (!m || !isMapLoadedRef.current) {
8705
9560
  toast({
@@ -8709,6 +9564,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8709
9564
  });
8710
9565
  throw new Error("Map is not ready");
8711
9566
  }
9567
+ (_a = syncCoalescerRef.current) == null ? void 0 : _a.flush();
8712
9568
  const SCREENSHOT_RENDER_TIMEOUT_MS = 1e4;
8713
9569
  try {
8714
9570
  await new Promise((resolve, reject) => {
@@ -8749,8 +9605,10 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8749
9605
  const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
8750
9606
  const currentLayers = layersRef.current;
8751
9607
  const targetLayerIds = layerIds ?? currentLayers.map((l) => l.id);
8752
- const targetFeatureIds = currentLayers.filter((l) => targetLayerIds.includes(l.id)).flatMap((l) => l.featureIds);
8753
- const targetFeatures = allFeatures.filter((f) => targetFeatureIds.includes(f.id));
9608
+ const targetFeatureIds = new Set(
9609
+ currentLayers.filter((l) => targetLayerIds.includes(l.id)).flatMap((l) => l.featureIds)
9610
+ );
9611
+ const targetFeatures = allFeatures.filter((f) => targetFeatureIds.has(f.id));
8754
9612
  if (targetFeatures.length === 0) return;
8755
9613
  const fc = turf.featureCollection(targetFeatures);
8756
9614
  const bbox = turf.bbox(fc);
@@ -8800,28 +9658,10 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8800
9658
  };
8801
9659
  if (geojson) {
8802
9660
  if (options == null ? void 0 : options.readOnly) {
8803
- let layerHasTemporal = false;
8804
- const featuresWithIds = geojson.features.map((f) => {
8805
- const id = f.id ? String(f.id) : crypto.randomUUID();
8806
- const props = f.properties || {};
8807
- if (!hasAnyTemporalValue(props)) {
8808
- return { ...f, id };
8809
- }
8810
- const { startDate, endDate } = normalizeTemporalProperties(props);
8811
- if (startDate || endDate) layerHasTemporal = true;
8812
- return {
8813
- ...f,
8814
- id,
8815
- properties: {
8816
- ...props,
8817
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
8818
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
8819
- }
8820
- };
8821
- });
8822
- readOnlyFeatures.current.set(layerId, featuresWithIds);
8823
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: layerHasTemporal });
8824
- newLayer.featureIds = featuresWithIds.map((f) => String(f.id));
9661
+ const prepared = prepareFeaturesForLayer(geojson.features, "addLayer");
9662
+ readOnlyFeatures.current.set(layerId, prepared.features);
9663
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9664
+ newLayer.featureIds = prepared.featureIds;
8825
9665
  } else if (draw.current) {
8826
9666
  isApiAddingRef.current = true;
8827
9667
  try {
@@ -8851,7 +9691,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8851
9691
  setLayers(updatedLayers);
8852
9692
  updateFeatureCount();
8853
9693
  scheduleTimelineUpdate();
8854
- syncFeaturesToCustomLayers();
9694
+ scheduleSync();
8855
9695
  if (!(options == null ? void 0 : options.skipFit) && geojson && geojson.features.length > 0 && map.current) {
8856
9696
  try {
8857
9697
  const bbox = turf.bbox(geojson);
@@ -8886,9 +9726,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8886
9726
  setLayers(updatedLayers);
8887
9727
  updateFeatureCount();
8888
9728
  scheduleTimelineUpdate();
8889
- requestAnimationFrame(() => {
8890
- syncRef.current();
8891
- });
9729
+ scheduleSync();
8892
9730
  return true;
8893
9731
  },
8894
9732
  setLayerVisibility: (layerId, visible) => {
@@ -8902,9 +9740,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8902
9740
  setLayers(nextLayers2);
8903
9741
  updateFeatureCount();
8904
9742
  scheduleTimelineUpdate();
8905
- requestAnimationFrame(() => {
8906
- syncRef.current();
8907
- });
9743
+ scheduleSync();
8908
9744
  return;
8909
9745
  }
8910
9746
  if (!draw.current) return;
@@ -8942,9 +9778,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8942
9778
  setLayers(nextLayers);
8943
9779
  updateFeatureCount();
8944
9780
  scheduleTimelineUpdate();
8945
- requestAnimationFrame(() => {
8946
- syncRef.current();
8947
- });
9781
+ scheduleSync();
8948
9782
  },
8949
9783
  addFeatures: (layerId, features, options) => {
8950
9784
  var _a;
@@ -8953,29 +9787,12 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8953
9787
  if (options == null ? void 0 : options.recordHistory) saveStateForUndo("add features");
8954
9788
  if (layer.readOnly) {
8955
9789
  const existing = readOnlyFeatures.current.get(layerId) || [];
8956
- let layerHasTemporal = ((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false;
8957
- const newFeaturesWithIds = features.map((f) => {
8958
- const id = f.id ? String(f.id) : crypto.randomUUID();
8959
- const props = f.properties || {};
8960
- if (!hasAnyTemporalValue(props)) {
8961
- return { ...f, id };
8962
- }
8963
- const { startDate, endDate } = normalizeTemporalProperties(props);
8964
- if (startDate || endDate) layerHasTemporal = true;
8965
- return {
8966
- ...f,
8967
- id,
8968
- properties: {
8969
- ...props,
8970
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
8971
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
8972
- }
8973
- };
8974
- });
8975
- const combined = [...existing, ...newFeaturesWithIds];
9790
+ const prepared = prepareFeaturesForLayer(features, "addFeatures");
9791
+ const layerHasTemporal = (((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false) || prepared.hasTemporal;
9792
+ const combined = [...existing, ...prepared.features];
8976
9793
  readOnlyFeatures.current.set(layerId, combined);
8977
9794
  layerTemporalCacheRef.current.set(layerId, { featureCount: combined.length, hasTemporal: layerHasTemporal });
8978
- const addedIds2 = newFeaturesWithIds.map((f) => String(f.id));
9795
+ const addedIds2 = prepared.featureIds;
8979
9796
  const updatedLayers2 = layersRef.current.map(
8980
9797
  (l) => l.id === layerId ? { ...l, featureIds: [...l.featureIds, ...addedIds2] } : l
8981
9798
  );
@@ -8985,9 +9802,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8985
9802
  if (layerHasTemporal) {
8986
9803
  scheduleTimelineUpdate();
8987
9804
  }
8988
- requestAnimationFrame(() => {
8989
- syncRef.current();
8990
- });
9805
+ scheduleSync();
8991
9806
  return addedIds2;
8992
9807
  }
8993
9808
  if (!draw.current) return [];
@@ -9017,7 +9832,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9017
9832
  setLayers(updatedLayers);
9018
9833
  updateFeatureCount();
9019
9834
  scheduleTimelineUpdate();
9020
- syncFeaturesToCustomLayers();
9835
+ scheduleSync();
9021
9836
  return addedIds;
9022
9837
  },
9023
9838
  removeFeatures: (featureIds, options) => {
@@ -9053,7 +9868,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9053
9868
  });
9054
9869
  updateFeatureCount();
9055
9870
  scheduleTimelineUpdate();
9056
- requestAnimationFrame(() => syncRef.current());
9871
+ scheduleSync();
9057
9872
  onFeatureDelete == null ? void 0 : onFeatureDelete(featureIds);
9058
9873
  },
9059
9874
  selectFeatures: (featureIds) => {
@@ -9129,7 +9944,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9129
9944
  ));
9130
9945
  updateFeatureCount();
9131
9946
  scheduleTimelineUpdate();
9132
- syncFeaturesToCustomLayers();
9947
+ scheduleSync();
9133
9948
  return addedIds;
9134
9949
  },
9135
9950
  getActiveEditableLayerId: () => {
@@ -9209,70 +10024,32 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9209
10024
  getDrawingMode: () => {
9210
10025
  return activeMode;
9211
10026
  },
9212
- updateReadOnlyLayer: (layerId, features) => {
9213
- const layer = layersRef.current.find((l) => l.id === layerId);
9214
- if (!layer || !layer.readOnly || !isMapLoadedRef.current) return false;
9215
- let layerHasTemporal = false;
9216
- const featuresWithIds = features.map((f) => {
9217
- const id = f.id ? String(f.id) : crypto.randomUUID();
9218
- const props = f.properties || {};
9219
- if (!hasAnyTemporalValue(props)) {
9220
- return { ...f, id };
9221
- }
9222
- const { startDate, endDate } = normalizeTemporalProperties(props);
9223
- if (startDate || endDate) layerHasTemporal = true;
9224
- return {
9225
- ...f,
9226
- id,
9227
- properties: {
9228
- ...props,
9229
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9230
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9231
- }
9232
- };
9233
- });
9234
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9235
- layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: layerHasTemporal });
9236
- if (layerHasTemporal) {
10027
+ updateReadOnlyLayer: (layerId, features) => {
10028
+ const layer = layersRef.current.find((l) => l.id === layerId);
10029
+ if (!layer || !layer.readOnly || !isMapLoadedRef.current) return false;
10030
+ const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer");
10031
+ readOnlyFeatures.current.set(layerId, prepared.features);
10032
+ layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: prepared.hasTemporal });
10033
+ if (prepared.hasTemporal) {
9237
10034
  scheduleTimelineUpdate();
9238
10035
  }
9239
- const newFeatureIds = featuresWithIds.map((f) => String(f.id));
10036
+ const newFeatureIds = prepared.featureIds;
9240
10037
  const updatedLayers = layersRef.current.map(
9241
10038
  (l) => l.id === layerId ? { ...l, featureIds: newFeatureIds } : l
9242
10039
  );
9243
10040
  layersRef.current = updatedLayers;
9244
10041
  setLayers(updatedLayers);
9245
10042
  updateFeatureCount();
9246
- requestAnimationFrame(() => {
9247
- syncRef.current();
9248
- });
10043
+ scheduleSync();
9249
10044
  return true;
9250
10045
  },
9251
10046
  setLayerData: (name, geojson, options) => {
9252
10047
  if (!isMapLoadedRef.current) return "";
9253
- let layerHasTemporal = false;
9254
- const featuresWithIds = geojson.features.map((f) => {
9255
- const id = f.id ? String(f.id) : crypto.randomUUID();
9256
- const props = f.properties || {};
9257
- if (!hasAnyTemporalValue(props)) {
9258
- return { ...f, id };
9259
- }
9260
- const { startDate, endDate } = normalizeTemporalProperties(props);
9261
- if (startDate || endDate) layerHasTemporal = true;
9262
- return {
9263
- ...f,
9264
- id,
9265
- properties: {
9266
- ...props,
9267
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9268
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9269
- }
9270
- };
9271
- });
9272
- const newFeatureIds = featuresWithIds.map((f) => String(f.id));
10048
+ const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData");
10049
+ const newFeatureIds = prepared.featureIds;
9273
10050
  const layerId = `managed-${name}`;
9274
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9275
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: layerHasTemporal });
10051
+ readOnlyFeatures.current.set(layerId, prepared.features);
10052
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9276
10053
  const buildLayerObj = (existing) => {
9277
10054
  const base = {
9278
10055
  id: layerId,
@@ -9319,9 +10096,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9319
10096
  return result;
9320
10097
  });
9321
10098
  updateFeatureCount();
9322
- requestAnimationFrame(() => {
9323
- syncRef.current();
9324
- });
10099
+ scheduleSync();
9325
10100
  if ((options == null ? void 0 : options.fitPadding) != null && geojson.features.length > 0 && map.current) {
9326
10101
  try {
9327
10102
  const bbox = turf.bbox(geojson);
@@ -9375,21 +10150,18 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9375
10150
  const features = [];
9376
10151
  const readOnly = readOnlyFeatures.current.get(layerId);
9377
10152
  if (readOnly) {
9378
- return readOnly.map((f) => JSON.parse(JSON.stringify(f)));
10153
+ return cloneFeatures(readOnly);
9379
10154
  }
9380
10155
  if (layer.visible) {
9381
10156
  layer.featureIds.forEach((id) => {
9382
10157
  var _a;
9383
10158
  const f = (_a = draw.current) == null ? void 0 : _a.get(id);
9384
- if (f) {
9385
- features.push(JSON.parse(JSON.stringify(f)));
9386
- }
10159
+ if (f) features.push(f);
9387
10160
  });
9388
10161
  } else {
9389
- const hidden = hiddenFeatures.current.get(layerId) || [];
9390
- return hidden.map((f) => JSON.parse(JSON.stringify(f)));
10162
+ return cloneFeatures(hiddenFeatures.current.get(layerId) || []);
9391
10163
  }
9392
- return features;
10164
+ return cloneFeatures(features);
9393
10165
  },
9394
10166
  getTimelineRange: () => {
9395
10167
  const ts = timelineStoreApi.getState();
@@ -9428,7 +10200,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9428
10200
  var _a;
9429
10201
  (_a = restoreEnrichedGeoJSONRef.current) == null ? void 0 : _a.call(restoreEnrichedGeoJSONRef, enriched);
9430
10202
  }
9431
- }), [layers, isEditMode, isMapLoaded, getSelectedFeatures, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onFeatureDelete, onTimelineChange, activeEditingLayerId, currentMapStyle, activeMode, saveStateForUndo, history]);
10203
+ }), [layers, isEditMode, isMapLoaded, getSelectedFeatures, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onFeatureDelete, onTimelineChange, activeEditingLayerId, currentMapStyle, activeMode, saveStateForUndo, history]);
9432
10204
  const handleModeChange = useCallback((mode) => {
9433
10205
  if (!draw.current || !isMapLoaded) return;
9434
10206
  if (!hasVisibleLayers && mode !== "simple_select" && mode !== "view_select") {
@@ -9505,12 +10277,12 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9505
10277
  setShowProperties(false);
9506
10278
  updateFeatureCount();
9507
10279
  scheduleTimelineUpdate();
9508
- syncFeaturesToCustomLayers();
10280
+ scheduleSync();
9509
10281
  toast({
9510
10282
  title: "Layer cleared",
9511
10283
  description: `Removed all features from "${activeLayer.name}"`
9512
10284
  });
9513
- }, [activeEditingLayerId, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, toast]);
10285
+ }, [activeEditingLayerId, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast]);
9514
10286
  const handleDeleteSelected = useCallback(() => {
9515
10287
  if (selectedFeatureIds.length === 0) return;
9516
10288
  const idSet = new Set(selectedFeatureIds);
@@ -9561,8 +10333,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9561
10333
  setShowProperties(false);
9562
10334
  updateFeatureCount();
9563
10335
  scheduleTimelineUpdate();
9564
- syncFeaturesToCustomLayers();
9565
- }, [selectedFeatureIds, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onFeatureDelete]);
10336
+ scheduleSync();
10337
+ }, [selectedFeatureIds, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onFeatureDelete]);
9566
10338
  const handleToggleEditMode = useCallback(() => {
9567
10339
  setIsEditMode((prev) => {
9568
10340
  const newMode = !prev;
@@ -9698,9 +10470,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9698
10470
  updateFeatureCount();
9699
10471
  scheduleTimelineUpdate();
9700
10472
  saveStateForUndo();
9701
- syncFeaturesToCustomLayers();
10473
+ scheduleSync();
9702
10474
  onFeatureCreate == null ? void 0 : onFeatureCreate(feature);
9703
- }, [isMapLoaded, externalPersistence, enableProperties, autoOpenProperties, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onFeatureCreate]);
10475
+ }, [isMapLoaded, externalPersistence, enableProperties, autoOpenProperties, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onFeatureCreate]);
9704
10476
  const handleFeatureContextMenu = useCallback((e) => {
9705
10477
  var _a, _b;
9706
10478
  contextMenuFiredRef.current = true;
@@ -9885,7 +10657,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9885
10657
  if (properties.kind === "text" || ((_c = drawFeature.properties) == null ? void 0 : _c.kind) === "text") {
9886
10658
  draw.current.setFeatureProperty(featureId, "text", void 0);
9887
10659
  }
9888
- syncFeaturesToCustomLayers();
10660
+ scheduleSync();
9889
10661
  scheduleTimelineUpdate();
9890
10662
  setFeatureUpdateCounter((c) => c + 1);
9891
10663
  const updated = draw.current.get(featureId);
@@ -9920,13 +10692,13 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9920
10692
  }
9921
10693
  });
9922
10694
  if (updatedFeature) {
9923
- syncFeaturesToCustomLayers();
10695
+ scheduleSync();
9924
10696
  scheduleTimelineUpdate();
9925
10697
  setFeatureUpdateCounter((c) => c + 1);
9926
10698
  onFeatureUpdate == null ? void 0 : onFeatureUpdate(updatedFeature);
9927
10699
  }
9928
10700
  }
9929
- }, [saveStateForUndo, scheduleTimelineUpdate, onFeatureUpdate, syncFeaturesToCustomLayers]);
10701
+ }, [saveStateForUndo, scheduleTimelineUpdate, onFeatureUpdate, scheduleSync]);
9930
10702
  const handleUpdateGeometry = useCallback((featureId, geometry) => {
9931
10703
  if (!draw.current || !map.current) return;
9932
10704
  const feature = draw.current.get(featureId);
@@ -9948,13 +10720,13 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9948
10720
  draw.current.setFeatureProperty(featureId, "_unsaved", true);
9949
10721
  }
9950
10722
  draw.current.changeMode("simple_select", { featureIds: [featureId] });
9951
- syncFeaturesToCustomLayers();
10723
+ scheduleSync();
9952
10724
  setFeatureUpdateCounter((c) => c + 1);
9953
10725
  const updated = draw.current.get(featureId);
9954
10726
  if (updated) {
9955
10727
  onFeatureUpdate == null ? void 0 : onFeatureUpdate(updated);
9956
10728
  }
9957
- }, [saveStateForUndo, onFeatureUpdate, syncFeaturesToCustomLayers]);
10729
+ }, [saveStateForUndo, onFeatureUpdate, scheduleSync]);
9958
10730
  const handleFeatureSaved = useCallback((oldId, newId, metadata) => {
9959
10731
  if (!draw.current) return;
9960
10732
  const feature = draw.current.get(oldId);
@@ -9999,7 +10771,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9999
10771
  setSelectedFeatureIds((prev) => prev.map((fid) => fid === oldId ? featureId : fid));
10000
10772
  draw.current.changeMode("simple_select", { featureIds: [featureId] });
10001
10773
  }
10002
- syncFeaturesToCustomLayers();
10774
+ scheduleSync();
10003
10775
  updateFeatureCount();
10004
10776
  setFeatureUpdateCounter((c) => c + 1);
10005
10777
  const savedFeatureId = featureId;
@@ -10010,7 +10782,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10010
10782
  }
10011
10783
  setFeatureUpdateCounter((c) => c + 1);
10012
10784
  });
10013
- }, [syncFeaturesToCustomLayers, updateFeatureCount]);
10785
+ }, [scheduleSync, updateFeatureCount]);
10014
10786
  const handleAddLayer = useCallback((name) => {
10015
10787
  const newLayer = {
10016
10788
  id: `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
@@ -10095,9 +10867,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10095
10867
  updateFeatureCount();
10096
10868
  scheduleTimelineUpdate();
10097
10869
  if (layer.readOnly) {
10098
- requestAnimationFrame(() => {
10099
- syncRef.current();
10100
- });
10870
+ scheduleSync();
10101
10871
  }
10102
10872
  }, [layers, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate]);
10103
10873
  const handleMoveFeatureToLayer = useCallback((featureId, targetLayerId) => {
@@ -10155,10 +10925,10 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10155
10925
  }
10156
10926
  return remaining.length !== l.featureIds.length ? { ...l, featureIds: remaining } : l;
10157
10927
  }));
10158
- syncFeaturesToCustomLayers();
10928
+ scheduleSync();
10159
10929
  updateFeatureCount();
10160
10930
  }
10161
- }, [saveStateForUndo, findFeatureById, updateFeatureCount, syncFeaturesToCustomLayers]);
10931
+ }, [saveStateForUndo, findFeatureById, updateFeatureCount, scheduleSync]);
10162
10932
  const handleCopyFeaturesToLayer = useCallback((featureIds, targetLayerId) => {
10163
10933
  if (!draw.current) return;
10164
10934
  saveStateForUndo();
@@ -10215,10 +10985,10 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10215
10985
  }),
10216
10986
  { id: newLayerId, name: layerName, visible: true, featureIds: movedIds }
10217
10987
  ]);
10218
- syncFeaturesToCustomLayers();
10988
+ scheduleSync();
10219
10989
  updateFeatureCount();
10220
10990
  }
10221
- }, [saveStateForUndo, findFeatureById, updateFeatureCount, syncFeaturesToCustomLayers]);
10991
+ }, [saveStateForUndo, findFeatureById, updateFeatureCount, scheduleSync]);
10222
10992
  const handleCreateLayerAndCopyFeatures = useCallback((featureIds, layerName) => {
10223
10993
  if (!draw.current) return;
10224
10994
  saveStateForUndo();
@@ -10510,20 +11280,23 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10510
11280
  useEffect(() => {
10511
11281
  if (!map.current || !isMapLoaded) return;
10512
11282
  const mapInstance = map.current;
11283
+ let rafId = null;
10513
11284
  const handleMove = () => {
10514
- if (!hasArrowFeaturesRef.current) return;
10515
- if (syncRef.current) {
10516
- syncRef.current();
10517
- }
11285
+ if (!hasArrowFeaturesRef.current || rafId !== null) return;
11286
+ rafId = requestAnimationFrame(() => {
11287
+ rafId = null;
11288
+ renderArrowOverlays(paintedArrowLinesRef.current);
11289
+ });
10518
11290
  };
10519
11291
  mapInstance.on("move", handleMove);
10520
11292
  return () => {
11293
+ if (rafId !== null) cancelAnimationFrame(rafId);
10521
11294
  try {
10522
11295
  mapInstance.off("move", handleMove);
10523
11296
  } catch {
10524
11297
  }
10525
11298
  };
10526
- }, [isMapLoaded]);
11299
+ }, [isMapLoaded, renderArrowOverlays]);
10527
11300
  useEffect(() => {
10528
11301
  if (!map.current || !isMapLoaded || !onViewportChange) return;
10529
11302
  const mapInstance = map.current;
@@ -10832,6 +11605,50 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10832
11605
  useEffect(() => {
10833
11606
  enableDrawingRef.current = enableDrawing;
10834
11607
  }, [enableDrawing]);
11608
+ const trySelectionFastPath = useCallback(() => {
11609
+ var _a;
11610
+ const m = map.current;
11611
+ if (!m) return true;
11612
+ const source = m.getSource("custom-features");
11613
+ const gate = enableSelectionRef.current || enableDrawingRef.current;
11614
+ const next = /* @__PURE__ */ new Set();
11615
+ if (gate) {
11616
+ (((_a = draw.current) == null ? void 0 : _a.getSelectedIds()) ?? []).forEach((id) => next.add(String(id)));
11617
+ selectedFeatureIdsRef.current.forEach((id) => next.add(String(id)));
11618
+ }
11619
+ return applySelectionFastPath(selectionPaintCacheRef.current, next, source);
11620
+ }, []);
11621
+ trySelectionFastPathRef.current = trySelectionFastPath;
11622
+ const tryTimelineFastPath = useCallback(() => {
11623
+ const m = map.current;
11624
+ if (!m) return true;
11625
+ if (hasArrowFeaturesRef.current) return false;
11626
+ if (layersRef.current.some((l) => {
11627
+ var _a;
11628
+ return l.visible && ((_a = l.traceConfig) == null ? void 0 : _a.enabled);
11629
+ })) return false;
11630
+ const source = m.getSource("custom-features");
11631
+ const { applied, toggled } = applyTimelineFastPath(
11632
+ selectionPaintCacheRef.current,
11633
+ timelineVisibleIdsRef.current,
11634
+ source
11635
+ );
11636
+ if (applied) {
11637
+ const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
11638
+ setVisibleFeatureCount(countVisibleFeatures(threshold));
11639
+ setLabelsSuppressed(false);
11640
+ mapPerfLog("timeline", "fast path applied", { toggled });
11641
+ }
11642
+ return applied;
11643
+ }, [autoLabelConfig, countVisibleFeatures]);
11644
+ tryTimelineFastPathRef.current = tryTimelineFastPath;
11645
+ const collectSelectionFeatureGroups = useCallback(() => {
11646
+ return collectVisibleFeatureGroups(
11647
+ draw.current ? draw.current.getAll().features : null,
11648
+ readOnlyFeatures.current,
11649
+ layersRef.current
11650
+ );
11651
+ }, []);
10835
11652
  useEffect(() => {
10836
11653
  if (!map.current || !isMapLoaded) {
10837
11654
  return;
@@ -10922,29 +11739,6 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10922
11739
  [minLng, maxLat]
10923
11740
  // close polygon
10924
11741
  ]]);
10925
- const drawFeatures = draw.current ? draw.current.getAll().features : [];
10926
- const readOnlyFeaturesList = [];
10927
- readOnlyFeatures.current.forEach((features, layerId) => {
10928
- const layer = layersRef.current.find((l) => l.id === layerId);
10929
- if (layer == null ? void 0 : layer.visible) pushAll(readOnlyFeaturesList, features);
10930
- });
10931
- const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
10932
- const selectedIds = [];
10933
- allFeatures.forEach((feature) => {
10934
- try {
10935
- const geom = feature.geometry;
10936
- let isInside = false;
10937
- if (geom.type === "Point") {
10938
- isInside = turf.booleanPointInPolygon(geom.coordinates, selectionPolygon);
10939
- } else if (geom.type === "LineString" || geom.type === "Polygon" || geom.type === "MultiPoint" || geom.type === "MultiLineString" || geom.type === "MultiPolygon") {
10940
- isInside = turf.booleanIntersects(feature, selectionPolygon);
10941
- }
10942
- if (isInside && feature.id) {
10943
- selectedIds.push(String(feature.id));
10944
- }
10945
- } catch (err) {
10946
- }
10947
- });
10948
11742
  const isFilterAction = filterActiveRef.current && onSelectionComplete;
10949
11743
  if (isFilterAction) {
10950
11744
  onSelectionComplete(selectionPolygon.geometry);
@@ -10958,6 +11752,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10958
11752
  ]);
10959
11753
  }
10960
11754
  } else {
11755
+ const selectedIds = hitTestSelection(collectSelectionFeatureGroups(), selectionPolygon, {
11756
+ axisAlignedRectangle: true
11757
+ });
10961
11758
  const finalIds = e.shiftKey ? Array.from(/* @__PURE__ */ new Set([...selectedFeatureIdsRef.current, ...selectedIds])) : selectedIds;
10962
11759
  applySelectionState(finalIds, { focusProperties: true });
10963
11760
  }
@@ -10973,29 +11770,6 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10973
11770
  const radiusKm = turf.distance(center, edge, { units: "kilometers" });
10974
11771
  if (radiusKm > 0) {
10975
11772
  const selectionPolygon = turf.circle([centerLngLat.lng, centerLngLat.lat], radiusKm, { steps: 64, units: "kilometers" });
10976
- const drawFeatures = draw.current ? draw.current.getAll().features : [];
10977
- const readOnlyFeaturesList = [];
10978
- readOnlyFeatures.current.forEach((features, layerId) => {
10979
- const layer = layersRef.current.find((l) => l.id === layerId);
10980
- if (layer == null ? void 0 : layer.visible) pushAll(readOnlyFeaturesList, features);
10981
- });
10982
- const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
10983
- const selectedIds = [];
10984
- allFeatures.forEach((feature) => {
10985
- try {
10986
- const geom = feature.geometry;
10987
- let isInside = false;
10988
- if (geom.type === "Point") {
10989
- isInside = turf.booleanPointInPolygon(geom.coordinates, selectionPolygon);
10990
- } else if (geom.type === "LineString" || geom.type === "Polygon" || geom.type === "MultiPoint" || geom.type === "MultiLineString" || geom.type === "MultiPolygon") {
10991
- isInside = turf.booleanIntersects(feature, selectionPolygon);
10992
- }
10993
- if (isInside && feature.id) {
10994
- selectedIds.push(String(feature.id));
10995
- }
10996
- } catch (err) {
10997
- }
10998
- });
10999
11773
  const isFilterAction = filterActiveRef.current && onSelectionComplete;
11000
11774
  if (isFilterAction) {
11001
11775
  onSelectionComplete(selectionPolygon.geometry);
@@ -11003,6 +11777,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11003
11777
  setPersistedSelectionPolygon(selectionPolygon.geometry.coordinates[0]);
11004
11778
  }
11005
11779
  } else {
11780
+ const selectedIds = hitTestSelection(collectSelectionFeatureGroups(), selectionPolygon);
11006
11781
  const finalIds = e.shiftKey ? Array.from(/* @__PURE__ */ new Set([...selectedFeatureIdsRef.current, ...selectedIds])) : selectedIds;
11007
11782
  applySelectionState(finalIds, { focusProperties: true });
11008
11783
  }
@@ -11029,29 +11804,6 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11029
11804
  }
11030
11805
  const closedPoints = [...currentPoints, currentPoints[0]];
11031
11806
  const selectionPolygon = turf.polygon([closedPoints]);
11032
- const drawFeatures = draw.current ? draw.current.getAll().features : [];
11033
- const readOnlyFeaturesList = [];
11034
- readOnlyFeatures.current.forEach((features, layerId) => {
11035
- const layer = layersRef.current.find((l) => l.id === layerId);
11036
- if (layer == null ? void 0 : layer.visible) pushAll(readOnlyFeaturesList, features);
11037
- });
11038
- const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
11039
- const selectedIds = [];
11040
- allFeatures.forEach((feature) => {
11041
- try {
11042
- const geom = feature.geometry;
11043
- let isInside = false;
11044
- if (geom.type === "Point") {
11045
- isInside = turf.booleanPointInPolygon(geom.coordinates, selectionPolygon);
11046
- } else if (geom.type === "LineString" || geom.type === "Polygon" || geom.type === "MultiPoint" || geom.type === "MultiLineString" || geom.type === "MultiPolygon") {
11047
- isInside = turf.booleanIntersects(feature, selectionPolygon);
11048
- }
11049
- if (isInside && feature.id) {
11050
- selectedIds.push(String(feature.id));
11051
- }
11052
- } catch (err) {
11053
- }
11054
- });
11055
11807
  const isFilterAction = filterActiveRef.current && onSelectionComplete;
11056
11808
  if (isFilterAction) {
11057
11809
  onSelectionComplete(selectionPolygon.geometry);
@@ -11059,6 +11811,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11059
11811
  setPersistedSelectionPolygon(closedPoints);
11060
11812
  }
11061
11813
  } else {
11814
+ const selectedIds = hitTestSelection(collectSelectionFeatureGroups(), selectionPolygon);
11062
11815
  const finalIds = e.shiftKey ? Array.from(/* @__PURE__ */ new Set([...selectedFeatureIdsRef.current, ...selectedIds])) : selectedIds;
11063
11816
  applySelectionState(finalIds, { focusProperties: true });
11064
11817
  }
@@ -11108,7 +11861,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11108
11861
  window.removeEventListener("keydown", handleKeyDown);
11109
11862
  canvas.removeEventListener("contextmenu", handleContextMenu);
11110
11863
  };
11111
- }, [selectionMode, isMapLoaded, onFeatureSelect, onSelectionComplete, persistSelection, isSelectionToolActive]);
11864
+ }, [selectionMode, isMapLoaded, onFeatureSelect, onSelectionComplete, persistSelection, isSelectionToolActive, collectSelectionFeatureGroups]);
11112
11865
  const shiftSelectionRef = useRef({ isActive: false, startPoint: null, completedAt: 0 });
11113
11866
  useEffect(() => {
11114
11867
  if (!map.current || !isMapLoaded || !draw.current) return;
@@ -11168,28 +11921,8 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11168
11921
  [minLng, minLat],
11169
11922
  [minLng, maxLat]
11170
11923
  ]]);
11171
- const drawFeatures = draw.current ? draw.current.getAll().features : [];
11172
- const readOnlyFeaturesList = [];
11173
- readOnlyFeatures.current.forEach((features, layerId) => {
11174
- const layer = layersRef.current.find((l) => l.id === layerId);
11175
- if (layer == null ? void 0 : layer.visible) pushAll(readOnlyFeaturesList, features);
11176
- });
11177
- const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
11178
- const selectedIds = [];
11179
- allFeatures.forEach((feature) => {
11180
- try {
11181
- const geom = feature.geometry;
11182
- let isInside = false;
11183
- if (geom.type === "Point") {
11184
- isInside = turf.booleanPointInPolygon(geom.coordinates, selectionPolygon);
11185
- } else if (geom.type === "LineString" || geom.type === "Polygon" || geom.type === "MultiPoint" || geom.type === "MultiLineString" || geom.type === "MultiPolygon") {
11186
- isInside = turf.booleanIntersects(feature, selectionPolygon);
11187
- }
11188
- if (isInside && feature.id) {
11189
- selectedIds.push(String(feature.id));
11190
- }
11191
- } catch {
11192
- }
11924
+ const selectedIds = hitTestSelection(collectSelectionFeatureGroups(), selectionPolygon, {
11925
+ axisAlignedRectangle: true
11193
11926
  });
11194
11927
  const mergedIds = Array.from(/* @__PURE__ */ new Set([...selectedFeatureIdsRef.current, ...selectedIds]));
11195
11928
  shiftSelectionRef.current = { isActive: false, startPoint: null, completedAt: Date.now() };
@@ -11209,7 +11942,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11209
11942
  map.current.dragPan.enable();
11210
11943
  }
11211
11944
  };
11212
- }, [isMapLoaded, isSelectionToolActive, applySelectionState]);
11945
+ }, [isMapLoaded, isSelectionToolActive, applySelectionState, collectSelectionFeatureGroups]);
11213
11946
  useEffect(() => {
11214
11947
  if (!map.current || !isMapLoaded) return;
11215
11948
  const mapInstance = map.current;
@@ -11343,7 +12076,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11343
12076
  (layer) => layer.id === targetLayer.id ? { ...layer, featureIds: [...layer.featureIds, featureId] } : layer
11344
12077
  );
11345
12078
  });
11346
- syncFeaturesToCustomLayers();
12079
+ scheduleSync();
11347
12080
  const newCount = drawInstance.getAll().features.length;
11348
12081
  setFeatureCount(newCount);
11349
12082
  drawInstance.changeMode("simple_select", { featureIds: [featureId] });
@@ -11465,7 +12198,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11465
12198
  (layer) => layer.id === targetLayer.id ? { ...layer, featureIds: [...layer.featureIds, featureId] } : layer
11466
12199
  );
11467
12200
  });
11468
- syncFeaturesToCustomLayers();
12201
+ scheduleSync();
11469
12202
  const newCount = drawInstance.getAll().features.length;
11470
12203
  setFeatureCount(newCount);
11471
12204
  justCreatedRectangleRef.current = true;
@@ -11662,7 +12395,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11662
12395
  layerMetadata
11663
12396
  }
11664
12397
  };
11665
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/json" });
12398
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/json" });
11666
12399
  downloadBlob(blob, `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`);
11667
12400
  }, [layers]);
11668
12401
  const handleLoadLayerGeoJSON = useCallback((layerId) => {
@@ -11739,7 +12472,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11739
12472
  const handleSaveAllGeoJSON = useCallback(() => {
11740
12473
  if (!draw.current) return;
11741
12474
  const geojson = buildEnrichedGeoJSON();
11742
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/geo+json" });
12475
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/geo+json" });
11743
12476
  downloadBlob(blob, "map_export.geojson");
11744
12477
  }, [buildEnrichedGeoJSON]);
11745
12478
  const handleSearchAndAddToNewLayer = useCallback(async () => {
@@ -11821,7 +12554,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11821
12554
  }
11822
12555
  updateFeatureCount();
11823
12556
  scheduleTimelineUpdate();
11824
- syncFeaturesToCustomLayers();
12557
+ scheduleSync();
11825
12558
  }
11826
12559
  } catch (error) {
11827
12560
  toast({
@@ -11830,7 +12563,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11830
12563
  variant: "destructive"
11831
12564
  });
11832
12565
  }
11833
- }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, toast]);
12566
+ }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast]);
11834
12567
  const restoreEnrichedGeoJSON = useCallback((enriched) => {
11835
12568
  var _a;
11836
12569
  const mapState = enriched["octostar:map"];
@@ -11900,7 +12633,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11900
12633
  setLayers(newLayers);
11901
12634
  updateFeatureCount();
11902
12635
  scheduleTimelineUpdate();
11903
- syncFeaturesToCustomLayers();
12636
+ scheduleSync();
11904
12637
  if (mapState.viewport && map.current) {
11905
12638
  map.current.flyTo({
11906
12639
  center: mapState.viewport.center,
@@ -11917,7 +12650,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11917
12650
  title: "Map restored",
11918
12651
  description: `Restored ${newLayers.length} layers with ${totalFeatures} features`
11919
12652
  });
11920
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onMapStateLoaded, toast]);
12653
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onMapStateLoaded, toast]);
11921
12654
  restoreEnrichedGeoJSONRef.current = restoreEnrichedGeoJSON;
11922
12655
  const handleWorkspaceLoad = useCallback(async () => {
11923
12656
  if (!onWorkspaceLoad) return;
@@ -11930,35 +12663,23 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11930
12663
  }
11931
12664
  saveStateForUndo();
11932
12665
  const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
11933
- let wsHasTemporal = false;
11934
- const featuresWithIds = result.features.map((f) => {
11935
- const props = f.properties || {};
11936
- const id = f.id ? String(f.id) : crypto.randomUUID();
11937
- if (!hasAnyTemporalValue(props)) return { ...f, id };
11938
- const { startDate, endDate } = normalizeTemporalProperties(props);
11939
- if (startDate || endDate) wsHasTemporal = true;
11940
- return {
11941
- ...f,
11942
- id,
11943
- properties: { ...props, startDate: (startDate == null ? void 0 : startDate.toISOString()) || null, endDate: (endDate == null ? void 0 : endDate.toISOString()) || null }
11944
- };
11945
- });
11946
- readOnlyFeatures.current.set(layerId, featuresWithIds);
11947
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: wsHasTemporal });
12666
+ const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad");
12667
+ readOnlyFeatures.current.set(layerId, prepared.features);
12668
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
11948
12669
  const newLayer = {
11949
12670
  id: layerId,
11950
12671
  name: "Loaded from workspace",
11951
12672
  visible: true,
11952
- featureIds: featuresWithIds.map((f) => String(f.id)),
12673
+ featureIds: prepared.featureIds,
11953
12674
  readOnly: true
11954
12675
  };
11955
12676
  setLayers((prev) => [...prev, newLayer]);
11956
12677
  updateFeatureCount();
11957
12678
  scheduleTimelineUpdate();
11958
- syncFeaturesToCustomLayers();
12679
+ scheduleSync();
11959
12680
  toast({
11960
12681
  title: "Features loaded",
11961
- description: `Created layer with ${featuresWithIds.length} features`
12682
+ description: `Created layer with ${prepared.features.length} features`
11962
12683
  });
11963
12684
  } catch (error) {
11964
12685
  toast({
@@ -11967,7 +12688,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11967
12688
  variant: "destructive"
11968
12689
  });
11969
12690
  }
11970
- }, [onWorkspaceLoad, saveStateForUndo, restoreEnrichedGeoJSON, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, toast]);
12691
+ }, [onWorkspaceLoad, saveStateForUndo, restoreEnrichedGeoJSON, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast]);
11971
12692
  const handleWorkspaceSave = useCallback(async () => {
11972
12693
  if (!onWorkspaceSave) return;
11973
12694
  const geojson = buildEnrichedGeoJSON();
@@ -12045,195 +12766,194 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12045
12766
  duration: 1e3
12046
12767
  });
12047
12768
  }, [layers, toast]);
12048
- const handleFileChange = useCallback((e) => {
12049
- var _a;
12050
- const file = (_a = e.target.files) == null ? void 0 : _a[0];
12051
- if (!file) return;
12052
- const requestedTargetLayerId = e.target.dataset.targetLayer || activeEditingLayerId;
12053
- const createNewLayer = e.target.dataset.createNewLayer === "true";
12054
- delete e.target.dataset.createNewLayer;
12055
- const reader = new FileReader();
12056
- reader.onload = (event) => {
12057
- var _a2, _b;
12058
- try {
12059
- const rawGeojson = JSON.parse((_a2 = event.target) == null ? void 0 : _a2.result);
12060
- if (rawGeojson.type !== "FeatureCollection" || !Array.isArray(rawGeojson.features)) {
12061
- throw new Error("Invalid GeoJSON format");
12062
- }
12063
- if (rawGeojson.features.length === 0) {
12064
- toast({
12065
- title: "Empty GeoJSON",
12066
- description: "The file contains no features",
12067
- variant: "destructive"
12068
- });
12069
- return;
12070
- }
12071
- if (rawGeojson["octostar:map"]) {
12072
- if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data: rawGeojson, file }) === true) {
12073
- return;
12074
- }
12075
- if (!draw.current) return;
12076
- restoreEnrichedGeoJSON(rawGeojson);
12077
- return;
12078
- }
12079
- if (!draw.current) return;
12080
- const { features: geojson, reprojected, sourceCRS } = detectAndReprojectGeoJSON(rawGeojson);
12081
- saveStateForUndo();
12082
- const layerMetadata = (_b = rawGeojson.properties) == null ? void 0 : _b.layerMetadata;
12083
- let fileHasTemporal = false;
12084
- const normalizedFeatures = geojson.features.map((f) => {
12085
- const props = f.properties || {};
12086
- if (!hasAnyTemporalValue(props)) return f;
12087
- const { startDate, endDate } = normalizeTemporalProperties(props);
12088
- if (startDate || endDate) fileHasTemporal = true;
12089
- return {
12090
- ...f,
12091
- properties: {
12092
- ...props,
12093
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
12094
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
12095
- }
12096
- };
12097
- });
12098
- if (createNewLayer) {
12099
- if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({
12100
- kind: "newLayer",
12101
- data: { type: "FeatureCollection", features: normalizedFeatures },
12102
- file,
12103
- reprojected,
12104
- sourceCRS: sourceCRS ?? void 0
12105
- }) === true) {
12106
- return;
12107
- }
12108
- const fileName = file.name.replace(/\.geojson$|\.json$/i, "");
12109
- const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12110
- const newLayer = {
12111
- id: layerId,
12112
- name: (layerMetadata == null ? void 0 : layerMetadata.name) || fileName,
12113
- visible: true,
12114
- featureIds: [],
12115
- readOnly: true,
12116
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12117
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12118
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12119
- };
12120
- const addedIds = [];
12121
- const featuresWithIds = [];
12122
- normalizedFeatures.forEach((f) => {
12123
- const featureId = f.id ? String(f.id) : crypto.randomUUID();
12124
- const normalizedFeature = { ...f, id: featureId };
12125
- featuresWithIds.push(normalizedFeature);
12126
- addedIds.push(featureId);
12127
- });
12128
- readOnlyFeatures.current.set(layerId, featuresWithIds);
12129
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: fileHasTemporal });
12130
- newLayer.featureIds = addedIds;
12131
- setLayers((prev) => [...prev, newLayer]);
12132
- updateFeatureCount();
12133
- scheduleTimelineUpdate();
12134
- syncFeaturesToCustomLayers();
12135
- if (map.current && geojson.features.length > 0) {
12136
- try {
12137
- const bbox = turf.bbox(geojson);
12138
- if (bbox && bbox.every((v) => isFinite(v))) {
12139
- map.current.fitBounds(
12140
- [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12141
- { padding: 50, maxZoom: 16, duration: 1e3 }
12142
- );
12143
- }
12144
- } catch (e2) {
12145
- }
12146
- }
12147
- const reprojectMsg2 = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12148
- toast({
12149
- title: "Layer created",
12150
- description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg2} (high-performance mode)`
12151
- });
12152
- return;
12153
- }
12154
- let targetLayer = layers.find((l) => l.id === requestedTargetLayerId && !l.readOnly);
12155
- if (!targetLayer) {
12156
- targetLayer = layers.find((l) => l.visible && !l.readOnly);
12157
- }
12158
- if (!targetLayer) {
12159
- targetLayer = layers.find((l) => !l.readOnly);
12160
- }
12161
- if (targetLayer == null ? void 0 : targetLayer.visible) {
12162
- const addedIds = [];
12163
- isApiAddingRef.current = true;
12164
- try {
12165
- normalizedFeatures.forEach((f) => {
12166
- const ids = draw.current.add(f);
12167
- addedIds.push(ids[0]);
12168
- });
12169
- } finally {
12170
- isApiAddingRef.current = false;
12171
- }
12172
- const targetId = targetLayer.id;
12173
- setLayers((prev) => prev.map((l) => {
12174
- if (l.id !== targetId) return l;
12175
- return {
12176
- ...l,
12177
- featureIds: [...l.featureIds, ...addedIds],
12178
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12179
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12180
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12181
- };
12182
- }));
12183
- } else if (targetLayer) {
12184
- const featuresWithIds = normalizedFeatures.map((f) => ({
12185
- ...f,
12186
- id: f.id || `feature-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
12187
- }));
12188
- const targetId = targetLayer.id;
12189
- const addedIds = featuresWithIds.map((f) => f.id);
12190
- const existing = hiddenFeatures.current.get(targetId) || [];
12191
- hiddenFeatures.current.set(targetId, [...existing, ...featuresWithIds]);
12192
- setLayers((prev) => prev.map((l) => {
12193
- if (l.id !== targetId) return l;
12194
- return {
12195
- ...l,
12196
- featureIds: [...l.featureIds, ...addedIds],
12197
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12198
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12199
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12200
- };
12201
- }));
12202
- }
12203
- updateFeatureCount();
12204
- scheduleTimelineUpdate();
12205
- syncFeaturesToCustomLayers();
12206
- const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12769
+ const loadGeoJSONFile = useCallback(async (file, requestedTargetLayerId, createNewLayer) => {
12770
+ let result;
12771
+ try {
12772
+ result = await getSharedIngestClient().ingest(file, {
12773
+ idStrategy: "uuid-fallback",
12774
+ emptyIsError: true
12775
+ });
12776
+ } catch (error) {
12777
+ toast({
12778
+ title: "Failed to load GeoJSON",
12779
+ description: error instanceof Error ? error.message : "Invalid file",
12780
+ variant: "destructive"
12781
+ });
12782
+ return;
12783
+ }
12784
+ if (result.kind === "error") {
12785
+ if (result.code === "empty") {
12207
12786
  toast({
12208
- title: "GeoJSON loaded",
12209
- description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
12787
+ title: "Empty GeoJSON",
12788
+ description: result.message,
12789
+ variant: "destructive"
12210
12790
  });
12211
- } catch (error) {
12791
+ } else {
12212
12792
  toast({
12213
12793
  title: "Failed to load GeoJSON",
12214
- description: error instanceof Error ? error.message : "Invalid file",
12794
+ description: result.message,
12215
12795
  variant: "destructive"
12216
12796
  });
12217
12797
  }
12218
- };
12219
- reader.readAsText(file);
12220
- e.target.value = "";
12221
- }, [layers, activeEditingLayerId, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12222
- const handleDropGeoJSON = useCallback((name, data) => {
12798
+ return;
12799
+ }
12800
+ if (result.kind === "enriched") {
12801
+ const rawGeojson = result.data;
12802
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data: rawGeojson, file }) === true) {
12803
+ return;
12804
+ }
12805
+ if (!draw.current) return;
12806
+ restoreEnrichedGeoJSON(rawGeojson);
12807
+ return;
12808
+ }
12809
+ if (!draw.current) return;
12810
+ const { features: normalizedFeatures, reprojected, sourceCRS, hasTemporal: fileHasTemporal } = result;
12811
+ const layerMetadata = result.layerMetadata;
12812
+ saveStateForUndo();
12813
+ if (createNewLayer) {
12814
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({
12815
+ kind: "newLayer",
12816
+ data: { type: "FeatureCollection", features: normalizedFeatures },
12817
+ file,
12818
+ reprojected,
12819
+ sourceCRS: sourceCRS ?? void 0
12820
+ }) === true) {
12821
+ return;
12822
+ }
12823
+ const fileName = file.name.replace(/\.geojson$|\.json$/i, "");
12824
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12825
+ const newLayer = {
12826
+ id: layerId,
12827
+ name: (layerMetadata == null ? void 0 : layerMetadata.name) || fileName,
12828
+ visible: true,
12829
+ featureIds: [],
12830
+ readOnly: true,
12831
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12832
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12833
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12834
+ };
12835
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
12836
+ readOnlyFeatures.current.set(layerId, normalizedFeatures);
12837
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: fileHasTemporal });
12838
+ newLayer.featureIds = addedIds;
12839
+ setLayers((prev) => [...prev, newLayer]);
12840
+ updateFeatureCount();
12841
+ scheduleTimelineUpdate();
12842
+ scheduleSync();
12843
+ if (map.current && result.bbox) {
12844
+ const bbox = result.bbox;
12845
+ map.current.fitBounds(
12846
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12847
+ { padding: 50, maxZoom: 16, duration: 1e3 }
12848
+ );
12849
+ }
12850
+ const reprojectMsg2 = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12851
+ toast({
12852
+ title: "Layer created",
12853
+ description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg2} (high-performance mode)`
12854
+ });
12855
+ return;
12856
+ }
12857
+ const currentLayers = layersRef.current;
12858
+ let targetLayer = currentLayers.find((l) => l.id === requestedTargetLayerId && !l.readOnly);
12859
+ if (!targetLayer) {
12860
+ targetLayer = currentLayers.find((l) => l.visible && !l.readOnly);
12861
+ }
12862
+ if (!targetLayer) {
12863
+ targetLayer = currentLayers.find((l) => !l.readOnly);
12864
+ }
12865
+ if (targetLayer == null ? void 0 : targetLayer.visible) {
12866
+ const addedIds = [];
12867
+ isApiAddingRef.current = true;
12868
+ try {
12869
+ normalizedFeatures.forEach((f) => {
12870
+ const ids = draw.current.add(f);
12871
+ addedIds.push(ids[0]);
12872
+ });
12873
+ } finally {
12874
+ isApiAddingRef.current = false;
12875
+ }
12876
+ const targetId = targetLayer.id;
12877
+ setLayers((prev) => prev.map((l) => {
12878
+ if (l.id !== targetId) return l;
12879
+ return {
12880
+ ...l,
12881
+ featureIds: [...l.featureIds, ...addedIds],
12882
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12883
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12884
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12885
+ };
12886
+ }));
12887
+ } else if (targetLayer) {
12888
+ const targetId = targetLayer.id;
12889
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
12890
+ const existing = hiddenFeatures.current.get(targetId) || [];
12891
+ hiddenFeatures.current.set(targetId, [...existing, ...normalizedFeatures]);
12892
+ setLayers((prev) => prev.map((l) => {
12893
+ if (l.id !== targetId) return l;
12894
+ return {
12895
+ ...l,
12896
+ featureIds: [...l.featureIds, ...addedIds],
12897
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12898
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12899
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12900
+ };
12901
+ }));
12902
+ }
12903
+ updateFeatureCount();
12904
+ scheduleTimelineUpdate();
12905
+ scheduleSync();
12906
+ const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12907
+ toast({
12908
+ title: "GeoJSON loaded",
12909
+ description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
12910
+ });
12911
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12912
+ const handleFileChange = useCallback((e) => {
12223
12913
  var _a;
12914
+ const file = (_a = e.target.files) == null ? void 0 : _a[0];
12915
+ if (!file) return;
12916
+ const requestedTargetLayerId = e.target.dataset.targetLayer || activeEditingLayerId;
12917
+ const createNewLayer = e.target.dataset.createNewLayer === "true";
12918
+ delete e.target.dataset.createNewLayer;
12919
+ e.target.value = "";
12920
+ void loadGeoJSONFile(file, requestedTargetLayerId, createNewLayer);
12921
+ }, [activeEditingLayerId, loadGeoJSONFile]);
12922
+ const ingestDroppedLayer = useCallback(async (name, input) => {
12923
+ if (!map.current) return;
12924
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12925
+ const startedAt = performance.now();
12926
+ let result;
12927
+ try {
12928
+ result = await getSharedIngestClient().ingest(input, { idStrategy: "layer-index", layerId });
12929
+ } catch (error) {
12930
+ toast({
12931
+ title: "Failed to load GeoJSON",
12932
+ description: error instanceof Error ? error.message : "Invalid file",
12933
+ variant: "destructive"
12934
+ });
12935
+ return;
12936
+ }
12224
12937
  if (!map.current) return;
12225
- if (data["octostar:map"]) {
12938
+ if (result.kind === "error") {
12939
+ toast({
12940
+ title: "Failed to load GeoJSON",
12941
+ description: result.message,
12942
+ variant: "destructive"
12943
+ });
12944
+ return;
12945
+ }
12946
+ if (result.kind === "enriched") {
12947
+ const data = result.data;
12226
12948
  if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data, sourceName: name }) === true) {
12227
12949
  return;
12228
12950
  }
12229
12951
  restoreEnrichedGeoJSON(data);
12230
12952
  return;
12231
12953
  }
12232
- const { features: reprojectedData, reprojected, sourceCRS } = detectAndReprojectGeoJSON(data);
12954
+ const { features: normalizedFeatures, reprojected, sourceCRS } = result;
12955
+ const layerMetadata = result.layerMetadata;
12233
12956
  saveStateForUndo();
12234
- const layerMetadata = (_a = data.properties) == null ? void 0 : _a.layerMetadata;
12235
- const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12236
- const layerHasAltitudeData = reprojectedData.features.some((f) => hasAltitudeData(f));
12237
12957
  const newLayer = {
12238
12958
  id: layerId,
12239
12959
  name: (layerMetadata == null ? void 0 : layerMetadata.name) || name,
@@ -12244,69 +12964,48 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12244
12964
  ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12245
12965
  ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12246
12966
  ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig },
12247
- ...layerHasAltitudeData && { hasAltitudeData: true, altitudeDisplayMode: "both" }
12967
+ ...result.hasAltitude && { hasAltitudeData: true, altitudeDisplayMode: "both" }
12248
12968
  };
12249
- const normalizedFeatures = [];
12250
- const addedIds = [];
12251
- let dropHasTemporal = false;
12252
- reprojectedData.features.forEach((f, index) => {
12253
- const featureId = f.id !== void 0 && f.id !== null ? String(f.id) : `${layerId}-f${index}`;
12254
- const props = f.properties || {};
12255
- if (!hasAnyTemporalValue(props)) {
12256
- normalizedFeatures.push({ ...f, id: featureId });
12257
- addedIds.push(featureId);
12258
- return;
12259
- }
12260
- const { startDate, endDate } = normalizeTemporalProperties(props);
12261
- if (startDate || endDate) dropHasTemporal = true;
12262
- normalizedFeatures.push({
12263
- ...f,
12264
- id: featureId,
12265
- properties: {
12266
- ...props,
12267
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
12268
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
12269
- }
12270
- });
12271
- addedIds.push(featureId);
12272
- });
12969
+ const addedIds = normalizedFeatures.map((f) => f.id);
12273
12970
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
12274
- layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: dropHasTemporal });
12971
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: result.hasTemporal });
12275
12972
  newLayer.featureIds = addedIds;
12276
12973
  const nextLayers = [...layersRef.current, newLayer];
12277
12974
  layersRef.current = nextLayers;
12278
12975
  setLayers(nextLayers);
12279
12976
  updateFeatureCount();
12280
12977
  scheduleTimelineUpdate();
12281
- syncFeaturesToCustomLayers();
12282
- if (reprojectedData.features.length > 0) {
12283
- try {
12284
- const bbox = turf.bbox(reprojectedData);
12285
- if (bbox && bbox.every((v) => isFinite(v))) {
12286
- map.current.fitBounds(
12287
- [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12288
- { padding: 50, maxZoom: 16, duration: 1e3 }
12289
- );
12290
- }
12291
- } catch (e) {
12292
- }
12978
+ scheduleSync();
12979
+ if (result.bbox) {
12980
+ const bbox = result.bbox;
12981
+ map.current.fitBounds(
12982
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12983
+ { padding: 50, maxZoom: 16, duration: 1e3 }
12984
+ );
12293
12985
  }
12986
+ mapPerfLog("ingest", `dropped layer "${newLayer.name}" applied`, {
12987
+ features: addedIds.length,
12988
+ totalMs: Math.round(performance.now() - startedAt)
12989
+ });
12294
12990
  const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12295
12991
  toast({
12296
12992
  title: "Layer added",
12297
12993
  description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg} (high-performance)`
12298
12994
  });
12299
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12995
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12996
+ const handleDropGeoJSON = useCallback((name, data) => {
12997
+ void ingestDroppedLayer(name, data);
12998
+ }, [ingestDroppedLayer]);
12999
+ const handleDropGeoJSONFile = useCallback((name, file) => {
13000
+ void ingestDroppedLayer(name, file);
13001
+ }, [ingestDroppedLayer]);
12300
13002
  const handleTimelineFilterChange = useCallback((visibleIds, hiddenIds, untimedIds) => {
12301
13003
  if (!draw.current || !map.current) return;
12302
- timelineVisibleIdsRef.current = /* @__PURE__ */ new Set([...visibleIds, ...untimedIds]);
12303
- if (timelineSyncRafRef.current == null) {
12304
- timelineSyncRafRef.current = requestAnimationFrame(() => {
12305
- timelineSyncRafRef.current = null;
12306
- syncFeaturesToCustomLayers();
12307
- });
12308
- }
12309
- }, [syncFeaturesToCustomLayers]);
13004
+ const nextVisible = new Set(visibleIds);
13005
+ untimedIds.forEach((id) => nextVisible.add(id));
13006
+ timelineVisibleIdsRef.current = nextVisible;
13007
+ scheduleSync("timeline");
13008
+ }, [scheduleSync]);
12310
13009
  const prevTimelineEnabledRef = useRef(timelineStore.isEnabled);
12311
13010
  useEffect(() => {
12312
13011
  const wasEnabled = prevTimelineEnabledRef.current;
@@ -12314,11 +13013,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12314
13013
  prevTimelineEnabledRef.current = isNowEnabled;
12315
13014
  if (!isNowEnabled || !timelineStore.hasTemporalData) {
12316
13015
  timelineVisibleIdsRef.current = null;
12317
- syncFeaturesToCustomLayers();
13016
+ scheduleSync();
12318
13017
  } else if (!wasEnabled && isNowEnabled) {
12319
13018
  updateTimelineStore();
12320
13019
  }
12321
- }, [timelineStore.isEnabled, timelineStore.hasTemporalData, syncFeaturesToCustomLayers, updateTimelineStore, scheduleTimelineUpdate]);
13020
+ }, [timelineStore.isEnabled, timelineStore.hasTemporalData, scheduleSync, updateTimelineStore, scheduleTimelineUpdate]);
12322
13021
  useEffect(() => {
12323
13022
  if (!map.current || !draw.current || !isMapLoaded) return;
12324
13023
  const mapInstance = map.current;
@@ -12689,7 +13388,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12689
13388
  ] }) });
12690
13389
  }
12691
13390
  const toastContextValue = toastProvider ?? null;
12692
- return /* @__PURE__ */ jsx(TimelineStoreContext.Provider, { value: timelineStoreApi, children: /* @__PURE__ */ jsx(ToastContext.Provider, { value: toastContextValue, children: /* @__PURE__ */ jsx(MapDropZone, { onDrop: handleDropGeoJSON, children: /* @__PURE__ */ jsxs("div", { className: `map-container w-full h-full min-w-0 relative overflow-hidden isolate ${className || ""}`, "data-testid": "map-editor-canvas", children: [
13391
+ return /* @__PURE__ */ jsx(TimelineStoreContext.Provider, { value: timelineStoreApi, children: /* @__PURE__ */ jsx(ToastContext.Provider, { value: toastContextValue, children: /* @__PURE__ */ jsx(MapDropZone, { onDrop: handleDropGeoJSON, onDropFile: handleDropGeoJSONFile, children: /* @__PURE__ */ jsxs("div", { className: `map-container w-full h-full min-w-0 relative overflow-hidden isolate ${className || ""}`, "data-testid": "map-editor-canvas", children: [
12693
13392
  /* @__PURE__ */ jsx(
12694
13393
  "div",
12695
13394
  {
@@ -13168,18 +13867,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13168
13867
  ))
13169
13868
  }
13170
13869
  ),
13171
- cursorCoords && /* @__PURE__ */ jsxs(
13172
- "div",
13173
- {
13174
- className: "absolute bottom-1 right-12 z-10 pointer-events-none font-mono text-[10px] text-muted-foreground/70 select-none",
13175
- "data-testid": "cursor-coordinates",
13176
- children: [
13177
- cursorCoords.lat.toFixed(5),
13178
- ", ",
13179
- cursorCoords.lng.toFixed(5)
13180
- ]
13181
- }
13182
- ),
13870
+ /* @__PURE__ */ jsx(CursorCoordinatesOverlay, { map: isMapLoaded ? map.current : null }),
13183
13871
  /* @__PURE__ */ jsx(
13184
13872
  "input",
13185
13873
  {
@@ -13943,7 +14631,15 @@ function DebugSidebar({ onAddRandomPoints, onImportKML, onAddDomMarkers, onRemov
13943
14631
  const geojson = parseKMLToGeoJSON(content);
13944
14632
  if (geojson && onImportKML) {
13945
14633
  const layerName = file.name.replace(/\.(kml|kmz)$/i, "");
13946
- onImportKML(layerName, geojson);
14634
+ void getSharedIngestClient().ingest(geojson, { idStrategy: "preserve" }).then((result) => {
14635
+ onImportKML(
14636
+ layerName,
14637
+ result.kind === "features" ? { type: "FeatureCollection", features: result.features } : geojson
14638
+ );
14639
+ }).catch((err) => {
14640
+ console.warn("[map-component] KML ingest normalization failed:", err);
14641
+ onImportKML(layerName, geojson);
14642
+ });
13947
14643
  }
13948
14644
  };
13949
14645
  reader.readAsText(file);