@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.cjs CHANGED
@@ -5,8 +5,8 @@ const react = require("react");
5
5
  const maplibregl = require("maplibre-gl");
6
6
  const MapboxDraw = require("@mapbox/mapbox-gl-draw");
7
7
  const turf = require("@turf/turf");
8
- const proj4 = require("proj4");
9
8
  const THREE = require("three");
9
+ const proj4 = require("proj4");
10
10
  const antd = require("antd");
11
11
  const clsx = require("clsx");
12
12
  const tailwindMerge = require("tailwind-merge");
@@ -14,6 +14,7 @@ const lucideReact = require("lucide-react");
14
14
  const reactDom = require("react-dom");
15
15
  const dateFns = require("date-fns");
16
16
  const zustand = require("zustand");
17
+ const Flatbush = require("flatbush");
17
18
  const dayjs = require("dayjs");
18
19
  const toGeoJSON = require("@mapbox/togeojson");
19
20
  function _interopNamespaceDefault(e) {
@@ -35,6 +36,472 @@ function _interopNamespaceDefault(e) {
35
36
  const turf__namespace = /* @__PURE__ */ _interopNamespaceDefault(turf);
36
37
  const THREE__namespace = /* @__PURE__ */ _interopNamespaceDefault(THREE);
37
38
  const toGeoJSON__namespace = /* @__PURE__ */ _interopNamespaceDefault(toGeoJSON);
39
+ function detectSourceCRS(geojson) {
40
+ var _a, _b;
41
+ const crsName = (_b = (_a = geojson.crs) == null ? void 0 : _a.properties) == null ? void 0 : _b.name;
42
+ let sourceCRS = null;
43
+ if (crsName) {
44
+ const epsgMatch = crsName.match(/EPSG::?(\d+)/i);
45
+ if (epsgMatch) sourceCRS = `EPSG:${epsgMatch[1]}`;
46
+ }
47
+ if (!sourceCRS && geojson.features.length > 0) {
48
+ const firstCoord = getFirstCoordinate(geojson.features[0].geometry);
49
+ if (firstCoord) {
50
+ const [x, y] = firstCoord;
51
+ if (Math.abs(x) <= 180 && Math.abs(y) <= 90) {
52
+ return { sourceCRS: "EPSG:4326", needsReprojection: false };
53
+ }
54
+ }
55
+ return { sourceCRS: null, needsReprojection: false };
56
+ }
57
+ return { sourceCRS, needsReprojection: sourceCRS !== null && sourceCRS !== "EPSG:4326" };
58
+ }
59
+ function getFirstCoordinate(geometry) {
60
+ var _a, _b, _c;
61
+ if (!geometry) return null;
62
+ switch (geometry.type) {
63
+ case "Point":
64
+ return geometry.coordinates;
65
+ case "MultiPoint":
66
+ case "LineString":
67
+ return geometry.coordinates[0];
68
+ case "MultiLineString":
69
+ case "Polygon":
70
+ return (_a = geometry.coordinates[0]) == null ? void 0 : _a[0];
71
+ case "MultiPolygon":
72
+ return (_c = (_b = geometry.coordinates[0]) == null ? void 0 : _b[0]) == null ? void 0 : _c[0];
73
+ default:
74
+ return null;
75
+ }
76
+ }
77
+ function hasAltitudeData(feature) {
78
+ var _a, _b;
79
+ if (((_a = feature.geometry) == null ? void 0 : _a.type) === "LineString") {
80
+ const coords = feature.geometry.coordinates;
81
+ return coords.some((c) => c.length >= 3 && c[2] !== 0);
82
+ }
83
+ if (((_b = feature.geometry) == null ? void 0 : _b.type) === "MultiLineString") {
84
+ const coords = feature.geometry.coordinates;
85
+ return coords.some((line) => line.some((c) => c.length >= 3 && c[2] !== 0));
86
+ }
87
+ return false;
88
+ }
89
+ const PRETTY_EXPORT_MAX_FEATURES = 1e4;
90
+ const TARGET_PART_CHARS = 8 * 1024 * 1024;
91
+ function featureCollectionBlobParts(collection, options) {
92
+ const prettyMax = PRETTY_EXPORT_MAX_FEATURES;
93
+ if (collection.features.length <= prettyMax) {
94
+ return [JSON.stringify(collection, null, 2)];
95
+ }
96
+ const targetChars = TARGET_PART_CHARS;
97
+ const { features, ...rest } = collection;
98
+ const head = JSON.stringify(rest);
99
+ const parts = [];
100
+ let pending = [];
101
+ let pendingChars = 0;
102
+ const push = (piece) => {
103
+ pending.push(piece);
104
+ pendingChars += piece.length;
105
+ if (pendingChars >= targetChars) {
106
+ parts.push(pending.join(""));
107
+ pending = [];
108
+ pendingChars = 0;
109
+ }
110
+ };
111
+ push(head.slice(0, -1));
112
+ push(head.length > 2 ? ',"features":[' : '"features":[');
113
+ for (let i = 0; i < features.length; i++) {
114
+ push(i === 0 ? JSON.stringify(features[i]) : "," + JSON.stringify(features[i]));
115
+ }
116
+ push("]}");
117
+ if (pending.length > 0) parts.push(pending.join(""));
118
+ return parts;
119
+ }
120
+ 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';
121
+ 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");
122
+ 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");
123
+ proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
124
+ proj4.defs("EPSG:32631", "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs");
125
+ function reprojectFeatures(features, sourceCRS) {
126
+ if (!proj4.defs(sourceCRS)) return null;
127
+ try {
128
+ return features.map((feature) => ({
129
+ ...feature,
130
+ geometry: reprojectGeometry(feature.geometry, sourceCRS)
131
+ }));
132
+ } catch (e) {
133
+ console.error("Reprojection failed:", e);
134
+ return null;
135
+ }
136
+ }
137
+ function reprojectGeometry(geometry, fromCRS) {
138
+ if (!geometry) return geometry;
139
+ const transform = (coord) => {
140
+ const [x, y] = proj4(fromCRS, "EPSG:4326", [coord[0], coord[1]]);
141
+ return coord.length > 2 ? [x, y, ...coord.slice(2)] : [x, y];
142
+ };
143
+ const reprojectCoords = (coords) => {
144
+ if (typeof coords[0] === "number") {
145
+ return transform(coords);
146
+ }
147
+ return coords.map(reprojectCoords);
148
+ };
149
+ if (geometry.type === "GeometryCollection") {
150
+ return {
151
+ type: "GeometryCollection",
152
+ geometries: geometry.geometries.map((g) => reprojectGeometry(g, fromCRS))
153
+ };
154
+ }
155
+ const geomWithCoords = geometry;
156
+ return {
157
+ ...geomWithCoords,
158
+ coordinates: reprojectCoords(geomWithCoords.coordinates)
159
+ };
160
+ }
161
+ function parseDate(value) {
162
+ if (!value) return null;
163
+ if (value instanceof Date) return value;
164
+ if (typeof value === "string" || typeof value === "number") {
165
+ const date = new Date(value);
166
+ return isNaN(date.getTime()) ? null : date;
167
+ }
168
+ return null;
169
+ }
170
+ function hasAnyTemporalValue(properties) {
171
+ 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);
172
+ }
173
+ function normalizeTemporalProperties(properties) {
174
+ 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);
175
+ let endDate = parseDate(properties.endDate) || parseDate(properties.enddate) || parseDate(properties.end_date) || parseDate(properties.end_time);
176
+ if (startDate && endDate && endDate < startDate) {
177
+ [startDate, endDate] = [endDate, startDate];
178
+ }
179
+ return { startDate, endDate };
180
+ }
181
+ function generateUuid() {
182
+ var _a, _b;
183
+ const uuid = (_b = (_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) == null ? void 0 : _b.bind(globalThis.crypto);
184
+ return uuid ? uuid() : `f-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
185
+ }
186
+ function assignId(feature, index, options) {
187
+ switch (options.idStrategy) {
188
+ case "preserve":
189
+ return feature.id;
190
+ case "layer-index":
191
+ return feature.id !== void 0 && feature.id !== null ? String(feature.id) : `${options.layerId}-f${index}`;
192
+ case "uuid-fallback":
193
+ return feature.id ? String(feature.id) : generateUuid();
194
+ }
195
+ }
196
+ function scanCoords(coords, box) {
197
+ if (!Array.isArray(coords)) return;
198
+ if (typeof coords[0] === "number") {
199
+ const x = coords[0];
200
+ const y = coords[1];
201
+ box[0] = Math.min(box[0], x);
202
+ box[1] = Math.min(box[1], y);
203
+ box[2] = Math.max(box[2], x);
204
+ box[3] = Math.max(box[3], y);
205
+ return;
206
+ }
207
+ for (const c of coords) scanCoords(c, box);
208
+ }
209
+ function scanGeometry(geometry, box) {
210
+ if (!geometry) return;
211
+ if (geometry.type === "GeometryCollection") {
212
+ for (const g of geometry.geometries) scanGeometry(g, box);
213
+ return;
214
+ }
215
+ scanCoords(geometry.coordinates, box);
216
+ }
217
+ function computeFeatureCollectionBbox(features) {
218
+ const box = [Infinity, Infinity, -Infinity, -Infinity];
219
+ for (const f of features) scanGeometry(f.geometry, box);
220
+ return box.every((v) => isFinite(v)) ? box : null;
221
+ }
222
+ function runIngestPipeline(source, options) {
223
+ var _a;
224
+ let data;
225
+ if (source.type === "text") {
226
+ try {
227
+ data = JSON.parse(source.text);
228
+ } catch (err) {
229
+ return {
230
+ kind: "error",
231
+ code: "parse-error",
232
+ message: err instanceof Error ? err.message : "Invalid file"
233
+ };
234
+ }
235
+ } else {
236
+ data = source.data;
237
+ }
238
+ if (data && data.type === "Feature") {
239
+ data = {
240
+ type: "FeatureCollection",
241
+ features: [data]
242
+ };
243
+ }
244
+ if (!data || data.type !== "FeatureCollection" || !Array.isArray(data.features)) {
245
+ return { kind: "error", code: "invalid-format", message: "Invalid GeoJSON format" };
246
+ }
247
+ if (options.emptyIsError && data.features.length === 0) {
248
+ return { kind: "error", code: "empty", message: "The file contains no features" };
249
+ }
250
+ if (data["octostar:map"]) {
251
+ return { kind: "enriched", data };
252
+ }
253
+ const { sourceCRS, needsReprojection } = detectSourceCRS(data);
254
+ let hasTemporal = false;
255
+ let hasAltitude = false;
256
+ const features = [];
257
+ data.features.forEach((f, index) => {
258
+ const id = assignId(f, index, options);
259
+ if (!hasAltitude && hasAltitudeData(f)) hasAltitude = true;
260
+ const props = f.properties || {};
261
+ if (!hasAnyTemporalValue(props)) {
262
+ features.push(options.idStrategy === "preserve" ? f : { ...f, id });
263
+ return;
264
+ }
265
+ const { startDate, endDate } = normalizeTemporalProperties(props);
266
+ if (startDate || endDate) hasTemporal = true;
267
+ features.push({
268
+ ...f,
269
+ id,
270
+ properties: {
271
+ ...props,
272
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
273
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
274
+ }
275
+ });
276
+ });
277
+ const layerMetadata = (_a = data.properties) == null ? void 0 : _a.layerMetadata;
278
+ return {
279
+ kind: "features",
280
+ features,
281
+ featureCount: features.length,
282
+ bbox: computeFeatureCollectionBbox(features),
283
+ hasTemporal,
284
+ hasAltitude,
285
+ reprojected: false,
286
+ sourceCRS,
287
+ ...needsReprojection && { needsReprojection },
288
+ ...layerMetadata && { layerMetadata }
289
+ };
290
+ }
291
+ const fromStorage = (() => {
292
+ var _a;
293
+ try {
294
+ return ((_a = globalThis.localStorage) == null ? void 0 : _a.getItem("octostar-map-perf-log")) === "1";
295
+ } catch {
296
+ return false;
297
+ }
298
+ })();
299
+ function mapPerfLogEnabled() {
300
+ return fromStorage || globalThis.__octostarMapPerfLog === true;
301
+ }
302
+ function mapPerfLog(area, message, data) {
303
+ if (!mapPerfLogEnabled()) return;
304
+ if (data === void 0) {
305
+ console.info(`[map-perf:${area}] ${message}`);
306
+ } else {
307
+ console.info(`[map-perf:${area}] ${message}`, data);
308
+ }
309
+ }
310
+ function finalizeReprojection(result) {
311
+ if (result.kind !== "features" || !result.needsReprojection || !result.sourceCRS) return result;
312
+ const reprojected = reprojectFeatures(result.features, result.sourceCRS);
313
+ if (!reprojected) {
314
+ return { ...result, needsReprojection: false };
315
+ }
316
+ return {
317
+ ...result,
318
+ features: reprojected,
319
+ reprojected: true,
320
+ needsReprojection: false,
321
+ bbox: computeFeatureCollectionBbox(reprojected)
322
+ };
323
+ }
324
+ function createWorkerPort() {
325
+ if (typeof Worker === "undefined") {
326
+ mapPerfLog("ingest", "Worker unavailable in this environment — using main-thread pipeline");
327
+ return null;
328
+ }
329
+ let url = null;
330
+ try {
331
+ url = URL.createObjectURL(new Blob([ingestWorkerSource], { type: "text/javascript" }));
332
+ const worker = new Worker(url);
333
+ let pendingUrl = url;
334
+ const revokePendingUrl = () => {
335
+ if (pendingUrl) URL.revokeObjectURL(pendingUrl);
336
+ pendingUrl = null;
337
+ };
338
+ mapPerfLog("ingest", "worker spawned");
339
+ return {
340
+ post: (msg) => worker.postMessage(msg),
341
+ onMessage: (cb) => {
342
+ worker.onmessage = (e) => {
343
+ revokePendingUrl();
344
+ cb(e.data);
345
+ };
346
+ },
347
+ onError: (cb) => {
348
+ worker.onerror = (e) => {
349
+ revokePendingUrl();
350
+ cb(e);
351
+ };
352
+ worker.onmessageerror = (e) => cb(e);
353
+ },
354
+ terminate: () => {
355
+ revokePendingUrl();
356
+ worker.terminate();
357
+ }
358
+ };
359
+ } catch (err) {
360
+ if (url) URL.revokeObjectURL(url);
361
+ console.warn(
362
+ "[map-component] Ingest worker could not be spawned (CSP may block blob: workers); file parsing will run on the main thread.",
363
+ err
364
+ );
365
+ return null;
366
+ }
367
+ }
368
+ const INGEST_TIMEOUT_MS = 12e4;
369
+ function createIngestClient(portFactory = createWorkerPort) {
370
+ let port = null;
371
+ let portUnavailable = false;
372
+ let nextId = 0;
373
+ const pending = /* @__PURE__ */ new Map();
374
+ const rejectAllPending = (reason) => {
375
+ pending.forEach((request) => {
376
+ clearTimeout(request.timeout);
377
+ request.reject(new Error(reason));
378
+ });
379
+ pending.clear();
380
+ };
381
+ const abandonPort = (reason) => {
382
+ rejectAllPending(reason);
383
+ port == null ? void 0 : port.terminate();
384
+ port = null;
385
+ };
386
+ const ensurePort = () => {
387
+ if (portUnavailable || port) return port;
388
+ try {
389
+ port = portFactory();
390
+ } catch {
391
+ port = null;
392
+ }
393
+ if (!port) {
394
+ portUnavailable = true;
395
+ return null;
396
+ }
397
+ port.onMessage((msg) => {
398
+ const request = pending.get(msg.id);
399
+ if (!request) return;
400
+ pending.delete(msg.id);
401
+ clearTimeout(request.timeout);
402
+ mapPerfLog("ingest", `worker request "${request.label}" finished`, {
403
+ ms: Math.round(performance.now() - request.startedAt),
404
+ ok: msg.ok
405
+ });
406
+ if (msg.ok) {
407
+ request.resolve(finalizeReprojection(msg.result));
408
+ } else {
409
+ request.reject(new Error(msg.error));
410
+ }
411
+ });
412
+ port.onError((err) => {
413
+ console.warn("[map-component] Ingest worker crashed; it will be respawned on next use.", err);
414
+ abandonPort("Ingest worker crashed");
415
+ });
416
+ return port;
417
+ };
418
+ const runInline = async (input, options) => {
419
+ const text = typeof input === "string" ? input : await input.text();
420
+ const startedAt = performance.now();
421
+ const result = finalizeReprojection(runIngestPipeline({ type: "text", text }, options));
422
+ mapPerfLog("ingest", "main-thread pipeline finished (no worker)", {
423
+ ms: Math.round(performance.now() - startedAt)
424
+ });
425
+ return result;
426
+ };
427
+ return {
428
+ ingest(input, options) {
429
+ if (typeof input === "object" && !(input instanceof Blob)) {
430
+ return Promise.resolve().then(
431
+ () => finalizeReprojection(runIngestPipeline({ type: "parsed", data: input }, options))
432
+ );
433
+ }
434
+ const activePort = ensurePort();
435
+ if (!activePort) return runInline(input, options);
436
+ const id = nextId++;
437
+ const label = input instanceof File ? input.name : typeof input === "string" ? "text" : "blob";
438
+ return new Promise((resolve, reject) => {
439
+ const timeout = setTimeout(() => {
440
+ console.warn(
441
+ `[map-component] Ingest worker unresponsive for "${label}" after ${INGEST_TIMEOUT_MS}ms; it will be respawned on next use.`
442
+ );
443
+ abandonPort("Ingest worker unresponsive — the file could not be parsed");
444
+ }, INGEST_TIMEOUT_MS);
445
+ pending.set(id, { resolve, reject, startedAt: performance.now(), label, timeout });
446
+ activePort.post({
447
+ id,
448
+ source: typeof input === "string" ? { type: "text", text: input } : { type: "blob", blob: input },
449
+ options
450
+ });
451
+ });
452
+ },
453
+ dispose() {
454
+ abandonPort("Ingest client disposed");
455
+ portUnavailable = false;
456
+ }
457
+ };
458
+ }
459
+ let sharedClient = null;
460
+ function getSharedIngestClient() {
461
+ if (!sharedClient) sharedClient = createIngestClient();
462
+ return sharedClient;
463
+ }
464
+ function CursorCoordinatesOverlay({ map }) {
465
+ const [coords, setCoords] = react.useState(null);
466
+ react.useEffect(() => {
467
+ if (!map) return;
468
+ let pending = null;
469
+ let frame = 0;
470
+ const flush = () => {
471
+ frame = 0;
472
+ setCoords(pending);
473
+ };
474
+ const schedule = (next) => {
475
+ pending = next;
476
+ if (!frame) frame = requestAnimationFrame(flush);
477
+ };
478
+ const onMove = (e) => schedule({ lng: e.lngLat.lng, lat: e.lngLat.lat });
479
+ const onOut = () => schedule(null);
480
+ map.on("mousemove", onMove);
481
+ map.on("mouseout", onOut);
482
+ return () => {
483
+ if (frame) cancelAnimationFrame(frame);
484
+ try {
485
+ map.off("mousemove", onMove);
486
+ map.off("mouseout", onOut);
487
+ } catch {
488
+ }
489
+ };
490
+ }, [map]);
491
+ if (!coords) return null;
492
+ return /* @__PURE__ */ jsxRuntime.jsxs(
493
+ "div",
494
+ {
495
+ className: "absolute bottom-1 right-12 z-10 pointer-events-none font-mono text-[10px] text-muted-foreground/70 select-none",
496
+ "data-testid": "cursor-coordinates",
497
+ children: [
498
+ coords.lat.toFixed(5),
499
+ ", ",
500
+ coords.lng.toFixed(5)
501
+ ]
502
+ }
503
+ );
504
+ }
38
505
  const ICONS = [
39
506
  // Location & Places
40
507
  { id: "map-pin", emoji: "📍", name: "Map Pin", category: "places" },
@@ -4524,26 +4991,6 @@ function StatusIndicator({ featureCount, selectedCount = 0 }) {
4524
4991
  }
4525
4992
  );
4526
4993
  }
4527
- function parseDate(value) {
4528
- if (!value) return null;
4529
- if (value instanceof Date) return value;
4530
- if (typeof value === "string" || typeof value === "number") {
4531
- const date = new Date(value);
4532
- return isNaN(date.getTime()) ? null : date;
4533
- }
4534
- return null;
4535
- }
4536
- function hasAnyTemporalValue(properties) {
4537
- 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);
4538
- }
4539
- function normalizeTemporalProperties(properties) {
4540
- 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);
4541
- let endDate = parseDate(properties.endDate) || parseDate(properties.enddate) || parseDate(properties.end_date) || parseDate(properties.end_time);
4542
- if (startDate && endDate && endDate < startDate) {
4543
- [startDate, endDate] = [endDate, startDate];
4544
- }
4545
- return { startDate, endDate };
4546
- }
4547
4994
  function isFeatureInRange(feature, rangeStart, rangeEnd) {
4548
4995
  if (!feature.startDate && !feature.endDate) return true;
4549
4996
  if (!rangeStart || !rangeEnd) return true;
@@ -4637,7 +5084,8 @@ const timelineStoreInitializer = (set, get) => ({
4637
5084
  const computedMax = maxDate;
4638
5085
  const sameFeatureIds = state.temporalFeatures.length === timedFeatures.length && timedFeatures.every((f, i) => f.id === state.temporalFeatures[i].id);
4639
5086
  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());
4640
- if (sameFeatureIds && sameDates && state.hasTemporalData) return;
5087
+ const sameUntimed = state.untimedFeatureIds.length === untimedIds.length && untimedIds.every((id, i) => id === state.untimedFeatureIds[i]);
5088
+ if (sameFeatureIds && sameDates && sameUntimed && state.hasTemporalData) return;
4641
5089
  const histogramBins = minDate && maxDate ? computeHistogramBins(timedFeatures, minDate, maxDate) : [];
4642
5090
  set({
4643
5091
  hasTemporalData: true,
@@ -5162,7 +5610,7 @@ function Timebar({ onFilterChange, selectedFeatureIds = [], selectedFeatureColor
5162
5610
  }
5163
5611
  );
5164
5612
  }
5165
- function MapDropZone({ onDrop, children }) {
5613
+ function MapDropZone({ onDrop, onDropFile, children }) {
5166
5614
  const [isDragOver, setIsDragOver] = react.useState(false);
5167
5615
  const handleDragOver = react.useCallback((e) => {
5168
5616
  e.preventDefault();
@@ -5197,13 +5645,17 @@ function MapDropZone({ onDrop, children }) {
5197
5645
  for (let i = 0; i < files.length; i++) {
5198
5646
  const file = files[i];
5199
5647
  if (!file.name.match(/\.(geojson|json)$/i)) continue;
5648
+ const name = file.name.replace(/\.(geojson|json)$/i, "");
5649
+ if (onDropFile) {
5650
+ onDropFile(name, file);
5651
+ continue;
5652
+ }
5200
5653
  const reader = new FileReader();
5201
5654
  reader.onload = (evt) => {
5202
5655
  var _a;
5203
5656
  try {
5204
5657
  const parsed = JSON.parse((_a = evt.target) == null ? void 0 : _a.result);
5205
5658
  if (parsed.type === "FeatureCollection" && Array.isArray(parsed.features)) {
5206
- const name = file.name.replace(/\.(geojson|json)$/i, "");
5207
5659
  onDrop(name, parsed);
5208
5660
  }
5209
5661
  } catch (err) {
@@ -5213,7 +5665,7 @@ function MapDropZone({ onDrop, children }) {
5213
5665
  reader.readAsText(file);
5214
5666
  }
5215
5667
  }
5216
- }, [onDrop]);
5668
+ }, [onDrop, onDropFile]);
5217
5669
  return /* @__PURE__ */ jsxRuntime.jsxs(
5218
5670
  "div",
5219
5671
  {
@@ -5407,23 +5859,438 @@ function countFeaturesInBounds(featureGroups, bounds, options) {
5407
5859
  }
5408
5860
  return count;
5409
5861
  }
5410
- const OTHER_BUCKET_KEY = "__other__";
5411
- const OTHER_BUCKET_LABEL = "Other";
5412
- const OTHER_BUCKET_COLOR = "#9ca3af";
5413
- function toDisplayName(name) {
5414
- return name === OTHER_BUCKET_KEY ? OTHER_BUCKET_LABEL : name;
5862
+ const rafScheduler = {
5863
+ request: (cb) => requestAnimationFrame(() => cb()),
5864
+ cancel: (handle) => cancelAnimationFrame(handle)
5865
+ };
5866
+ function createRafCoalescer(run, scheduler = rafScheduler) {
5867
+ let reasons = /* @__PURE__ */ new Set();
5868
+ let handle = null;
5869
+ let running = false;
5870
+ const fire = () => {
5871
+ handle = null;
5872
+ const snapshot = reasons;
5873
+ reasons = /* @__PURE__ */ new Set();
5874
+ running = true;
5875
+ try {
5876
+ run(snapshot);
5877
+ } finally {
5878
+ running = false;
5879
+ }
5880
+ };
5881
+ return {
5882
+ schedule(reason) {
5883
+ reasons.add(reason);
5884
+ if (handle === null) {
5885
+ handle = scheduler.request(fire);
5886
+ }
5887
+ },
5888
+ isPending() {
5889
+ return handle !== null;
5890
+ },
5891
+ flush() {
5892
+ if (running || handle === null) return;
5893
+ scheduler.cancel(handle);
5894
+ fire();
5895
+ },
5896
+ cancel() {
5897
+ if (handle !== null) {
5898
+ scheduler.cancel(handle);
5899
+ handle = null;
5900
+ }
5901
+ reasons.clear();
5902
+ }
5903
+ };
5415
5904
  }
5416
- function createPieSVG(categories, total, size = 44, onSliceHover) {
5417
- const container = document.createElement("div");
5418
- container.style.width = `${size}px`;
5419
- container.style.height = `${size}px`;
5420
- container.style.cursor = "pointer";
5421
- const radius = size / 2;
5422
- const innerRadius = radius * 0.5;
5423
- const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
5424
- svg.setAttribute("width", String(size));
5425
- svg.setAttribute("height", String(size));
5426
- svg.setAttribute("viewBox", `0 0 ${size} ${size}`);
5905
+ const DEFAULT_LABEL_PRIORITY = 100;
5906
+ const DEFAULT_VISIBLE_STROKE_OPACITY = 1;
5907
+ const DEFAULT_VISIBLE_FILL_OPACITY = 0.2;
5908
+ function createSelectionPaintCache() {
5909
+ return {
5910
+ presentIds: /* @__PURE__ */ new Set(),
5911
+ appliedSelectedIds: /* @__PURE__ */ new Set(),
5912
+ basePriorityById: /* @__PURE__ */ new Map(),
5913
+ appliedHiddenIds: /* @__PURE__ */ new Set(),
5914
+ visibleStrokeOpacityById: /* @__PURE__ */ new Map(),
5915
+ visibleFillOpacityById: /* @__PURE__ */ new Map(),
5916
+ updatable: true
5917
+ };
5918
+ }
5919
+ function recordPaintedFeature(cache, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
5920
+ if (cache.presentIds.has(featureId)) {
5921
+ cache.updatable = false;
5922
+ } else {
5923
+ cache.presentIds.add(featureId);
5924
+ }
5925
+ cache.basePriorityById.set(featureId, basePriority);
5926
+ if (isSelected) cache.appliedSelectedIds.add(featureId);
5927
+ if (visibleStrokeOpacity !== DEFAULT_VISIBLE_STROKE_OPACITY) {
5928
+ cache.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
5929
+ }
5930
+ if (visibleFillOpacity !== DEFAULT_VISIBLE_FILL_OPACITY) {
5931
+ cache.visibleFillOpacityById.set(featureId, visibleFillOpacity);
5932
+ }
5933
+ if (isTimelineHidden) cache.appliedHiddenIds.add(featureId);
5934
+ }
5935
+ function applySelectionFastPath(cache, nextSelectedIds, source) {
5936
+ if (!cache || !cache.updatable || !source) return false;
5937
+ const diff = buildSelectionDiff(cache, nextSelectedIds);
5938
+ if (diff) {
5939
+ try {
5940
+ source.updateData(diff);
5941
+ } catch {
5942
+ return false;
5943
+ }
5944
+ }
5945
+ const applied = /* @__PURE__ */ new Set();
5946
+ nextSelectedIds.forEach((id) => {
5947
+ if (cache.presentIds.has(id)) applied.add(id);
5948
+ });
5949
+ cache.appliedSelectedIds = applied;
5950
+ return true;
5951
+ }
5952
+ function needsDrawSelectionUpdate(input) {
5953
+ return input.editableSelectionCount > 0 || input.drawSelectedCount > 0 || input.currentMode !== input.targetMode;
5954
+ }
5955
+ function buildSelectionDiff(cache, nextSelectedIds) {
5956
+ const update = [];
5957
+ cache.appliedSelectedIds.forEach((id) => {
5958
+ if (!nextSelectedIds.has(id) && cache.presentIds.has(id)) {
5959
+ update.push({
5960
+ id,
5961
+ addOrUpdateProperties: [
5962
+ { key: "isSelected", value: 0 },
5963
+ { key: "_labelPriority", value: cache.basePriorityById.get(id) ?? DEFAULT_LABEL_PRIORITY }
5964
+ ]
5965
+ });
5966
+ }
5967
+ });
5968
+ nextSelectedIds.forEach((id) => {
5969
+ if (!cache.appliedSelectedIds.has(id) && cache.presentIds.has(id)) {
5970
+ update.push({
5971
+ id,
5972
+ addOrUpdateProperties: [
5973
+ { key: "isSelected", value: 1 },
5974
+ { key: "_labelPriority", value: 0 }
5975
+ ]
5976
+ });
5977
+ }
5978
+ });
5979
+ return update.length > 0 ? { update } : null;
5980
+ }
5981
+ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
5982
+ const update = [];
5983
+ const nextHiddenIds = /* @__PURE__ */ new Set();
5984
+ cache.presentIds.forEach((id) => {
5985
+ const nextHidden = nextVisibleSet !== null && !nextVisibleSet.has(id);
5986
+ if (nextHidden) nextHiddenIds.add(id);
5987
+ if (nextHidden === cache.appliedHiddenIds.has(id)) return;
5988
+ if (nextHidden) {
5989
+ update.push({
5990
+ id,
5991
+ addOrUpdateProperties: [
5992
+ { key: "stroke-opacity", value: 0 },
5993
+ { key: "fill-opacity", value: 0 },
5994
+ { key: "isTimelineHidden", value: 1 }
5995
+ ]
5996
+ });
5997
+ } else {
5998
+ update.push({
5999
+ id,
6000
+ addOrUpdateProperties: [
6001
+ { key: "stroke-opacity", value: cache.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
6002
+ { key: "fill-opacity", value: cache.visibleFillOpacityById.get(id) ?? DEFAULT_VISIBLE_FILL_OPACITY },
6003
+ { key: "isTimelineHidden", value: 0 }
6004
+ ]
6005
+ });
6006
+ }
6007
+ });
6008
+ return { diff: update.length > 0 ? { update } : null, nextHiddenIds };
6009
+ }
6010
+ function applyTimelineFastPath(cache, nextVisibleSet, source) {
6011
+ var _a;
6012
+ if (!cache || !cache.updatable || !source) return { applied: false, toggled: 0 };
6013
+ const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache, nextVisibleSet);
6014
+ if (diff) {
6015
+ try {
6016
+ source.updateData(diff);
6017
+ } catch {
6018
+ return { applied: false, toggled: 0 };
6019
+ }
6020
+ }
6021
+ cache.appliedHiddenIds = nextHiddenIds;
6022
+ return { applied: true, toggled: ((_a = diff == null ? void 0 : diff.update) == null ? void 0 : _a.length) ?? 0 };
6023
+ }
6024
+ function deepClone(value) {
6025
+ try {
6026
+ return structuredClone(value);
6027
+ } catch {
6028
+ return JSON.parse(JSON.stringify(value));
6029
+ }
6030
+ }
6031
+ function cloneFeatures(features) {
6032
+ try {
6033
+ return structuredClone(features);
6034
+ } catch {
6035
+ return features.map((f) => deepClone(f));
6036
+ }
6037
+ }
6038
+ function numberEquals(a, b) {
6039
+ return a === b || !Number.isFinite(a) && !Number.isFinite(b);
6040
+ }
6041
+ function coordinatesEqual(a, b) {
6042
+ if (typeof a === "number" || typeof b === "number") {
6043
+ return typeof a === "number" && typeof b === "number" && numberEquals(a, b);
6044
+ }
6045
+ if (a.length !== b.length) return false;
6046
+ for (let i = 0; i < a.length; i++) {
6047
+ if (!coordinatesEqual(a[i], b[i])) return false;
6048
+ }
6049
+ return true;
6050
+ }
6051
+ function bboxEqual(a, b) {
6052
+ if (a === void 0 || b === void 0) return a === b;
6053
+ if (a.length !== b.length) return false;
6054
+ for (let i = 0; i < a.length; i++) {
6055
+ if (!numberEquals(a[i], b[i])) return false;
6056
+ }
6057
+ return true;
6058
+ }
6059
+ function geometryEquals(a, b) {
6060
+ if (a == null || b == null) return a === b;
6061
+ if (a.type !== b.type) return false;
6062
+ if (!bboxEqual(a.bbox, b.bbox)) return false;
6063
+ if (a.type === "GeometryCollection") {
6064
+ const bGeometries = b.geometries;
6065
+ if (a.geometries.length !== bGeometries.length) return false;
6066
+ for (let i = 0; i < a.geometries.length; i++) {
6067
+ if (!geometryEquals(a.geometries[i], bGeometries[i])) return false;
6068
+ }
6069
+ return true;
6070
+ }
6071
+ return coordinatesEqual(
6072
+ a.coordinates,
6073
+ b.coordinates
6074
+ );
6075
+ }
6076
+ function prepareFeaturesForLayer(input, caller) {
6077
+ const logging = mapPerfLogEnabled();
6078
+ const started = logging ? performance.now() : 0;
6079
+ const count = input.length;
6080
+ const features = new Array(count);
6081
+ const featureIds = new Array(count);
6082
+ let hasTemporal = false;
6083
+ let temporalCount = 0;
6084
+ let reused = 0;
6085
+ for (let i = 0; i < count; i++) {
6086
+ const f = input[i];
6087
+ const props = f.properties || {};
6088
+ if (!hasAnyTemporalValue(props)) {
6089
+ if (typeof f.id === "string" && f.id) {
6090
+ features[i] = f;
6091
+ featureIds[i] = f.id;
6092
+ reused++;
6093
+ } else {
6094
+ const id2 = f.id ? String(f.id) : crypto.randomUUID();
6095
+ features[i] = { ...f, id: id2 };
6096
+ featureIds[i] = id2;
6097
+ }
6098
+ continue;
6099
+ }
6100
+ const id = f.id ? String(f.id) : crypto.randomUUID();
6101
+ featureIds[i] = id;
6102
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6103
+ if (startDate || endDate) hasTemporal = true;
6104
+ temporalCount++;
6105
+ features[i] = {
6106
+ ...f,
6107
+ id,
6108
+ properties: {
6109
+ ...props,
6110
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
6111
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
6112
+ }
6113
+ };
6114
+ }
6115
+ if (logging) {
6116
+ mapPerfLog("normalize", `${caller ?? "prepareFeaturesForLayer"} normalized ${count} features`, {
6117
+ ms: Math.round((performance.now() - started) * 10) / 10,
6118
+ withTemporalKeys: temporalCount,
6119
+ hasTemporal,
6120
+ reused,
6121
+ copied: count - reused
6122
+ });
6123
+ }
6124
+ return { features, featureIds, hasTemporal };
6125
+ }
6126
+ function scanTemporalFeatures(features, resolveLayerId, out) {
6127
+ let foundTemporal = false;
6128
+ for (let i = 0; i < features.length; i++) {
6129
+ const feature = features[i];
6130
+ const id = feature.id;
6131
+ const props = feature.properties || {};
6132
+ if (!hasAnyTemporalValue(props)) {
6133
+ out.untimedIds.push(id);
6134
+ continue;
6135
+ }
6136
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6137
+ if (startDate || endDate) {
6138
+ out.temporal.push({ id, startDate, endDate, layerId: resolveLayerId(id) });
6139
+ foundTemporal = true;
6140
+ } else {
6141
+ out.untimedIds.push(id);
6142
+ }
6143
+ }
6144
+ return foundTemporal;
6145
+ }
6146
+ function shouldDiffDrawRender({ mode, pointerDown, hasSelection }) {
6147
+ if (mode === "view_select") return false;
6148
+ if (mode === "simple_select" || mode === "direct_select") return pointerDown && hasSelection;
6149
+ return true;
6150
+ }
6151
+ function extendBounds(bounds, coords) {
6152
+ if (!Array.isArray(coords) || coords.length === 0) return;
6153
+ if (typeof coords[0] === "number") {
6154
+ const lng = coords[0];
6155
+ const lat = coords[1];
6156
+ if (lng < bounds.minLng) bounds.minLng = lng;
6157
+ if (lng > bounds.maxLng) bounds.maxLng = lng;
6158
+ if (lat < bounds.minLat) bounds.minLat = lat;
6159
+ if (lat > bounds.maxLat) bounds.maxLat = lat;
6160
+ return;
6161
+ }
6162
+ for (const nested of coords) extendBounds(bounds, nested);
6163
+ }
6164
+ function computeBounds(coords) {
6165
+ const bounds = { minLng: Infinity, minLat: Infinity, maxLng: -Infinity, maxLat: -Infinity };
6166
+ extendBounds(bounds, coords);
6167
+ return bounds;
6168
+ }
6169
+ function boundsDisjoint(a, b) {
6170
+ return a.maxLng < b.minLng || a.minLng > b.maxLng || a.maxLat < b.minLat || a.minLat > b.maxLat;
6171
+ }
6172
+ function pointInBounds(lng, lat, b) {
6173
+ return lng >= b.minLng && lng <= b.maxLng && lat >= b.minLat && lat <= b.maxLat;
6174
+ }
6175
+ function buildGroupSpatialIndex(features) {
6176
+ var _a;
6177
+ const boxes = [];
6178
+ const positions = [];
6179
+ for (let p = 0; p < features.length; p++) {
6180
+ const geom = (_a = features[p]) == null ? void 0 : _a.geometry;
6181
+ const b = computeBounds(geom == null ? void 0 : geom.coordinates);
6182
+ if (!isFinite(b.minLng) || !isFinite(b.minLat) || !isFinite(b.maxLng) || !isFinite(b.maxLat)) {
6183
+ continue;
6184
+ }
6185
+ boxes.push(b.minLng, b.minLat, b.maxLng, b.maxLat);
6186
+ positions.push(p);
6187
+ }
6188
+ if (positions.length === 0) {
6189
+ return { tree: null, positions, size: features.length };
6190
+ }
6191
+ const startedAt = performance.now();
6192
+ const tree = new Flatbush(positions.length);
6193
+ for (let i = 0; i < boxes.length; i += 4) {
6194
+ tree.add(boxes[i], boxes[i + 1], boxes[i + 2], boxes[i + 3]);
6195
+ }
6196
+ tree.finish();
6197
+ mapPerfLog("spatial-index", "built group index", {
6198
+ indexed: positions.length,
6199
+ of: features.length,
6200
+ ms: Math.round(performance.now() - startedAt)
6201
+ });
6202
+ return { tree, positions, size: features.length };
6203
+ }
6204
+ const indexCache = /* @__PURE__ */ new WeakMap();
6205
+ const failedBuilds = /* @__PURE__ */ new WeakSet();
6206
+ function getGroupSpatialIndex(features) {
6207
+ if (failedBuilds.has(features)) return void 0;
6208
+ let index = indexCache.get(features);
6209
+ if (!index) {
6210
+ try {
6211
+ index = buildGroupSpatialIndex(features);
6212
+ } catch {
6213
+ failedBuilds.add(features);
6214
+ return void 0;
6215
+ }
6216
+ indexCache.set(features, index);
6217
+ }
6218
+ return index;
6219
+ }
6220
+ function queryCandidatePositions(index, bounds) {
6221
+ if (!index.tree) return [];
6222
+ const items = index.tree.search(bounds.minLng, bounds.minLat, bounds.maxLng, bounds.maxLat);
6223
+ const positions = items.map((i) => index.positions[i]);
6224
+ positions.sort((a, b) => a - b);
6225
+ return positions;
6226
+ }
6227
+ function collectVisibleFeatureGroups(drawFeatures, readOnlyByLayer, layers) {
6228
+ const groups = [];
6229
+ if (drawFeatures) groups.push({ features: drawFeatures });
6230
+ const layerById = new Map(layers.map((l) => [l.id, l]));
6231
+ readOnlyByLayer.forEach((features, layerId) => {
6232
+ var _a;
6233
+ if ((_a = layerById.get(layerId)) == null ? void 0 : _a.visible) {
6234
+ groups.push({ features, index: getGroupSpatialIndex(features) });
6235
+ }
6236
+ });
6237
+ return groups;
6238
+ }
6239
+ function featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) {
6240
+ const geom = feature.geometry;
6241
+ if ((geom == null ? void 0 : geom.type) === "Point") {
6242
+ const lng = geom.coordinates[0];
6243
+ const lat = geom.coordinates[1];
6244
+ return typeof lng === "number" && typeof lat === "number" && pointInBounds(lng, lat, selectionBounds) && (rectExactForPoints || turf__namespace.booleanPointInPolygon(geom.coordinates, selectionPolygon));
6245
+ }
6246
+ 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") {
6247
+ return !boundsDisjoint(computeBounds(geom.coordinates), selectionBounds) && turf__namespace.booleanIntersects(feature, selectionPolygon);
6248
+ }
6249
+ return false;
6250
+ }
6251
+ function hitTestSelection(featureGroups, selectionPolygon, options) {
6252
+ const selectionBounds = computeBounds(selectionPolygon.geometry.coordinates);
6253
+ const rectExactForPoints = (options == null ? void 0 : options.axisAlignedRectangle) === true;
6254
+ const selectedIds = [];
6255
+ let visited = 0;
6256
+ let total = 0;
6257
+ for (const group of featureGroups) {
6258
+ const { features, index } = group;
6259
+ total += features.length;
6260
+ const useIndex = index !== void 0 && index.size === features.length;
6261
+ const candidates = useIndex ? queryCandidatePositions(index, selectionBounds) : null;
6262
+ const count = candidates ? candidates.length : features.length;
6263
+ visited += count;
6264
+ for (let i = 0; i < count; i++) {
6265
+ const feature = candidates ? features[candidates[i]] : features[i];
6266
+ try {
6267
+ if (featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) && feature.id) {
6268
+ selectedIds.push(String(feature.id));
6269
+ }
6270
+ } catch {
6271
+ }
6272
+ }
6273
+ }
6274
+ mapPerfLog("hit-test", "selection gesture", { visited, total, selected: selectedIds.length });
6275
+ return selectedIds;
6276
+ }
6277
+ const OTHER_BUCKET_KEY = "__other__";
6278
+ const OTHER_BUCKET_LABEL = "Other";
6279
+ const OTHER_BUCKET_COLOR = "#9ca3af";
6280
+ function toDisplayName(name) {
6281
+ return name === OTHER_BUCKET_KEY ? OTHER_BUCKET_LABEL : name;
6282
+ }
6283
+ function createPieSVG(categories, total, size = 44, onSliceHover) {
6284
+ const container = document.createElement("div");
6285
+ container.style.width = `${size}px`;
6286
+ container.style.height = `${size}px`;
6287
+ container.style.cursor = "pointer";
6288
+ const radius = size / 2;
6289
+ const innerRadius = radius * 0.5;
6290
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
6291
+ svg.setAttribute("width", String(size));
6292
+ svg.setAttribute("height", String(size));
6293
+ svg.setAttribute("viewBox", `0 0 ${size} ${size}`);
5427
6294
  svg.style.display = "block";
5428
6295
  const bgCircle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
5429
6296
  bgCircle.setAttribute("cx", String(radius));
@@ -5713,92 +6580,6 @@ function ClusterPieManager(props) {
5713
6580
  }, [visible, updateMarkers]);
5714
6581
  return null;
5715
6582
  }
5716
- 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");
5717
- 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");
5718
- proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
5719
- proj4.defs("EPSG:32631", "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs");
5720
- function detectAndReprojectGeoJSON(geojson) {
5721
- var _a;
5722
- const crsProperty = geojson.crs;
5723
- let sourceCRS = null;
5724
- if ((_a = crsProperty == null ? void 0 : crsProperty.properties) == null ? void 0 : _a.name) {
5725
- const crsName = crsProperty.properties.name;
5726
- const epsgMatch = crsName.match(/EPSG::?(\d+)/i);
5727
- if (epsgMatch) {
5728
- sourceCRS = `EPSG:${epsgMatch[1]}`;
5729
- }
5730
- }
5731
- if (!sourceCRS && geojson.features.length > 0) {
5732
- const firstCoord = getFirstCoordinate(geojson.features[0].geometry);
5733
- if (firstCoord) {
5734
- const [x, y] = firstCoord;
5735
- const looksLikeWGS84 = Math.abs(x) <= 180 && Math.abs(y) <= 90;
5736
- if (looksLikeWGS84) {
5737
- return { features: geojson, reprojected: false, sourceCRS: "EPSG:4326" };
5738
- }
5739
- }
5740
- }
5741
- if (sourceCRS === "EPSG:4326") {
5742
- return { features: geojson, reprojected: false, sourceCRS };
5743
- }
5744
- if (sourceCRS && proj4.defs(sourceCRS)) {
5745
- try {
5746
- const reprojectedFeatures = geojson.features.map((feature) => ({
5747
- ...feature,
5748
- geometry: reprojectGeometry(feature.geometry, sourceCRS)
5749
- }));
5750
- return {
5751
- features: { ...geojson, type: "FeatureCollection", features: reprojectedFeatures },
5752
- reprojected: true,
5753
- sourceCRS
5754
- };
5755
- } catch (e) {
5756
- console.error("Reprojection failed:", e);
5757
- }
5758
- }
5759
- return { features: geojson, reprojected: false, sourceCRS };
5760
- }
5761
- function getFirstCoordinate(geometry) {
5762
- var _a, _b, _c;
5763
- if (!geometry) return null;
5764
- switch (geometry.type) {
5765
- case "Point":
5766
- return geometry.coordinates;
5767
- case "MultiPoint":
5768
- case "LineString":
5769
- return geometry.coordinates[0];
5770
- case "MultiLineString":
5771
- case "Polygon":
5772
- return (_a = geometry.coordinates[0]) == null ? void 0 : _a[0];
5773
- case "MultiPolygon":
5774
- return (_c = (_b = geometry.coordinates[0]) == null ? void 0 : _b[0]) == null ? void 0 : _c[0];
5775
- default:
5776
- return null;
5777
- }
5778
- }
5779
- function reprojectGeometry(geometry, fromCRS) {
5780
- const transform = (coord) => {
5781
- const [x, y] = proj4(fromCRS, "EPSG:4326", [coord[0], coord[1]]);
5782
- return coord.length > 2 ? [x, y, ...coord.slice(2)] : [x, y];
5783
- };
5784
- const reprojectCoords = (coords) => {
5785
- if (typeof coords[0] === "number") {
5786
- return transform(coords);
5787
- }
5788
- return coords.map(reprojectCoords);
5789
- };
5790
- if (geometry.type === "GeometryCollection") {
5791
- return {
5792
- type: "GeometryCollection",
5793
- geometries: geometry.geometries.map((g) => reprojectGeometry(g, fromCRS))
5794
- };
5795
- }
5796
- const geomWithCoords = geometry;
5797
- return {
5798
- ...geomWithCoords,
5799
- coordinates: reprojectCoords(geomWithCoords.coordinates)
5800
- };
5801
- }
5802
6583
  const EMOJI_CANVAS_SIZE = 48;
5803
6584
  function renderEmojiToCanvas(emoji, size = EMOJI_CANVAS_SIZE) {
5804
6585
  const ratio = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
@@ -5938,17 +6719,6 @@ function createFlightPath3DLayer(layerId, mapInstance, flightPaths) {
5938
6719
  }
5939
6720
  };
5940
6721
  }
5941
- function hasAltitudeData(feature) {
5942
- if (feature.geometry.type === "LineString") {
5943
- const coords = feature.geometry.coordinates;
5944
- return coords.some((c) => c.length >= 3 && c[2] !== 0);
5945
- }
5946
- if (feature.geometry.type === "MultiLineString") {
5947
- const coords = feature.geometry.coordinates;
5948
- return coords.some((line) => line.some((c) => c.length >= 3 && c[2] !== 0));
5949
- }
5950
- return false;
5951
- }
5952
6722
  function extract3DFlightPaths(features) {
5953
6723
  const paths = [];
5954
6724
  features.forEach((feature) => {
@@ -6214,7 +6984,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6214
6984
  const [visibleFeatureCount, setVisibleFeatureCount] = react.useState(Infinity);
6215
6985
  const lastLabelVisibility = react.useRef(false);
6216
6986
  const [labelsSuppressed, setLabelsSuppressed] = react.useState(true);
6217
- const [cursorCoords, setCursorCoords] = react.useState(null);
6218
6987
  const [contextMenu, setContextMenu] = react.useState(null);
6219
6988
  const [timelineStoreApi] = react.useState(createTimelineStore);
6220
6989
  const timelineStore = zustand.useStore(timelineStoreApi);
@@ -6390,14 +7159,22 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6390
7159
  return false;
6391
7160
  }
6392
7161
  });
6393
- draw.current.changeMode(mode, { featureIds: visibleEditableIds });
7162
+ const needsDrawCall = needsDrawSelectionUpdate({
7163
+ editableSelectionCount: visibleEditableIds.length,
7164
+ drawSelectedCount: draw.current.getSelectedIds().length,
7165
+ currentMode: draw.current.getMode(),
7166
+ targetMode: mode
7167
+ });
7168
+ if (needsDrawCall) {
7169
+ draw.current.changeMode(mode, { featureIds: visibleEditableIds });
7170
+ }
6394
7171
  setSelectedFeatureIds(nextIds);
6395
7172
  selectedFeatureIdsRef.current = nextIds;
6396
7173
  if (options == null ? void 0 : options.focusProperties) setShowProperties(nextIds.length > 0);
6397
7174
  if (onFeatureSelect) {
6398
7175
  onFeatureSelect(nextIds.map((id) => getFeatureById(id)).filter(Boolean));
6399
7176
  }
6400
- syncRef.current();
7177
+ scheduleSync("selection");
6401
7178
  if (readOnlyIds.length > 0) {
6402
7179
  queueMicrotask(() => {
6403
7180
  isSelectingReadOnlyRef.current = false;
@@ -6420,9 +7197,39 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6420
7197
  setFeatureCount(drawFeatureCount + hiddenCount + readOnlyCount);
6421
7198
  }, []);
6422
7199
  const timelineVisibleIdsRef = react.useRef(null);
6423
- const timelineSyncRafRef = react.useRef(null);
6424
7200
  const syncRef = react.useRef(() => {
6425
7201
  });
7202
+ const trySelectionFastPathRef = react.useRef(null);
7203
+ const tryTimelineFastPathRef = react.useRef(null);
7204
+ const syncCoalescerRef = react.useRef(null);
7205
+ if (syncCoalescerRef.current === null) {
7206
+ syncCoalescerRef.current = createRafCoalescer((reasons) => {
7207
+ var _a, _b;
7208
+ if (!reasons.has("full")) {
7209
+ let handled = true;
7210
+ if (reasons.has("timeline")) handled = ((_a = tryTimelineFastPathRef.current) == null ? void 0 : _a.call(tryTimelineFastPathRef)) ?? false;
7211
+ if (handled && reasons.has("selection")) handled = ((_b = trySelectionFastPathRef.current) == null ? void 0 : _b.call(trySelectionFastPathRef)) ?? false;
7212
+ if (handled) {
7213
+ mapPerfLog("sync", "frame handled by fast path(s)", reasons);
7214
+ return;
7215
+ }
7216
+ mapPerfLog("sync", "fast path bailed — full rebuild", reasons);
7217
+ }
7218
+ syncRef.current();
7219
+ });
7220
+ }
7221
+ const fullSyncCallersRef = react.useRef([]);
7222
+ const scheduleSync = react.useCallback((reason = "full") => {
7223
+ var _a, _b;
7224
+ if (reason === "full" && mapPerfLogEnabled() && fullSyncCallersRef.current.length < 4) {
7225
+ const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n").slice(2, 5).map((line) => line.trim()).join(" ← ");
7226
+ if (stack) fullSyncCallersRef.current.push(stack);
7227
+ }
7228
+ (_b = syncCoalescerRef.current) == null ? void 0 : _b.schedule(reason);
7229
+ }, []);
7230
+ react.useEffect(() => {
7231
+ scheduleSync();
7232
+ }, [layers, scheduleSync]);
6426
7233
  const hashStringToColor$1 = react.useCallback((str) => hashStringToColor(str), []);
6427
7234
  const selectedFeatureColors = react.useMemo(() => {
6428
7235
  if (selectedFeatureIds.length === 0) return /* @__PURE__ */ new Map();
@@ -6508,17 +7315,116 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6508
7315
  );
6509
7316
  }, []);
6510
7317
  const isSyncingRef = react.useRef(false);
7318
+ const selectionPaintCacheRef = react.useRef(null);
7319
+ const paintedArrowLinesRef = react.useRef([]);
7320
+ const renderArrowOverlays = react.useCallback((arrowLines) => {
7321
+ const mapInstance = map.current;
7322
+ if (!mapInstance) return;
7323
+ const arrowHeadSource = mapInstance.getSource("arrow-heads");
7324
+ if (arrowHeadSource) {
7325
+ const arrowHeadTriangles = [];
7326
+ const headLength = 16;
7327
+ const headWidth = 10;
7328
+ arrowLines.forEach((f) => {
7329
+ const coords = f.geometry.coordinates;
7330
+ if (coords.length < 2) return;
7331
+ const end = coords[coords.length - 1];
7332
+ const prev = coords[coords.length - 2];
7333
+ const endScreen = mapInstance.project(end);
7334
+ const prevScreen = mapInstance.project(prev);
7335
+ const dx = endScreen.x - prevScreen.x;
7336
+ const dy = endScreen.y - prevScreen.y;
7337
+ const len = Math.sqrt(dx * dx + dy * dy);
7338
+ if (len < 1e-3) return;
7339
+ const dirX = dx / len;
7340
+ const dirY = dy / len;
7341
+ const perpX = -dirY;
7342
+ const perpY = dirX;
7343
+ const tipScreen = { x: endScreen.x, y: endScreen.y };
7344
+ const baseLeftScreen = {
7345
+ x: endScreen.x - dirX * headLength - perpX * headWidth,
7346
+ y: endScreen.y - dirY * headLength - perpY * headWidth
7347
+ };
7348
+ const baseRightScreen = {
7349
+ x: endScreen.x - dirX * headLength + perpX * headWidth,
7350
+ y: endScreen.y - dirY * headLength + perpY * headWidth
7351
+ };
7352
+ const tipGeo = mapInstance.unproject([tipScreen.x, tipScreen.y]);
7353
+ const baseLeftGeo = mapInstance.unproject([baseLeftScreen.x, baseLeftScreen.y]);
7354
+ const baseRightGeo = mapInstance.unproject([baseRightScreen.x, baseRightScreen.y]);
7355
+ arrowHeadTriangles.push({
7356
+ type: "Feature",
7357
+ geometry: {
7358
+ type: "Polygon",
7359
+ coordinates: [[
7360
+ [tipGeo.lng, tipGeo.lat],
7361
+ [baseLeftGeo.lng, baseLeftGeo.lat],
7362
+ [baseRightGeo.lng, baseRightGeo.lat],
7363
+ [tipGeo.lng, tipGeo.lat]
7364
+ // Close the polygon
7365
+ ]]
7366
+ },
7367
+ properties: {
7368
+ ...f.properties
7369
+ }
7370
+ });
7371
+ });
7372
+ arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
7373
+ }
7374
+ const arrowLabelSource = mapInstance.getSource("arrow-labels");
7375
+ if (arrowLabelSource) {
7376
+ const arrowLabelPoints = [];
7377
+ arrowLines.forEach((f) => {
7378
+ var _a;
7379
+ const name = (_a = f.properties) == null ? void 0 : _a.name;
7380
+ if (!name) return;
7381
+ const coords = f.geometry.coordinates;
7382
+ if (coords.length < 2) return;
7383
+ const start = coords[0];
7384
+ const end = coords[coords.length - 1];
7385
+ const midPoint = [
7386
+ (start[0] + end[0]) / 2,
7387
+ (start[1] + end[1]) / 2
7388
+ ];
7389
+ const dLng = end[0] - start[0];
7390
+ const dLat = end[1] - start[1];
7391
+ const angleFromEast = Math.atan2(dLat, dLng) * (180 / Math.PI);
7392
+ let labelBearing = -angleFromEast;
7393
+ labelBearing = (labelBearing % 360 + 540) % 360 - 180;
7394
+ if (labelBearing > 90) {
7395
+ labelBearing -= 180;
7396
+ } else if (labelBearing < -90) {
7397
+ labelBearing += 180;
7398
+ }
7399
+ arrowLabelPoints.push({
7400
+ type: "Feature",
7401
+ geometry: {
7402
+ type: "Point",
7403
+ coordinates: midPoint
7404
+ },
7405
+ properties: {
7406
+ ...f.properties,
7407
+ labelBearing
7408
+ }
7409
+ });
7410
+ });
7411
+ arrowLabelSource.setData({ type: "FeatureCollection", features: arrowLabelPoints });
7412
+ }
7413
+ }, []);
6511
7414
  const syncFeaturesToCustomLayers = react.useCallback(() => {
6512
7415
  if (!map.current) return;
6513
7416
  if (isSyncingRef.current) return;
6514
7417
  isSyncingRef.current = true;
7418
+ const fullSyncStart = performance.now();
6515
7419
  try {
6516
7420
  const source = map.current.getSource("custom-features");
6517
7421
  if (!source) return;
6518
7422
  const drawFeatures = draw.current ? draw.current.getAll() : { type: "FeatureCollection", features: [] };
6519
7423
  const drawSelectedIds = draw.current ? draw.current.getSelectedIds() : [];
6520
7424
  const componentSelectedIds = selectedFeatureIdsRef.current;
6521
- const selectedIds = Array.from(/* @__PURE__ */ new Set([...drawSelectedIds, ...componentSelectedIds]));
7425
+ const selectedIdSet = /* @__PURE__ */ new Set();
7426
+ drawSelectedIds.forEach((id) => selectedIdSet.add(String(id)));
7427
+ componentSelectedIds.forEach((id) => selectedIdSet.add(String(id)));
6522
7428
  const visibleSet = timelineVisibleIdsRef.current;
6523
7429
  const currentLayers = layersRef.current;
6524
7430
  const isLayerVisible = (layer) => {
@@ -6623,6 +7529,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6623
7529
  }
6624
7530
  });
6625
7531
  });
7532
+ const paintCache = createSelectionPaintCache();
6626
7533
  const sourceData = {
6627
7534
  type: "FeatureCollection",
6628
7535
  features: allFeatures.map((f) => {
@@ -6631,7 +7538,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6631
7538
  const layer = featureToLayer.get(featureId);
6632
7539
  const visualConfig = layer == null ? void 0 : layer.visualConfig;
6633
7540
  const isTimelineVisible = visibleSet === null || visibleSet.has(featureId);
6634
- const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? 1;
7541
+ const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? DEFAULT_VISIBLE_STROKE_OPACITY;
6635
7542
  let strokeColor = ((_b = f.properties) == null ? void 0 : _b.stroke) || "#3b82f6";
6636
7543
  const colorConfig = visualConfig == null ? void 0 : visualConfig.color;
6637
7544
  if (colorConfig) {
@@ -6700,7 +7607,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6700
7607
  const isPoint = f.geometry.type === "Point";
6701
7608
  const hideByHeatmap = isPoint && ((_i = layer == null ? void 0 : layer.heatmapConfig) == null ? void 0 : _i.enabled) === true;
6702
7609
  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);
6703
- const isSelected = selectedIds.includes(featureId);
6704
7610
  const hideByTrace = false;
6705
7611
  const isLine = f.geometry.type === "LineString" || f.geometry.type === "MultiLineString";
6706
7612
  const hideFlatFor3DOnly = isLine && (layer == null ? void 0 : layer.hasAltitudeData) && (layer == null ? void 0 : layer.altitudeDisplayMode) === "3d";
@@ -6718,14 +7624,12 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6718
7624
  }
6719
7625
  });
6720
7626
  }
6721
- const isFeatureSelected = (enableSelectionRef.current || enableDrawingRef.current) && selectedIds.includes(featureId) ? 1 : 0;
6722
- let labelPriority = 100;
6723
- if (isFeatureSelected) {
6724
- labelPriority = 0;
6725
- } else if (traceLabel) {
6726
- labelPriority = 5;
7627
+ const isFeatureSelected = (enableSelectionRef.current || enableDrawingRef.current) && selectedIdSet.has(featureId) ? 1 : 0;
7628
+ let basePriority = DEFAULT_LABEL_PRIORITY;
7629
+ if (traceLabel) {
7630
+ basePriority = 5;
6727
7631
  } else if (((_l = f.properties) == null ? void 0 : _l.kind) === "text") {
6728
- labelPriority = ((_m = f.properties) == null ? void 0 : _m.fontWeight) === "bold" ? 8 : 10;
7632
+ basePriority = ((_m = f.properties) == null ? void 0 : _m.fontWeight) === "bold" ? 8 : 10;
6729
7633
  } else {
6730
7634
  const idStr = String(featureId);
6731
7635
  let h = 0;
@@ -6733,8 +7637,20 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6733
7637
  h = (h << 5) - h + idStr.charCodeAt(i);
6734
7638
  h |= 0;
6735
7639
  }
6736
- labelPriority = 100 + Math.abs(h) % 1e3;
6737
- }
7640
+ basePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
7641
+ }
7642
+ const labelPriority = isFeatureSelected ? 0 : basePriority;
7643
+ const visibleStrokeOpacity = hideFlatFor3DOnly ? 0 : baseOpacity;
7644
+ const visibleFillOpacity = hideFlatFor3DOnly ? 0 : ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? DEFAULT_VISIBLE_FILL_OPACITY;
7645
+ recordPaintedFeature(
7646
+ paintCache,
7647
+ featureId,
7648
+ basePriority,
7649
+ isFeatureSelected === 1,
7650
+ visibleStrokeOpacity,
7651
+ visibleFillOpacity,
7652
+ !isTimelineVisible
7653
+ );
6738
7654
  return {
6739
7655
  type: "Feature",
6740
7656
  id: featureId,
@@ -6755,9 +7671,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6755
7671
  iconSize: featureIconSize,
6756
7672
  stroke: strokeColor,
6757
7673
  "stroke-width": strokeWidth,
6758
- "stroke-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? baseOpacity : 0,
7674
+ "stroke-opacity": isTimelineVisible ? visibleStrokeOpacity : 0,
6759
7675
  fill: strokeColor,
6760
- "fill-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? 0.2 : 0,
7676
+ "fill-opacity": isTimelineVisible ? visibleFillOpacity : 0,
6761
7677
  pointRadius,
6762
7678
  isHiddenFor3DOnly: hideFlatFor3DOnly ? 1 : 0,
6763
7679
  isTimelineHidden: isTimelineVisible ? 0 : 1,
@@ -6767,6 +7683,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6767
7683
  })
6768
7684
  };
6769
7685
  source.setData(sourceData);
7686
+ selectionPaintCacheRef.current = paintCache;
6770
7687
  const traceSource = map.current.getSource("trace-features");
6771
7688
  if (traceSource) {
6772
7689
  const traceSegments = [];
@@ -6855,104 +7772,19 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6855
7772
  });
6856
7773
  traceSource.setData({ type: "FeatureCollection", features: traceSegments });
6857
7774
  }
6858
- const arrowHeadSource = map.current.getSource("arrow-heads");
6859
- if (arrowHeadSource && map.current) {
6860
- const arrowHeadTriangles = [];
6861
- const mapInstance = map.current;
7775
+ {
6862
7776
  let sawArrowFeature = false;
6863
- const headLength = 16;
6864
- const headWidth = 10;
7777
+ const arrowLines = [];
6865
7778
  sourceData.features.forEach((f) => {
6866
7779
  var _a;
6867
7780
  const isArrow = ((_a = f.properties) == null ? void 0 : _a.kind) === "arrow" || arrowFeatureIdsRef.current.has(String(f.id));
6868
- if (isArrow) sawArrowFeature = true;
6869
- if (f.geometry.type !== "LineString" || !isArrow) return;
6870
- const coords = f.geometry.coordinates;
6871
- if (coords.length < 2) return;
6872
- const end = coords[coords.length - 1];
6873
- const prev = coords[coords.length - 2];
6874
- const endScreen = mapInstance.project(end);
6875
- const prevScreen = mapInstance.project(prev);
6876
- const dx = endScreen.x - prevScreen.x;
6877
- const dy = endScreen.y - prevScreen.y;
6878
- const len = Math.sqrt(dx * dx + dy * dy);
6879
- if (len < 1e-3) return;
6880
- const dirX = dx / len;
6881
- const dirY = dy / len;
6882
- const perpX = -dirY;
6883
- const perpY = dirX;
6884
- const tipScreen = { x: endScreen.x, y: endScreen.y };
6885
- const baseLeftScreen = {
6886
- x: endScreen.x - dirX * headLength - perpX * headWidth,
6887
- y: endScreen.y - dirY * headLength - perpY * headWidth
6888
- };
6889
- const baseRightScreen = {
6890
- x: endScreen.x - dirX * headLength + perpX * headWidth,
6891
- y: endScreen.y - dirY * headLength + perpY * headWidth
6892
- };
6893
- const tipGeo = mapInstance.unproject([tipScreen.x, tipScreen.y]);
6894
- const baseLeftGeo = mapInstance.unproject([baseLeftScreen.x, baseLeftScreen.y]);
6895
- const baseRightGeo = mapInstance.unproject([baseRightScreen.x, baseRightScreen.y]);
6896
- arrowHeadTriangles.push({
6897
- type: "Feature",
6898
- geometry: {
6899
- type: "Polygon",
6900
- coordinates: [[
6901
- [tipGeo.lng, tipGeo.lat],
6902
- [baseLeftGeo.lng, baseLeftGeo.lat],
6903
- [baseRightGeo.lng, baseRightGeo.lat],
6904
- [tipGeo.lng, tipGeo.lat]
6905
- // Close the polygon
6906
- ]]
6907
- },
6908
- properties: {
6909
- ...f.properties
6910
- }
6911
- });
7781
+ if (!isArrow) return;
7782
+ sawArrowFeature = true;
7783
+ if (f.geometry.type === "LineString") arrowLines.push(f);
6912
7784
  });
6913
- arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
6914
7785
  hasArrowFeaturesRef.current = sawArrowFeature;
6915
- }
6916
- const arrowLabelSource = map.current.getSource("arrow-labels");
6917
- if (arrowLabelSource) {
6918
- const arrowLabelPoints = [];
6919
- sourceData.features.forEach((f) => {
6920
- var _a, _b;
6921
- const isArrow = ((_a = f.properties) == null ? void 0 : _a.kind) === "arrow" || arrowFeatureIdsRef.current.has(String(f.id));
6922
- if (f.geometry.type !== "LineString" || !isArrow) return;
6923
- const name = (_b = f.properties) == null ? void 0 : _b.name;
6924
- if (!name) return;
6925
- const coords = f.geometry.coordinates;
6926
- if (coords.length < 2) return;
6927
- const start = coords[0];
6928
- const end = coords[coords.length - 1];
6929
- const midPoint = [
6930
- (start[0] + end[0]) / 2,
6931
- (start[1] + end[1]) / 2
6932
- ];
6933
- const dLng = end[0] - start[0];
6934
- const dLat = end[1] - start[1];
6935
- const angleFromEast = Math.atan2(dLat, dLng) * (180 / Math.PI);
6936
- let labelBearing = -angleFromEast;
6937
- labelBearing = (labelBearing % 360 + 540) % 360 - 180;
6938
- if (labelBearing > 90) {
6939
- labelBearing -= 180;
6940
- } else if (labelBearing < -90) {
6941
- labelBearing += 180;
6942
- }
6943
- arrowLabelPoints.push({
6944
- type: "Feature",
6945
- geometry: {
6946
- type: "Point",
6947
- coordinates: midPoint
6948
- },
6949
- properties: {
6950
- ...f.properties,
6951
- labelBearing
6952
- }
6953
- });
6954
- });
6955
- arrowLabelSource.setData({ type: "FeatureCollection", features: arrowLabelPoints });
7786
+ paintedArrowLinesRef.current = arrowLines;
7787
+ renderArrowOverlays(arrowLines);
6956
7788
  }
6957
7789
  if (update3DFlightPathsRef == null ? void 0 : update3DFlightPathsRef.current) {
6958
7790
  update3DFlightPathsRef.current();
@@ -6962,11 +7794,18 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6962
7794
  setVisibleFeatureCount(countVisibleFeatures(threshold));
6963
7795
  setLabelsSuppressed(false);
6964
7796
  }
7797
+ const requestedBy = fullSyncCallersRef.current.splice(0);
7798
+ mapPerfLog("sync", "full rebuild", {
7799
+ features: sourceData.features.length,
7800
+ ms: Math.round(performance.now() - fullSyncStart),
7801
+ requestedBy
7802
+ });
6965
7803
  } finally {
6966
7804
  isSyncingRef.current = false;
6967
7805
  }
6968
- }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures]);
7806
+ }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures, renderArrowOverlays]);
6969
7807
  const update3DFlightPaths = react.useCallback(() => {
7808
+ var _a;
6970
7809
  if (!map.current || !is3DTerrainEnabled) {
6971
7810
  if (map.current && flightPath3DLayerId.current) {
6972
7811
  try {
@@ -6987,20 +7826,21 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6987
7826
  const allFeatures = [];
6988
7827
  const currentLayers = layersRef.current;
6989
7828
  if (draw.current) {
6990
- const drawFeatures = draw.current.getAll().features.filter((feature) => {
6991
- var _a;
6992
- if (!isFeatureVisibleInTimeline(feature)) return false;
6993
- const featureId = feature.id;
6994
- const layer2 = currentLayers.find((l) => l.featureIds.includes(featureId));
6995
- return ((_a = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a.enabled) === true;
6996
- });
7829
+ const traceFeatureIds = /* @__PURE__ */ new Set();
7830
+ for (const l of currentLayers) {
7831
+ if (((_a = l.traceConfig) == null ? void 0 : _a.enabled) !== true) continue;
7832
+ for (const featureId of l.featureIds) traceFeatureIds.add(featureId);
7833
+ }
7834
+ const drawFeatures = draw.current.getAll().features.filter(
7835
+ (feature) => isFeatureVisibleInTimeline(feature) && traceFeatureIds.has(feature.id)
7836
+ );
6997
7837
  pushAll(allFeatures, drawFeatures);
6998
7838
  }
6999
7839
  readOnlyFeatures.current.forEach((features, layerId2) => {
7000
- var _a;
7840
+ var _a2;
7001
7841
  const layer2 = currentLayers.find((l) => l.id === layerId2);
7002
7842
  const altitudeMode = (layer2 == null ? void 0 : layer2.altitudeDisplayMode) ?? "both";
7003
- const traceEnabled = ((_a = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a.enabled) === true;
7843
+ const traceEnabled = ((_a2 = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a2.enabled) === true;
7004
7844
  if ((layer2 == null ? void 0 : layer2.visible) && traceEnabled && (altitudeMode === "3d" || altitudeMode === "both")) {
7005
7845
  const visibleFeatures = features.filter(isFeatureVisibleInTimeline);
7006
7846
  pushAll(allFeatures, visibleFeatures);
@@ -7055,52 +7895,24 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7055
7895
  featureToLayer.set(fid, layer.id);
7056
7896
  }
7057
7897
  }
7058
- const temporalFeatures = [];
7059
- const untimedIds = [];
7060
- for (const feature of drawFeatures) {
7061
- const props = feature.properties || {};
7062
- if (!hasAnyTemporalValue(props)) {
7063
- untimedIds.push(feature.id);
7064
- continue;
7065
- }
7066
- const { startDate, endDate } = normalizeTemporalProperties(props);
7067
- if (startDate || endDate) {
7068
- temporalFeatures.push({
7069
- id: feature.id,
7070
- startDate,
7071
- endDate,
7072
- layerId: featureToLayer.get(feature.id) || "default"
7073
- });
7074
- } else {
7075
- untimedIds.push(feature.id);
7076
- }
7077
- }
7898
+ const scan = { temporal: [], untimedIds: [] };
7899
+ scanTemporalFeatures(
7900
+ drawFeatures,
7901
+ (id) => featureToLayer.get(id) || "default",
7902
+ scan
7903
+ );
7078
7904
  readOnlyFeatures.current.forEach((features, layerId) => {
7079
7905
  const layer = currentLayers.find((l) => l.id === layerId);
7080
7906
  if (!(layer == null ? void 0 : layer.visible)) return;
7081
7907
  const cached = layerTemporalCacheRef.current.get(layerId);
7082
7908
  if (cached && cached.featureCount === features.length && !cached.hasTemporal) {
7083
- for (const f of features) untimedIds.push(f.id);
7909
+ for (const f of features) scan.untimedIds.push(f.id);
7084
7910
  return;
7085
7911
  }
7086
- let layerHasTemporal = false;
7087
- for (const feature of features) {
7088
- const props = feature.properties || {};
7089
- if (!hasAnyTemporalValue(props)) {
7090
- untimedIds.push(feature.id);
7091
- continue;
7092
- }
7093
- const { startDate, endDate } = normalizeTemporalProperties(props);
7094
- if (startDate || endDate) {
7095
- temporalFeatures.push({ id: feature.id, startDate, endDate, layerId });
7096
- layerHasTemporal = true;
7097
- } else {
7098
- untimedIds.push(feature.id);
7099
- }
7100
- }
7912
+ const layerHasTemporal = scanTemporalFeatures(features, () => layerId, scan);
7101
7913
  layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: layerHasTemporal });
7102
7914
  });
7103
- timelineStoreApi.getState().setTemporalFeatures(temporalFeatures, untimedIds);
7915
+ timelineStoreApi.getState().setTemporalFeatures(scan.temporal, scan.untimedIds);
7104
7916
  }, [timelineStoreApi]);
7105
7917
  const scheduleTimelineUpdate = react.useCallback(() => {
7106
7918
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
@@ -7285,13 +8097,13 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7285
8097
  layerTemporalCacheRef.current.clear();
7286
8098
  updateFeatureCount();
7287
8099
  scheduleTimelineUpdate();
7288
- syncFeaturesToCustomLayers();
8100
+ scheduleSync();
7289
8101
  setFeatureUpdateCounter((c) => c + 1);
7290
8102
  queueMicrotask(() => {
7291
8103
  isSelectingReadOnlyRef.current = false;
7292
8104
  });
7293
8105
  },
7294
- [cleanupOrphanLayerSources, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers]
8106
+ [cleanupOrphanLayerSources, updateFeatureCount, scheduleTimelineUpdate, scheduleSync]
7295
8107
  );
7296
8108
  const buildDiffCommand = react.useCallback(
7297
8109
  (label, coalesceKey, before, after, beforeLayers, afterLayers, beforeSelectedIds, afterSelectedIds) => {
@@ -7376,6 +8188,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7376
8188
  }, [finalizeCapture]);
7377
8189
  react.useEffect(() => {
7378
8190
  if (!mapContainer.current || map.current) return;
8191
+ let removeDrawGateListeners;
7379
8192
  try {
7380
8193
  const baseStyle = createBaseStyle({
7381
8194
  glyphsUrl,
@@ -7434,12 +8247,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7434
8247
  ]
7435
8248
  });
7436
8249
  mapInstance.addControl(drawInstance);
7437
- mapInstance.on("mousemove", (e) => {
7438
- setCursorCoords({ lng: e.lngLat.lng, lat: e.lngLat.lat });
7439
- });
7440
- mapInstance.on("mouseout", () => {
7441
- setCursorCoords(null);
7442
- });
7443
8250
  requestAnimationFrame(() => {
7444
8251
  try {
7445
8252
  const container = mapInstance.getContainer();
@@ -8403,7 +9210,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8403
9210
  saveStateForUndo("draw feature", {
8404
9211
  excludeDrawIds: new Set(newFeatures.map((f) => String(f.id)))
8405
9212
  });
8406
- syncRef.current();
9213
+ scheduleSync();
8407
9214
  setTimeout(() => {
8408
9215
  setActiveMode("simple_select");
8409
9216
  if (drawInstance.getMode() !== "simple_select") {
@@ -8414,8 +9221,52 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8414
9221
  onFeatureCreate == null ? void 0 : onFeatureCreate(feature);
8415
9222
  });
8416
9223
  });
9224
+ let drawGatePointerDown = false;
9225
+ const onDrawGatePointerDown = () => {
9226
+ drawGatePointerDown = true;
9227
+ };
9228
+ const onDrawGatePointerUp = () => {
9229
+ drawGatePointerDown = false;
9230
+ };
9231
+ const drawGateCanvas = mapInstance.getCanvasContainer();
9232
+ drawGateCanvas.addEventListener("pointerdown", onDrawGatePointerDown);
9233
+ window.addEventListener("pointerup", onDrawGatePointerUp);
9234
+ window.addEventListener("pointercancel", onDrawGatePointerUp);
9235
+ window.addEventListener("blur", onDrawGatePointerUp);
9236
+ removeDrawGateListeners = () => {
9237
+ drawGateCanvas.removeEventListener("pointerdown", onDrawGatePointerDown);
9238
+ window.removeEventListener("pointerup", onDrawGatePointerUp);
9239
+ window.removeEventListener("pointercancel", onDrawGatePointerUp);
9240
+ window.removeEventListener("blur", onDrawGatePointerUp);
9241
+ };
9242
+ let lastDrawGeometries = /* @__PURE__ */ new Map();
9243
+ let drawGateSkips = 0;
8417
9244
  mapInstance.on("draw.render", () => {
8418
- syncRef.current();
9245
+ if (!shouldDiffDrawRender({
9246
+ mode: drawInstance.getMode(),
9247
+ pointerDown: drawGatePointerDown,
9248
+ hasSelection: drawInstance.getSelectedIds().length > 0
9249
+ })) {
9250
+ drawGateSkips++;
9251
+ return;
9252
+ }
9253
+ if (drawGateSkips > 0) {
9254
+ mapPerfLog("sync", "draw.render diff resumed", { skippedWhileIdle: drawGateSkips });
9255
+ drawGateSkips = 0;
9256
+ }
9257
+ const features = drawInstance.getAll().features;
9258
+ let changed = features.length !== lastDrawGeometries.size;
9259
+ const next = /* @__PURE__ */ new Map();
9260
+ features.forEach((f) => {
9261
+ const id = String(f.id);
9262
+ next.set(id, f.geometry);
9263
+ if (!changed) {
9264
+ const prev = lastDrawGeometries.get(id);
9265
+ if (!prev || !geometryEquals(prev, f.geometry)) changed = true;
9266
+ }
9267
+ });
9268
+ lastDrawGeometries = next;
9269
+ if (changed) scheduleSync();
8419
9270
  });
8420
9271
  mapInstance.on("draw.update", (e) => {
8421
9272
  const activeLayerId = activeEditingLayerIdRef.current;
@@ -8445,9 +9296,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8445
9296
  }
8446
9297
  } else {
8447
9298
  const previousGeometry = originalGeometriesRef.current.get(fid);
8448
- const geometryChanged = !previousGeometry || JSON.stringify(previousGeometry) !== JSON.stringify(feature.geometry);
9299
+ const geometryChanged = !previousGeometry || !geometryEquals(previousGeometry, feature.geometry);
8449
9300
  if (geometryChanged) {
8450
- originalGeometriesRef.current.set(fid, JSON.parse(JSON.stringify(feature.geometry)));
9301
+ originalGeometriesRef.current.set(fid, deepClone(feature.geometry));
8451
9302
  if (!externalPersistence) {
8452
9303
  drawInstance.setFeatureProperty(fid, "_unsaved", true);
8453
9304
  }
@@ -8456,8 +9307,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8456
9307
  }
8457
9308
  }
8458
9309
  });
8459
- syncRef.current();
8460
- if (e.action === "change_coordinates" && !hasRevertedFeatures) {
9310
+ scheduleSync();
9311
+ if ((e.action === "move" || e.action === "change_coordinates") && !hasRevertedFeatures) {
8461
9312
  scheduleTimelineUpdate();
8462
9313
  recordMoveFromPreDrag();
8463
9314
  }
@@ -8476,7 +9327,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8476
9327
  updateFeatureCount();
8477
9328
  scheduleTimelineUpdate();
8478
9329
  saveStateForUndo("delete feature", { addDrawFeatures: e.features });
8479
- syncRef.current();
9330
+ scheduleSync();
8480
9331
  onFeatureDelete == null ? void 0 : onFeatureDelete(deletedIds);
8481
9332
  });
8482
9333
  mapInstance.on("draw.selectionchange", (e) => {
@@ -8492,7 +9343,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8492
9343
  e.features.forEach((feature) => {
8493
9344
  const fid = feature.id;
8494
9345
  if (!originalGeometriesRef.current.has(fid)) {
8495
- originalGeometriesRef.current.set(fid, JSON.parse(JSON.stringify(feature.geometry)));
9346
+ originalGeometriesRef.current.set(fid, deepClone(feature.geometry));
8496
9347
  }
8497
9348
  });
8498
9349
  }
@@ -8509,11 +9360,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8509
9360
  if (enableProperties && (autoOpenProperties || !wasJustCreated)) {
8510
9361
  setShowProperties(ids.length > 0);
8511
9362
  }
8512
- syncRef.current();
9363
+ scheduleSync("selection");
8513
9364
  onFeatureSelect == null ? void 0 : onFeatureSelect(e.features);
8514
9365
  });
8515
9366
  mapInstance.on("draw.modechange", () => {
8516
- syncRef.current();
9367
+ scheduleSync();
8517
9368
  });
8518
9369
  mapInstance.on("click", (e) => {
8519
9370
  var _a;
@@ -8561,7 +9412,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8561
9412
  setSelectedFeatureIds(nextIds);
8562
9413
  selectedFeatureIdsRef.current = nextIds;
8563
9414
  if (enableProperties) setShowProperties(nextIds.length > 0);
8564
- syncRef.current();
9415
+ scheduleSync("selection");
8565
9416
  const selectedFeatures2 = [];
8566
9417
  for (const id of nextIds) {
8567
9418
  readOnlyFeatures.current.forEach((layerFeatures) => {
@@ -8594,7 +9445,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8594
9445
  setMapError(error instanceof Error ? error.message : "Failed to initialize map");
8595
9446
  }
8596
9447
  return () => {
9448
+ var _a;
8597
9449
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
9450
+ (_a = syncCoalescerRef.current) == null ? void 0 : _a.cancel();
9451
+ removeDrawGateListeners == null ? void 0 : removeDrawGateListeners();
8598
9452
  if (map.current) {
8599
9453
  map.current.remove();
8600
9454
  map.current = null;
@@ -8717,10 +9571,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8717
9571
  updateFeatureCount();
8718
9572
  scheduleTimelineUpdate();
8719
9573
  }
8720
- requestAnimationFrame(() => syncRef.current());
9574
+ scheduleSync();
8721
9575
  return true;
8722
9576
  },
8723
9577
  captureScreenshot: async (options) => {
9578
+ var _a;
8724
9579
  const m = map.current;
8725
9580
  if (!m || !isMapLoadedRef.current) {
8726
9581
  toast({
@@ -8730,6 +9585,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8730
9585
  });
8731
9586
  throw new Error("Map is not ready");
8732
9587
  }
9588
+ (_a = syncCoalescerRef.current) == null ? void 0 : _a.flush();
8733
9589
  const SCREENSHOT_RENDER_TIMEOUT_MS = 1e4;
8734
9590
  try {
8735
9591
  await new Promise((resolve, reject) => {
@@ -8770,8 +9626,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8770
9626
  const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
8771
9627
  const currentLayers = layersRef.current;
8772
9628
  const targetLayerIds = layerIds ?? currentLayers.map((l) => l.id);
8773
- const targetFeatureIds = currentLayers.filter((l) => targetLayerIds.includes(l.id)).flatMap((l) => l.featureIds);
8774
- const targetFeatures = allFeatures.filter((f) => targetFeatureIds.includes(f.id));
9629
+ const targetFeatureIds = new Set(
9630
+ currentLayers.filter((l) => targetLayerIds.includes(l.id)).flatMap((l) => l.featureIds)
9631
+ );
9632
+ const targetFeatures = allFeatures.filter((f) => targetFeatureIds.has(f.id));
8775
9633
  if (targetFeatures.length === 0) return;
8776
9634
  const fc = turf__namespace.featureCollection(targetFeatures);
8777
9635
  const bbox = turf__namespace.bbox(fc);
@@ -8821,28 +9679,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8821
9679
  };
8822
9680
  if (geojson) {
8823
9681
  if (options == null ? void 0 : options.readOnly) {
8824
- let layerHasTemporal = false;
8825
- const featuresWithIds = geojson.features.map((f) => {
8826
- const id = f.id ? String(f.id) : crypto.randomUUID();
8827
- const props = f.properties || {};
8828
- if (!hasAnyTemporalValue(props)) {
8829
- return { ...f, id };
8830
- }
8831
- const { startDate, endDate } = normalizeTemporalProperties(props);
8832
- if (startDate || endDate) layerHasTemporal = true;
8833
- return {
8834
- ...f,
8835
- id,
8836
- properties: {
8837
- ...props,
8838
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
8839
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
8840
- }
8841
- };
8842
- });
8843
- readOnlyFeatures.current.set(layerId, featuresWithIds);
8844
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: layerHasTemporal });
8845
- newLayer.featureIds = featuresWithIds.map((f) => String(f.id));
9682
+ const prepared = prepareFeaturesForLayer(geojson.features, "addLayer");
9683
+ readOnlyFeatures.current.set(layerId, prepared.features);
9684
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9685
+ newLayer.featureIds = prepared.featureIds;
8846
9686
  } else if (draw.current) {
8847
9687
  isApiAddingRef.current = true;
8848
9688
  try {
@@ -8872,7 +9712,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8872
9712
  setLayers(updatedLayers);
8873
9713
  updateFeatureCount();
8874
9714
  scheduleTimelineUpdate();
8875
- syncFeaturesToCustomLayers();
9715
+ scheduleSync();
8876
9716
  if (!(options == null ? void 0 : options.skipFit) && geojson && geojson.features.length > 0 && map.current) {
8877
9717
  try {
8878
9718
  const bbox = turf__namespace.bbox(geojson);
@@ -8907,9 +9747,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8907
9747
  setLayers(updatedLayers);
8908
9748
  updateFeatureCount();
8909
9749
  scheduleTimelineUpdate();
8910
- requestAnimationFrame(() => {
8911
- syncRef.current();
8912
- });
9750
+ scheduleSync();
8913
9751
  return true;
8914
9752
  },
8915
9753
  setLayerVisibility: (layerId, visible) => {
@@ -8923,9 +9761,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8923
9761
  setLayers(nextLayers2);
8924
9762
  updateFeatureCount();
8925
9763
  scheduleTimelineUpdate();
8926
- requestAnimationFrame(() => {
8927
- syncRef.current();
8928
- });
9764
+ scheduleSync();
8929
9765
  return;
8930
9766
  }
8931
9767
  if (!draw.current) return;
@@ -8963,9 +9799,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8963
9799
  setLayers(nextLayers);
8964
9800
  updateFeatureCount();
8965
9801
  scheduleTimelineUpdate();
8966
- requestAnimationFrame(() => {
8967
- syncRef.current();
8968
- });
9802
+ scheduleSync();
8969
9803
  },
8970
9804
  addFeatures: (layerId, features, options) => {
8971
9805
  var _a;
@@ -8974,29 +9808,12 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8974
9808
  if (options == null ? void 0 : options.recordHistory) saveStateForUndo("add features");
8975
9809
  if (layer.readOnly) {
8976
9810
  const existing = readOnlyFeatures.current.get(layerId) || [];
8977
- let layerHasTemporal = ((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false;
8978
- const newFeaturesWithIds = features.map((f) => {
8979
- const id = f.id ? String(f.id) : crypto.randomUUID();
8980
- const props = f.properties || {};
8981
- if (!hasAnyTemporalValue(props)) {
8982
- return { ...f, id };
8983
- }
8984
- const { startDate, endDate } = normalizeTemporalProperties(props);
8985
- if (startDate || endDate) layerHasTemporal = true;
8986
- return {
8987
- ...f,
8988
- id,
8989
- properties: {
8990
- ...props,
8991
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
8992
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
8993
- }
8994
- };
8995
- });
8996
- const combined = [...existing, ...newFeaturesWithIds];
9811
+ const prepared = prepareFeaturesForLayer(features, "addFeatures");
9812
+ const layerHasTemporal = (((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false) || prepared.hasTemporal;
9813
+ const combined = [...existing, ...prepared.features];
8997
9814
  readOnlyFeatures.current.set(layerId, combined);
8998
9815
  layerTemporalCacheRef.current.set(layerId, { featureCount: combined.length, hasTemporal: layerHasTemporal });
8999
- const addedIds2 = newFeaturesWithIds.map((f) => String(f.id));
9816
+ const addedIds2 = prepared.featureIds;
9000
9817
  const updatedLayers2 = layersRef.current.map(
9001
9818
  (l) => l.id === layerId ? { ...l, featureIds: [...l.featureIds, ...addedIds2] } : l
9002
9819
  );
@@ -9006,9 +9823,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9006
9823
  if (layerHasTemporal) {
9007
9824
  scheduleTimelineUpdate();
9008
9825
  }
9009
- requestAnimationFrame(() => {
9010
- syncRef.current();
9011
- });
9826
+ scheduleSync();
9012
9827
  return addedIds2;
9013
9828
  }
9014
9829
  if (!draw.current) return [];
@@ -9038,7 +9853,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9038
9853
  setLayers(updatedLayers);
9039
9854
  updateFeatureCount();
9040
9855
  scheduleTimelineUpdate();
9041
- syncFeaturesToCustomLayers();
9856
+ scheduleSync();
9042
9857
  return addedIds;
9043
9858
  },
9044
9859
  removeFeatures: (featureIds, options) => {
@@ -9074,7 +9889,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9074
9889
  });
9075
9890
  updateFeatureCount();
9076
9891
  scheduleTimelineUpdate();
9077
- requestAnimationFrame(() => syncRef.current());
9892
+ scheduleSync();
9078
9893
  onFeatureDelete == null ? void 0 : onFeatureDelete(featureIds);
9079
9894
  },
9080
9895
  selectFeatures: (featureIds) => {
@@ -9150,7 +9965,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9150
9965
  ));
9151
9966
  updateFeatureCount();
9152
9967
  scheduleTimelineUpdate();
9153
- syncFeaturesToCustomLayers();
9968
+ scheduleSync();
9154
9969
  return addedIds;
9155
9970
  },
9156
9971
  getActiveEditableLayerId: () => {
@@ -9230,70 +10045,32 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9230
10045
  getDrawingMode: () => {
9231
10046
  return activeMode;
9232
10047
  },
9233
- updateReadOnlyLayer: (layerId, features) => {
9234
- const layer = layersRef.current.find((l) => l.id === layerId);
9235
- if (!layer || !layer.readOnly || !isMapLoadedRef.current) return false;
9236
- let layerHasTemporal = false;
9237
- const featuresWithIds = features.map((f) => {
9238
- const id = f.id ? String(f.id) : crypto.randomUUID();
9239
- const props = f.properties || {};
9240
- if (!hasAnyTemporalValue(props)) {
9241
- return { ...f, id };
9242
- }
9243
- const { startDate, endDate } = normalizeTemporalProperties(props);
9244
- if (startDate || endDate) layerHasTemporal = true;
9245
- return {
9246
- ...f,
9247
- id,
9248
- properties: {
9249
- ...props,
9250
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9251
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9252
- }
9253
- };
9254
- });
9255
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9256
- layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: layerHasTemporal });
9257
- if (layerHasTemporal) {
10048
+ updateReadOnlyLayer: (layerId, features) => {
10049
+ const layer = layersRef.current.find((l) => l.id === layerId);
10050
+ if (!layer || !layer.readOnly || !isMapLoadedRef.current) return false;
10051
+ const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer");
10052
+ readOnlyFeatures.current.set(layerId, prepared.features);
10053
+ layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: prepared.hasTemporal });
10054
+ if (prepared.hasTemporal) {
9258
10055
  scheduleTimelineUpdate();
9259
10056
  }
9260
- const newFeatureIds = featuresWithIds.map((f) => String(f.id));
10057
+ const newFeatureIds = prepared.featureIds;
9261
10058
  const updatedLayers = layersRef.current.map(
9262
10059
  (l) => l.id === layerId ? { ...l, featureIds: newFeatureIds } : l
9263
10060
  );
9264
10061
  layersRef.current = updatedLayers;
9265
10062
  setLayers(updatedLayers);
9266
10063
  updateFeatureCount();
9267
- requestAnimationFrame(() => {
9268
- syncRef.current();
9269
- });
10064
+ scheduleSync();
9270
10065
  return true;
9271
10066
  },
9272
10067
  setLayerData: (name, geojson, options) => {
9273
10068
  if (!isMapLoadedRef.current) return "";
9274
- let layerHasTemporal = false;
9275
- const featuresWithIds = geojson.features.map((f) => {
9276
- const id = f.id ? String(f.id) : crypto.randomUUID();
9277
- const props = f.properties || {};
9278
- if (!hasAnyTemporalValue(props)) {
9279
- return { ...f, id };
9280
- }
9281
- const { startDate, endDate } = normalizeTemporalProperties(props);
9282
- if (startDate || endDate) layerHasTemporal = true;
9283
- return {
9284
- ...f,
9285
- id,
9286
- properties: {
9287
- ...props,
9288
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9289
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9290
- }
9291
- };
9292
- });
9293
- const newFeatureIds = featuresWithIds.map((f) => String(f.id));
10069
+ const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData");
10070
+ const newFeatureIds = prepared.featureIds;
9294
10071
  const layerId = `managed-${name}`;
9295
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9296
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: layerHasTemporal });
10072
+ readOnlyFeatures.current.set(layerId, prepared.features);
10073
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9297
10074
  const buildLayerObj = (existing) => {
9298
10075
  const base = {
9299
10076
  id: layerId,
@@ -9340,9 +10117,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9340
10117
  return result;
9341
10118
  });
9342
10119
  updateFeatureCount();
9343
- requestAnimationFrame(() => {
9344
- syncRef.current();
9345
- });
10120
+ scheduleSync();
9346
10121
  if ((options == null ? void 0 : options.fitPadding) != null && geojson.features.length > 0 && map.current) {
9347
10122
  try {
9348
10123
  const bbox = turf__namespace.bbox(geojson);
@@ -9396,21 +10171,18 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9396
10171
  const features = [];
9397
10172
  const readOnly = readOnlyFeatures.current.get(layerId);
9398
10173
  if (readOnly) {
9399
- return readOnly.map((f) => JSON.parse(JSON.stringify(f)));
10174
+ return cloneFeatures(readOnly);
9400
10175
  }
9401
10176
  if (layer.visible) {
9402
10177
  layer.featureIds.forEach((id) => {
9403
10178
  var _a;
9404
10179
  const f = (_a = draw.current) == null ? void 0 : _a.get(id);
9405
- if (f) {
9406
- features.push(JSON.parse(JSON.stringify(f)));
9407
- }
10180
+ if (f) features.push(f);
9408
10181
  });
9409
10182
  } else {
9410
- const hidden = hiddenFeatures.current.get(layerId) || [];
9411
- return hidden.map((f) => JSON.parse(JSON.stringify(f)));
10183
+ return cloneFeatures(hiddenFeatures.current.get(layerId) || []);
9412
10184
  }
9413
- return features;
10185
+ return cloneFeatures(features);
9414
10186
  },
9415
10187
  getTimelineRange: () => {
9416
10188
  const ts = timelineStoreApi.getState();
@@ -9449,7 +10221,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9449
10221
  var _a;
9450
10222
  (_a = restoreEnrichedGeoJSONRef.current) == null ? void 0 : _a.call(restoreEnrichedGeoJSONRef, enriched);
9451
10223
  }
9452
- }), [layers, isEditMode, isMapLoaded, getSelectedFeatures, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onFeatureDelete, onTimelineChange, activeEditingLayerId, currentMapStyle, activeMode, saveStateForUndo, history]);
10224
+ }), [layers, isEditMode, isMapLoaded, getSelectedFeatures, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onFeatureDelete, onTimelineChange, activeEditingLayerId, currentMapStyle, activeMode, saveStateForUndo, history]);
9453
10225
  const handleModeChange = react.useCallback((mode) => {
9454
10226
  if (!draw.current || !isMapLoaded) return;
9455
10227
  if (!hasVisibleLayers && mode !== "simple_select" && mode !== "view_select") {
@@ -9526,12 +10298,12 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9526
10298
  setShowProperties(false);
9527
10299
  updateFeatureCount();
9528
10300
  scheduleTimelineUpdate();
9529
- syncFeaturesToCustomLayers();
10301
+ scheduleSync();
9530
10302
  toast({
9531
10303
  title: "Layer cleared",
9532
10304
  description: `Removed all features from "${activeLayer.name}"`
9533
10305
  });
9534
- }, [activeEditingLayerId, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, toast]);
10306
+ }, [activeEditingLayerId, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast]);
9535
10307
  const handleDeleteSelected = react.useCallback(() => {
9536
10308
  if (selectedFeatureIds.length === 0) return;
9537
10309
  const idSet = new Set(selectedFeatureIds);
@@ -9582,8 +10354,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9582
10354
  setShowProperties(false);
9583
10355
  updateFeatureCount();
9584
10356
  scheduleTimelineUpdate();
9585
- syncFeaturesToCustomLayers();
9586
- }, [selectedFeatureIds, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onFeatureDelete]);
10357
+ scheduleSync();
10358
+ }, [selectedFeatureIds, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onFeatureDelete]);
9587
10359
  const handleToggleEditMode = react.useCallback(() => {
9588
10360
  setIsEditMode((prev) => {
9589
10361
  const newMode = !prev;
@@ -9719,9 +10491,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9719
10491
  updateFeatureCount();
9720
10492
  scheduleTimelineUpdate();
9721
10493
  saveStateForUndo();
9722
- syncFeaturesToCustomLayers();
10494
+ scheduleSync();
9723
10495
  onFeatureCreate == null ? void 0 : onFeatureCreate(feature);
9724
- }, [isMapLoaded, externalPersistence, enableProperties, autoOpenProperties, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onFeatureCreate]);
10496
+ }, [isMapLoaded, externalPersistence, enableProperties, autoOpenProperties, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onFeatureCreate]);
9725
10497
  const handleFeatureContextMenu = react.useCallback((e) => {
9726
10498
  var _a, _b;
9727
10499
  contextMenuFiredRef.current = true;
@@ -9906,7 +10678,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9906
10678
  if (properties.kind === "text" || ((_c = drawFeature.properties) == null ? void 0 : _c.kind) === "text") {
9907
10679
  draw.current.setFeatureProperty(featureId, "text", void 0);
9908
10680
  }
9909
- syncFeaturesToCustomLayers();
10681
+ scheduleSync();
9910
10682
  scheduleTimelineUpdate();
9911
10683
  setFeatureUpdateCounter((c) => c + 1);
9912
10684
  const updated = draw.current.get(featureId);
@@ -9941,13 +10713,13 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9941
10713
  }
9942
10714
  });
9943
10715
  if (updatedFeature) {
9944
- syncFeaturesToCustomLayers();
10716
+ scheduleSync();
9945
10717
  scheduleTimelineUpdate();
9946
10718
  setFeatureUpdateCounter((c) => c + 1);
9947
10719
  onFeatureUpdate == null ? void 0 : onFeatureUpdate(updatedFeature);
9948
10720
  }
9949
10721
  }
9950
- }, [saveStateForUndo, scheduleTimelineUpdate, onFeatureUpdate, syncFeaturesToCustomLayers]);
10722
+ }, [saveStateForUndo, scheduleTimelineUpdate, onFeatureUpdate, scheduleSync]);
9951
10723
  const handleUpdateGeometry = react.useCallback((featureId, geometry) => {
9952
10724
  if (!draw.current || !map.current) return;
9953
10725
  const feature = draw.current.get(featureId);
@@ -9969,13 +10741,13 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9969
10741
  draw.current.setFeatureProperty(featureId, "_unsaved", true);
9970
10742
  }
9971
10743
  draw.current.changeMode("simple_select", { featureIds: [featureId] });
9972
- syncFeaturesToCustomLayers();
10744
+ scheduleSync();
9973
10745
  setFeatureUpdateCounter((c) => c + 1);
9974
10746
  const updated = draw.current.get(featureId);
9975
10747
  if (updated) {
9976
10748
  onFeatureUpdate == null ? void 0 : onFeatureUpdate(updated);
9977
10749
  }
9978
- }, [saveStateForUndo, onFeatureUpdate, syncFeaturesToCustomLayers]);
10750
+ }, [saveStateForUndo, onFeatureUpdate, scheduleSync]);
9979
10751
  const handleFeatureSaved = react.useCallback((oldId, newId, metadata) => {
9980
10752
  if (!draw.current) return;
9981
10753
  const feature = draw.current.get(oldId);
@@ -10020,7 +10792,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10020
10792
  setSelectedFeatureIds((prev) => prev.map((fid) => fid === oldId ? featureId : fid));
10021
10793
  draw.current.changeMode("simple_select", { featureIds: [featureId] });
10022
10794
  }
10023
- syncFeaturesToCustomLayers();
10795
+ scheduleSync();
10024
10796
  updateFeatureCount();
10025
10797
  setFeatureUpdateCounter((c) => c + 1);
10026
10798
  const savedFeatureId = featureId;
@@ -10031,7 +10803,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10031
10803
  }
10032
10804
  setFeatureUpdateCounter((c) => c + 1);
10033
10805
  });
10034
- }, [syncFeaturesToCustomLayers, updateFeatureCount]);
10806
+ }, [scheduleSync, updateFeatureCount]);
10035
10807
  const handleAddLayer = react.useCallback((name) => {
10036
10808
  const newLayer = {
10037
10809
  id: `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
@@ -10116,9 +10888,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10116
10888
  updateFeatureCount();
10117
10889
  scheduleTimelineUpdate();
10118
10890
  if (layer.readOnly) {
10119
- requestAnimationFrame(() => {
10120
- syncRef.current();
10121
- });
10891
+ scheduleSync();
10122
10892
  }
10123
10893
  }, [layers, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate]);
10124
10894
  const handleMoveFeatureToLayer = react.useCallback((featureId, targetLayerId) => {
@@ -10176,10 +10946,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10176
10946
  }
10177
10947
  return remaining.length !== l.featureIds.length ? { ...l, featureIds: remaining } : l;
10178
10948
  }));
10179
- syncFeaturesToCustomLayers();
10949
+ scheduleSync();
10180
10950
  updateFeatureCount();
10181
10951
  }
10182
- }, [saveStateForUndo, findFeatureById, updateFeatureCount, syncFeaturesToCustomLayers]);
10952
+ }, [saveStateForUndo, findFeatureById, updateFeatureCount, scheduleSync]);
10183
10953
  const handleCopyFeaturesToLayer = react.useCallback((featureIds, targetLayerId) => {
10184
10954
  if (!draw.current) return;
10185
10955
  saveStateForUndo();
@@ -10236,10 +11006,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10236
11006
  }),
10237
11007
  { id: newLayerId, name: layerName, visible: true, featureIds: movedIds }
10238
11008
  ]);
10239
- syncFeaturesToCustomLayers();
11009
+ scheduleSync();
10240
11010
  updateFeatureCount();
10241
11011
  }
10242
- }, [saveStateForUndo, findFeatureById, updateFeatureCount, syncFeaturesToCustomLayers]);
11012
+ }, [saveStateForUndo, findFeatureById, updateFeatureCount, scheduleSync]);
10243
11013
  const handleCreateLayerAndCopyFeatures = react.useCallback((featureIds, layerName) => {
10244
11014
  if (!draw.current) return;
10245
11015
  saveStateForUndo();
@@ -10531,20 +11301,23 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10531
11301
  react.useEffect(() => {
10532
11302
  if (!map.current || !isMapLoaded) return;
10533
11303
  const mapInstance = map.current;
11304
+ let rafId = null;
10534
11305
  const handleMove = () => {
10535
- if (!hasArrowFeaturesRef.current) return;
10536
- if (syncRef.current) {
10537
- syncRef.current();
10538
- }
11306
+ if (!hasArrowFeaturesRef.current || rafId !== null) return;
11307
+ rafId = requestAnimationFrame(() => {
11308
+ rafId = null;
11309
+ renderArrowOverlays(paintedArrowLinesRef.current);
11310
+ });
10539
11311
  };
10540
11312
  mapInstance.on("move", handleMove);
10541
11313
  return () => {
11314
+ if (rafId !== null) cancelAnimationFrame(rafId);
10542
11315
  try {
10543
11316
  mapInstance.off("move", handleMove);
10544
11317
  } catch {
10545
11318
  }
10546
11319
  };
10547
- }, [isMapLoaded]);
11320
+ }, [isMapLoaded, renderArrowOverlays]);
10548
11321
  react.useEffect(() => {
10549
11322
  if (!map.current || !isMapLoaded || !onViewportChange) return;
10550
11323
  const mapInstance = map.current;
@@ -10853,6 +11626,50 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10853
11626
  react.useEffect(() => {
10854
11627
  enableDrawingRef.current = enableDrawing;
10855
11628
  }, [enableDrawing]);
11629
+ const trySelectionFastPath = react.useCallback(() => {
11630
+ var _a;
11631
+ const m = map.current;
11632
+ if (!m) return true;
11633
+ const source = m.getSource("custom-features");
11634
+ const gate = enableSelectionRef.current || enableDrawingRef.current;
11635
+ const next = /* @__PURE__ */ new Set();
11636
+ if (gate) {
11637
+ (((_a = draw.current) == null ? void 0 : _a.getSelectedIds()) ?? []).forEach((id) => next.add(String(id)));
11638
+ selectedFeatureIdsRef.current.forEach((id) => next.add(String(id)));
11639
+ }
11640
+ return applySelectionFastPath(selectionPaintCacheRef.current, next, source);
11641
+ }, []);
11642
+ trySelectionFastPathRef.current = trySelectionFastPath;
11643
+ const tryTimelineFastPath = react.useCallback(() => {
11644
+ const m = map.current;
11645
+ if (!m) return true;
11646
+ if (hasArrowFeaturesRef.current) return false;
11647
+ if (layersRef.current.some((l) => {
11648
+ var _a;
11649
+ return l.visible && ((_a = l.traceConfig) == null ? void 0 : _a.enabled);
11650
+ })) return false;
11651
+ const source = m.getSource("custom-features");
11652
+ const { applied, toggled } = applyTimelineFastPath(
11653
+ selectionPaintCacheRef.current,
11654
+ timelineVisibleIdsRef.current,
11655
+ source
11656
+ );
11657
+ if (applied) {
11658
+ const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
11659
+ setVisibleFeatureCount(countVisibleFeatures(threshold));
11660
+ setLabelsSuppressed(false);
11661
+ mapPerfLog("timeline", "fast path applied", { toggled });
11662
+ }
11663
+ return applied;
11664
+ }, [autoLabelConfig, countVisibleFeatures]);
11665
+ tryTimelineFastPathRef.current = tryTimelineFastPath;
11666
+ const collectSelectionFeatureGroups = react.useCallback(() => {
11667
+ return collectVisibleFeatureGroups(
11668
+ draw.current ? draw.current.getAll().features : null,
11669
+ readOnlyFeatures.current,
11670
+ layersRef.current
11671
+ );
11672
+ }, []);
10856
11673
  react.useEffect(() => {
10857
11674
  if (!map.current || !isMapLoaded) {
10858
11675
  return;
@@ -10943,29 +11760,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10943
11760
  [minLng, maxLat]
10944
11761
  // close polygon
10945
11762
  ]]);
10946
- const drawFeatures = draw.current ? draw.current.getAll().features : [];
10947
- const readOnlyFeaturesList = [];
10948
- readOnlyFeatures.current.forEach((features, layerId) => {
10949
- const layer = layersRef.current.find((l) => l.id === layerId);
10950
- if (layer == null ? void 0 : layer.visible) pushAll(readOnlyFeaturesList, features);
10951
- });
10952
- const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
10953
- const selectedIds = [];
10954
- allFeatures.forEach((feature) => {
10955
- try {
10956
- const geom = feature.geometry;
10957
- let isInside = false;
10958
- if (geom.type === "Point") {
10959
- isInside = turf__namespace.booleanPointInPolygon(geom.coordinates, selectionPolygon);
10960
- } else if (geom.type === "LineString" || geom.type === "Polygon" || geom.type === "MultiPoint" || geom.type === "MultiLineString" || geom.type === "MultiPolygon") {
10961
- isInside = turf__namespace.booleanIntersects(feature, selectionPolygon);
10962
- }
10963
- if (isInside && feature.id) {
10964
- selectedIds.push(String(feature.id));
10965
- }
10966
- } catch (err) {
10967
- }
10968
- });
10969
11763
  const isFilterAction = filterActiveRef.current && onSelectionComplete;
10970
11764
  if (isFilterAction) {
10971
11765
  onSelectionComplete(selectionPolygon.geometry);
@@ -10979,6 +11773,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10979
11773
  ]);
10980
11774
  }
10981
11775
  } else {
11776
+ const selectedIds = hitTestSelection(collectSelectionFeatureGroups(), selectionPolygon, {
11777
+ axisAlignedRectangle: true
11778
+ });
10982
11779
  const finalIds = e.shiftKey ? Array.from(/* @__PURE__ */ new Set([...selectedFeatureIdsRef.current, ...selectedIds])) : selectedIds;
10983
11780
  applySelectionState(finalIds, { focusProperties: true });
10984
11781
  }
@@ -10994,29 +11791,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10994
11791
  const radiusKm = turf__namespace.distance(center, edge, { units: "kilometers" });
10995
11792
  if (radiusKm > 0) {
10996
11793
  const selectionPolygon = turf__namespace.circle([centerLngLat.lng, centerLngLat.lat], radiusKm, { steps: 64, units: "kilometers" });
10997
- const drawFeatures = draw.current ? draw.current.getAll().features : [];
10998
- const readOnlyFeaturesList = [];
10999
- readOnlyFeatures.current.forEach((features, layerId) => {
11000
- const layer = layersRef.current.find((l) => l.id === layerId);
11001
- if (layer == null ? void 0 : layer.visible) pushAll(readOnlyFeaturesList, features);
11002
- });
11003
- const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
11004
- const selectedIds = [];
11005
- allFeatures.forEach((feature) => {
11006
- try {
11007
- const geom = feature.geometry;
11008
- let isInside = false;
11009
- if (geom.type === "Point") {
11010
- isInside = turf__namespace.booleanPointInPolygon(geom.coordinates, selectionPolygon);
11011
- } else if (geom.type === "LineString" || geom.type === "Polygon" || geom.type === "MultiPoint" || geom.type === "MultiLineString" || geom.type === "MultiPolygon") {
11012
- isInside = turf__namespace.booleanIntersects(feature, selectionPolygon);
11013
- }
11014
- if (isInside && feature.id) {
11015
- selectedIds.push(String(feature.id));
11016
- }
11017
- } catch (err) {
11018
- }
11019
- });
11020
11794
  const isFilterAction = filterActiveRef.current && onSelectionComplete;
11021
11795
  if (isFilterAction) {
11022
11796
  onSelectionComplete(selectionPolygon.geometry);
@@ -11024,6 +11798,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11024
11798
  setPersistedSelectionPolygon(selectionPolygon.geometry.coordinates[0]);
11025
11799
  }
11026
11800
  } else {
11801
+ const selectedIds = hitTestSelection(collectSelectionFeatureGroups(), selectionPolygon);
11027
11802
  const finalIds = e.shiftKey ? Array.from(/* @__PURE__ */ new Set([...selectedFeatureIdsRef.current, ...selectedIds])) : selectedIds;
11028
11803
  applySelectionState(finalIds, { focusProperties: true });
11029
11804
  }
@@ -11050,29 +11825,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11050
11825
  }
11051
11826
  const closedPoints = [...currentPoints, currentPoints[0]];
11052
11827
  const selectionPolygon = turf__namespace.polygon([closedPoints]);
11053
- const drawFeatures = draw.current ? draw.current.getAll().features : [];
11054
- const readOnlyFeaturesList = [];
11055
- readOnlyFeatures.current.forEach((features, layerId) => {
11056
- const layer = layersRef.current.find((l) => l.id === layerId);
11057
- if (layer == null ? void 0 : layer.visible) pushAll(readOnlyFeaturesList, features);
11058
- });
11059
- const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
11060
- const selectedIds = [];
11061
- allFeatures.forEach((feature) => {
11062
- try {
11063
- const geom = feature.geometry;
11064
- let isInside = false;
11065
- if (geom.type === "Point") {
11066
- isInside = turf__namespace.booleanPointInPolygon(geom.coordinates, selectionPolygon);
11067
- } else if (geom.type === "LineString" || geom.type === "Polygon" || geom.type === "MultiPoint" || geom.type === "MultiLineString" || geom.type === "MultiPolygon") {
11068
- isInside = turf__namespace.booleanIntersects(feature, selectionPolygon);
11069
- }
11070
- if (isInside && feature.id) {
11071
- selectedIds.push(String(feature.id));
11072
- }
11073
- } catch (err) {
11074
- }
11075
- });
11076
11828
  const isFilterAction = filterActiveRef.current && onSelectionComplete;
11077
11829
  if (isFilterAction) {
11078
11830
  onSelectionComplete(selectionPolygon.geometry);
@@ -11080,6 +11832,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11080
11832
  setPersistedSelectionPolygon(closedPoints);
11081
11833
  }
11082
11834
  } else {
11835
+ const selectedIds = hitTestSelection(collectSelectionFeatureGroups(), selectionPolygon);
11083
11836
  const finalIds = e.shiftKey ? Array.from(/* @__PURE__ */ new Set([...selectedFeatureIdsRef.current, ...selectedIds])) : selectedIds;
11084
11837
  applySelectionState(finalIds, { focusProperties: true });
11085
11838
  }
@@ -11129,7 +11882,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11129
11882
  window.removeEventListener("keydown", handleKeyDown);
11130
11883
  canvas.removeEventListener("contextmenu", handleContextMenu);
11131
11884
  };
11132
- }, [selectionMode, isMapLoaded, onFeatureSelect, onSelectionComplete, persistSelection, isSelectionToolActive]);
11885
+ }, [selectionMode, isMapLoaded, onFeatureSelect, onSelectionComplete, persistSelection, isSelectionToolActive, collectSelectionFeatureGroups]);
11133
11886
  const shiftSelectionRef = react.useRef({ isActive: false, startPoint: null, completedAt: 0 });
11134
11887
  react.useEffect(() => {
11135
11888
  if (!map.current || !isMapLoaded || !draw.current) return;
@@ -11189,28 +11942,8 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11189
11942
  [minLng, minLat],
11190
11943
  [minLng, maxLat]
11191
11944
  ]]);
11192
- const drawFeatures = draw.current ? draw.current.getAll().features : [];
11193
- const readOnlyFeaturesList = [];
11194
- readOnlyFeatures.current.forEach((features, layerId) => {
11195
- const layer = layersRef.current.find((l) => l.id === layerId);
11196
- if (layer == null ? void 0 : layer.visible) pushAll(readOnlyFeaturesList, features);
11197
- });
11198
- const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
11199
- const selectedIds = [];
11200
- allFeatures.forEach((feature) => {
11201
- try {
11202
- const geom = feature.geometry;
11203
- let isInside = false;
11204
- if (geom.type === "Point") {
11205
- isInside = turf__namespace.booleanPointInPolygon(geom.coordinates, selectionPolygon);
11206
- } else if (geom.type === "LineString" || geom.type === "Polygon" || geom.type === "MultiPoint" || geom.type === "MultiLineString" || geom.type === "MultiPolygon") {
11207
- isInside = turf__namespace.booleanIntersects(feature, selectionPolygon);
11208
- }
11209
- if (isInside && feature.id) {
11210
- selectedIds.push(String(feature.id));
11211
- }
11212
- } catch {
11213
- }
11945
+ const selectedIds = hitTestSelection(collectSelectionFeatureGroups(), selectionPolygon, {
11946
+ axisAlignedRectangle: true
11214
11947
  });
11215
11948
  const mergedIds = Array.from(/* @__PURE__ */ new Set([...selectedFeatureIdsRef.current, ...selectedIds]));
11216
11949
  shiftSelectionRef.current = { isActive: false, startPoint: null, completedAt: Date.now() };
@@ -11230,7 +11963,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11230
11963
  map.current.dragPan.enable();
11231
11964
  }
11232
11965
  };
11233
- }, [isMapLoaded, isSelectionToolActive, applySelectionState]);
11966
+ }, [isMapLoaded, isSelectionToolActive, applySelectionState, collectSelectionFeatureGroups]);
11234
11967
  react.useEffect(() => {
11235
11968
  if (!map.current || !isMapLoaded) return;
11236
11969
  const mapInstance = map.current;
@@ -11364,7 +12097,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11364
12097
  (layer) => layer.id === targetLayer.id ? { ...layer, featureIds: [...layer.featureIds, featureId] } : layer
11365
12098
  );
11366
12099
  });
11367
- syncFeaturesToCustomLayers();
12100
+ scheduleSync();
11368
12101
  const newCount = drawInstance.getAll().features.length;
11369
12102
  setFeatureCount(newCount);
11370
12103
  drawInstance.changeMode("simple_select", { featureIds: [featureId] });
@@ -11486,7 +12219,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11486
12219
  (layer) => layer.id === targetLayer.id ? { ...layer, featureIds: [...layer.featureIds, featureId] } : layer
11487
12220
  );
11488
12221
  });
11489
- syncFeaturesToCustomLayers();
12222
+ scheduleSync();
11490
12223
  const newCount = drawInstance.getAll().features.length;
11491
12224
  setFeatureCount(newCount);
11492
12225
  justCreatedRectangleRef.current = true;
@@ -11683,7 +12416,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11683
12416
  layerMetadata
11684
12417
  }
11685
12418
  };
11686
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/json" });
12419
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/json" });
11687
12420
  downloadBlob(blob, `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`);
11688
12421
  }, [layers]);
11689
12422
  const handleLoadLayerGeoJSON = react.useCallback((layerId) => {
@@ -11760,7 +12493,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11760
12493
  const handleSaveAllGeoJSON = react.useCallback(() => {
11761
12494
  if (!draw.current) return;
11762
12495
  const geojson = buildEnrichedGeoJSON();
11763
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/geo+json" });
12496
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/geo+json" });
11764
12497
  downloadBlob(blob, "map_export.geojson");
11765
12498
  }, [buildEnrichedGeoJSON]);
11766
12499
  const handleSearchAndAddToNewLayer = react.useCallback(async () => {
@@ -11842,7 +12575,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11842
12575
  }
11843
12576
  updateFeatureCount();
11844
12577
  scheduleTimelineUpdate();
11845
- syncFeaturesToCustomLayers();
12578
+ scheduleSync();
11846
12579
  }
11847
12580
  } catch (error) {
11848
12581
  toast({
@@ -11851,7 +12584,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11851
12584
  variant: "destructive"
11852
12585
  });
11853
12586
  }
11854
- }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, toast]);
12587
+ }, [onSearchEngineRequest, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast]);
11855
12588
  const restoreEnrichedGeoJSON = react.useCallback((enriched) => {
11856
12589
  var _a;
11857
12590
  const mapState = enriched["octostar:map"];
@@ -11921,7 +12654,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11921
12654
  setLayers(newLayers);
11922
12655
  updateFeatureCount();
11923
12656
  scheduleTimelineUpdate();
11924
- syncFeaturesToCustomLayers();
12657
+ scheduleSync();
11925
12658
  if (mapState.viewport && map.current) {
11926
12659
  map.current.flyTo({
11927
12660
  center: mapState.viewport.center,
@@ -11938,7 +12671,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11938
12671
  title: "Map restored",
11939
12672
  description: `Restored ${newLayers.length} layers with ${totalFeatures} features`
11940
12673
  });
11941
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, onMapStateLoaded, toast]);
12674
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, onMapStateLoaded, toast]);
11942
12675
  restoreEnrichedGeoJSONRef.current = restoreEnrichedGeoJSON;
11943
12676
  const handleWorkspaceLoad = react.useCallback(async () => {
11944
12677
  if (!onWorkspaceLoad) return;
@@ -11951,35 +12684,23 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11951
12684
  }
11952
12685
  saveStateForUndo();
11953
12686
  const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
11954
- let wsHasTemporal = false;
11955
- const featuresWithIds = result.features.map((f) => {
11956
- const props = f.properties || {};
11957
- const id = f.id ? String(f.id) : crypto.randomUUID();
11958
- if (!hasAnyTemporalValue(props)) return { ...f, id };
11959
- const { startDate, endDate } = normalizeTemporalProperties(props);
11960
- if (startDate || endDate) wsHasTemporal = true;
11961
- return {
11962
- ...f,
11963
- id,
11964
- properties: { ...props, startDate: (startDate == null ? void 0 : startDate.toISOString()) || null, endDate: (endDate == null ? void 0 : endDate.toISOString()) || null }
11965
- };
11966
- });
11967
- readOnlyFeatures.current.set(layerId, featuresWithIds);
11968
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: wsHasTemporal });
12687
+ const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad");
12688
+ readOnlyFeatures.current.set(layerId, prepared.features);
12689
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
11969
12690
  const newLayer = {
11970
12691
  id: layerId,
11971
12692
  name: "Loaded from workspace",
11972
12693
  visible: true,
11973
- featureIds: featuresWithIds.map((f) => String(f.id)),
12694
+ featureIds: prepared.featureIds,
11974
12695
  readOnly: true
11975
12696
  };
11976
12697
  setLayers((prev) => [...prev, newLayer]);
11977
12698
  updateFeatureCount();
11978
12699
  scheduleTimelineUpdate();
11979
- syncFeaturesToCustomLayers();
12700
+ scheduleSync();
11980
12701
  toast({
11981
12702
  title: "Features loaded",
11982
- description: `Created layer with ${featuresWithIds.length} features`
12703
+ description: `Created layer with ${prepared.features.length} features`
11983
12704
  });
11984
12705
  } catch (error) {
11985
12706
  toast({
@@ -11988,7 +12709,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11988
12709
  variant: "destructive"
11989
12710
  });
11990
12711
  }
11991
- }, [onWorkspaceLoad, saveStateForUndo, restoreEnrichedGeoJSON, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, toast]);
12712
+ }, [onWorkspaceLoad, saveStateForUndo, restoreEnrichedGeoJSON, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, toast]);
11992
12713
  const handleWorkspaceSave = react.useCallback(async () => {
11993
12714
  if (!onWorkspaceSave) return;
11994
12715
  const geojson = buildEnrichedGeoJSON();
@@ -12066,195 +12787,194 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12066
12787
  duration: 1e3
12067
12788
  });
12068
12789
  }, [layers, toast]);
12069
- const handleFileChange = react.useCallback((e) => {
12070
- var _a;
12071
- const file = (_a = e.target.files) == null ? void 0 : _a[0];
12072
- if (!file) return;
12073
- const requestedTargetLayerId = e.target.dataset.targetLayer || activeEditingLayerId;
12074
- const createNewLayer = e.target.dataset.createNewLayer === "true";
12075
- delete e.target.dataset.createNewLayer;
12076
- const reader = new FileReader();
12077
- reader.onload = (event) => {
12078
- var _a2, _b;
12079
- try {
12080
- const rawGeojson = JSON.parse((_a2 = event.target) == null ? void 0 : _a2.result);
12081
- if (rawGeojson.type !== "FeatureCollection" || !Array.isArray(rawGeojson.features)) {
12082
- throw new Error("Invalid GeoJSON format");
12083
- }
12084
- if (rawGeojson.features.length === 0) {
12085
- toast({
12086
- title: "Empty GeoJSON",
12087
- description: "The file contains no features",
12088
- variant: "destructive"
12089
- });
12090
- return;
12091
- }
12092
- if (rawGeojson["octostar:map"]) {
12093
- if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data: rawGeojson, file }) === true) {
12094
- return;
12095
- }
12096
- if (!draw.current) return;
12097
- restoreEnrichedGeoJSON(rawGeojson);
12098
- return;
12099
- }
12100
- if (!draw.current) return;
12101
- const { features: geojson, reprojected, sourceCRS } = detectAndReprojectGeoJSON(rawGeojson);
12102
- saveStateForUndo();
12103
- const layerMetadata = (_b = rawGeojson.properties) == null ? void 0 : _b.layerMetadata;
12104
- let fileHasTemporal = false;
12105
- const normalizedFeatures = geojson.features.map((f) => {
12106
- const props = f.properties || {};
12107
- if (!hasAnyTemporalValue(props)) return f;
12108
- const { startDate, endDate } = normalizeTemporalProperties(props);
12109
- if (startDate || endDate) fileHasTemporal = true;
12110
- return {
12111
- ...f,
12112
- properties: {
12113
- ...props,
12114
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
12115
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
12116
- }
12117
- };
12118
- });
12119
- if (createNewLayer) {
12120
- if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({
12121
- kind: "newLayer",
12122
- data: { type: "FeatureCollection", features: normalizedFeatures },
12123
- file,
12124
- reprojected,
12125
- sourceCRS: sourceCRS ?? void 0
12126
- }) === true) {
12127
- return;
12128
- }
12129
- const fileName = file.name.replace(/\.geojson$|\.json$/i, "");
12130
- const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12131
- const newLayer = {
12132
- id: layerId,
12133
- name: (layerMetadata == null ? void 0 : layerMetadata.name) || fileName,
12134
- visible: true,
12135
- featureIds: [],
12136
- readOnly: true,
12137
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12138
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12139
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12140
- };
12141
- const addedIds = [];
12142
- const featuresWithIds = [];
12143
- normalizedFeatures.forEach((f) => {
12144
- const featureId = f.id ? String(f.id) : crypto.randomUUID();
12145
- const normalizedFeature = { ...f, id: featureId };
12146
- featuresWithIds.push(normalizedFeature);
12147
- addedIds.push(featureId);
12148
- });
12149
- readOnlyFeatures.current.set(layerId, featuresWithIds);
12150
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: fileHasTemporal });
12151
- newLayer.featureIds = addedIds;
12152
- setLayers((prev) => [...prev, newLayer]);
12153
- updateFeatureCount();
12154
- scheduleTimelineUpdate();
12155
- syncFeaturesToCustomLayers();
12156
- if (map.current && geojson.features.length > 0) {
12157
- try {
12158
- const bbox = turf__namespace.bbox(geojson);
12159
- if (bbox && bbox.every((v) => isFinite(v))) {
12160
- map.current.fitBounds(
12161
- [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12162
- { padding: 50, maxZoom: 16, duration: 1e3 }
12163
- );
12164
- }
12165
- } catch (e2) {
12166
- }
12167
- }
12168
- const reprojectMsg2 = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12169
- toast({
12170
- title: "Layer created",
12171
- description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg2} (high-performance mode)`
12172
- });
12173
- return;
12174
- }
12175
- let targetLayer = layers.find((l) => l.id === requestedTargetLayerId && !l.readOnly);
12176
- if (!targetLayer) {
12177
- targetLayer = layers.find((l) => l.visible && !l.readOnly);
12178
- }
12179
- if (!targetLayer) {
12180
- targetLayer = layers.find((l) => !l.readOnly);
12181
- }
12182
- if (targetLayer == null ? void 0 : targetLayer.visible) {
12183
- const addedIds = [];
12184
- isApiAddingRef.current = true;
12185
- try {
12186
- normalizedFeatures.forEach((f) => {
12187
- const ids = draw.current.add(f);
12188
- addedIds.push(ids[0]);
12189
- });
12190
- } finally {
12191
- isApiAddingRef.current = false;
12192
- }
12193
- const targetId = targetLayer.id;
12194
- setLayers((prev) => prev.map((l) => {
12195
- if (l.id !== targetId) return l;
12196
- return {
12197
- ...l,
12198
- featureIds: [...l.featureIds, ...addedIds],
12199
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12200
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12201
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12202
- };
12203
- }));
12204
- } else if (targetLayer) {
12205
- const featuresWithIds = normalizedFeatures.map((f) => ({
12206
- ...f,
12207
- id: f.id || `feature-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
12208
- }));
12209
- const targetId = targetLayer.id;
12210
- const addedIds = featuresWithIds.map((f) => f.id);
12211
- const existing = hiddenFeatures.current.get(targetId) || [];
12212
- hiddenFeatures.current.set(targetId, [...existing, ...featuresWithIds]);
12213
- setLayers((prev) => prev.map((l) => {
12214
- if (l.id !== targetId) return l;
12215
- return {
12216
- ...l,
12217
- featureIds: [...l.featureIds, ...addedIds],
12218
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12219
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12220
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12221
- };
12222
- }));
12223
- }
12224
- updateFeatureCount();
12225
- scheduleTimelineUpdate();
12226
- syncFeaturesToCustomLayers();
12227
- const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12790
+ const loadGeoJSONFile = react.useCallback(async (file, requestedTargetLayerId, createNewLayer) => {
12791
+ let result;
12792
+ try {
12793
+ result = await getSharedIngestClient().ingest(file, {
12794
+ idStrategy: "uuid-fallback",
12795
+ emptyIsError: true
12796
+ });
12797
+ } catch (error) {
12798
+ toast({
12799
+ title: "Failed to load GeoJSON",
12800
+ description: error instanceof Error ? error.message : "Invalid file",
12801
+ variant: "destructive"
12802
+ });
12803
+ return;
12804
+ }
12805
+ if (result.kind === "error") {
12806
+ if (result.code === "empty") {
12228
12807
  toast({
12229
- title: "GeoJSON loaded",
12230
- description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
12808
+ title: "Empty GeoJSON",
12809
+ description: result.message,
12810
+ variant: "destructive"
12231
12811
  });
12232
- } catch (error) {
12812
+ } else {
12233
12813
  toast({
12234
12814
  title: "Failed to load GeoJSON",
12235
- description: error instanceof Error ? error.message : "Invalid file",
12815
+ description: result.message,
12236
12816
  variant: "destructive"
12237
12817
  });
12238
12818
  }
12239
- };
12240
- reader.readAsText(file);
12241
- e.target.value = "";
12242
- }, [layers, activeEditingLayerId, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12243
- const handleDropGeoJSON = react.useCallback((name, data) => {
12819
+ return;
12820
+ }
12821
+ if (result.kind === "enriched") {
12822
+ const rawGeojson = result.data;
12823
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data: rawGeojson, file }) === true) {
12824
+ return;
12825
+ }
12826
+ if (!draw.current) return;
12827
+ restoreEnrichedGeoJSON(rawGeojson);
12828
+ return;
12829
+ }
12830
+ if (!draw.current) return;
12831
+ const { features: normalizedFeatures, reprojected, sourceCRS, hasTemporal: fileHasTemporal } = result;
12832
+ const layerMetadata = result.layerMetadata;
12833
+ saveStateForUndo();
12834
+ if (createNewLayer) {
12835
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({
12836
+ kind: "newLayer",
12837
+ data: { type: "FeatureCollection", features: normalizedFeatures },
12838
+ file,
12839
+ reprojected,
12840
+ sourceCRS: sourceCRS ?? void 0
12841
+ }) === true) {
12842
+ return;
12843
+ }
12844
+ const fileName = file.name.replace(/\.geojson$|\.json$/i, "");
12845
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12846
+ const newLayer = {
12847
+ id: layerId,
12848
+ name: (layerMetadata == null ? void 0 : layerMetadata.name) || fileName,
12849
+ visible: true,
12850
+ featureIds: [],
12851
+ readOnly: true,
12852
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12853
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12854
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12855
+ };
12856
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
12857
+ readOnlyFeatures.current.set(layerId, normalizedFeatures);
12858
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: fileHasTemporal });
12859
+ newLayer.featureIds = addedIds;
12860
+ setLayers((prev) => [...prev, newLayer]);
12861
+ updateFeatureCount();
12862
+ scheduleTimelineUpdate();
12863
+ scheduleSync();
12864
+ if (map.current && result.bbox) {
12865
+ const bbox = result.bbox;
12866
+ map.current.fitBounds(
12867
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12868
+ { padding: 50, maxZoom: 16, duration: 1e3 }
12869
+ );
12870
+ }
12871
+ const reprojectMsg2 = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12872
+ toast({
12873
+ title: "Layer created",
12874
+ description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg2} (high-performance mode)`
12875
+ });
12876
+ return;
12877
+ }
12878
+ const currentLayers = layersRef.current;
12879
+ let targetLayer = currentLayers.find((l) => l.id === requestedTargetLayerId && !l.readOnly);
12880
+ if (!targetLayer) {
12881
+ targetLayer = currentLayers.find((l) => l.visible && !l.readOnly);
12882
+ }
12883
+ if (!targetLayer) {
12884
+ targetLayer = currentLayers.find((l) => !l.readOnly);
12885
+ }
12886
+ if (targetLayer == null ? void 0 : targetLayer.visible) {
12887
+ const addedIds = [];
12888
+ isApiAddingRef.current = true;
12889
+ try {
12890
+ normalizedFeatures.forEach((f) => {
12891
+ const ids = draw.current.add(f);
12892
+ addedIds.push(ids[0]);
12893
+ });
12894
+ } finally {
12895
+ isApiAddingRef.current = false;
12896
+ }
12897
+ const targetId = targetLayer.id;
12898
+ setLayers((prev) => prev.map((l) => {
12899
+ if (l.id !== targetId) return l;
12900
+ return {
12901
+ ...l,
12902
+ featureIds: [...l.featureIds, ...addedIds],
12903
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12904
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12905
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12906
+ };
12907
+ }));
12908
+ } else if (targetLayer) {
12909
+ const targetId = targetLayer.id;
12910
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
12911
+ const existing = hiddenFeatures.current.get(targetId) || [];
12912
+ hiddenFeatures.current.set(targetId, [...existing, ...normalizedFeatures]);
12913
+ setLayers((prev) => prev.map((l) => {
12914
+ if (l.id !== targetId) return l;
12915
+ return {
12916
+ ...l,
12917
+ featureIds: [...l.featureIds, ...addedIds],
12918
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12919
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12920
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12921
+ };
12922
+ }));
12923
+ }
12924
+ updateFeatureCount();
12925
+ scheduleTimelineUpdate();
12926
+ scheduleSync();
12927
+ const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12928
+ toast({
12929
+ title: "GeoJSON loaded",
12930
+ description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
12931
+ });
12932
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12933
+ const handleFileChange = react.useCallback((e) => {
12244
12934
  var _a;
12935
+ const file = (_a = e.target.files) == null ? void 0 : _a[0];
12936
+ if (!file) return;
12937
+ const requestedTargetLayerId = e.target.dataset.targetLayer || activeEditingLayerId;
12938
+ const createNewLayer = e.target.dataset.createNewLayer === "true";
12939
+ delete e.target.dataset.createNewLayer;
12940
+ e.target.value = "";
12941
+ void loadGeoJSONFile(file, requestedTargetLayerId, createNewLayer);
12942
+ }, [activeEditingLayerId, loadGeoJSONFile]);
12943
+ const ingestDroppedLayer = react.useCallback(async (name, input) => {
12944
+ if (!map.current) return;
12945
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12946
+ const startedAt = performance.now();
12947
+ let result;
12948
+ try {
12949
+ result = await getSharedIngestClient().ingest(input, { idStrategy: "layer-index", layerId });
12950
+ } catch (error) {
12951
+ toast({
12952
+ title: "Failed to load GeoJSON",
12953
+ description: error instanceof Error ? error.message : "Invalid file",
12954
+ variant: "destructive"
12955
+ });
12956
+ return;
12957
+ }
12245
12958
  if (!map.current) return;
12246
- if (data["octostar:map"]) {
12959
+ if (result.kind === "error") {
12960
+ toast({
12961
+ title: "Failed to load GeoJSON",
12962
+ description: result.message,
12963
+ variant: "destructive"
12964
+ });
12965
+ return;
12966
+ }
12967
+ if (result.kind === "enriched") {
12968
+ const data = result.data;
12247
12969
  if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data, sourceName: name }) === true) {
12248
12970
  return;
12249
12971
  }
12250
12972
  restoreEnrichedGeoJSON(data);
12251
12973
  return;
12252
12974
  }
12253
- const { features: reprojectedData, reprojected, sourceCRS } = detectAndReprojectGeoJSON(data);
12975
+ const { features: normalizedFeatures, reprojected, sourceCRS } = result;
12976
+ const layerMetadata = result.layerMetadata;
12254
12977
  saveStateForUndo();
12255
- const layerMetadata = (_a = data.properties) == null ? void 0 : _a.layerMetadata;
12256
- const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12257
- const layerHasAltitudeData = reprojectedData.features.some((f) => hasAltitudeData(f));
12258
12978
  const newLayer = {
12259
12979
  id: layerId,
12260
12980
  name: (layerMetadata == null ? void 0 : layerMetadata.name) || name,
@@ -12265,69 +12985,48 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12265
12985
  ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12266
12986
  ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12267
12987
  ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig },
12268
- ...layerHasAltitudeData && { hasAltitudeData: true, altitudeDisplayMode: "both" }
12988
+ ...result.hasAltitude && { hasAltitudeData: true, altitudeDisplayMode: "both" }
12269
12989
  };
12270
- const normalizedFeatures = [];
12271
- const addedIds = [];
12272
- let dropHasTemporal = false;
12273
- reprojectedData.features.forEach((f, index) => {
12274
- const featureId = f.id !== void 0 && f.id !== null ? String(f.id) : `${layerId}-f${index}`;
12275
- const props = f.properties || {};
12276
- if (!hasAnyTemporalValue(props)) {
12277
- normalizedFeatures.push({ ...f, id: featureId });
12278
- addedIds.push(featureId);
12279
- return;
12280
- }
12281
- const { startDate, endDate } = normalizeTemporalProperties(props);
12282
- if (startDate || endDate) dropHasTemporal = true;
12283
- normalizedFeatures.push({
12284
- ...f,
12285
- id: featureId,
12286
- properties: {
12287
- ...props,
12288
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
12289
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
12290
- }
12291
- });
12292
- addedIds.push(featureId);
12293
- });
12990
+ const addedIds = normalizedFeatures.map((f) => f.id);
12294
12991
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
12295
- layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: dropHasTemporal });
12992
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: result.hasTemporal });
12296
12993
  newLayer.featureIds = addedIds;
12297
12994
  const nextLayers = [...layersRef.current, newLayer];
12298
12995
  layersRef.current = nextLayers;
12299
12996
  setLayers(nextLayers);
12300
12997
  updateFeatureCount();
12301
12998
  scheduleTimelineUpdate();
12302
- syncFeaturesToCustomLayers();
12303
- if (reprojectedData.features.length > 0) {
12304
- try {
12305
- const bbox = turf__namespace.bbox(reprojectedData);
12306
- if (bbox && bbox.every((v) => isFinite(v))) {
12307
- map.current.fitBounds(
12308
- [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12309
- { padding: 50, maxZoom: 16, duration: 1e3 }
12310
- );
12311
- }
12312
- } catch (e) {
12313
- }
12999
+ scheduleSync();
13000
+ if (result.bbox) {
13001
+ const bbox = result.bbox;
13002
+ map.current.fitBounds(
13003
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
13004
+ { padding: 50, maxZoom: 16, duration: 1e3 }
13005
+ );
12314
13006
  }
13007
+ mapPerfLog("ingest", `dropped layer "${newLayer.name}" applied`, {
13008
+ features: addedIds.length,
13009
+ totalMs: Math.round(performance.now() - startedAt)
13010
+ });
12315
13011
  const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12316
13012
  toast({
12317
13013
  title: "Layer added",
12318
13014
  description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg} (high-performance)`
12319
13015
  });
12320
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, syncFeaturesToCustomLayers, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
13016
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
13017
+ const handleDropGeoJSON = react.useCallback((name, data) => {
13018
+ void ingestDroppedLayer(name, data);
13019
+ }, [ingestDroppedLayer]);
13020
+ const handleDropGeoJSONFile = react.useCallback((name, file) => {
13021
+ void ingestDroppedLayer(name, file);
13022
+ }, [ingestDroppedLayer]);
12321
13023
  const handleTimelineFilterChange = react.useCallback((visibleIds, hiddenIds, untimedIds) => {
12322
13024
  if (!draw.current || !map.current) return;
12323
- timelineVisibleIdsRef.current = /* @__PURE__ */ new Set([...visibleIds, ...untimedIds]);
12324
- if (timelineSyncRafRef.current == null) {
12325
- timelineSyncRafRef.current = requestAnimationFrame(() => {
12326
- timelineSyncRafRef.current = null;
12327
- syncFeaturesToCustomLayers();
12328
- });
12329
- }
12330
- }, [syncFeaturesToCustomLayers]);
13025
+ const nextVisible = new Set(visibleIds);
13026
+ untimedIds.forEach((id) => nextVisible.add(id));
13027
+ timelineVisibleIdsRef.current = nextVisible;
13028
+ scheduleSync("timeline");
13029
+ }, [scheduleSync]);
12331
13030
  const prevTimelineEnabledRef = react.useRef(timelineStore.isEnabled);
12332
13031
  react.useEffect(() => {
12333
13032
  const wasEnabled = prevTimelineEnabledRef.current;
@@ -12335,11 +13034,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12335
13034
  prevTimelineEnabledRef.current = isNowEnabled;
12336
13035
  if (!isNowEnabled || !timelineStore.hasTemporalData) {
12337
13036
  timelineVisibleIdsRef.current = null;
12338
- syncFeaturesToCustomLayers();
13037
+ scheduleSync();
12339
13038
  } else if (!wasEnabled && isNowEnabled) {
12340
13039
  updateTimelineStore();
12341
13040
  }
12342
- }, [timelineStore.isEnabled, timelineStore.hasTemporalData, syncFeaturesToCustomLayers, updateTimelineStore, scheduleTimelineUpdate]);
13041
+ }, [timelineStore.isEnabled, timelineStore.hasTemporalData, scheduleSync, updateTimelineStore, scheduleTimelineUpdate]);
12343
13042
  react.useEffect(() => {
12344
13043
  if (!map.current || !draw.current || !isMapLoaded) return;
12345
13044
  const mapInstance = map.current;
@@ -12710,7 +13409,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12710
13409
  ] }) });
12711
13410
  }
12712
13411
  const toastContextValue = toastProvider ?? null;
12713
- return /* @__PURE__ */ jsxRuntime.jsx(TimelineStoreContext.Provider, { value: timelineStoreApi, children: /* @__PURE__ */ jsxRuntime.jsx(ToastContext.Provider, { value: toastContextValue, children: /* @__PURE__ */ jsxRuntime.jsx(MapDropZone, { onDrop: handleDropGeoJSON, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `map-container w-full h-full min-w-0 relative overflow-hidden isolate ${className || ""}`, "data-testid": "map-editor-canvas", children: [
13412
+ return /* @__PURE__ */ jsxRuntime.jsx(TimelineStoreContext.Provider, { value: timelineStoreApi, children: /* @__PURE__ */ jsxRuntime.jsx(ToastContext.Provider, { value: toastContextValue, children: /* @__PURE__ */ jsxRuntime.jsx(MapDropZone, { onDrop: handleDropGeoJSON, onDropFile: handleDropGeoJSONFile, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `map-container w-full h-full min-w-0 relative overflow-hidden isolate ${className || ""}`, "data-testid": "map-editor-canvas", children: [
12714
13413
  /* @__PURE__ */ jsxRuntime.jsx(
12715
13414
  "div",
12716
13415
  {
@@ -13189,18 +13888,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13189
13888
  ))
13190
13889
  }
13191
13890
  ),
13192
- cursorCoords && /* @__PURE__ */ jsxRuntime.jsxs(
13193
- "div",
13194
- {
13195
- className: "absolute bottom-1 right-12 z-10 pointer-events-none font-mono text-[10px] text-muted-foreground/70 select-none",
13196
- "data-testid": "cursor-coordinates",
13197
- children: [
13198
- cursorCoords.lat.toFixed(5),
13199
- ", ",
13200
- cursorCoords.lng.toFixed(5)
13201
- ]
13202
- }
13203
- ),
13891
+ /* @__PURE__ */ jsxRuntime.jsx(CursorCoordinatesOverlay, { map: isMapLoaded ? map.current : null }),
13204
13892
  /* @__PURE__ */ jsxRuntime.jsx(
13205
13893
  "input",
13206
13894
  {
@@ -13964,7 +14652,15 @@ function DebugSidebar({ onAddRandomPoints, onImportKML, onAddDomMarkers, onRemov
13964
14652
  const geojson = parseKMLToGeoJSON(content);
13965
14653
  if (geojson && onImportKML) {
13966
14654
  const layerName = file.name.replace(/\.(kml|kmz)$/i, "");
13967
- onImportKML(layerName, geojson);
14655
+ void getSharedIngestClient().ingest(geojson, { idStrategy: "preserve" }).then((result) => {
14656
+ onImportKML(
14657
+ layerName,
14658
+ result.kind === "features" ? { type: "FeatureCollection", features: result.features } : geojson
14659
+ );
14660
+ }).catch((err) => {
14661
+ console.warn("[map-component] KML ingest normalization failed:", err);
14662
+ onImportKML(layerName, geojson);
14663
+ });
13968
14664
  }
13969
14665
  };
13970
14666
  reader.readAsText(file);