@octostar/map-component 0.2.12 → 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 (44) hide show
  1. package/dist/index.cjs +1171 -639
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +1172 -640
  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/draw-render-gate.d.ts +10 -0
  13. package/dist/types/lib/draw-render-gate.d.ts.map +1 -0
  14. package/dist/types/lib/geojson-crs.d.ts +10 -0
  15. package/dist/types/lib/geojson-crs.d.ts.map +1 -0
  16. package/dist/types/lib/geojson-reproject.d.ts +15 -0
  17. package/dist/types/lib/geojson-reproject.d.ts.map +1 -0
  18. package/dist/types/lib/geojson-serialize.d.ts +21 -0
  19. package/dist/types/lib/geojson-serialize.d.ts.map +1 -0
  20. package/dist/types/lib/ingest-client.d.ts +25 -0
  21. package/dist/types/lib/ingest-client.d.ts.map +1 -0
  22. package/dist/types/lib/ingest-pipeline.d.ts +74 -0
  23. package/dist/types/lib/ingest-pipeline.d.ts.map +1 -0
  24. package/dist/types/lib/ingest.worker.d.ts +2 -0
  25. package/dist/types/lib/ingest.worker.d.ts.map +1 -0
  26. package/dist/types/lib/map-editor-api.d.ts +5 -0
  27. package/dist/types/lib/map-editor-api.d.ts.map +1 -1
  28. package/dist/types/lib/perf-log.d.ts +3 -0
  29. package/dist/types/lib/perf-log.d.ts.map +1 -0
  30. package/dist/types/lib/selection-diff.d.ts +24 -1
  31. package/dist/types/lib/selection-diff.d.ts.map +1 -1
  32. package/dist/types/lib/selection-hit-test.d.ts +25 -14
  33. package/dist/types/lib/selection-hit-test.d.ts.map +1 -1
  34. package/dist/types/lib/selection-spatial-index.d.ts +63 -0
  35. package/dist/types/lib/selection-spatial-index.d.ts.map +1 -0
  36. package/dist/types/lib/temporal-ingest.d.ts +53 -0
  37. package/dist/types/lib/temporal-ingest.d.ts.map +1 -0
  38. package/dist/types/lib/temporal-normalize.d.ts +11 -0
  39. package/dist/types/lib/temporal-normalize.d.ts.map +1 -0
  40. package/dist/types/lib/timeline-diff.d.ts +43 -0
  41. package/dist/types/lib/timeline-diff.d.ts.map +1 -0
  42. package/dist/types/lib/timeline-store.d.ts +1 -9
  43. package/dist/types/lib/timeline-store.d.ts.map +1 -1
  44. package/package.json +5 -4
package/dist/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  import { jsxs, Fragment, jsx } from "react/jsx-runtime";
2
- import { useState, useCallback, useMemo, createContext, useContext, useRef, useEffect, forwardRef, useImperativeHandle } from "react";
2
+ import { useState, useEffect, useCallback, useMemo, createContext, useContext, useRef, forwardRef, useImperativeHandle } from "react";
3
3
  import maplibregl from "maplibre-gl";
4
4
  import MapboxDraw from "@mapbox/mapbox-gl-draw";
5
5
  import * as turf from "@turf/turf";
6
- import proj4 from "proj4";
7
6
  import * as THREE from "three";
7
+ import proj4 from "proj4";
8
8
  import { Button, Modal, Input, App, message, Tooltip, Dropdown, Divider, Popover, Switch, Slider, Tag, Select, Collapse, ColorPicker, Tabs, Card, Table, DatePicker } from "antd";
9
9
  import { clsx } from "clsx";
10
10
  import { twMerge } from "tailwind-merge";
@@ -12,8 +12,475 @@ import { MousePointer2, Square, Hexagon, Circle, MoreVertical, ChevronDown, Filt
12
12
  import { createPortal } from "react-dom";
13
13
  import { format } from "date-fns";
14
14
  import { useStore, createStore } from "zustand";
15
+ import Flatbush from "flatbush";
15
16
  import dayjs from "dayjs";
16
17
  import * as toGeoJSON from "@mapbox/togeojson";
18
+ function detectSourceCRS(geojson) {
19
+ var _a, _b;
20
+ const crsName = (_b = (_a = geojson.crs) == null ? void 0 : _a.properties) == null ? void 0 : _b.name;
21
+ let sourceCRS = null;
22
+ if (crsName) {
23
+ const epsgMatch = crsName.match(/EPSG::?(\d+)/i);
24
+ if (epsgMatch) sourceCRS = `EPSG:${epsgMatch[1]}`;
25
+ }
26
+ if (!sourceCRS && geojson.features.length > 0) {
27
+ const firstCoord = getFirstCoordinate(geojson.features[0].geometry);
28
+ if (firstCoord) {
29
+ const [x, y] = firstCoord;
30
+ if (Math.abs(x) <= 180 && Math.abs(y) <= 90) {
31
+ return { sourceCRS: "EPSG:4326", needsReprojection: false };
32
+ }
33
+ }
34
+ return { sourceCRS: null, needsReprojection: false };
35
+ }
36
+ return { sourceCRS, needsReprojection: sourceCRS !== null && sourceCRS !== "EPSG:4326" };
37
+ }
38
+ function getFirstCoordinate(geometry) {
39
+ var _a, _b, _c;
40
+ if (!geometry) return null;
41
+ switch (geometry.type) {
42
+ case "Point":
43
+ return geometry.coordinates;
44
+ case "MultiPoint":
45
+ case "LineString":
46
+ return geometry.coordinates[0];
47
+ case "MultiLineString":
48
+ case "Polygon":
49
+ return (_a = geometry.coordinates[0]) == null ? void 0 : _a[0];
50
+ case "MultiPolygon":
51
+ return (_c = (_b = geometry.coordinates[0]) == null ? void 0 : _b[0]) == null ? void 0 : _c[0];
52
+ default:
53
+ return null;
54
+ }
55
+ }
56
+ function hasAltitudeData(feature) {
57
+ var _a, _b;
58
+ if (((_a = feature.geometry) == null ? void 0 : _a.type) === "LineString") {
59
+ const coords = feature.geometry.coordinates;
60
+ return coords.some((c) => c.length >= 3 && c[2] !== 0);
61
+ }
62
+ if (((_b = feature.geometry) == null ? void 0 : _b.type) === "MultiLineString") {
63
+ const coords = feature.geometry.coordinates;
64
+ return coords.some((line) => line.some((c) => c.length >= 3 && c[2] !== 0));
65
+ }
66
+ return false;
67
+ }
68
+ const PRETTY_EXPORT_MAX_FEATURES = 1e4;
69
+ const TARGET_PART_CHARS = 8 * 1024 * 1024;
70
+ function featureCollectionBlobParts(collection, options) {
71
+ const prettyMax = PRETTY_EXPORT_MAX_FEATURES;
72
+ if (collection.features.length <= prettyMax) {
73
+ return [JSON.stringify(collection, null, 2)];
74
+ }
75
+ const targetChars = TARGET_PART_CHARS;
76
+ const { features, ...rest } = collection;
77
+ const head = JSON.stringify(rest);
78
+ const parts = [];
79
+ let pending = [];
80
+ let pendingChars = 0;
81
+ const push = (piece) => {
82
+ pending.push(piece);
83
+ pendingChars += piece.length;
84
+ if (pendingChars >= targetChars) {
85
+ parts.push(pending.join(""));
86
+ pending = [];
87
+ pendingChars = 0;
88
+ }
89
+ };
90
+ push(head.slice(0, -1));
91
+ push(head.length > 2 ? ',"features":[' : '"features":[');
92
+ for (let i = 0; i < features.length; i++) {
93
+ push(i === 0 ? JSON.stringify(features[i]) : "," + JSON.stringify(features[i]));
94
+ }
95
+ push("]}");
96
+ if (pending.length > 0) parts.push(pending.join(""));
97
+ return parts;
98
+ }
99
+ const ingestWorkerSource = '"use strict";(()=>{function y(e){let n=e.crs?.properties?.name,t=null;if(n){let r=n.match(/EPSG::?(\\d+)/i);r&&(t=`EPSG:${r[1]}`)}if(!t&&e.features.length>0){let r=D(e.features[0].geometry);if(r){let[o,u]=r;if(Math.abs(o)<=180&&Math.abs(u)<=90)return{sourceCRS:"EPSG:4326",needsReprojection:!1}}return{sourceCRS:null,needsReprojection:!1}}return{sourceCRS:t,needsReprojection:t!==null&&t!=="EPSG:4326"}}function D(e){if(!e)return null;switch(e.type){case"Point":return e.coordinates;case"MultiPoint":case"LineString":return e.coordinates[0];case"MultiLineString":case"Polygon":return e.coordinates[0]?.[0];case"MultiPolygon":return e.coordinates[0]?.[0]?.[0];default:return null}}function b(e){return e.geometry?.type==="LineString"?e.geometry.coordinates.some(t=>t.length>=3&&t[2]!==0):e.geometry?.type==="MultiLineString"?e.geometry.coordinates.some(t=>t.some(r=>r.length>=3&&r[2]!==0)):!1}function a(e){if(!e)return null;if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let n=new Date(e);return isNaN(n.getTime())?null:n}return null}function p(e){return!!(e.startDate||e.startdate||e.start_date||e.start_time||e.date||e.timestamp||e.flightDate||e.time||e.datetime||e.endDate||e.enddate||e.end_date||e.end_time)}function S(e){let n=a(e.startDate)||a(e.startdate)||a(e.start_date)||a(e.start_time)||a(e.date)||a(e.timestamp)||a(e.flightDate)||a(e.time)||a(e.datetime),t=a(e.endDate)||a(e.enddate)||a(e.end_date)||a(e.end_time);return n&&t&&t<n&&([n,t]=[t,n]),{startDate:n,endDate:t}}function x(){let e=globalThis.crypto?.randomUUID?.bind(globalThis.crypto);return e?e():`f-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function G(e,n,t){switch(t.idStrategy){case"preserve":return e.id;case"layer-index":return e.id!==void 0&&e.id!==null?String(e.id):`${t.layerId}-f${n}`;case"uuid-fallback":return e.id?String(e.id):x()}}function I(e,n){if(Array.isArray(e)){if(typeof e[0]=="number"){let t=e[0],r=e[1];n[0]=Math.min(n[0],t),n[1]=Math.min(n[1],r),n[2]=Math.max(n[2],t),n[3]=Math.max(n[3],r);return}for(let t of e)I(t,n)}}function h(e,n){if(e){if(e.type==="GeometryCollection"){for(let t of e.geometries)h(t,n);return}I(e.coordinates,n)}}function O(e){let n=[1/0,1/0,-1/0,-1/0];for(let t of e)h(t.geometry,n);return n.every(t=>isFinite(t))?n:null}function k(e,n){let t;if(e.type==="text")try{t=JSON.parse(e.text)}catch(s){return{kind:"error",code:"parse-error",message:s instanceof Error?s.message:"Invalid file"}}else t=e.data;if(t&&t.type==="Feature"&&(t={type:"FeatureCollection",features:[t]}),!t||t.type!=="FeatureCollection"||!Array.isArray(t.features))return{kind:"error",code:"invalid-format",message:"Invalid GeoJSON format"};if(n.emptyIsError&&t.features.length===0)return{kind:"error",code:"empty",message:"The file contains no features"};if(t["octostar:map"])return{kind:"enriched",data:t};let{sourceCRS:r,needsReprojection:o}=y(t),u=!1,l=!1,i=[];t.features.forEach((s,C)=>{let m=G(s,C,n);!l&&b(s)&&(l=!0);let d=s.properties||{};if(!p(d)){i.push(n.idStrategy==="preserve"?s:{...s,id:m});return}let{startDate:f,endDate:g}=S(d);(f||g)&&(u=!0),i.push({...s,id:m,properties:{...d,startDate:f?.toISOString()||null,endDate:g?.toISOString()||null}})});let c=t.properties?.layerMetadata;return{kind:"features",features:i,featureCount:i.length,bbox:O(i),hasTemporal:u,hasAltitude:l,reprojected:!1,sourceCRS:r,...o&&{needsReprojection:o},...c&&{layerMetadata:c}}}var R=e=>self.postMessage(e);self.onmessage=async e=>{let{id:n,source:t,options:r}=e.data;try{let o=t.type==="blob"?{type:"text",text:await t.blob.text()}:t;R({id:n,ok:!0,result:k(o,r)})}catch(o){R({id:n,ok:!1,error:o instanceof Error?o.message:String(o)})}};})();\n';
100
+ proj4.defs("EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs");
101
+ proj4.defs("EPSG:3857", "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs");
102
+ proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
103
+ proj4.defs("EPSG:32631", "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs");
104
+ function reprojectFeatures(features, sourceCRS) {
105
+ if (!proj4.defs(sourceCRS)) return null;
106
+ try {
107
+ return features.map((feature) => ({
108
+ ...feature,
109
+ geometry: reprojectGeometry(feature.geometry, sourceCRS)
110
+ }));
111
+ } catch (e) {
112
+ console.error("Reprojection failed:", e);
113
+ return null;
114
+ }
115
+ }
116
+ function reprojectGeometry(geometry, fromCRS) {
117
+ if (!geometry) return geometry;
118
+ const transform = (coord) => {
119
+ const [x, y] = proj4(fromCRS, "EPSG:4326", [coord[0], coord[1]]);
120
+ return coord.length > 2 ? [x, y, ...coord.slice(2)] : [x, y];
121
+ };
122
+ const reprojectCoords = (coords) => {
123
+ if (typeof coords[0] === "number") {
124
+ return transform(coords);
125
+ }
126
+ return coords.map(reprojectCoords);
127
+ };
128
+ if (geometry.type === "GeometryCollection") {
129
+ return {
130
+ type: "GeometryCollection",
131
+ geometries: geometry.geometries.map((g) => reprojectGeometry(g, fromCRS))
132
+ };
133
+ }
134
+ const geomWithCoords = geometry;
135
+ return {
136
+ ...geomWithCoords,
137
+ coordinates: reprojectCoords(geomWithCoords.coordinates)
138
+ };
139
+ }
140
+ function parseDate(value) {
141
+ if (!value) return null;
142
+ if (value instanceof Date) return value;
143
+ if (typeof value === "string" || typeof value === "number") {
144
+ const date = new Date(value);
145
+ return isNaN(date.getTime()) ? null : date;
146
+ }
147
+ return null;
148
+ }
149
+ function hasAnyTemporalValue(properties) {
150
+ return !!(properties.startDate || properties.startdate || properties.start_date || properties.start_time || properties.date || properties.timestamp || properties.flightDate || properties.time || properties.datetime || properties.endDate || properties.enddate || properties.end_date || properties.end_time);
151
+ }
152
+ function normalizeTemporalProperties(properties) {
153
+ let startDate = parseDate(properties.startDate) || parseDate(properties.startdate) || parseDate(properties.start_date) || parseDate(properties.start_time) || parseDate(properties.date) || parseDate(properties.timestamp) || parseDate(properties.flightDate) || parseDate(properties.time) || parseDate(properties.datetime);
154
+ let endDate = parseDate(properties.endDate) || parseDate(properties.enddate) || parseDate(properties.end_date) || parseDate(properties.end_time);
155
+ if (startDate && endDate && endDate < startDate) {
156
+ [startDate, endDate] = [endDate, startDate];
157
+ }
158
+ return { startDate, endDate };
159
+ }
160
+ function generateUuid() {
161
+ var _a, _b;
162
+ const uuid = (_b = (_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) == null ? void 0 : _b.bind(globalThis.crypto);
163
+ return uuid ? uuid() : `f-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
164
+ }
165
+ function assignId(feature, index, options) {
166
+ switch (options.idStrategy) {
167
+ case "preserve":
168
+ return feature.id;
169
+ case "layer-index":
170
+ return feature.id !== void 0 && feature.id !== null ? String(feature.id) : `${options.layerId}-f${index}`;
171
+ case "uuid-fallback":
172
+ return feature.id ? String(feature.id) : generateUuid();
173
+ }
174
+ }
175
+ function scanCoords(coords, box) {
176
+ if (!Array.isArray(coords)) return;
177
+ if (typeof coords[0] === "number") {
178
+ const x = coords[0];
179
+ const y = coords[1];
180
+ box[0] = Math.min(box[0], x);
181
+ box[1] = Math.min(box[1], y);
182
+ box[2] = Math.max(box[2], x);
183
+ box[3] = Math.max(box[3], y);
184
+ return;
185
+ }
186
+ for (const c of coords) scanCoords(c, box);
187
+ }
188
+ function scanGeometry(geometry, box) {
189
+ if (!geometry) return;
190
+ if (geometry.type === "GeometryCollection") {
191
+ for (const g of geometry.geometries) scanGeometry(g, box);
192
+ return;
193
+ }
194
+ scanCoords(geometry.coordinates, box);
195
+ }
196
+ function computeFeatureCollectionBbox(features) {
197
+ const box = [Infinity, Infinity, -Infinity, -Infinity];
198
+ for (const f of features) scanGeometry(f.geometry, box);
199
+ return box.every((v) => isFinite(v)) ? box : null;
200
+ }
201
+ function runIngestPipeline(source, options) {
202
+ var _a;
203
+ let data;
204
+ if (source.type === "text") {
205
+ try {
206
+ data = JSON.parse(source.text);
207
+ } catch (err) {
208
+ return {
209
+ kind: "error",
210
+ code: "parse-error",
211
+ message: err instanceof Error ? err.message : "Invalid file"
212
+ };
213
+ }
214
+ } else {
215
+ data = source.data;
216
+ }
217
+ if (data && data.type === "Feature") {
218
+ data = {
219
+ type: "FeatureCollection",
220
+ features: [data]
221
+ };
222
+ }
223
+ if (!data || data.type !== "FeatureCollection" || !Array.isArray(data.features)) {
224
+ return { kind: "error", code: "invalid-format", message: "Invalid GeoJSON format" };
225
+ }
226
+ if (options.emptyIsError && data.features.length === 0) {
227
+ return { kind: "error", code: "empty", message: "The file contains no features" };
228
+ }
229
+ if (data["octostar:map"]) {
230
+ return { kind: "enriched", data };
231
+ }
232
+ const { sourceCRS, needsReprojection } = detectSourceCRS(data);
233
+ let hasTemporal = false;
234
+ let hasAltitude = false;
235
+ const features = [];
236
+ data.features.forEach((f, index) => {
237
+ const id = assignId(f, index, options);
238
+ if (!hasAltitude && hasAltitudeData(f)) hasAltitude = true;
239
+ const props = f.properties || {};
240
+ if (!hasAnyTemporalValue(props)) {
241
+ features.push(options.idStrategy === "preserve" ? f : { ...f, id });
242
+ return;
243
+ }
244
+ const { startDate, endDate } = normalizeTemporalProperties(props);
245
+ if (startDate || endDate) hasTemporal = true;
246
+ features.push({
247
+ ...f,
248
+ id,
249
+ properties: {
250
+ ...props,
251
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
252
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
253
+ }
254
+ });
255
+ });
256
+ const layerMetadata = (_a = data.properties) == null ? void 0 : _a.layerMetadata;
257
+ return {
258
+ kind: "features",
259
+ features,
260
+ featureCount: features.length,
261
+ bbox: computeFeatureCollectionBbox(features),
262
+ hasTemporal,
263
+ hasAltitude,
264
+ reprojected: false,
265
+ sourceCRS,
266
+ ...needsReprojection && { needsReprojection },
267
+ ...layerMetadata && { layerMetadata }
268
+ };
269
+ }
270
+ const fromStorage = (() => {
271
+ var _a;
272
+ try {
273
+ return ((_a = globalThis.localStorage) == null ? void 0 : _a.getItem("octostar-map-perf-log")) === "1";
274
+ } catch {
275
+ return false;
276
+ }
277
+ })();
278
+ function mapPerfLogEnabled() {
279
+ return fromStorage || globalThis.__octostarMapPerfLog === true;
280
+ }
281
+ function mapPerfLog(area, message2, data) {
282
+ if (!mapPerfLogEnabled()) return;
283
+ if (data === void 0) {
284
+ console.info(`[map-perf:${area}] ${message2}`);
285
+ } else {
286
+ console.info(`[map-perf:${area}] ${message2}`, data);
287
+ }
288
+ }
289
+ function finalizeReprojection(result) {
290
+ if (result.kind !== "features" || !result.needsReprojection || !result.sourceCRS) return result;
291
+ const reprojected = reprojectFeatures(result.features, result.sourceCRS);
292
+ if (!reprojected) {
293
+ return { ...result, needsReprojection: false };
294
+ }
295
+ return {
296
+ ...result,
297
+ features: reprojected,
298
+ reprojected: true,
299
+ needsReprojection: false,
300
+ bbox: computeFeatureCollectionBbox(reprojected)
301
+ };
302
+ }
303
+ function createWorkerPort() {
304
+ if (typeof Worker === "undefined") {
305
+ mapPerfLog("ingest", "Worker unavailable in this environment — using main-thread pipeline");
306
+ return null;
307
+ }
308
+ let url = null;
309
+ try {
310
+ url = URL.createObjectURL(new Blob([ingestWorkerSource], { type: "text/javascript" }));
311
+ const worker = new Worker(url);
312
+ let pendingUrl = url;
313
+ const revokePendingUrl = () => {
314
+ if (pendingUrl) URL.revokeObjectURL(pendingUrl);
315
+ pendingUrl = null;
316
+ };
317
+ mapPerfLog("ingest", "worker spawned");
318
+ return {
319
+ post: (msg) => worker.postMessage(msg),
320
+ onMessage: (cb) => {
321
+ worker.onmessage = (e) => {
322
+ revokePendingUrl();
323
+ cb(e.data);
324
+ };
325
+ },
326
+ onError: (cb) => {
327
+ worker.onerror = (e) => {
328
+ revokePendingUrl();
329
+ cb(e);
330
+ };
331
+ worker.onmessageerror = (e) => cb(e);
332
+ },
333
+ terminate: () => {
334
+ revokePendingUrl();
335
+ worker.terminate();
336
+ }
337
+ };
338
+ } catch (err) {
339
+ if (url) URL.revokeObjectURL(url);
340
+ console.warn(
341
+ "[map-component] Ingest worker could not be spawned (CSP may block blob: workers); file parsing will run on the main thread.",
342
+ err
343
+ );
344
+ return null;
345
+ }
346
+ }
347
+ const INGEST_TIMEOUT_MS = 12e4;
348
+ function createIngestClient(portFactory = createWorkerPort) {
349
+ let port = null;
350
+ let portUnavailable = false;
351
+ let nextId = 0;
352
+ const pending = /* @__PURE__ */ new Map();
353
+ const rejectAllPending = (reason) => {
354
+ pending.forEach((request) => {
355
+ clearTimeout(request.timeout);
356
+ request.reject(new Error(reason));
357
+ });
358
+ pending.clear();
359
+ };
360
+ const abandonPort = (reason) => {
361
+ rejectAllPending(reason);
362
+ port == null ? void 0 : port.terminate();
363
+ port = null;
364
+ };
365
+ const ensurePort = () => {
366
+ if (portUnavailable || port) return port;
367
+ try {
368
+ port = portFactory();
369
+ } catch {
370
+ port = null;
371
+ }
372
+ if (!port) {
373
+ portUnavailable = true;
374
+ return null;
375
+ }
376
+ port.onMessage((msg) => {
377
+ const request = pending.get(msg.id);
378
+ if (!request) return;
379
+ pending.delete(msg.id);
380
+ clearTimeout(request.timeout);
381
+ mapPerfLog("ingest", `worker request "${request.label}" finished`, {
382
+ ms: Math.round(performance.now() - request.startedAt),
383
+ ok: msg.ok
384
+ });
385
+ if (msg.ok) {
386
+ request.resolve(finalizeReprojection(msg.result));
387
+ } else {
388
+ request.reject(new Error(msg.error));
389
+ }
390
+ });
391
+ port.onError((err) => {
392
+ console.warn("[map-component] Ingest worker crashed; it will be respawned on next use.", err);
393
+ abandonPort("Ingest worker crashed");
394
+ });
395
+ return port;
396
+ };
397
+ const runInline = async (input, options) => {
398
+ const text = typeof input === "string" ? input : await input.text();
399
+ const startedAt = performance.now();
400
+ const result = finalizeReprojection(runIngestPipeline({ type: "text", text }, options));
401
+ mapPerfLog("ingest", "main-thread pipeline finished (no worker)", {
402
+ ms: Math.round(performance.now() - startedAt)
403
+ });
404
+ return result;
405
+ };
406
+ return {
407
+ ingest(input, options) {
408
+ if (typeof input === "object" && !(input instanceof Blob)) {
409
+ return Promise.resolve().then(
410
+ () => finalizeReprojection(runIngestPipeline({ type: "parsed", data: input }, options))
411
+ );
412
+ }
413
+ const activePort = ensurePort();
414
+ if (!activePort) return runInline(input, options);
415
+ const id = nextId++;
416
+ const label = input instanceof File ? input.name : typeof input === "string" ? "text" : "blob";
417
+ return new Promise((resolve, reject) => {
418
+ const timeout = setTimeout(() => {
419
+ console.warn(
420
+ `[map-component] Ingest worker unresponsive for "${label}" after ${INGEST_TIMEOUT_MS}ms; it will be respawned on next use.`
421
+ );
422
+ abandonPort("Ingest worker unresponsive — the file could not be parsed");
423
+ }, INGEST_TIMEOUT_MS);
424
+ pending.set(id, { resolve, reject, startedAt: performance.now(), label, timeout });
425
+ activePort.post({
426
+ id,
427
+ source: typeof input === "string" ? { type: "text", text: input } : { type: "blob", blob: input },
428
+ options
429
+ });
430
+ });
431
+ },
432
+ dispose() {
433
+ abandonPort("Ingest client disposed");
434
+ portUnavailable = false;
435
+ }
436
+ };
437
+ }
438
+ let sharedClient = null;
439
+ function getSharedIngestClient() {
440
+ if (!sharedClient) sharedClient = createIngestClient();
441
+ return sharedClient;
442
+ }
443
+ function CursorCoordinatesOverlay({ map }) {
444
+ const [coords, setCoords] = useState(null);
445
+ useEffect(() => {
446
+ if (!map) return;
447
+ let pending = null;
448
+ let frame = 0;
449
+ const flush = () => {
450
+ frame = 0;
451
+ setCoords(pending);
452
+ };
453
+ const schedule = (next) => {
454
+ pending = next;
455
+ if (!frame) frame = requestAnimationFrame(flush);
456
+ };
457
+ const onMove = (e) => schedule({ lng: e.lngLat.lng, lat: e.lngLat.lat });
458
+ const onOut = () => schedule(null);
459
+ map.on("mousemove", onMove);
460
+ map.on("mouseout", onOut);
461
+ return () => {
462
+ if (frame) cancelAnimationFrame(frame);
463
+ try {
464
+ map.off("mousemove", onMove);
465
+ map.off("mouseout", onOut);
466
+ } catch {
467
+ }
468
+ };
469
+ }, [map]);
470
+ if (!coords) return null;
471
+ return /* @__PURE__ */ jsxs(
472
+ "div",
473
+ {
474
+ className: "absolute bottom-1 right-12 z-10 pointer-events-none font-mono text-[10px] text-muted-foreground/70 select-none",
475
+ "data-testid": "cursor-coordinates",
476
+ children: [
477
+ coords.lat.toFixed(5),
478
+ ", ",
479
+ coords.lng.toFixed(5)
480
+ ]
481
+ }
482
+ );
483
+ }
17
484
  const ICONS = [
18
485
  // Location & Places
19
486
  { id: "map-pin", emoji: "📍", name: "Map Pin", category: "places" },
@@ -4503,26 +4970,6 @@ function StatusIndicator({ featureCount, selectedCount = 0 }) {
4503
4970
  }
4504
4971
  );
4505
4972
  }
4506
- function parseDate(value) {
4507
- if (!value) return null;
4508
- if (value instanceof Date) return value;
4509
- if (typeof value === "string" || typeof value === "number") {
4510
- const date = new Date(value);
4511
- return isNaN(date.getTime()) ? null : date;
4512
- }
4513
- return null;
4514
- }
4515
- function hasAnyTemporalValue(properties) {
4516
- return !!(properties.startDate || properties.startdate || properties.start_date || properties.start_time || properties.date || properties.timestamp || properties.flightDate || properties.time || properties.datetime || properties.endDate || properties.enddate || properties.end_date || properties.end_time);
4517
- }
4518
- function normalizeTemporalProperties(properties) {
4519
- let startDate = parseDate(properties.startDate) || parseDate(properties.startdate) || parseDate(properties.start_date) || parseDate(properties.start_time) || parseDate(properties.date) || parseDate(properties.timestamp) || parseDate(properties.flightDate) || parseDate(properties.time) || parseDate(properties.datetime);
4520
- let endDate = parseDate(properties.endDate) || parseDate(properties.enddate) || parseDate(properties.end_date) || parseDate(properties.end_time);
4521
- if (startDate && endDate && endDate < startDate) {
4522
- [startDate, endDate] = [endDate, startDate];
4523
- }
4524
- return { startDate, endDate };
4525
- }
4526
4973
  function isFeatureInRange(feature, rangeStart, rangeEnd) {
4527
4974
  if (!feature.startDate && !feature.endDate) return true;
4528
4975
  if (!rangeStart || !rangeEnd) return true;
@@ -4616,7 +5063,8 @@ const timelineStoreInitializer = (set, get) => ({
4616
5063
  const computedMax = maxDate;
4617
5064
  const sameFeatureIds = state.temporalFeatures.length === timedFeatures.length && timedFeatures.every((f, i) => f.id === state.temporalFeatures[i].id);
4618
5065
  const sameDates = ((_a = state.globalMinDate) == null ? void 0 : _a.getTime()) === (computedMin == null ? void 0 : computedMin.getTime()) && ((_b = state.globalMaxDate) == null ? void 0 : _b.getTime()) === (computedMax == null ? void 0 : computedMax.getTime());
4619
- if (sameFeatureIds && sameDates && state.hasTemporalData) return;
5066
+ const sameUntimed = state.untimedFeatureIds.length === untimedIds.length && untimedIds.every((id, i) => id === state.untimedFeatureIds[i]);
5067
+ if (sameFeatureIds && sameDates && sameUntimed && state.hasTemporalData) return;
4620
5068
  const histogramBins = minDate && maxDate ? computeHistogramBins(timedFeatures, minDate, maxDate) : [];
4621
5069
  set({
4622
5070
  hasTemporalData: true,
@@ -5141,7 +5589,7 @@ function Timebar({ onFilterChange, selectedFeatureIds = [], selectedFeatureColor
5141
5589
  }
5142
5590
  );
5143
5591
  }
5144
- function MapDropZone({ onDrop, children }) {
5592
+ function MapDropZone({ onDrop, onDropFile, children }) {
5145
5593
  const [isDragOver, setIsDragOver] = useState(false);
5146
5594
  const handleDragOver = useCallback((e) => {
5147
5595
  e.preventDefault();
@@ -5176,13 +5624,17 @@ function MapDropZone({ onDrop, children }) {
5176
5624
  for (let i = 0; i < files.length; i++) {
5177
5625
  const file = files[i];
5178
5626
  if (!file.name.match(/\.(geojson|json)$/i)) continue;
5627
+ const name = file.name.replace(/\.(geojson|json)$/i, "");
5628
+ if (onDropFile) {
5629
+ onDropFile(name, file);
5630
+ continue;
5631
+ }
5179
5632
  const reader = new FileReader();
5180
5633
  reader.onload = (evt) => {
5181
5634
  var _a;
5182
5635
  try {
5183
5636
  const parsed = JSON.parse((_a = evt.target) == null ? void 0 : _a.result);
5184
5637
  if (parsed.type === "FeatureCollection" && Array.isArray(parsed.features)) {
5185
- const name = file.name.replace(/\.(geojson|json)$/i, "");
5186
5638
  onDrop(name, parsed);
5187
5639
  }
5188
5640
  } catch (err) {
@@ -5192,7 +5644,7 @@ function MapDropZone({ onDrop, children }) {
5192
5644
  reader.readAsText(file);
5193
5645
  }
5194
5646
  }
5195
- }, [onDrop]);
5647
+ }, [onDrop, onDropFile]);
5196
5648
  return /* @__PURE__ */ jsxs(
5197
5649
  "div",
5198
5650
  {
@@ -5430,15 +5882,20 @@ function createRafCoalescer(run, scheduler = rafScheduler) {
5430
5882
  };
5431
5883
  }
5432
5884
  const DEFAULT_LABEL_PRIORITY = 100;
5885
+ const DEFAULT_VISIBLE_STROKE_OPACITY = 1;
5886
+ const DEFAULT_VISIBLE_FILL_OPACITY = 0.2;
5433
5887
  function createSelectionPaintCache() {
5434
5888
  return {
5435
5889
  presentIds: /* @__PURE__ */ new Set(),
5436
5890
  appliedSelectedIds: /* @__PURE__ */ new Set(),
5437
5891
  basePriorityById: /* @__PURE__ */ new Map(),
5892
+ appliedHiddenIds: /* @__PURE__ */ new Set(),
5893
+ visibleStrokeOpacityById: /* @__PURE__ */ new Map(),
5894
+ visibleFillOpacityById: /* @__PURE__ */ new Map(),
5438
5895
  updatable: true
5439
5896
  };
5440
5897
  }
5441
- function recordPaintedFeature(cache, featureId, basePriority, isSelected) {
5898
+ function recordPaintedFeature(cache, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
5442
5899
  if (cache.presentIds.has(featureId)) {
5443
5900
  cache.updatable = false;
5444
5901
  } else {
@@ -5446,6 +5903,13 @@ function recordPaintedFeature(cache, featureId, basePriority, isSelected) {
5446
5903
  }
5447
5904
  cache.basePriorityById.set(featureId, basePriority);
5448
5905
  if (isSelected) cache.appliedSelectedIds.add(featureId);
5906
+ if (visibleStrokeOpacity !== DEFAULT_VISIBLE_STROKE_OPACITY) {
5907
+ cache.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
5908
+ }
5909
+ if (visibleFillOpacity !== DEFAULT_VISIBLE_FILL_OPACITY) {
5910
+ cache.visibleFillOpacityById.set(featureId, visibleFillOpacity);
5911
+ }
5912
+ if (isTimelineHidden) cache.appliedHiddenIds.add(featureId);
5449
5913
  }
5450
5914
  function applySelectionFastPath(cache, nextSelectedIds, source) {
5451
5915
  if (!cache || !cache.updatable || !source) return false;
@@ -5493,6 +5957,49 @@ function buildSelectionDiff(cache, nextSelectedIds) {
5493
5957
  });
5494
5958
  return update.length > 0 ? { update } : null;
5495
5959
  }
5960
+ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
5961
+ const update = [];
5962
+ const nextHiddenIds = /* @__PURE__ */ new Set();
5963
+ cache.presentIds.forEach((id) => {
5964
+ const nextHidden = nextVisibleSet !== null && !nextVisibleSet.has(id);
5965
+ if (nextHidden) nextHiddenIds.add(id);
5966
+ if (nextHidden === cache.appliedHiddenIds.has(id)) return;
5967
+ if (nextHidden) {
5968
+ update.push({
5969
+ id,
5970
+ addOrUpdateProperties: [
5971
+ { key: "stroke-opacity", value: 0 },
5972
+ { key: "fill-opacity", value: 0 },
5973
+ { key: "isTimelineHidden", value: 1 }
5974
+ ]
5975
+ });
5976
+ } else {
5977
+ update.push({
5978
+ id,
5979
+ addOrUpdateProperties: [
5980
+ { key: "stroke-opacity", value: cache.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
5981
+ { key: "fill-opacity", value: cache.visibleFillOpacityById.get(id) ?? DEFAULT_VISIBLE_FILL_OPACITY },
5982
+ { key: "isTimelineHidden", value: 0 }
5983
+ ]
5984
+ });
5985
+ }
5986
+ });
5987
+ return { diff: update.length > 0 ? { update } : null, nextHiddenIds };
5988
+ }
5989
+ function applyTimelineFastPath(cache, nextVisibleSet, source) {
5990
+ var _a;
5991
+ if (!cache || !cache.updatable || !source) return { applied: false, toggled: 0 };
5992
+ const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache, nextVisibleSet);
5993
+ if (diff) {
5994
+ try {
5995
+ source.updateData(diff);
5996
+ } catch {
5997
+ return { applied: false, toggled: 0 };
5998
+ }
5999
+ }
6000
+ cache.appliedHiddenIds = nextHiddenIds;
6001
+ return { applied: true, toggled: ((_a = diff == null ? void 0 : diff.update) == null ? void 0 : _a.length) ?? 0 };
6002
+ }
5496
6003
  function deepClone(value) {
5497
6004
  try {
5498
6005
  return structuredClone(value);
@@ -5545,15 +6052,80 @@ function geometryEquals(a, b) {
5545
6052
  b.coordinates
5546
6053
  );
5547
6054
  }
5548
- function collectVisibleFeatureGroups(drawFeatures, readOnlyByLayer, layers) {
5549
- const groups = [];
5550
- if (drawFeatures) groups.push(drawFeatures);
5551
- const layerById = new Map(layers.map((l) => [l.id, l]));
5552
- readOnlyByLayer.forEach((features, layerId) => {
5553
- var _a;
5554
- if ((_a = layerById.get(layerId)) == null ? void 0 : _a.visible) groups.push(features);
5555
- });
5556
- return groups;
6055
+ function prepareFeaturesForLayer(input, caller) {
6056
+ const logging = mapPerfLogEnabled();
6057
+ const started = logging ? performance.now() : 0;
6058
+ const count = input.length;
6059
+ const features = new Array(count);
6060
+ const featureIds = new Array(count);
6061
+ let hasTemporal = false;
6062
+ let temporalCount = 0;
6063
+ let reused = 0;
6064
+ for (let i = 0; i < count; i++) {
6065
+ const f = input[i];
6066
+ const props = f.properties || {};
6067
+ if (!hasAnyTemporalValue(props)) {
6068
+ if (typeof f.id === "string" && f.id) {
6069
+ features[i] = f;
6070
+ featureIds[i] = f.id;
6071
+ reused++;
6072
+ } else {
6073
+ const id2 = f.id ? String(f.id) : crypto.randomUUID();
6074
+ features[i] = { ...f, id: id2 };
6075
+ featureIds[i] = id2;
6076
+ }
6077
+ continue;
6078
+ }
6079
+ const id = f.id ? String(f.id) : crypto.randomUUID();
6080
+ featureIds[i] = id;
6081
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6082
+ if (startDate || endDate) hasTemporal = true;
6083
+ temporalCount++;
6084
+ features[i] = {
6085
+ ...f,
6086
+ id,
6087
+ properties: {
6088
+ ...props,
6089
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
6090
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
6091
+ }
6092
+ };
6093
+ }
6094
+ if (logging) {
6095
+ mapPerfLog("normalize", `${caller ?? "prepareFeaturesForLayer"} normalized ${count} features`, {
6096
+ ms: Math.round((performance.now() - started) * 10) / 10,
6097
+ withTemporalKeys: temporalCount,
6098
+ hasTemporal,
6099
+ reused,
6100
+ copied: count - reused
6101
+ });
6102
+ }
6103
+ return { features, featureIds, hasTemporal };
6104
+ }
6105
+ function scanTemporalFeatures(features, resolveLayerId, out) {
6106
+ let foundTemporal = false;
6107
+ for (let i = 0; i < features.length; i++) {
6108
+ const feature = features[i];
6109
+ const id = feature.id;
6110
+ const props = feature.properties || {};
6111
+ if (!hasAnyTemporalValue(props)) {
6112
+ out.untimedIds.push(id);
6113
+ continue;
6114
+ }
6115
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6116
+ if (startDate || endDate) {
6117
+ out.temporal.push({ id, startDate, endDate, layerId: resolveLayerId(id) });
6118
+ foundTemporal = true;
6119
+ } else {
6120
+ out.untimedIds.push(id);
6121
+ }
6122
+ }
6123
+ return foundTemporal;
6124
+ }
6125
+ function shouldDiffDrawRender({ mode, pointerDown, hasSelection }) {
6126
+ if (mode === "view_select") return false;
6127
+ if (mode === "simple_select" || mode === "direct_select") return pointerDown && hasSelection;
6128
+ return true;
5557
6129
  }
5558
6130
  function extendBounds(bounds, coords) {
5559
6131
  if (!Array.isArray(coords) || coords.length === 0) return;
@@ -5579,29 +6151,106 @@ function boundsDisjoint(a, b) {
5579
6151
  function pointInBounds(lng, lat, b) {
5580
6152
  return lng >= b.minLng && lng <= b.maxLng && lat >= b.minLat && lat <= b.maxLat;
5581
6153
  }
6154
+ function buildGroupSpatialIndex(features) {
6155
+ var _a;
6156
+ const boxes = [];
6157
+ const positions = [];
6158
+ for (let p = 0; p < features.length; p++) {
6159
+ const geom = (_a = features[p]) == null ? void 0 : _a.geometry;
6160
+ const b = computeBounds(geom == null ? void 0 : geom.coordinates);
6161
+ if (!isFinite(b.minLng) || !isFinite(b.minLat) || !isFinite(b.maxLng) || !isFinite(b.maxLat)) {
6162
+ continue;
6163
+ }
6164
+ boxes.push(b.minLng, b.minLat, b.maxLng, b.maxLat);
6165
+ positions.push(p);
6166
+ }
6167
+ if (positions.length === 0) {
6168
+ return { tree: null, positions, size: features.length };
6169
+ }
6170
+ const startedAt = performance.now();
6171
+ const tree = new Flatbush(positions.length);
6172
+ for (let i = 0; i < boxes.length; i += 4) {
6173
+ tree.add(boxes[i], boxes[i + 1], boxes[i + 2], boxes[i + 3]);
6174
+ }
6175
+ tree.finish();
6176
+ mapPerfLog("spatial-index", "built group index", {
6177
+ indexed: positions.length,
6178
+ of: features.length,
6179
+ ms: Math.round(performance.now() - startedAt)
6180
+ });
6181
+ return { tree, positions, size: features.length };
6182
+ }
6183
+ const indexCache = /* @__PURE__ */ new WeakMap();
6184
+ const failedBuilds = /* @__PURE__ */ new WeakSet();
6185
+ function getGroupSpatialIndex(features) {
6186
+ if (failedBuilds.has(features)) return void 0;
6187
+ let index = indexCache.get(features);
6188
+ if (!index) {
6189
+ try {
6190
+ index = buildGroupSpatialIndex(features);
6191
+ } catch {
6192
+ failedBuilds.add(features);
6193
+ return void 0;
6194
+ }
6195
+ indexCache.set(features, index);
6196
+ }
6197
+ return index;
6198
+ }
6199
+ function queryCandidatePositions(index, bounds) {
6200
+ if (!index.tree) return [];
6201
+ const items = index.tree.search(bounds.minLng, bounds.minLat, bounds.maxLng, bounds.maxLat);
6202
+ const positions = items.map((i) => index.positions[i]);
6203
+ positions.sort((a, b) => a - b);
6204
+ return positions;
6205
+ }
6206
+ function collectVisibleFeatureGroups(drawFeatures, readOnlyByLayer, layers) {
6207
+ const groups = [];
6208
+ if (drawFeatures) groups.push({ features: drawFeatures });
6209
+ const layerById = new Map(layers.map((l) => [l.id, l]));
6210
+ readOnlyByLayer.forEach((features, layerId) => {
6211
+ var _a;
6212
+ if ((_a = layerById.get(layerId)) == null ? void 0 : _a.visible) {
6213
+ groups.push({ features, index: getGroupSpatialIndex(features) });
6214
+ }
6215
+ });
6216
+ return groups;
6217
+ }
6218
+ function featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) {
6219
+ const geom = feature.geometry;
6220
+ if ((geom == null ? void 0 : geom.type) === "Point") {
6221
+ const lng = geom.coordinates[0];
6222
+ const lat = geom.coordinates[1];
6223
+ return typeof lng === "number" && typeof lat === "number" && pointInBounds(lng, lat, selectionBounds) && (rectExactForPoints || turf.booleanPointInPolygon(geom.coordinates, selectionPolygon));
6224
+ }
6225
+ if ((geom == null ? void 0 : geom.type) === "LineString" || (geom == null ? void 0 : geom.type) === "Polygon" || (geom == null ? void 0 : geom.type) === "MultiPoint" || (geom == null ? void 0 : geom.type) === "MultiLineString" || (geom == null ? void 0 : geom.type) === "MultiPolygon") {
6226
+ return !boundsDisjoint(computeBounds(geom.coordinates), selectionBounds) && turf.booleanIntersects(feature, selectionPolygon);
6227
+ }
6228
+ return false;
6229
+ }
5582
6230
  function hitTestSelection(featureGroups, selectionPolygon, options) {
5583
6231
  const selectionBounds = computeBounds(selectionPolygon.geometry.coordinates);
5584
6232
  const rectExactForPoints = (options == null ? void 0 : options.axisAlignedRectangle) === true;
5585
6233
  const selectedIds = [];
5586
- for (const features of featureGroups) {
5587
- for (const feature of features) {
6234
+ let visited = 0;
6235
+ let total = 0;
6236
+ for (const group of featureGroups) {
6237
+ const { features, index } = group;
6238
+ total += features.length;
6239
+ const useIndex = index !== void 0 && index.size === features.length;
6240
+ const candidates = useIndex ? queryCandidatePositions(index, selectionBounds) : null;
6241
+ const count = candidates ? candidates.length : features.length;
6242
+ visited += count;
6243
+ for (let i = 0; i < count; i++) {
6244
+ const feature = candidates ? features[candidates[i]] : features[i];
5588
6245
  try {
5589
- const geom = feature.geometry;
5590
- let isInside = false;
5591
- if ((geom == null ? void 0 : geom.type) === "Point") {
5592
- const lng = geom.coordinates[0];
5593
- const lat = geom.coordinates[1];
5594
- isInside = typeof lng === "number" && typeof lat === "number" && pointInBounds(lng, lat, selectionBounds) && (rectExactForPoints || turf.booleanPointInPolygon(geom.coordinates, selectionPolygon));
5595
- } else 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") {
5596
- isInside = !boundsDisjoint(computeBounds(geom.coordinates), selectionBounds) && turf.booleanIntersects(feature, selectionPolygon);
5597
- }
5598
- if (isInside && feature.id) {
6246
+ if (featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) && feature.id) {
5599
6247
  selectedIds.push(String(feature.id));
5600
6248
  }
5601
6249
  } catch {
5602
6250
  }
5603
6251
  }
5604
6252
  }
6253
+ mapPerfLog("hit-test", "selection gesture", { visited, total, selected: selectedIds.length });
5605
6254
  return selectedIds;
5606
6255
  }
5607
6256
  const OTHER_BUCKET_KEY = "__other__";
@@ -5910,92 +6559,6 @@ function ClusterPieManager(props) {
5910
6559
  }, [visible, updateMarkers]);
5911
6560
  return null;
5912
6561
  }
5913
- 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");
5914
- 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");
5915
- proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
5916
- proj4.defs("EPSG:32631", "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs");
5917
- function detectAndReprojectGeoJSON(geojson) {
5918
- var _a;
5919
- const crsProperty = geojson.crs;
5920
- let sourceCRS = null;
5921
- if ((_a = crsProperty == null ? void 0 : crsProperty.properties) == null ? void 0 : _a.name) {
5922
- const crsName = crsProperty.properties.name;
5923
- const epsgMatch = crsName.match(/EPSG::?(\d+)/i);
5924
- if (epsgMatch) {
5925
- sourceCRS = `EPSG:${epsgMatch[1]}`;
5926
- }
5927
- }
5928
- if (!sourceCRS && geojson.features.length > 0) {
5929
- const firstCoord = getFirstCoordinate(geojson.features[0].geometry);
5930
- if (firstCoord) {
5931
- const [x, y] = firstCoord;
5932
- const looksLikeWGS84 = Math.abs(x) <= 180 && Math.abs(y) <= 90;
5933
- if (looksLikeWGS84) {
5934
- return { features: geojson, reprojected: false, sourceCRS: "EPSG:4326" };
5935
- }
5936
- }
5937
- }
5938
- if (sourceCRS === "EPSG:4326") {
5939
- return { features: geojson, reprojected: false, sourceCRS };
5940
- }
5941
- if (sourceCRS && proj4.defs(sourceCRS)) {
5942
- try {
5943
- const reprojectedFeatures = geojson.features.map((feature) => ({
5944
- ...feature,
5945
- geometry: reprojectGeometry(feature.geometry, sourceCRS)
5946
- }));
5947
- return {
5948
- features: { ...geojson, type: "FeatureCollection", features: reprojectedFeatures },
5949
- reprojected: true,
5950
- sourceCRS
5951
- };
5952
- } catch (e) {
5953
- console.error("Reprojection failed:", e);
5954
- }
5955
- }
5956
- return { features: geojson, reprojected: false, sourceCRS };
5957
- }
5958
- function getFirstCoordinate(geometry) {
5959
- var _a, _b, _c;
5960
- if (!geometry) return null;
5961
- switch (geometry.type) {
5962
- case "Point":
5963
- return geometry.coordinates;
5964
- case "MultiPoint":
5965
- case "LineString":
5966
- return geometry.coordinates[0];
5967
- case "MultiLineString":
5968
- case "Polygon":
5969
- return (_a = geometry.coordinates[0]) == null ? void 0 : _a[0];
5970
- case "MultiPolygon":
5971
- return (_c = (_b = geometry.coordinates[0]) == null ? void 0 : _b[0]) == null ? void 0 : _c[0];
5972
- default:
5973
- return null;
5974
- }
5975
- }
5976
- function reprojectGeometry(geometry, fromCRS) {
5977
- const transform = (coord) => {
5978
- const [x, y] = proj4(fromCRS, "EPSG:4326", [coord[0], coord[1]]);
5979
- return coord.length > 2 ? [x, y, ...coord.slice(2)] : [x, y];
5980
- };
5981
- const reprojectCoords = (coords) => {
5982
- if (typeof coords[0] === "number") {
5983
- return transform(coords);
5984
- }
5985
- return coords.map(reprojectCoords);
5986
- };
5987
- if (geometry.type === "GeometryCollection") {
5988
- return {
5989
- type: "GeometryCollection",
5990
- geometries: geometry.geometries.map((g) => reprojectGeometry(g, fromCRS))
5991
- };
5992
- }
5993
- const geomWithCoords = geometry;
5994
- return {
5995
- ...geomWithCoords,
5996
- coordinates: reprojectCoords(geomWithCoords.coordinates)
5997
- };
5998
- }
5999
6562
  const EMOJI_CANVAS_SIZE = 48;
6000
6563
  function renderEmojiToCanvas(emoji, size = EMOJI_CANVAS_SIZE) {
6001
6564
  const ratio = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
@@ -6135,17 +6698,6 @@ function createFlightPath3DLayer(layerId, mapInstance, flightPaths) {
6135
6698
  }
6136
6699
  };
6137
6700
  }
6138
- function hasAltitudeData(feature) {
6139
- if (feature.geometry.type === "LineString") {
6140
- const coords = feature.geometry.coordinates;
6141
- return coords.some((c) => c.length >= 3 && c[2] !== 0);
6142
- }
6143
- if (feature.geometry.type === "MultiLineString") {
6144
- const coords = feature.geometry.coordinates;
6145
- return coords.some((line) => line.some((c) => c.length >= 3 && c[2] !== 0));
6146
- }
6147
- return false;
6148
- }
6149
6701
  function extract3DFlightPaths(features) {
6150
6702
  const paths = [];
6151
6703
  features.forEach((feature) => {
@@ -6411,7 +6963,6 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6411
6963
  const [visibleFeatureCount, setVisibleFeatureCount] = useState(Infinity);
6412
6964
  const lastLabelVisibility = useRef(false);
6413
6965
  const [labelsSuppressed, setLabelsSuppressed] = useState(true);
6414
- const [cursorCoords, setCursorCoords] = useState(null);
6415
6966
  const [contextMenu, setContextMenu] = useState(null);
6416
6967
  const [timelineStoreApi] = useState(createTimelineStore);
6417
6968
  const timelineStore = useStore(timelineStoreApi);
@@ -6628,19 +7179,32 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6628
7179
  const syncRef = useRef(() => {
6629
7180
  });
6630
7181
  const trySelectionFastPathRef = useRef(null);
7182
+ const tryTimelineFastPathRef = useRef(null);
6631
7183
  const syncCoalescerRef = useRef(null);
6632
7184
  if (syncCoalescerRef.current === null) {
6633
7185
  syncCoalescerRef.current = createRafCoalescer((reasons) => {
6634
- var _a;
6635
- if (reasons.size === 1 && reasons.has("selection") && ((_a = trySelectionFastPathRef.current) == null ? void 0 : _a.call(trySelectionFastPathRef))) {
6636
- return;
7186
+ var _a, _b;
7187
+ if (!reasons.has("full")) {
7188
+ let handled = true;
7189
+ if (reasons.has("timeline")) handled = ((_a = tryTimelineFastPathRef.current) == null ? void 0 : _a.call(tryTimelineFastPathRef)) ?? false;
7190
+ if (handled && reasons.has("selection")) handled = ((_b = trySelectionFastPathRef.current) == null ? void 0 : _b.call(trySelectionFastPathRef)) ?? false;
7191
+ if (handled) {
7192
+ mapPerfLog("sync", "frame handled by fast path(s)", reasons);
7193
+ return;
7194
+ }
7195
+ mapPerfLog("sync", "fast path bailed — full rebuild", reasons);
6637
7196
  }
6638
7197
  syncRef.current();
6639
7198
  });
6640
7199
  }
7200
+ const fullSyncCallersRef = useRef([]);
6641
7201
  const scheduleSync = useCallback((reason = "full") => {
6642
- var _a;
6643
- (_a = syncCoalescerRef.current) == null ? void 0 : _a.schedule(reason);
7202
+ var _a, _b;
7203
+ if (reason === "full" && mapPerfLogEnabled() && fullSyncCallersRef.current.length < 4) {
7204
+ const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n").slice(2, 5).map((line) => line.trim()).join(" ← ");
7205
+ if (stack) fullSyncCallersRef.current.push(stack);
7206
+ }
7207
+ (_b = syncCoalescerRef.current) == null ? void 0 : _b.schedule(reason);
6644
7208
  }, []);
6645
7209
  useEffect(() => {
6646
7210
  scheduleSync();
@@ -6731,10 +7295,106 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6731
7295
  }, []);
6732
7296
  const isSyncingRef = useRef(false);
6733
7297
  const selectionPaintCacheRef = useRef(null);
7298
+ const paintedArrowLinesRef = useRef([]);
7299
+ const renderArrowOverlays = useCallback((arrowLines) => {
7300
+ const mapInstance = map.current;
7301
+ if (!mapInstance) return;
7302
+ const arrowHeadSource = mapInstance.getSource("arrow-heads");
7303
+ if (arrowHeadSource) {
7304
+ const arrowHeadTriangles = [];
7305
+ const headLength = 16;
7306
+ const headWidth = 10;
7307
+ arrowLines.forEach((f) => {
7308
+ const coords = f.geometry.coordinates;
7309
+ if (coords.length < 2) return;
7310
+ const end = coords[coords.length - 1];
7311
+ const prev = coords[coords.length - 2];
7312
+ const endScreen = mapInstance.project(end);
7313
+ const prevScreen = mapInstance.project(prev);
7314
+ const dx = endScreen.x - prevScreen.x;
7315
+ const dy = endScreen.y - prevScreen.y;
7316
+ const len = Math.sqrt(dx * dx + dy * dy);
7317
+ if (len < 1e-3) return;
7318
+ const dirX = dx / len;
7319
+ const dirY = dy / len;
7320
+ const perpX = -dirY;
7321
+ const perpY = dirX;
7322
+ const tipScreen = { x: endScreen.x, y: endScreen.y };
7323
+ const baseLeftScreen = {
7324
+ x: endScreen.x - dirX * headLength - perpX * headWidth,
7325
+ y: endScreen.y - dirY * headLength - perpY * headWidth
7326
+ };
7327
+ const baseRightScreen = {
7328
+ x: endScreen.x - dirX * headLength + perpX * headWidth,
7329
+ y: endScreen.y - dirY * headLength + perpY * headWidth
7330
+ };
7331
+ const tipGeo = mapInstance.unproject([tipScreen.x, tipScreen.y]);
7332
+ const baseLeftGeo = mapInstance.unproject([baseLeftScreen.x, baseLeftScreen.y]);
7333
+ const baseRightGeo = mapInstance.unproject([baseRightScreen.x, baseRightScreen.y]);
7334
+ arrowHeadTriangles.push({
7335
+ type: "Feature",
7336
+ geometry: {
7337
+ type: "Polygon",
7338
+ coordinates: [[
7339
+ [tipGeo.lng, tipGeo.lat],
7340
+ [baseLeftGeo.lng, baseLeftGeo.lat],
7341
+ [baseRightGeo.lng, baseRightGeo.lat],
7342
+ [tipGeo.lng, tipGeo.lat]
7343
+ // Close the polygon
7344
+ ]]
7345
+ },
7346
+ properties: {
7347
+ ...f.properties
7348
+ }
7349
+ });
7350
+ });
7351
+ arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
7352
+ }
7353
+ const arrowLabelSource = mapInstance.getSource("arrow-labels");
7354
+ if (arrowLabelSource) {
7355
+ const arrowLabelPoints = [];
7356
+ arrowLines.forEach((f) => {
7357
+ var _a;
7358
+ const name = (_a = f.properties) == null ? void 0 : _a.name;
7359
+ if (!name) return;
7360
+ const coords = f.geometry.coordinates;
7361
+ if (coords.length < 2) return;
7362
+ const start = coords[0];
7363
+ const end = coords[coords.length - 1];
7364
+ const midPoint = [
7365
+ (start[0] + end[0]) / 2,
7366
+ (start[1] + end[1]) / 2
7367
+ ];
7368
+ const dLng = end[0] - start[0];
7369
+ const dLat = end[1] - start[1];
7370
+ const angleFromEast = Math.atan2(dLat, dLng) * (180 / Math.PI);
7371
+ let labelBearing = -angleFromEast;
7372
+ labelBearing = (labelBearing % 360 + 540) % 360 - 180;
7373
+ if (labelBearing > 90) {
7374
+ labelBearing -= 180;
7375
+ } else if (labelBearing < -90) {
7376
+ labelBearing += 180;
7377
+ }
7378
+ arrowLabelPoints.push({
7379
+ type: "Feature",
7380
+ geometry: {
7381
+ type: "Point",
7382
+ coordinates: midPoint
7383
+ },
7384
+ properties: {
7385
+ ...f.properties,
7386
+ labelBearing
7387
+ }
7388
+ });
7389
+ });
7390
+ arrowLabelSource.setData({ type: "FeatureCollection", features: arrowLabelPoints });
7391
+ }
7392
+ }, []);
6734
7393
  const syncFeaturesToCustomLayers = useCallback(() => {
6735
7394
  if (!map.current) return;
6736
7395
  if (isSyncingRef.current) return;
6737
7396
  isSyncingRef.current = true;
7397
+ const fullSyncStart = performance.now();
6738
7398
  try {
6739
7399
  const source = map.current.getSource("custom-features");
6740
7400
  if (!source) return;
@@ -6857,7 +7517,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6857
7517
  const layer = featureToLayer.get(featureId);
6858
7518
  const visualConfig = layer == null ? void 0 : layer.visualConfig;
6859
7519
  const isTimelineVisible = visibleSet === null || visibleSet.has(featureId);
6860
- const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? 1;
7520
+ const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? DEFAULT_VISIBLE_STROKE_OPACITY;
6861
7521
  let strokeColor = ((_b = f.properties) == null ? void 0 : _b.stroke) || "#3b82f6";
6862
7522
  const colorConfig = visualConfig == null ? void 0 : visualConfig.color;
6863
7523
  if (colorConfig) {
@@ -6959,7 +7619,17 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6959
7619
  basePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
6960
7620
  }
6961
7621
  const labelPriority = isFeatureSelected ? 0 : basePriority;
6962
- recordPaintedFeature(paintCache, featureId, basePriority, isFeatureSelected === 1);
7622
+ const visibleStrokeOpacity = hideFlatFor3DOnly ? 0 : baseOpacity;
7623
+ const visibleFillOpacity = hideFlatFor3DOnly ? 0 : ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? DEFAULT_VISIBLE_FILL_OPACITY;
7624
+ recordPaintedFeature(
7625
+ paintCache,
7626
+ featureId,
7627
+ basePriority,
7628
+ isFeatureSelected === 1,
7629
+ visibleStrokeOpacity,
7630
+ visibleFillOpacity,
7631
+ !isTimelineVisible
7632
+ );
6963
7633
  return {
6964
7634
  type: "Feature",
6965
7635
  id: featureId,
@@ -6980,9 +7650,9 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
6980
7650
  iconSize: featureIconSize,
6981
7651
  stroke: strokeColor,
6982
7652
  "stroke-width": strokeWidth,
6983
- "stroke-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? baseOpacity : 0,
7653
+ "stroke-opacity": isTimelineVisible ? visibleStrokeOpacity : 0,
6984
7654
  fill: strokeColor,
6985
- "fill-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? 0.2 : 0,
7655
+ "fill-opacity": isTimelineVisible ? visibleFillOpacity : 0,
6986
7656
  pointRadius,
6987
7657
  isHiddenFor3DOnly: hideFlatFor3DOnly ? 1 : 0,
6988
7658
  isTimelineHidden: isTimelineVisible ? 0 : 1,
@@ -7081,104 +7751,19 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7081
7751
  });
7082
7752
  traceSource.setData({ type: "FeatureCollection", features: traceSegments });
7083
7753
  }
7084
- const arrowHeadSource = map.current.getSource("arrow-heads");
7085
- if (arrowHeadSource && map.current) {
7086
- const arrowHeadTriangles = [];
7087
- const mapInstance = map.current;
7754
+ {
7088
7755
  let sawArrowFeature = false;
7089
- const headLength = 16;
7090
- const headWidth = 10;
7756
+ const arrowLines = [];
7091
7757
  sourceData.features.forEach((f) => {
7092
7758
  var _a;
7093
7759
  const isArrow = ((_a = f.properties) == null ? void 0 : _a.kind) === "arrow" || arrowFeatureIdsRef.current.has(String(f.id));
7094
- if (isArrow) sawArrowFeature = true;
7095
- if (f.geometry.type !== "LineString" || !isArrow) return;
7096
- const coords = f.geometry.coordinates;
7097
- if (coords.length < 2) return;
7098
- const end = coords[coords.length - 1];
7099
- const prev = coords[coords.length - 2];
7100
- const endScreen = mapInstance.project(end);
7101
- const prevScreen = mapInstance.project(prev);
7102
- const dx = endScreen.x - prevScreen.x;
7103
- const dy = endScreen.y - prevScreen.y;
7104
- const len = Math.sqrt(dx * dx + dy * dy);
7105
- if (len < 1e-3) return;
7106
- const dirX = dx / len;
7107
- const dirY = dy / len;
7108
- const perpX = -dirY;
7109
- const perpY = dirX;
7110
- const tipScreen = { x: endScreen.x, y: endScreen.y };
7111
- const baseLeftScreen = {
7112
- x: endScreen.x - dirX * headLength - perpX * headWidth,
7113
- y: endScreen.y - dirY * headLength - perpY * headWidth
7114
- };
7115
- const baseRightScreen = {
7116
- x: endScreen.x - dirX * headLength + perpX * headWidth,
7117
- y: endScreen.y - dirY * headLength + perpY * headWidth
7118
- };
7119
- const tipGeo = mapInstance.unproject([tipScreen.x, tipScreen.y]);
7120
- const baseLeftGeo = mapInstance.unproject([baseLeftScreen.x, baseLeftScreen.y]);
7121
- const baseRightGeo = mapInstance.unproject([baseRightScreen.x, baseRightScreen.y]);
7122
- arrowHeadTriangles.push({
7123
- type: "Feature",
7124
- geometry: {
7125
- type: "Polygon",
7126
- coordinates: [[
7127
- [tipGeo.lng, tipGeo.lat],
7128
- [baseLeftGeo.lng, baseLeftGeo.lat],
7129
- [baseRightGeo.lng, baseRightGeo.lat],
7130
- [tipGeo.lng, tipGeo.lat]
7131
- // Close the polygon
7132
- ]]
7133
- },
7134
- properties: {
7135
- ...f.properties
7136
- }
7137
- });
7760
+ if (!isArrow) return;
7761
+ sawArrowFeature = true;
7762
+ if (f.geometry.type === "LineString") arrowLines.push(f);
7138
7763
  });
7139
- arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
7140
7764
  hasArrowFeaturesRef.current = sawArrowFeature;
7141
- }
7142
- const arrowLabelSource = map.current.getSource("arrow-labels");
7143
- if (arrowLabelSource) {
7144
- const arrowLabelPoints = [];
7145
- sourceData.features.forEach((f) => {
7146
- var _a, _b;
7147
- const isArrow = ((_a = f.properties) == null ? void 0 : _a.kind) === "arrow" || arrowFeatureIdsRef.current.has(String(f.id));
7148
- if (f.geometry.type !== "LineString" || !isArrow) return;
7149
- const name = (_b = f.properties) == null ? void 0 : _b.name;
7150
- if (!name) return;
7151
- const coords = f.geometry.coordinates;
7152
- if (coords.length < 2) return;
7153
- const start = coords[0];
7154
- const end = coords[coords.length - 1];
7155
- const midPoint = [
7156
- (start[0] + end[0]) / 2,
7157
- (start[1] + end[1]) / 2
7158
- ];
7159
- const dLng = end[0] - start[0];
7160
- const dLat = end[1] - start[1];
7161
- const angleFromEast = Math.atan2(dLat, dLng) * (180 / Math.PI);
7162
- let labelBearing = -angleFromEast;
7163
- labelBearing = (labelBearing % 360 + 540) % 360 - 180;
7164
- if (labelBearing > 90) {
7165
- labelBearing -= 180;
7166
- } else if (labelBearing < -90) {
7167
- labelBearing += 180;
7168
- }
7169
- arrowLabelPoints.push({
7170
- type: "Feature",
7171
- geometry: {
7172
- type: "Point",
7173
- coordinates: midPoint
7174
- },
7175
- properties: {
7176
- ...f.properties,
7177
- labelBearing
7178
- }
7179
- });
7180
- });
7181
- arrowLabelSource.setData({ type: "FeatureCollection", features: arrowLabelPoints });
7765
+ paintedArrowLinesRef.current = arrowLines;
7766
+ renderArrowOverlays(arrowLines);
7182
7767
  }
7183
7768
  if (update3DFlightPathsRef == null ? void 0 : update3DFlightPathsRef.current) {
7184
7769
  update3DFlightPathsRef.current();
@@ -7188,11 +7773,18 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7188
7773
  setVisibleFeatureCount(countVisibleFeatures(threshold));
7189
7774
  setLabelsSuppressed(false);
7190
7775
  }
7776
+ const requestedBy = fullSyncCallersRef.current.splice(0);
7777
+ mapPerfLog("sync", "full rebuild", {
7778
+ features: sourceData.features.length,
7779
+ ms: Math.round(performance.now() - fullSyncStart),
7780
+ requestedBy
7781
+ });
7191
7782
  } finally {
7192
7783
  isSyncingRef.current = false;
7193
7784
  }
7194
- }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures]);
7785
+ }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures, renderArrowOverlays]);
7195
7786
  const update3DFlightPaths = useCallback(() => {
7787
+ var _a;
7196
7788
  if (!map.current || !is3DTerrainEnabled) {
7197
7789
  if (map.current && flightPath3DLayerId.current) {
7198
7790
  try {
@@ -7213,20 +7805,21 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7213
7805
  const allFeatures = [];
7214
7806
  const currentLayers = layersRef.current;
7215
7807
  if (draw.current) {
7216
- const drawFeatures = draw.current.getAll().features.filter((feature) => {
7217
- var _a;
7218
- if (!isFeatureVisibleInTimeline(feature)) return false;
7219
- const featureId = feature.id;
7220
- const layer2 = currentLayers.find((l) => l.featureIds.includes(featureId));
7221
- return ((_a = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a.enabled) === true;
7222
- });
7808
+ const traceFeatureIds = /* @__PURE__ */ new Set();
7809
+ for (const l of currentLayers) {
7810
+ if (((_a = l.traceConfig) == null ? void 0 : _a.enabled) !== true) continue;
7811
+ for (const featureId of l.featureIds) traceFeatureIds.add(featureId);
7812
+ }
7813
+ const drawFeatures = draw.current.getAll().features.filter(
7814
+ (feature) => isFeatureVisibleInTimeline(feature) && traceFeatureIds.has(feature.id)
7815
+ );
7223
7816
  pushAll(allFeatures, drawFeatures);
7224
7817
  }
7225
7818
  readOnlyFeatures.current.forEach((features, layerId2) => {
7226
- var _a;
7819
+ var _a2;
7227
7820
  const layer2 = currentLayers.find((l) => l.id === layerId2);
7228
7821
  const altitudeMode = (layer2 == null ? void 0 : layer2.altitudeDisplayMode) ?? "both";
7229
- const traceEnabled = ((_a = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a.enabled) === true;
7822
+ const traceEnabled = ((_a2 = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a2.enabled) === true;
7230
7823
  if ((layer2 == null ? void 0 : layer2.visible) && traceEnabled && (altitudeMode === "3d" || altitudeMode === "both")) {
7231
7824
  const visibleFeatures = features.filter(isFeatureVisibleInTimeline);
7232
7825
  pushAll(allFeatures, visibleFeatures);
@@ -7281,52 +7874,24 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7281
7874
  featureToLayer.set(fid, layer.id);
7282
7875
  }
7283
7876
  }
7284
- const temporalFeatures = [];
7285
- const untimedIds = [];
7286
- for (const feature of drawFeatures) {
7287
- const props = feature.properties || {};
7288
- if (!hasAnyTemporalValue(props)) {
7289
- untimedIds.push(feature.id);
7290
- continue;
7291
- }
7292
- const { startDate, endDate } = normalizeTemporalProperties(props);
7293
- if (startDate || endDate) {
7294
- temporalFeatures.push({
7295
- id: feature.id,
7296
- startDate,
7297
- endDate,
7298
- layerId: featureToLayer.get(feature.id) || "default"
7299
- });
7300
- } else {
7301
- untimedIds.push(feature.id);
7302
- }
7303
- }
7877
+ const scan = { temporal: [], untimedIds: [] };
7878
+ scanTemporalFeatures(
7879
+ drawFeatures,
7880
+ (id) => featureToLayer.get(id) || "default",
7881
+ scan
7882
+ );
7304
7883
  readOnlyFeatures.current.forEach((features, layerId) => {
7305
7884
  const layer = currentLayers.find((l) => l.id === layerId);
7306
7885
  if (!(layer == null ? void 0 : layer.visible)) return;
7307
7886
  const cached = layerTemporalCacheRef.current.get(layerId);
7308
7887
  if (cached && cached.featureCount === features.length && !cached.hasTemporal) {
7309
- for (const f of features) untimedIds.push(f.id);
7888
+ for (const f of features) scan.untimedIds.push(f.id);
7310
7889
  return;
7311
7890
  }
7312
- let layerHasTemporal = false;
7313
- for (const feature of features) {
7314
- const props = feature.properties || {};
7315
- if (!hasAnyTemporalValue(props)) {
7316
- untimedIds.push(feature.id);
7317
- continue;
7318
- }
7319
- const { startDate, endDate } = normalizeTemporalProperties(props);
7320
- if (startDate || endDate) {
7321
- temporalFeatures.push({ id: feature.id, startDate, endDate, layerId });
7322
- layerHasTemporal = true;
7323
- } else {
7324
- untimedIds.push(feature.id);
7325
- }
7326
- }
7891
+ const layerHasTemporal = scanTemporalFeatures(features, () => layerId, scan);
7327
7892
  layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: layerHasTemporal });
7328
7893
  });
7329
- timelineStoreApi.getState().setTemporalFeatures(temporalFeatures, untimedIds);
7894
+ timelineStoreApi.getState().setTemporalFeatures(scan.temporal, scan.untimedIds);
7330
7895
  }, [timelineStoreApi]);
7331
7896
  const scheduleTimelineUpdate = useCallback(() => {
7332
7897
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
@@ -7602,6 +8167,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7602
8167
  }, [finalizeCapture]);
7603
8168
  useEffect(() => {
7604
8169
  if (!mapContainer.current || map.current) return;
8170
+ let removeDrawGateListeners;
7605
8171
  try {
7606
8172
  const baseStyle = createBaseStyle({
7607
8173
  glyphsUrl,
@@ -7660,12 +8226,6 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
7660
8226
  ]
7661
8227
  });
7662
8228
  mapInstance.addControl(drawInstance);
7663
- mapInstance.on("mousemove", (e) => {
7664
- setCursorCoords({ lng: e.lngLat.lng, lat: e.lngLat.lat });
7665
- });
7666
- mapInstance.on("mouseout", () => {
7667
- setCursorCoords(null);
7668
- });
7669
8229
  requestAnimationFrame(() => {
7670
8230
  try {
7671
8231
  const container = mapInstance.getContainer();
@@ -8640,8 +9200,52 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8640
9200
  onFeatureCreate == null ? void 0 : onFeatureCreate(feature);
8641
9201
  });
8642
9202
  });
9203
+ let drawGatePointerDown = false;
9204
+ const onDrawGatePointerDown = () => {
9205
+ drawGatePointerDown = true;
9206
+ };
9207
+ const onDrawGatePointerUp = () => {
9208
+ drawGatePointerDown = false;
9209
+ };
9210
+ const drawGateCanvas = mapInstance.getCanvasContainer();
9211
+ drawGateCanvas.addEventListener("pointerdown", onDrawGatePointerDown);
9212
+ window.addEventListener("pointerup", onDrawGatePointerUp);
9213
+ window.addEventListener("pointercancel", onDrawGatePointerUp);
9214
+ window.addEventListener("blur", onDrawGatePointerUp);
9215
+ removeDrawGateListeners = () => {
9216
+ drawGateCanvas.removeEventListener("pointerdown", onDrawGatePointerDown);
9217
+ window.removeEventListener("pointerup", onDrawGatePointerUp);
9218
+ window.removeEventListener("pointercancel", onDrawGatePointerUp);
9219
+ window.removeEventListener("blur", onDrawGatePointerUp);
9220
+ };
9221
+ let lastDrawGeometries = /* @__PURE__ */ new Map();
9222
+ let drawGateSkips = 0;
8643
9223
  mapInstance.on("draw.render", () => {
8644
- scheduleSync();
9224
+ if (!shouldDiffDrawRender({
9225
+ mode: drawInstance.getMode(),
9226
+ pointerDown: drawGatePointerDown,
9227
+ hasSelection: drawInstance.getSelectedIds().length > 0
9228
+ })) {
9229
+ drawGateSkips++;
9230
+ return;
9231
+ }
9232
+ if (drawGateSkips > 0) {
9233
+ mapPerfLog("sync", "draw.render diff resumed", { skippedWhileIdle: drawGateSkips });
9234
+ drawGateSkips = 0;
9235
+ }
9236
+ const features = drawInstance.getAll().features;
9237
+ let changed = features.length !== lastDrawGeometries.size;
9238
+ const next = /* @__PURE__ */ new Map();
9239
+ features.forEach((f) => {
9240
+ const id = String(f.id);
9241
+ next.set(id, f.geometry);
9242
+ if (!changed) {
9243
+ const prev = lastDrawGeometries.get(id);
9244
+ if (!prev || !geometryEquals(prev, f.geometry)) changed = true;
9245
+ }
9246
+ });
9247
+ lastDrawGeometries = next;
9248
+ if (changed) scheduleSync();
8645
9249
  });
8646
9250
  mapInstance.on("draw.update", (e) => {
8647
9251
  const activeLayerId = activeEditingLayerIdRef.current;
@@ -8683,7 +9287,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8683
9287
  }
8684
9288
  });
8685
9289
  scheduleSync();
8686
- if (e.action === "change_coordinates" && !hasRevertedFeatures) {
9290
+ if ((e.action === "move" || e.action === "change_coordinates") && !hasRevertedFeatures) {
8687
9291
  scheduleTimelineUpdate();
8688
9292
  recordMoveFromPreDrag();
8689
9293
  }
@@ -8823,6 +9427,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
8823
9427
  var _a;
8824
9428
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
8825
9429
  (_a = syncCoalescerRef.current) == null ? void 0 : _a.cancel();
9430
+ removeDrawGateListeners == null ? void 0 : removeDrawGateListeners();
8826
9431
  if (map.current) {
8827
9432
  map.current.remove();
8828
9433
  map.current = null;
@@ -9000,8 +9605,10 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9000
9605
  const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
9001
9606
  const currentLayers = layersRef.current;
9002
9607
  const targetLayerIds = layerIds ?? currentLayers.map((l) => l.id);
9003
- const targetFeatureIds = currentLayers.filter((l) => targetLayerIds.includes(l.id)).flatMap((l) => l.featureIds);
9004
- const targetFeatures = allFeatures.filter((f) => targetFeatureIds.includes(f.id));
9608
+ const targetFeatureIds = new Set(
9609
+ currentLayers.filter((l) => targetLayerIds.includes(l.id)).flatMap((l) => l.featureIds)
9610
+ );
9611
+ const targetFeatures = allFeatures.filter((f) => targetFeatureIds.has(f.id));
9005
9612
  if (targetFeatures.length === 0) return;
9006
9613
  const fc = turf.featureCollection(targetFeatures);
9007
9614
  const bbox = turf.bbox(fc);
@@ -9051,28 +9658,10 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9051
9658
  };
9052
9659
  if (geojson) {
9053
9660
  if (options == null ? void 0 : options.readOnly) {
9054
- let layerHasTemporal = false;
9055
- const featuresWithIds = geojson.features.map((f) => {
9056
- const id = f.id ? String(f.id) : crypto.randomUUID();
9057
- const props = f.properties || {};
9058
- if (!hasAnyTemporalValue(props)) {
9059
- return { ...f, id };
9060
- }
9061
- const { startDate, endDate } = normalizeTemporalProperties(props);
9062
- if (startDate || endDate) layerHasTemporal = true;
9063
- return {
9064
- ...f,
9065
- id,
9066
- properties: {
9067
- ...props,
9068
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9069
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9070
- }
9071
- };
9072
- });
9073
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9074
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: layerHasTemporal });
9075
- newLayer.featureIds = featuresWithIds.map((f) => String(f.id));
9661
+ const prepared = prepareFeaturesForLayer(geojson.features, "addLayer");
9662
+ readOnlyFeatures.current.set(layerId, prepared.features);
9663
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9664
+ newLayer.featureIds = prepared.featureIds;
9076
9665
  } else if (draw.current) {
9077
9666
  isApiAddingRef.current = true;
9078
9667
  try {
@@ -9198,29 +9787,12 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9198
9787
  if (options == null ? void 0 : options.recordHistory) saveStateForUndo("add features");
9199
9788
  if (layer.readOnly) {
9200
9789
  const existing = readOnlyFeatures.current.get(layerId) || [];
9201
- let layerHasTemporal = ((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false;
9202
- const newFeaturesWithIds = features.map((f) => {
9203
- const id = f.id ? String(f.id) : crypto.randomUUID();
9204
- const props = f.properties || {};
9205
- if (!hasAnyTemporalValue(props)) {
9206
- return { ...f, id };
9207
- }
9208
- const { startDate, endDate } = normalizeTemporalProperties(props);
9209
- if (startDate || endDate) layerHasTemporal = true;
9210
- return {
9211
- ...f,
9212
- id,
9213
- properties: {
9214
- ...props,
9215
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9216
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9217
- }
9218
- };
9219
- });
9220
- const combined = [...existing, ...newFeaturesWithIds];
9790
+ const prepared = prepareFeaturesForLayer(features, "addFeatures");
9791
+ const layerHasTemporal = (((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false) || prepared.hasTemporal;
9792
+ const combined = [...existing, ...prepared.features];
9221
9793
  readOnlyFeatures.current.set(layerId, combined);
9222
9794
  layerTemporalCacheRef.current.set(layerId, { featureCount: combined.length, hasTemporal: layerHasTemporal });
9223
- const addedIds2 = newFeaturesWithIds.map((f) => String(f.id));
9795
+ const addedIds2 = prepared.featureIds;
9224
9796
  const updatedLayers2 = layersRef.current.map(
9225
9797
  (l) => l.id === layerId ? { ...l, featureIds: [...l.featureIds, ...addedIds2] } : l
9226
9798
  );
@@ -9455,31 +10027,13 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9455
10027
  updateReadOnlyLayer: (layerId, features) => {
9456
10028
  const layer = layersRef.current.find((l) => l.id === layerId);
9457
10029
  if (!layer || !layer.readOnly || !isMapLoadedRef.current) return false;
9458
- let layerHasTemporal = false;
9459
- const featuresWithIds = features.map((f) => {
9460
- const id = f.id ? String(f.id) : crypto.randomUUID();
9461
- const props = f.properties || {};
9462
- if (!hasAnyTemporalValue(props)) {
9463
- return { ...f, id };
9464
- }
9465
- const { startDate, endDate } = normalizeTemporalProperties(props);
9466
- if (startDate || endDate) layerHasTemporal = true;
9467
- return {
9468
- ...f,
9469
- id,
9470
- properties: {
9471
- ...props,
9472
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9473
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9474
- }
9475
- };
9476
- });
9477
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9478
- layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: layerHasTemporal });
9479
- if (layerHasTemporal) {
10030
+ const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer");
10031
+ readOnlyFeatures.current.set(layerId, prepared.features);
10032
+ layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: prepared.hasTemporal });
10033
+ if (prepared.hasTemporal) {
9480
10034
  scheduleTimelineUpdate();
9481
10035
  }
9482
- const newFeatureIds = featuresWithIds.map((f) => String(f.id));
10036
+ const newFeatureIds = prepared.featureIds;
9483
10037
  const updatedLayers = layersRef.current.map(
9484
10038
  (l) => l.id === layerId ? { ...l, featureIds: newFeatureIds } : l
9485
10039
  );
@@ -9491,29 +10045,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
9491
10045
  },
9492
10046
  setLayerData: (name, geojson, options) => {
9493
10047
  if (!isMapLoadedRef.current) return "";
9494
- let layerHasTemporal = false;
9495
- const featuresWithIds = geojson.features.map((f) => {
9496
- const id = f.id ? String(f.id) : crypto.randomUUID();
9497
- const props = f.properties || {};
9498
- if (!hasAnyTemporalValue(props)) {
9499
- return { ...f, id };
9500
- }
9501
- const { startDate, endDate } = normalizeTemporalProperties(props);
9502
- if (startDate || endDate) layerHasTemporal = true;
9503
- return {
9504
- ...f,
9505
- id,
9506
- properties: {
9507
- ...props,
9508
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9509
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9510
- }
9511
- };
9512
- });
9513
- const newFeatureIds = featuresWithIds.map((f) => String(f.id));
10048
+ const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData");
10049
+ const newFeatureIds = prepared.featureIds;
9514
10050
  const layerId = `managed-${name}`;
9515
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9516
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: layerHasTemporal });
10051
+ readOnlyFeatures.current.set(layerId, prepared.features);
10052
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9517
10053
  const buildLayerObj = (existing) => {
9518
10054
  const base = {
9519
10055
  id: layerId,
@@ -10744,18 +11280,23 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
10744
11280
  useEffect(() => {
10745
11281
  if (!map.current || !isMapLoaded) return;
10746
11282
  const mapInstance = map.current;
11283
+ let rafId = null;
10747
11284
  const handleMove = () => {
10748
- if (!hasArrowFeaturesRef.current) return;
10749
- scheduleSync();
11285
+ if (!hasArrowFeaturesRef.current || rafId !== null) return;
11286
+ rafId = requestAnimationFrame(() => {
11287
+ rafId = null;
11288
+ renderArrowOverlays(paintedArrowLinesRef.current);
11289
+ });
10750
11290
  };
10751
11291
  mapInstance.on("move", handleMove);
10752
11292
  return () => {
11293
+ if (rafId !== null) cancelAnimationFrame(rafId);
10753
11294
  try {
10754
11295
  mapInstance.off("move", handleMove);
10755
11296
  } catch {
10756
11297
  }
10757
11298
  };
10758
- }, [isMapLoaded]);
11299
+ }, [isMapLoaded, renderArrowOverlays]);
10759
11300
  useEffect(() => {
10760
11301
  if (!map.current || !isMapLoaded || !onViewportChange) return;
10761
11302
  const mapInstance = map.current;
@@ -11078,6 +11619,29 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11078
11619
  return applySelectionFastPath(selectionPaintCacheRef.current, next, source);
11079
11620
  }, []);
11080
11621
  trySelectionFastPathRef.current = trySelectionFastPath;
11622
+ const tryTimelineFastPath = useCallback(() => {
11623
+ const m = map.current;
11624
+ if (!m) return true;
11625
+ if (hasArrowFeaturesRef.current) return false;
11626
+ if (layersRef.current.some((l) => {
11627
+ var _a;
11628
+ return l.visible && ((_a = l.traceConfig) == null ? void 0 : _a.enabled);
11629
+ })) return false;
11630
+ const source = m.getSource("custom-features");
11631
+ const { applied, toggled } = applyTimelineFastPath(
11632
+ selectionPaintCacheRef.current,
11633
+ timelineVisibleIdsRef.current,
11634
+ source
11635
+ );
11636
+ if (applied) {
11637
+ const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
11638
+ setVisibleFeatureCount(countVisibleFeatures(threshold));
11639
+ setLabelsSuppressed(false);
11640
+ mapPerfLog("timeline", "fast path applied", { toggled });
11641
+ }
11642
+ return applied;
11643
+ }, [autoLabelConfig, countVisibleFeatures]);
11644
+ tryTimelineFastPathRef.current = tryTimelineFastPath;
11081
11645
  const collectSelectionFeatureGroups = useCallback(() => {
11082
11646
  return collectVisibleFeatureGroups(
11083
11647
  draw.current ? draw.current.getAll().features : null,
@@ -11831,7 +12395,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11831
12395
  layerMetadata
11832
12396
  }
11833
12397
  };
11834
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/json" });
12398
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/json" });
11835
12399
  downloadBlob(blob, `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`);
11836
12400
  }, [layers]);
11837
12401
  const handleLoadLayerGeoJSON = useCallback((layerId) => {
@@ -11908,7 +12472,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
11908
12472
  const handleSaveAllGeoJSON = useCallback(() => {
11909
12473
  if (!draw.current) return;
11910
12474
  const geojson = buildEnrichedGeoJSON();
11911
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/geo+json" });
12475
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/geo+json" });
11912
12476
  downloadBlob(blob, "map_export.geojson");
11913
12477
  }, [buildEnrichedGeoJSON]);
11914
12478
  const handleSearchAndAddToNewLayer = useCallback(async () => {
@@ -12099,26 +12663,14 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12099
12663
  }
12100
12664
  saveStateForUndo();
12101
12665
  const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12102
- let wsHasTemporal = false;
12103
- const featuresWithIds = result.features.map((f) => {
12104
- const props = f.properties || {};
12105
- const id = f.id ? String(f.id) : crypto.randomUUID();
12106
- if (!hasAnyTemporalValue(props)) return { ...f, id };
12107
- const { startDate, endDate } = normalizeTemporalProperties(props);
12108
- if (startDate || endDate) wsHasTemporal = true;
12109
- return {
12110
- ...f,
12111
- id,
12112
- properties: { ...props, startDate: (startDate == null ? void 0 : startDate.toISOString()) || null, endDate: (endDate == null ? void 0 : endDate.toISOString()) || null }
12113
- };
12114
- });
12115
- readOnlyFeatures.current.set(layerId, featuresWithIds);
12116
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: wsHasTemporal });
12666
+ const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad");
12667
+ readOnlyFeatures.current.set(layerId, prepared.features);
12668
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
12117
12669
  const newLayer = {
12118
12670
  id: layerId,
12119
12671
  name: "Loaded from workspace",
12120
12672
  visible: true,
12121
- featureIds: featuresWithIds.map((f) => String(f.id)),
12673
+ featureIds: prepared.featureIds,
12122
12674
  readOnly: true
12123
12675
  };
12124
12676
  setLayers((prev) => [...prev, newLayer]);
@@ -12127,7 +12679,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12127
12679
  scheduleSync();
12128
12680
  toast({
12129
12681
  title: "Features loaded",
12130
- description: `Created layer with ${featuresWithIds.length} features`
12682
+ description: `Created layer with ${prepared.features.length} features`
12131
12683
  });
12132
12684
  } catch (error) {
12133
12685
  toast({
@@ -12214,195 +12766,194 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12214
12766
  duration: 1e3
12215
12767
  });
12216
12768
  }, [layers, toast]);
12217
- const handleFileChange = useCallback((e) => {
12218
- var _a;
12219
- const file = (_a = e.target.files) == null ? void 0 : _a[0];
12220
- if (!file) return;
12221
- const requestedTargetLayerId = e.target.dataset.targetLayer || activeEditingLayerId;
12222
- const createNewLayer = e.target.dataset.createNewLayer === "true";
12223
- delete e.target.dataset.createNewLayer;
12224
- const reader = new FileReader();
12225
- reader.onload = (event) => {
12226
- var _a2, _b;
12227
- try {
12228
- const rawGeojson = JSON.parse((_a2 = event.target) == null ? void 0 : _a2.result);
12229
- if (rawGeojson.type !== "FeatureCollection" || !Array.isArray(rawGeojson.features)) {
12230
- throw new Error("Invalid GeoJSON format");
12231
- }
12232
- if (rawGeojson.features.length === 0) {
12233
- toast({
12234
- title: "Empty GeoJSON",
12235
- description: "The file contains no features",
12236
- variant: "destructive"
12237
- });
12238
- return;
12239
- }
12240
- if (rawGeojson["octostar:map"]) {
12241
- if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data: rawGeojson, file }) === true) {
12242
- return;
12243
- }
12244
- if (!draw.current) return;
12245
- restoreEnrichedGeoJSON(rawGeojson);
12246
- return;
12247
- }
12248
- if (!draw.current) return;
12249
- const { features: geojson, reprojected, sourceCRS } = detectAndReprojectGeoJSON(rawGeojson);
12250
- saveStateForUndo();
12251
- const layerMetadata = (_b = rawGeojson.properties) == null ? void 0 : _b.layerMetadata;
12252
- let fileHasTemporal = false;
12253
- const normalizedFeatures = geojson.features.map((f) => {
12254
- const props = f.properties || {};
12255
- if (!hasAnyTemporalValue(props)) return f;
12256
- const { startDate, endDate } = normalizeTemporalProperties(props);
12257
- if (startDate || endDate) fileHasTemporal = true;
12258
- return {
12259
- ...f,
12260
- properties: {
12261
- ...props,
12262
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
12263
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
12264
- }
12265
- };
12266
- });
12267
- if (createNewLayer) {
12268
- if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({
12269
- kind: "newLayer",
12270
- data: { type: "FeatureCollection", features: normalizedFeatures },
12271
- file,
12272
- reprojected,
12273
- sourceCRS: sourceCRS ?? void 0
12274
- }) === true) {
12275
- return;
12276
- }
12277
- const fileName = file.name.replace(/\.geojson$|\.json$/i, "");
12278
- const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12279
- const newLayer = {
12280
- id: layerId,
12281
- name: (layerMetadata == null ? void 0 : layerMetadata.name) || fileName,
12282
- visible: true,
12283
- featureIds: [],
12284
- readOnly: true,
12285
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12286
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12287
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12288
- };
12289
- const addedIds = [];
12290
- const featuresWithIds = [];
12291
- normalizedFeatures.forEach((f) => {
12292
- const featureId = f.id ? String(f.id) : crypto.randomUUID();
12293
- const normalizedFeature = { ...f, id: featureId };
12294
- featuresWithIds.push(normalizedFeature);
12295
- addedIds.push(featureId);
12296
- });
12297
- readOnlyFeatures.current.set(layerId, featuresWithIds);
12298
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: fileHasTemporal });
12299
- newLayer.featureIds = addedIds;
12300
- setLayers((prev) => [...prev, newLayer]);
12301
- updateFeatureCount();
12302
- scheduleTimelineUpdate();
12303
- scheduleSync();
12304
- if (map.current && geojson.features.length > 0) {
12305
- try {
12306
- const bbox = turf.bbox(geojson);
12307
- if (bbox && bbox.every((v) => isFinite(v))) {
12308
- map.current.fitBounds(
12309
- [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12310
- { padding: 50, maxZoom: 16, duration: 1e3 }
12311
- );
12312
- }
12313
- } catch (e2) {
12314
- }
12315
- }
12316
- const reprojectMsg2 = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12317
- toast({
12318
- title: "Layer created",
12319
- description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg2} (high-performance mode)`
12320
- });
12321
- return;
12322
- }
12323
- let targetLayer = layers.find((l) => l.id === requestedTargetLayerId && !l.readOnly);
12324
- if (!targetLayer) {
12325
- targetLayer = layers.find((l) => l.visible && !l.readOnly);
12326
- }
12327
- if (!targetLayer) {
12328
- targetLayer = layers.find((l) => !l.readOnly);
12329
- }
12330
- if (targetLayer == null ? void 0 : targetLayer.visible) {
12331
- const addedIds = [];
12332
- isApiAddingRef.current = true;
12333
- try {
12334
- normalizedFeatures.forEach((f) => {
12335
- const ids = draw.current.add(f);
12336
- addedIds.push(ids[0]);
12337
- });
12338
- } finally {
12339
- isApiAddingRef.current = false;
12340
- }
12341
- const targetId = targetLayer.id;
12342
- setLayers((prev) => prev.map((l) => {
12343
- if (l.id !== targetId) return l;
12344
- return {
12345
- ...l,
12346
- featureIds: [...l.featureIds, ...addedIds],
12347
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12348
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12349
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12350
- };
12351
- }));
12352
- } else if (targetLayer) {
12353
- const featuresWithIds = normalizedFeatures.map((f) => ({
12354
- ...f,
12355
- id: f.id || `feature-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
12356
- }));
12357
- const targetId = targetLayer.id;
12358
- const addedIds = featuresWithIds.map((f) => f.id);
12359
- const existing = hiddenFeatures.current.get(targetId) || [];
12360
- hiddenFeatures.current.set(targetId, [...existing, ...featuresWithIds]);
12361
- setLayers((prev) => prev.map((l) => {
12362
- if (l.id !== targetId) return l;
12363
- return {
12364
- ...l,
12365
- featureIds: [...l.featureIds, ...addedIds],
12366
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12367
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12368
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12369
- };
12370
- }));
12371
- }
12372
- updateFeatureCount();
12373
- scheduleTimelineUpdate();
12374
- scheduleSync();
12375
- const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12769
+ const loadGeoJSONFile = useCallback(async (file, requestedTargetLayerId, createNewLayer) => {
12770
+ let result;
12771
+ try {
12772
+ result = await getSharedIngestClient().ingest(file, {
12773
+ idStrategy: "uuid-fallback",
12774
+ emptyIsError: true
12775
+ });
12776
+ } catch (error) {
12777
+ toast({
12778
+ title: "Failed to load GeoJSON",
12779
+ description: error instanceof Error ? error.message : "Invalid file",
12780
+ variant: "destructive"
12781
+ });
12782
+ return;
12783
+ }
12784
+ if (result.kind === "error") {
12785
+ if (result.code === "empty") {
12376
12786
  toast({
12377
- title: "GeoJSON loaded",
12378
- description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
12787
+ title: "Empty GeoJSON",
12788
+ description: result.message,
12789
+ variant: "destructive"
12379
12790
  });
12380
- } catch (error) {
12791
+ } else {
12381
12792
  toast({
12382
12793
  title: "Failed to load GeoJSON",
12383
- description: error instanceof Error ? error.message : "Invalid file",
12794
+ description: result.message,
12384
12795
  variant: "destructive"
12385
12796
  });
12386
12797
  }
12387
- };
12388
- reader.readAsText(file);
12389
- e.target.value = "";
12390
- }, [layers, activeEditingLayerId, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12391
- const handleDropGeoJSON = useCallback((name, data) => {
12798
+ return;
12799
+ }
12800
+ if (result.kind === "enriched") {
12801
+ const rawGeojson = result.data;
12802
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data: rawGeojson, file }) === true) {
12803
+ return;
12804
+ }
12805
+ if (!draw.current) return;
12806
+ restoreEnrichedGeoJSON(rawGeojson);
12807
+ return;
12808
+ }
12809
+ if (!draw.current) return;
12810
+ const { features: normalizedFeatures, reprojected, sourceCRS, hasTemporal: fileHasTemporal } = result;
12811
+ const layerMetadata = result.layerMetadata;
12812
+ saveStateForUndo();
12813
+ if (createNewLayer) {
12814
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({
12815
+ kind: "newLayer",
12816
+ data: { type: "FeatureCollection", features: normalizedFeatures },
12817
+ file,
12818
+ reprojected,
12819
+ sourceCRS: sourceCRS ?? void 0
12820
+ }) === true) {
12821
+ return;
12822
+ }
12823
+ const fileName = file.name.replace(/\.geojson$|\.json$/i, "");
12824
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12825
+ const newLayer = {
12826
+ id: layerId,
12827
+ name: (layerMetadata == null ? void 0 : layerMetadata.name) || fileName,
12828
+ visible: true,
12829
+ featureIds: [],
12830
+ readOnly: true,
12831
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12832
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12833
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12834
+ };
12835
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
12836
+ readOnlyFeatures.current.set(layerId, normalizedFeatures);
12837
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: fileHasTemporal });
12838
+ newLayer.featureIds = addedIds;
12839
+ setLayers((prev) => [...prev, newLayer]);
12840
+ updateFeatureCount();
12841
+ scheduleTimelineUpdate();
12842
+ scheduleSync();
12843
+ if (map.current && result.bbox) {
12844
+ const bbox = result.bbox;
12845
+ map.current.fitBounds(
12846
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12847
+ { padding: 50, maxZoom: 16, duration: 1e3 }
12848
+ );
12849
+ }
12850
+ const reprojectMsg2 = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12851
+ toast({
12852
+ title: "Layer created",
12853
+ description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg2} (high-performance mode)`
12854
+ });
12855
+ return;
12856
+ }
12857
+ const currentLayers = layersRef.current;
12858
+ let targetLayer = currentLayers.find((l) => l.id === requestedTargetLayerId && !l.readOnly);
12859
+ if (!targetLayer) {
12860
+ targetLayer = currentLayers.find((l) => l.visible && !l.readOnly);
12861
+ }
12862
+ if (!targetLayer) {
12863
+ targetLayer = currentLayers.find((l) => !l.readOnly);
12864
+ }
12865
+ if (targetLayer == null ? void 0 : targetLayer.visible) {
12866
+ const addedIds = [];
12867
+ isApiAddingRef.current = true;
12868
+ try {
12869
+ normalizedFeatures.forEach((f) => {
12870
+ const ids = draw.current.add(f);
12871
+ addedIds.push(ids[0]);
12872
+ });
12873
+ } finally {
12874
+ isApiAddingRef.current = false;
12875
+ }
12876
+ const targetId = targetLayer.id;
12877
+ setLayers((prev) => prev.map((l) => {
12878
+ if (l.id !== targetId) return l;
12879
+ return {
12880
+ ...l,
12881
+ featureIds: [...l.featureIds, ...addedIds],
12882
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12883
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12884
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12885
+ };
12886
+ }));
12887
+ } else if (targetLayer) {
12888
+ const targetId = targetLayer.id;
12889
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
12890
+ const existing = hiddenFeatures.current.get(targetId) || [];
12891
+ hiddenFeatures.current.set(targetId, [...existing, ...normalizedFeatures]);
12892
+ setLayers((prev) => prev.map((l) => {
12893
+ if (l.id !== targetId) return l;
12894
+ return {
12895
+ ...l,
12896
+ featureIds: [...l.featureIds, ...addedIds],
12897
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12898
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12899
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12900
+ };
12901
+ }));
12902
+ }
12903
+ updateFeatureCount();
12904
+ scheduleTimelineUpdate();
12905
+ scheduleSync();
12906
+ const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12907
+ toast({
12908
+ title: "GeoJSON loaded",
12909
+ description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
12910
+ });
12911
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12912
+ const handleFileChange = useCallback((e) => {
12392
12913
  var _a;
12914
+ const file = (_a = e.target.files) == null ? void 0 : _a[0];
12915
+ if (!file) return;
12916
+ const requestedTargetLayerId = e.target.dataset.targetLayer || activeEditingLayerId;
12917
+ const createNewLayer = e.target.dataset.createNewLayer === "true";
12918
+ delete e.target.dataset.createNewLayer;
12919
+ e.target.value = "";
12920
+ void loadGeoJSONFile(file, requestedTargetLayerId, createNewLayer);
12921
+ }, [activeEditingLayerId, loadGeoJSONFile]);
12922
+ const ingestDroppedLayer = useCallback(async (name, input) => {
12923
+ if (!map.current) return;
12924
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12925
+ const startedAt = performance.now();
12926
+ let result;
12927
+ try {
12928
+ result = await getSharedIngestClient().ingest(input, { idStrategy: "layer-index", layerId });
12929
+ } catch (error) {
12930
+ toast({
12931
+ title: "Failed to load GeoJSON",
12932
+ description: error instanceof Error ? error.message : "Invalid file",
12933
+ variant: "destructive"
12934
+ });
12935
+ return;
12936
+ }
12393
12937
  if (!map.current) return;
12394
- if (data["octostar:map"]) {
12938
+ if (result.kind === "error") {
12939
+ toast({
12940
+ title: "Failed to load GeoJSON",
12941
+ description: result.message,
12942
+ variant: "destructive"
12943
+ });
12944
+ return;
12945
+ }
12946
+ if (result.kind === "enriched") {
12947
+ const data = result.data;
12395
12948
  if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data, sourceName: name }) === true) {
12396
12949
  return;
12397
12950
  }
12398
12951
  restoreEnrichedGeoJSON(data);
12399
12952
  return;
12400
12953
  }
12401
- const { features: reprojectedData, reprojected, sourceCRS } = detectAndReprojectGeoJSON(data);
12954
+ const { features: normalizedFeatures, reprojected, sourceCRS } = result;
12955
+ const layerMetadata = result.layerMetadata;
12402
12956
  saveStateForUndo();
12403
- const layerMetadata = (_a = data.properties) == null ? void 0 : _a.layerMetadata;
12404
- const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12405
- const layerHasAltitudeData = reprojectedData.features.some((f) => hasAltitudeData(f));
12406
12957
  const newLayer = {
12407
12958
  id: layerId,
12408
12959
  name: (layerMetadata == null ? void 0 : layerMetadata.name) || name,
@@ -12413,34 +12964,11 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12413
12964
  ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12414
12965
  ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12415
12966
  ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig },
12416
- ...layerHasAltitudeData && { hasAltitudeData: true, altitudeDisplayMode: "both" }
12967
+ ...result.hasAltitude && { hasAltitudeData: true, altitudeDisplayMode: "both" }
12417
12968
  };
12418
- const normalizedFeatures = [];
12419
- const addedIds = [];
12420
- let dropHasTemporal = false;
12421
- reprojectedData.features.forEach((f, index) => {
12422
- const featureId = f.id !== void 0 && f.id !== null ? String(f.id) : `${layerId}-f${index}`;
12423
- const props = f.properties || {};
12424
- if (!hasAnyTemporalValue(props)) {
12425
- normalizedFeatures.push({ ...f, id: featureId });
12426
- addedIds.push(featureId);
12427
- return;
12428
- }
12429
- const { startDate, endDate } = normalizeTemporalProperties(props);
12430
- if (startDate || endDate) dropHasTemporal = true;
12431
- normalizedFeatures.push({
12432
- ...f,
12433
- id: featureId,
12434
- properties: {
12435
- ...props,
12436
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
12437
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
12438
- }
12439
- });
12440
- addedIds.push(featureId);
12441
- });
12969
+ const addedIds = normalizedFeatures.map((f) => f.id);
12442
12970
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
12443
- layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: dropHasTemporal });
12971
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: result.hasTemporal });
12444
12972
  newLayer.featureIds = addedIds;
12445
12973
  const nextLayers = [...layersRef.current, newLayer];
12446
12974
  layersRef.current = nextLayers;
@@ -12448,28 +12976,35 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12448
12976
  updateFeatureCount();
12449
12977
  scheduleTimelineUpdate();
12450
12978
  scheduleSync();
12451
- if (reprojectedData.features.length > 0) {
12452
- try {
12453
- const bbox = turf.bbox(reprojectedData);
12454
- if (bbox && bbox.every((v) => isFinite(v))) {
12455
- map.current.fitBounds(
12456
- [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12457
- { padding: 50, maxZoom: 16, duration: 1e3 }
12458
- );
12459
- }
12460
- } catch (e) {
12461
- }
12979
+ if (result.bbox) {
12980
+ const bbox = result.bbox;
12981
+ map.current.fitBounds(
12982
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12983
+ { padding: 50, maxZoom: 16, duration: 1e3 }
12984
+ );
12462
12985
  }
12986
+ mapPerfLog("ingest", `dropped layer "${newLayer.name}" applied`, {
12987
+ features: addedIds.length,
12988
+ totalMs: Math.round(performance.now() - startedAt)
12989
+ });
12463
12990
  const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12464
12991
  toast({
12465
12992
  title: "Layer added",
12466
12993
  description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg} (high-performance)`
12467
12994
  });
12468
12995
  }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12996
+ const handleDropGeoJSON = useCallback((name, data) => {
12997
+ void ingestDroppedLayer(name, data);
12998
+ }, [ingestDroppedLayer]);
12999
+ const handleDropGeoJSONFile = useCallback((name, file) => {
13000
+ void ingestDroppedLayer(name, file);
13001
+ }, [ingestDroppedLayer]);
12469
13002
  const handleTimelineFilterChange = useCallback((visibleIds, hiddenIds, untimedIds) => {
12470
13003
  if (!draw.current || !map.current) return;
12471
- timelineVisibleIdsRef.current = /* @__PURE__ */ new Set([...visibleIds, ...untimedIds]);
12472
- scheduleSync();
13004
+ const nextVisible = new Set(visibleIds);
13005
+ untimedIds.forEach((id) => nextVisible.add(id));
13006
+ timelineVisibleIdsRef.current = nextVisible;
13007
+ scheduleSync("timeline");
12473
13008
  }, [scheduleSync]);
12474
13009
  const prevTimelineEnabledRef = useRef(timelineStore.isEnabled);
12475
13010
  useEffect(() => {
@@ -12853,7 +13388,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
12853
13388
  ] }) });
12854
13389
  }
12855
13390
  const toastContextValue = toastProvider ?? null;
12856
- return /* @__PURE__ */ jsx(TimelineStoreContext.Provider, { value: timelineStoreApi, children: /* @__PURE__ */ jsx(ToastContext.Provider, { value: toastContextValue, children: /* @__PURE__ */ jsx(MapDropZone, { onDrop: handleDropGeoJSON, children: /* @__PURE__ */ jsxs("div", { className: `map-container w-full h-full min-w-0 relative overflow-hidden isolate ${className || ""}`, "data-testid": "map-editor-canvas", children: [
13391
+ return /* @__PURE__ */ jsx(TimelineStoreContext.Provider, { value: timelineStoreApi, children: /* @__PURE__ */ jsx(ToastContext.Provider, { value: toastContextValue, children: /* @__PURE__ */ jsx(MapDropZone, { onDrop: handleDropGeoJSON, onDropFile: handleDropGeoJSONFile, children: /* @__PURE__ */ jsxs("div", { className: `map-container w-full h-full min-w-0 relative overflow-hidden isolate ${className || ""}`, "data-testid": "map-editor-canvas", children: [
12857
13392
  /* @__PURE__ */ jsx(
12858
13393
  "div",
12859
13394
  {
@@ -13332,18 +13867,7 @@ const MapEditorCanvas = forwardRef(function MapEditorCanvas2({
13332
13867
  ))
13333
13868
  }
13334
13869
  ),
13335
- cursorCoords && /* @__PURE__ */ jsxs(
13336
- "div",
13337
- {
13338
- className: "absolute bottom-1 right-12 z-10 pointer-events-none font-mono text-[10px] text-muted-foreground/70 select-none",
13339
- "data-testid": "cursor-coordinates",
13340
- children: [
13341
- cursorCoords.lat.toFixed(5),
13342
- ", ",
13343
- cursorCoords.lng.toFixed(5)
13344
- ]
13345
- }
13346
- ),
13870
+ /* @__PURE__ */ jsx(CursorCoordinatesOverlay, { map: isMapLoaded ? map.current : null }),
13347
13871
  /* @__PURE__ */ jsx(
13348
13872
  "input",
13349
13873
  {
@@ -14107,7 +14631,15 @@ function DebugSidebar({ onAddRandomPoints, onImportKML, onAddDomMarkers, onRemov
14107
14631
  const geojson = parseKMLToGeoJSON(content);
14108
14632
  if (geojson && onImportKML) {
14109
14633
  const layerName = file.name.replace(/\.(kml|kmz)$/i, "");
14110
- onImportKML(layerName, geojson);
14634
+ void getSharedIngestClient().ingest(geojson, { idStrategy: "preserve" }).then((result) => {
14635
+ onImportKML(
14636
+ layerName,
14637
+ result.kind === "features" ? { type: "FeatureCollection", features: result.features } : geojson
14638
+ );
14639
+ }).catch((err) => {
14640
+ console.warn("[map-component] KML ingest normalization failed:", err);
14641
+ onImportKML(layerName, geojson);
14642
+ });
14111
14643
  }
14112
14644
  };
14113
14645
  reader.readAsText(file);