@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.cjs CHANGED
@@ -5,8 +5,8 @@ const react = require("react");
5
5
  const maplibregl = require("maplibre-gl");
6
6
  const MapboxDraw = require("@mapbox/mapbox-gl-draw");
7
7
  const turf = require("@turf/turf");
8
- const proj4 = require("proj4");
9
8
  const THREE = require("three");
9
+ const proj4 = require("proj4");
10
10
  const antd = require("antd");
11
11
  const clsx = require("clsx");
12
12
  const tailwindMerge = require("tailwind-merge");
@@ -14,6 +14,7 @@ const lucideReact = require("lucide-react");
14
14
  const reactDom = require("react-dom");
15
15
  const dateFns = require("date-fns");
16
16
  const zustand = require("zustand");
17
+ const Flatbush = require("flatbush");
17
18
  const dayjs = require("dayjs");
18
19
  const toGeoJSON = require("@mapbox/togeojson");
19
20
  function _interopNamespaceDefault(e) {
@@ -35,6 +36,472 @@ function _interopNamespaceDefault(e) {
35
36
  const turf__namespace = /* @__PURE__ */ _interopNamespaceDefault(turf);
36
37
  const THREE__namespace = /* @__PURE__ */ _interopNamespaceDefault(THREE);
37
38
  const toGeoJSON__namespace = /* @__PURE__ */ _interopNamespaceDefault(toGeoJSON);
39
+ function detectSourceCRS(geojson) {
40
+ var _a, _b;
41
+ const crsName = (_b = (_a = geojson.crs) == null ? void 0 : _a.properties) == null ? void 0 : _b.name;
42
+ let sourceCRS = null;
43
+ if (crsName) {
44
+ const epsgMatch = crsName.match(/EPSG::?(\d+)/i);
45
+ if (epsgMatch) sourceCRS = `EPSG:${epsgMatch[1]}`;
46
+ }
47
+ if (!sourceCRS && geojson.features.length > 0) {
48
+ const firstCoord = getFirstCoordinate(geojson.features[0].geometry);
49
+ if (firstCoord) {
50
+ const [x, y] = firstCoord;
51
+ if (Math.abs(x) <= 180 && Math.abs(y) <= 90) {
52
+ return { sourceCRS: "EPSG:4326", needsReprojection: false };
53
+ }
54
+ }
55
+ return { sourceCRS: null, needsReprojection: false };
56
+ }
57
+ return { sourceCRS, needsReprojection: sourceCRS !== null && sourceCRS !== "EPSG:4326" };
58
+ }
59
+ function getFirstCoordinate(geometry) {
60
+ var _a, _b, _c;
61
+ if (!geometry) return null;
62
+ switch (geometry.type) {
63
+ case "Point":
64
+ return geometry.coordinates;
65
+ case "MultiPoint":
66
+ case "LineString":
67
+ return geometry.coordinates[0];
68
+ case "MultiLineString":
69
+ case "Polygon":
70
+ return (_a = geometry.coordinates[0]) == null ? void 0 : _a[0];
71
+ case "MultiPolygon":
72
+ return (_c = (_b = geometry.coordinates[0]) == null ? void 0 : _b[0]) == null ? void 0 : _c[0];
73
+ default:
74
+ return null;
75
+ }
76
+ }
77
+ function hasAltitudeData(feature) {
78
+ var _a, _b;
79
+ if (((_a = feature.geometry) == null ? void 0 : _a.type) === "LineString") {
80
+ const coords = feature.geometry.coordinates;
81
+ return coords.some((c) => c.length >= 3 && c[2] !== 0);
82
+ }
83
+ if (((_b = feature.geometry) == null ? void 0 : _b.type) === "MultiLineString") {
84
+ const coords = feature.geometry.coordinates;
85
+ return coords.some((line) => line.some((c) => c.length >= 3 && c[2] !== 0));
86
+ }
87
+ return false;
88
+ }
89
+ const PRETTY_EXPORT_MAX_FEATURES = 1e4;
90
+ const TARGET_PART_CHARS = 8 * 1024 * 1024;
91
+ function featureCollectionBlobParts(collection, options) {
92
+ const prettyMax = PRETTY_EXPORT_MAX_FEATURES;
93
+ if (collection.features.length <= prettyMax) {
94
+ return [JSON.stringify(collection, null, 2)];
95
+ }
96
+ const targetChars = TARGET_PART_CHARS;
97
+ const { features, ...rest } = collection;
98
+ const head = JSON.stringify(rest);
99
+ const parts = [];
100
+ let pending = [];
101
+ let pendingChars = 0;
102
+ const push = (piece) => {
103
+ pending.push(piece);
104
+ pendingChars += piece.length;
105
+ if (pendingChars >= targetChars) {
106
+ parts.push(pending.join(""));
107
+ pending = [];
108
+ pendingChars = 0;
109
+ }
110
+ };
111
+ push(head.slice(0, -1));
112
+ push(head.length > 2 ? ',"features":[' : '"features":[');
113
+ for (let i = 0; i < features.length; i++) {
114
+ push(i === 0 ? JSON.stringify(features[i]) : "," + JSON.stringify(features[i]));
115
+ }
116
+ push("]}");
117
+ if (pending.length > 0) parts.push(pending.join(""));
118
+ return parts;
119
+ }
120
+ const ingestWorkerSource = '"use strict";(()=>{function y(e){let n=e.crs?.properties?.name,t=null;if(n){let r=n.match(/EPSG::?(\\d+)/i);r&&(t=`EPSG:${r[1]}`)}if(!t&&e.features.length>0){let r=D(e.features[0].geometry);if(r){let[o,u]=r;if(Math.abs(o)<=180&&Math.abs(u)<=90)return{sourceCRS:"EPSG:4326",needsReprojection:!1}}return{sourceCRS:null,needsReprojection:!1}}return{sourceCRS:t,needsReprojection:t!==null&&t!=="EPSG:4326"}}function D(e){if(!e)return null;switch(e.type){case"Point":return e.coordinates;case"MultiPoint":case"LineString":return e.coordinates[0];case"MultiLineString":case"Polygon":return e.coordinates[0]?.[0];case"MultiPolygon":return e.coordinates[0]?.[0]?.[0];default:return null}}function b(e){return e.geometry?.type==="LineString"?e.geometry.coordinates.some(t=>t.length>=3&&t[2]!==0):e.geometry?.type==="MultiLineString"?e.geometry.coordinates.some(t=>t.some(r=>r.length>=3&&r[2]!==0)):!1}function a(e){if(!e)return null;if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let n=new Date(e);return isNaN(n.getTime())?null:n}return null}function p(e){return!!(e.startDate||e.startdate||e.start_date||e.start_time||e.date||e.timestamp||e.flightDate||e.time||e.datetime||e.endDate||e.enddate||e.end_date||e.end_time)}function S(e){let n=a(e.startDate)||a(e.startdate)||a(e.start_date)||a(e.start_time)||a(e.date)||a(e.timestamp)||a(e.flightDate)||a(e.time)||a(e.datetime),t=a(e.endDate)||a(e.enddate)||a(e.end_date)||a(e.end_time);return n&&t&&t<n&&([n,t]=[t,n]),{startDate:n,endDate:t}}function x(){let e=globalThis.crypto?.randomUUID?.bind(globalThis.crypto);return e?e():`f-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function G(e,n,t){switch(t.idStrategy){case"preserve":return e.id;case"layer-index":return e.id!==void 0&&e.id!==null?String(e.id):`${t.layerId}-f${n}`;case"uuid-fallback":return e.id?String(e.id):x()}}function I(e,n){if(Array.isArray(e)){if(typeof e[0]=="number"){let t=e[0],r=e[1];n[0]=Math.min(n[0],t),n[1]=Math.min(n[1],r),n[2]=Math.max(n[2],t),n[3]=Math.max(n[3],r);return}for(let t of e)I(t,n)}}function h(e,n){if(e){if(e.type==="GeometryCollection"){for(let t of e.geometries)h(t,n);return}I(e.coordinates,n)}}function O(e){let n=[1/0,1/0,-1/0,-1/0];for(let t of e)h(t.geometry,n);return n.every(t=>isFinite(t))?n:null}function k(e,n){let t;if(e.type==="text")try{t=JSON.parse(e.text)}catch(s){return{kind:"error",code:"parse-error",message:s instanceof Error?s.message:"Invalid file"}}else t=e.data;if(t&&t.type==="Feature"&&(t={type:"FeatureCollection",features:[t]}),!t||t.type!=="FeatureCollection"||!Array.isArray(t.features))return{kind:"error",code:"invalid-format",message:"Invalid GeoJSON format"};if(n.emptyIsError&&t.features.length===0)return{kind:"error",code:"empty",message:"The file contains no features"};if(t["octostar:map"])return{kind:"enriched",data:t};let{sourceCRS:r,needsReprojection:o}=y(t),u=!1,l=!1,i=[];t.features.forEach((s,C)=>{let m=G(s,C,n);!l&&b(s)&&(l=!0);let d=s.properties||{};if(!p(d)){i.push(n.idStrategy==="preserve"?s:{...s,id:m});return}let{startDate:f,endDate:g}=S(d);(f||g)&&(u=!0),i.push({...s,id:m,properties:{...d,startDate:f?.toISOString()||null,endDate:g?.toISOString()||null}})});let c=t.properties?.layerMetadata;return{kind:"features",features:i,featureCount:i.length,bbox:O(i),hasTemporal:u,hasAltitude:l,reprojected:!1,sourceCRS:r,...o&&{needsReprojection:o},...c&&{layerMetadata:c}}}var R=e=>self.postMessage(e);self.onmessage=async e=>{let{id:n,source:t,options:r}=e.data;try{let o=t.type==="blob"?{type:"text",text:await t.blob.text()}:t;R({id:n,ok:!0,result:k(o,r)})}catch(o){R({id:n,ok:!1,error:o instanceof Error?o.message:String(o)})}};})();\n';
121
+ proj4.defs("EPSG:27700", "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +towgs84=446.448,-125.157,542.06,0.15,0.247,0.842,-20.489 +units=m +no_defs");
122
+ proj4.defs("EPSG:3857", "+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs");
123
+ proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
124
+ proj4.defs("EPSG:32631", "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs");
125
+ function reprojectFeatures(features, sourceCRS) {
126
+ if (!proj4.defs(sourceCRS)) return null;
127
+ try {
128
+ return features.map((feature) => ({
129
+ ...feature,
130
+ geometry: reprojectGeometry(feature.geometry, sourceCRS)
131
+ }));
132
+ } catch (e) {
133
+ console.error("Reprojection failed:", e);
134
+ return null;
135
+ }
136
+ }
137
+ function reprojectGeometry(geometry, fromCRS) {
138
+ if (!geometry) return geometry;
139
+ const transform = (coord) => {
140
+ const [x, y] = proj4(fromCRS, "EPSG:4326", [coord[0], coord[1]]);
141
+ return coord.length > 2 ? [x, y, ...coord.slice(2)] : [x, y];
142
+ };
143
+ const reprojectCoords = (coords) => {
144
+ if (typeof coords[0] === "number") {
145
+ return transform(coords);
146
+ }
147
+ return coords.map(reprojectCoords);
148
+ };
149
+ if (geometry.type === "GeometryCollection") {
150
+ return {
151
+ type: "GeometryCollection",
152
+ geometries: geometry.geometries.map((g) => reprojectGeometry(g, fromCRS))
153
+ };
154
+ }
155
+ const geomWithCoords = geometry;
156
+ return {
157
+ ...geomWithCoords,
158
+ coordinates: reprojectCoords(geomWithCoords.coordinates)
159
+ };
160
+ }
161
+ function parseDate(value) {
162
+ if (!value) return null;
163
+ if (value instanceof Date) return value;
164
+ if (typeof value === "string" || typeof value === "number") {
165
+ const date = new Date(value);
166
+ return isNaN(date.getTime()) ? null : date;
167
+ }
168
+ return null;
169
+ }
170
+ function hasAnyTemporalValue(properties) {
171
+ return !!(properties.startDate || properties.startdate || properties.start_date || properties.start_time || properties.date || properties.timestamp || properties.flightDate || properties.time || properties.datetime || properties.endDate || properties.enddate || properties.end_date || properties.end_time);
172
+ }
173
+ function normalizeTemporalProperties(properties) {
174
+ let startDate = parseDate(properties.startDate) || parseDate(properties.startdate) || parseDate(properties.start_date) || parseDate(properties.start_time) || parseDate(properties.date) || parseDate(properties.timestamp) || parseDate(properties.flightDate) || parseDate(properties.time) || parseDate(properties.datetime);
175
+ let endDate = parseDate(properties.endDate) || parseDate(properties.enddate) || parseDate(properties.end_date) || parseDate(properties.end_time);
176
+ if (startDate && endDate && endDate < startDate) {
177
+ [startDate, endDate] = [endDate, startDate];
178
+ }
179
+ return { startDate, endDate };
180
+ }
181
+ function generateUuid() {
182
+ var _a, _b;
183
+ const uuid = (_b = (_a = globalThis.crypto) == null ? void 0 : _a.randomUUID) == null ? void 0 : _b.bind(globalThis.crypto);
184
+ return uuid ? uuid() : `f-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
185
+ }
186
+ function assignId(feature, index, options) {
187
+ switch (options.idStrategy) {
188
+ case "preserve":
189
+ return feature.id;
190
+ case "layer-index":
191
+ return feature.id !== void 0 && feature.id !== null ? String(feature.id) : `${options.layerId}-f${index}`;
192
+ case "uuid-fallback":
193
+ return feature.id ? String(feature.id) : generateUuid();
194
+ }
195
+ }
196
+ function scanCoords(coords, box) {
197
+ if (!Array.isArray(coords)) return;
198
+ if (typeof coords[0] === "number") {
199
+ const x = coords[0];
200
+ const y = coords[1];
201
+ box[0] = Math.min(box[0], x);
202
+ box[1] = Math.min(box[1], y);
203
+ box[2] = Math.max(box[2], x);
204
+ box[3] = Math.max(box[3], y);
205
+ return;
206
+ }
207
+ for (const c of coords) scanCoords(c, box);
208
+ }
209
+ function scanGeometry(geometry, box) {
210
+ if (!geometry) return;
211
+ if (geometry.type === "GeometryCollection") {
212
+ for (const g of geometry.geometries) scanGeometry(g, box);
213
+ return;
214
+ }
215
+ scanCoords(geometry.coordinates, box);
216
+ }
217
+ function computeFeatureCollectionBbox(features) {
218
+ const box = [Infinity, Infinity, -Infinity, -Infinity];
219
+ for (const f of features) scanGeometry(f.geometry, box);
220
+ return box.every((v) => isFinite(v)) ? box : null;
221
+ }
222
+ function runIngestPipeline(source, options) {
223
+ var _a;
224
+ let data;
225
+ if (source.type === "text") {
226
+ try {
227
+ data = JSON.parse(source.text);
228
+ } catch (err) {
229
+ return {
230
+ kind: "error",
231
+ code: "parse-error",
232
+ message: err instanceof Error ? err.message : "Invalid file"
233
+ };
234
+ }
235
+ } else {
236
+ data = source.data;
237
+ }
238
+ if (data && data.type === "Feature") {
239
+ data = {
240
+ type: "FeatureCollection",
241
+ features: [data]
242
+ };
243
+ }
244
+ if (!data || data.type !== "FeatureCollection" || !Array.isArray(data.features)) {
245
+ return { kind: "error", code: "invalid-format", message: "Invalid GeoJSON format" };
246
+ }
247
+ if (options.emptyIsError && data.features.length === 0) {
248
+ return { kind: "error", code: "empty", message: "The file contains no features" };
249
+ }
250
+ if (data["octostar:map"]) {
251
+ return { kind: "enriched", data };
252
+ }
253
+ const { sourceCRS, needsReprojection } = detectSourceCRS(data);
254
+ let hasTemporal = false;
255
+ let hasAltitude = false;
256
+ const features = [];
257
+ data.features.forEach((f, index) => {
258
+ const id = assignId(f, index, options);
259
+ if (!hasAltitude && hasAltitudeData(f)) hasAltitude = true;
260
+ const props = f.properties || {};
261
+ if (!hasAnyTemporalValue(props)) {
262
+ features.push(options.idStrategy === "preserve" ? f : { ...f, id });
263
+ return;
264
+ }
265
+ const { startDate, endDate } = normalizeTemporalProperties(props);
266
+ if (startDate || endDate) hasTemporal = true;
267
+ features.push({
268
+ ...f,
269
+ id,
270
+ properties: {
271
+ ...props,
272
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
273
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
274
+ }
275
+ });
276
+ });
277
+ const layerMetadata = (_a = data.properties) == null ? void 0 : _a.layerMetadata;
278
+ return {
279
+ kind: "features",
280
+ features,
281
+ featureCount: features.length,
282
+ bbox: computeFeatureCollectionBbox(features),
283
+ hasTemporal,
284
+ hasAltitude,
285
+ reprojected: false,
286
+ sourceCRS,
287
+ ...needsReprojection && { needsReprojection },
288
+ ...layerMetadata && { layerMetadata }
289
+ };
290
+ }
291
+ const fromStorage = (() => {
292
+ var _a;
293
+ try {
294
+ return ((_a = globalThis.localStorage) == null ? void 0 : _a.getItem("octostar-map-perf-log")) === "1";
295
+ } catch {
296
+ return false;
297
+ }
298
+ })();
299
+ function mapPerfLogEnabled() {
300
+ return fromStorage || globalThis.__octostarMapPerfLog === true;
301
+ }
302
+ function mapPerfLog(area, message, data) {
303
+ if (!mapPerfLogEnabled()) return;
304
+ if (data === void 0) {
305
+ console.info(`[map-perf:${area}] ${message}`);
306
+ } else {
307
+ console.info(`[map-perf:${area}] ${message}`, data);
308
+ }
309
+ }
310
+ function finalizeReprojection(result) {
311
+ if (result.kind !== "features" || !result.needsReprojection || !result.sourceCRS) return result;
312
+ const reprojected = reprojectFeatures(result.features, result.sourceCRS);
313
+ if (!reprojected) {
314
+ return { ...result, needsReprojection: false };
315
+ }
316
+ return {
317
+ ...result,
318
+ features: reprojected,
319
+ reprojected: true,
320
+ needsReprojection: false,
321
+ bbox: computeFeatureCollectionBbox(reprojected)
322
+ };
323
+ }
324
+ function createWorkerPort() {
325
+ if (typeof Worker === "undefined") {
326
+ mapPerfLog("ingest", "Worker unavailable in this environment — using main-thread pipeline");
327
+ return null;
328
+ }
329
+ let url = null;
330
+ try {
331
+ url = URL.createObjectURL(new Blob([ingestWorkerSource], { type: "text/javascript" }));
332
+ const worker = new Worker(url);
333
+ let pendingUrl = url;
334
+ const revokePendingUrl = () => {
335
+ if (pendingUrl) URL.revokeObjectURL(pendingUrl);
336
+ pendingUrl = null;
337
+ };
338
+ mapPerfLog("ingest", "worker spawned");
339
+ return {
340
+ post: (msg) => worker.postMessage(msg),
341
+ onMessage: (cb) => {
342
+ worker.onmessage = (e) => {
343
+ revokePendingUrl();
344
+ cb(e.data);
345
+ };
346
+ },
347
+ onError: (cb) => {
348
+ worker.onerror = (e) => {
349
+ revokePendingUrl();
350
+ cb(e);
351
+ };
352
+ worker.onmessageerror = (e) => cb(e);
353
+ },
354
+ terminate: () => {
355
+ revokePendingUrl();
356
+ worker.terminate();
357
+ }
358
+ };
359
+ } catch (err) {
360
+ if (url) URL.revokeObjectURL(url);
361
+ console.warn(
362
+ "[map-component] Ingest worker could not be spawned (CSP may block blob: workers); file parsing will run on the main thread.",
363
+ err
364
+ );
365
+ return null;
366
+ }
367
+ }
368
+ const INGEST_TIMEOUT_MS = 12e4;
369
+ function createIngestClient(portFactory = createWorkerPort) {
370
+ let port = null;
371
+ let portUnavailable = false;
372
+ let nextId = 0;
373
+ const pending = /* @__PURE__ */ new Map();
374
+ const rejectAllPending = (reason) => {
375
+ pending.forEach((request) => {
376
+ clearTimeout(request.timeout);
377
+ request.reject(new Error(reason));
378
+ });
379
+ pending.clear();
380
+ };
381
+ const abandonPort = (reason) => {
382
+ rejectAllPending(reason);
383
+ port == null ? void 0 : port.terminate();
384
+ port = null;
385
+ };
386
+ const ensurePort = () => {
387
+ if (portUnavailable || port) return port;
388
+ try {
389
+ port = portFactory();
390
+ } catch {
391
+ port = null;
392
+ }
393
+ if (!port) {
394
+ portUnavailable = true;
395
+ return null;
396
+ }
397
+ port.onMessage((msg) => {
398
+ const request = pending.get(msg.id);
399
+ if (!request) return;
400
+ pending.delete(msg.id);
401
+ clearTimeout(request.timeout);
402
+ mapPerfLog("ingest", `worker request "${request.label}" finished`, {
403
+ ms: Math.round(performance.now() - request.startedAt),
404
+ ok: msg.ok
405
+ });
406
+ if (msg.ok) {
407
+ request.resolve(finalizeReprojection(msg.result));
408
+ } else {
409
+ request.reject(new Error(msg.error));
410
+ }
411
+ });
412
+ port.onError((err) => {
413
+ console.warn("[map-component] Ingest worker crashed; it will be respawned on next use.", err);
414
+ abandonPort("Ingest worker crashed");
415
+ });
416
+ return port;
417
+ };
418
+ const runInline = async (input, options) => {
419
+ const text = typeof input === "string" ? input : await input.text();
420
+ const startedAt = performance.now();
421
+ const result = finalizeReprojection(runIngestPipeline({ type: "text", text }, options));
422
+ mapPerfLog("ingest", "main-thread pipeline finished (no worker)", {
423
+ ms: Math.round(performance.now() - startedAt)
424
+ });
425
+ return result;
426
+ };
427
+ return {
428
+ ingest(input, options) {
429
+ if (typeof input === "object" && !(input instanceof Blob)) {
430
+ return Promise.resolve().then(
431
+ () => finalizeReprojection(runIngestPipeline({ type: "parsed", data: input }, options))
432
+ );
433
+ }
434
+ const activePort = ensurePort();
435
+ if (!activePort) return runInline(input, options);
436
+ const id = nextId++;
437
+ const label = input instanceof File ? input.name : typeof input === "string" ? "text" : "blob";
438
+ return new Promise((resolve, reject) => {
439
+ const timeout = setTimeout(() => {
440
+ console.warn(
441
+ `[map-component] Ingest worker unresponsive for "${label}" after ${INGEST_TIMEOUT_MS}ms; it will be respawned on next use.`
442
+ );
443
+ abandonPort("Ingest worker unresponsive — the file could not be parsed");
444
+ }, INGEST_TIMEOUT_MS);
445
+ pending.set(id, { resolve, reject, startedAt: performance.now(), label, timeout });
446
+ activePort.post({
447
+ id,
448
+ source: typeof input === "string" ? { type: "text", text: input } : { type: "blob", blob: input },
449
+ options
450
+ });
451
+ });
452
+ },
453
+ dispose() {
454
+ abandonPort("Ingest client disposed");
455
+ portUnavailable = false;
456
+ }
457
+ };
458
+ }
459
+ let sharedClient = null;
460
+ function getSharedIngestClient() {
461
+ if (!sharedClient) sharedClient = createIngestClient();
462
+ return sharedClient;
463
+ }
464
+ function CursorCoordinatesOverlay({ map }) {
465
+ const [coords, setCoords] = react.useState(null);
466
+ react.useEffect(() => {
467
+ if (!map) return;
468
+ let pending = null;
469
+ let frame = 0;
470
+ const flush = () => {
471
+ frame = 0;
472
+ setCoords(pending);
473
+ };
474
+ const schedule = (next) => {
475
+ pending = next;
476
+ if (!frame) frame = requestAnimationFrame(flush);
477
+ };
478
+ const onMove = (e) => schedule({ lng: e.lngLat.lng, lat: e.lngLat.lat });
479
+ const onOut = () => schedule(null);
480
+ map.on("mousemove", onMove);
481
+ map.on("mouseout", onOut);
482
+ return () => {
483
+ if (frame) cancelAnimationFrame(frame);
484
+ try {
485
+ map.off("mousemove", onMove);
486
+ map.off("mouseout", onOut);
487
+ } catch {
488
+ }
489
+ };
490
+ }, [map]);
491
+ if (!coords) return null;
492
+ return /* @__PURE__ */ jsxRuntime.jsxs(
493
+ "div",
494
+ {
495
+ className: "absolute bottom-1 right-12 z-10 pointer-events-none font-mono text-[10px] text-muted-foreground/70 select-none",
496
+ "data-testid": "cursor-coordinates",
497
+ children: [
498
+ coords.lat.toFixed(5),
499
+ ", ",
500
+ coords.lng.toFixed(5)
501
+ ]
502
+ }
503
+ );
504
+ }
38
505
  const ICONS = [
39
506
  // Location & Places
40
507
  { id: "map-pin", emoji: "📍", name: "Map Pin", category: "places" },
@@ -4524,26 +4991,6 @@ function StatusIndicator({ featureCount, selectedCount = 0 }) {
4524
4991
  }
4525
4992
  );
4526
4993
  }
4527
- function parseDate(value) {
4528
- if (!value) return null;
4529
- if (value instanceof Date) return value;
4530
- if (typeof value === "string" || typeof value === "number") {
4531
- const date = new Date(value);
4532
- return isNaN(date.getTime()) ? null : date;
4533
- }
4534
- return null;
4535
- }
4536
- function hasAnyTemporalValue(properties) {
4537
- return !!(properties.startDate || properties.startdate || properties.start_date || properties.start_time || properties.date || properties.timestamp || properties.flightDate || properties.time || properties.datetime || properties.endDate || properties.enddate || properties.end_date || properties.end_time);
4538
- }
4539
- function normalizeTemporalProperties(properties) {
4540
- let startDate = parseDate(properties.startDate) || parseDate(properties.startdate) || parseDate(properties.start_date) || parseDate(properties.start_time) || parseDate(properties.date) || parseDate(properties.timestamp) || parseDate(properties.flightDate) || parseDate(properties.time) || parseDate(properties.datetime);
4541
- let endDate = parseDate(properties.endDate) || parseDate(properties.enddate) || parseDate(properties.end_date) || parseDate(properties.end_time);
4542
- if (startDate && endDate && endDate < startDate) {
4543
- [startDate, endDate] = [endDate, startDate];
4544
- }
4545
- return { startDate, endDate };
4546
- }
4547
4994
  function isFeatureInRange(feature, rangeStart, rangeEnd) {
4548
4995
  if (!feature.startDate && !feature.endDate) return true;
4549
4996
  if (!rangeStart || !rangeEnd) return true;
@@ -4637,7 +5084,8 @@ const timelineStoreInitializer = (set, get) => ({
4637
5084
  const computedMax = maxDate;
4638
5085
  const sameFeatureIds = state.temporalFeatures.length === timedFeatures.length && timedFeatures.every((f, i) => f.id === state.temporalFeatures[i].id);
4639
5086
  const sameDates = ((_a = state.globalMinDate) == null ? void 0 : _a.getTime()) === (computedMin == null ? void 0 : computedMin.getTime()) && ((_b = state.globalMaxDate) == null ? void 0 : _b.getTime()) === (computedMax == null ? void 0 : computedMax.getTime());
4640
- if (sameFeatureIds && sameDates && state.hasTemporalData) return;
5087
+ const sameUntimed = state.untimedFeatureIds.length === untimedIds.length && untimedIds.every((id, i) => id === state.untimedFeatureIds[i]);
5088
+ if (sameFeatureIds && sameDates && sameUntimed && state.hasTemporalData) return;
4641
5089
  const histogramBins = minDate && maxDate ? computeHistogramBins(timedFeatures, minDate, maxDate) : [];
4642
5090
  set({
4643
5091
  hasTemporalData: true,
@@ -5162,7 +5610,7 @@ function Timebar({ onFilterChange, selectedFeatureIds = [], selectedFeatureColor
5162
5610
  }
5163
5611
  );
5164
5612
  }
5165
- function MapDropZone({ onDrop, children }) {
5613
+ function MapDropZone({ onDrop, onDropFile, children }) {
5166
5614
  const [isDragOver, setIsDragOver] = react.useState(false);
5167
5615
  const handleDragOver = react.useCallback((e) => {
5168
5616
  e.preventDefault();
@@ -5197,13 +5645,17 @@ function MapDropZone({ onDrop, children }) {
5197
5645
  for (let i = 0; i < files.length; i++) {
5198
5646
  const file = files[i];
5199
5647
  if (!file.name.match(/\.(geojson|json)$/i)) continue;
5648
+ const name = file.name.replace(/\.(geojson|json)$/i, "");
5649
+ if (onDropFile) {
5650
+ onDropFile(name, file);
5651
+ continue;
5652
+ }
5200
5653
  const reader = new FileReader();
5201
5654
  reader.onload = (evt) => {
5202
5655
  var _a;
5203
5656
  try {
5204
5657
  const parsed = JSON.parse((_a = evt.target) == null ? void 0 : _a.result);
5205
5658
  if (parsed.type === "FeatureCollection" && Array.isArray(parsed.features)) {
5206
- const name = file.name.replace(/\.(geojson|json)$/i, "");
5207
5659
  onDrop(name, parsed);
5208
5660
  }
5209
5661
  } catch (err) {
@@ -5213,7 +5665,7 @@ function MapDropZone({ onDrop, children }) {
5213
5665
  reader.readAsText(file);
5214
5666
  }
5215
5667
  }
5216
- }, [onDrop]);
5668
+ }, [onDrop, onDropFile]);
5217
5669
  return /* @__PURE__ */ jsxRuntime.jsxs(
5218
5670
  "div",
5219
5671
  {
@@ -5451,15 +5903,20 @@ function createRafCoalescer(run, scheduler = rafScheduler) {
5451
5903
  };
5452
5904
  }
5453
5905
  const DEFAULT_LABEL_PRIORITY = 100;
5906
+ const DEFAULT_VISIBLE_STROKE_OPACITY = 1;
5907
+ const DEFAULT_VISIBLE_FILL_OPACITY = 0.2;
5454
5908
  function createSelectionPaintCache() {
5455
5909
  return {
5456
5910
  presentIds: /* @__PURE__ */ new Set(),
5457
5911
  appliedSelectedIds: /* @__PURE__ */ new Set(),
5458
5912
  basePriorityById: /* @__PURE__ */ new Map(),
5913
+ appliedHiddenIds: /* @__PURE__ */ new Set(),
5914
+ visibleStrokeOpacityById: /* @__PURE__ */ new Map(),
5915
+ visibleFillOpacityById: /* @__PURE__ */ new Map(),
5459
5916
  updatable: true
5460
5917
  };
5461
5918
  }
5462
- function recordPaintedFeature(cache, featureId, basePriority, isSelected) {
5919
+ function recordPaintedFeature(cache, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
5463
5920
  if (cache.presentIds.has(featureId)) {
5464
5921
  cache.updatable = false;
5465
5922
  } else {
@@ -5467,6 +5924,13 @@ function recordPaintedFeature(cache, featureId, basePriority, isSelected) {
5467
5924
  }
5468
5925
  cache.basePriorityById.set(featureId, basePriority);
5469
5926
  if (isSelected) cache.appliedSelectedIds.add(featureId);
5927
+ if (visibleStrokeOpacity !== DEFAULT_VISIBLE_STROKE_OPACITY) {
5928
+ cache.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
5929
+ }
5930
+ if (visibleFillOpacity !== DEFAULT_VISIBLE_FILL_OPACITY) {
5931
+ cache.visibleFillOpacityById.set(featureId, visibleFillOpacity);
5932
+ }
5933
+ if (isTimelineHidden) cache.appliedHiddenIds.add(featureId);
5470
5934
  }
5471
5935
  function applySelectionFastPath(cache, nextSelectedIds, source) {
5472
5936
  if (!cache || !cache.updatable || !source) return false;
@@ -5514,6 +5978,49 @@ function buildSelectionDiff(cache, nextSelectedIds) {
5514
5978
  });
5515
5979
  return update.length > 0 ? { update } : null;
5516
5980
  }
5981
+ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
5982
+ const update = [];
5983
+ const nextHiddenIds = /* @__PURE__ */ new Set();
5984
+ cache.presentIds.forEach((id) => {
5985
+ const nextHidden = nextVisibleSet !== null && !nextVisibleSet.has(id);
5986
+ if (nextHidden) nextHiddenIds.add(id);
5987
+ if (nextHidden === cache.appliedHiddenIds.has(id)) return;
5988
+ if (nextHidden) {
5989
+ update.push({
5990
+ id,
5991
+ addOrUpdateProperties: [
5992
+ { key: "stroke-opacity", value: 0 },
5993
+ { key: "fill-opacity", value: 0 },
5994
+ { key: "isTimelineHidden", value: 1 }
5995
+ ]
5996
+ });
5997
+ } else {
5998
+ update.push({
5999
+ id,
6000
+ addOrUpdateProperties: [
6001
+ { key: "stroke-opacity", value: cache.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
6002
+ { key: "fill-opacity", value: cache.visibleFillOpacityById.get(id) ?? DEFAULT_VISIBLE_FILL_OPACITY },
6003
+ { key: "isTimelineHidden", value: 0 }
6004
+ ]
6005
+ });
6006
+ }
6007
+ });
6008
+ return { diff: update.length > 0 ? { update } : null, nextHiddenIds };
6009
+ }
6010
+ function applyTimelineFastPath(cache, nextVisibleSet, source) {
6011
+ var _a;
6012
+ if (!cache || !cache.updatable || !source) return { applied: false, toggled: 0 };
6013
+ const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache, nextVisibleSet);
6014
+ if (diff) {
6015
+ try {
6016
+ source.updateData(diff);
6017
+ } catch {
6018
+ return { applied: false, toggled: 0 };
6019
+ }
6020
+ }
6021
+ cache.appliedHiddenIds = nextHiddenIds;
6022
+ return { applied: true, toggled: ((_a = diff == null ? void 0 : diff.update) == null ? void 0 : _a.length) ?? 0 };
6023
+ }
5517
6024
  function deepClone(value) {
5518
6025
  try {
5519
6026
  return structuredClone(value);
@@ -5566,15 +6073,80 @@ function geometryEquals(a, b) {
5566
6073
  b.coordinates
5567
6074
  );
5568
6075
  }
5569
- function collectVisibleFeatureGroups(drawFeatures, readOnlyByLayer, layers) {
5570
- const groups = [];
5571
- if (drawFeatures) groups.push(drawFeatures);
5572
- const layerById = new Map(layers.map((l) => [l.id, l]));
5573
- readOnlyByLayer.forEach((features, layerId) => {
5574
- var _a;
5575
- if ((_a = layerById.get(layerId)) == null ? void 0 : _a.visible) groups.push(features);
5576
- });
5577
- return groups;
6076
+ function prepareFeaturesForLayer(input, caller) {
6077
+ const logging = mapPerfLogEnabled();
6078
+ const started = logging ? performance.now() : 0;
6079
+ const count = input.length;
6080
+ const features = new Array(count);
6081
+ const featureIds = new Array(count);
6082
+ let hasTemporal = false;
6083
+ let temporalCount = 0;
6084
+ let reused = 0;
6085
+ for (let i = 0; i < count; i++) {
6086
+ const f = input[i];
6087
+ const props = f.properties || {};
6088
+ if (!hasAnyTemporalValue(props)) {
6089
+ if (typeof f.id === "string" && f.id) {
6090
+ features[i] = f;
6091
+ featureIds[i] = f.id;
6092
+ reused++;
6093
+ } else {
6094
+ const id2 = f.id ? String(f.id) : crypto.randomUUID();
6095
+ features[i] = { ...f, id: id2 };
6096
+ featureIds[i] = id2;
6097
+ }
6098
+ continue;
6099
+ }
6100
+ const id = f.id ? String(f.id) : crypto.randomUUID();
6101
+ featureIds[i] = id;
6102
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6103
+ if (startDate || endDate) hasTemporal = true;
6104
+ temporalCount++;
6105
+ features[i] = {
6106
+ ...f,
6107
+ id,
6108
+ properties: {
6109
+ ...props,
6110
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
6111
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
6112
+ }
6113
+ };
6114
+ }
6115
+ if (logging) {
6116
+ mapPerfLog("normalize", `${caller ?? "prepareFeaturesForLayer"} normalized ${count} features`, {
6117
+ ms: Math.round((performance.now() - started) * 10) / 10,
6118
+ withTemporalKeys: temporalCount,
6119
+ hasTemporal,
6120
+ reused,
6121
+ copied: count - reused
6122
+ });
6123
+ }
6124
+ return { features, featureIds, hasTemporal };
6125
+ }
6126
+ function scanTemporalFeatures(features, resolveLayerId, out) {
6127
+ let foundTemporal = false;
6128
+ for (let i = 0; i < features.length; i++) {
6129
+ const feature = features[i];
6130
+ const id = feature.id;
6131
+ const props = feature.properties || {};
6132
+ if (!hasAnyTemporalValue(props)) {
6133
+ out.untimedIds.push(id);
6134
+ continue;
6135
+ }
6136
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6137
+ if (startDate || endDate) {
6138
+ out.temporal.push({ id, startDate, endDate, layerId: resolveLayerId(id) });
6139
+ foundTemporal = true;
6140
+ } else {
6141
+ out.untimedIds.push(id);
6142
+ }
6143
+ }
6144
+ return foundTemporal;
6145
+ }
6146
+ function shouldDiffDrawRender({ mode, pointerDown, hasSelection }) {
6147
+ if (mode === "view_select") return false;
6148
+ if (mode === "simple_select" || mode === "direct_select") return pointerDown && hasSelection;
6149
+ return true;
5578
6150
  }
5579
6151
  function extendBounds(bounds, coords) {
5580
6152
  if (!Array.isArray(coords) || coords.length === 0) return;
@@ -5600,29 +6172,106 @@ function boundsDisjoint(a, b) {
5600
6172
  function pointInBounds(lng, lat, b) {
5601
6173
  return lng >= b.minLng && lng <= b.maxLng && lat >= b.minLat && lat <= b.maxLat;
5602
6174
  }
6175
+ function buildGroupSpatialIndex(features) {
6176
+ var _a;
6177
+ const boxes = [];
6178
+ const positions = [];
6179
+ for (let p = 0; p < features.length; p++) {
6180
+ const geom = (_a = features[p]) == null ? void 0 : _a.geometry;
6181
+ const b = computeBounds(geom == null ? void 0 : geom.coordinates);
6182
+ if (!isFinite(b.minLng) || !isFinite(b.minLat) || !isFinite(b.maxLng) || !isFinite(b.maxLat)) {
6183
+ continue;
6184
+ }
6185
+ boxes.push(b.minLng, b.minLat, b.maxLng, b.maxLat);
6186
+ positions.push(p);
6187
+ }
6188
+ if (positions.length === 0) {
6189
+ return { tree: null, positions, size: features.length };
6190
+ }
6191
+ const startedAt = performance.now();
6192
+ const tree = new Flatbush(positions.length);
6193
+ for (let i = 0; i < boxes.length; i += 4) {
6194
+ tree.add(boxes[i], boxes[i + 1], boxes[i + 2], boxes[i + 3]);
6195
+ }
6196
+ tree.finish();
6197
+ mapPerfLog("spatial-index", "built group index", {
6198
+ indexed: positions.length,
6199
+ of: features.length,
6200
+ ms: Math.round(performance.now() - startedAt)
6201
+ });
6202
+ return { tree, positions, size: features.length };
6203
+ }
6204
+ const indexCache = /* @__PURE__ */ new WeakMap();
6205
+ const failedBuilds = /* @__PURE__ */ new WeakSet();
6206
+ function getGroupSpatialIndex(features) {
6207
+ if (failedBuilds.has(features)) return void 0;
6208
+ let index = indexCache.get(features);
6209
+ if (!index) {
6210
+ try {
6211
+ index = buildGroupSpatialIndex(features);
6212
+ } catch {
6213
+ failedBuilds.add(features);
6214
+ return void 0;
6215
+ }
6216
+ indexCache.set(features, index);
6217
+ }
6218
+ return index;
6219
+ }
6220
+ function queryCandidatePositions(index, bounds) {
6221
+ if (!index.tree) return [];
6222
+ const items = index.tree.search(bounds.minLng, bounds.minLat, bounds.maxLng, bounds.maxLat);
6223
+ const positions = items.map((i) => index.positions[i]);
6224
+ positions.sort((a, b) => a - b);
6225
+ return positions;
6226
+ }
6227
+ function collectVisibleFeatureGroups(drawFeatures, readOnlyByLayer, layers) {
6228
+ const groups = [];
6229
+ if (drawFeatures) groups.push({ features: drawFeatures });
6230
+ const layerById = new Map(layers.map((l) => [l.id, l]));
6231
+ readOnlyByLayer.forEach((features, layerId) => {
6232
+ var _a;
6233
+ if ((_a = layerById.get(layerId)) == null ? void 0 : _a.visible) {
6234
+ groups.push({ features, index: getGroupSpatialIndex(features) });
6235
+ }
6236
+ });
6237
+ return groups;
6238
+ }
6239
+ function featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) {
6240
+ const geom = feature.geometry;
6241
+ if ((geom == null ? void 0 : geom.type) === "Point") {
6242
+ const lng = geom.coordinates[0];
6243
+ const lat = geom.coordinates[1];
6244
+ return typeof lng === "number" && typeof lat === "number" && pointInBounds(lng, lat, selectionBounds) && (rectExactForPoints || turf__namespace.booleanPointInPolygon(geom.coordinates, selectionPolygon));
6245
+ }
6246
+ if ((geom == null ? void 0 : geom.type) === "LineString" || (geom == null ? void 0 : geom.type) === "Polygon" || (geom == null ? void 0 : geom.type) === "MultiPoint" || (geom == null ? void 0 : geom.type) === "MultiLineString" || (geom == null ? void 0 : geom.type) === "MultiPolygon") {
6247
+ return !boundsDisjoint(computeBounds(geom.coordinates), selectionBounds) && turf__namespace.booleanIntersects(feature, selectionPolygon);
6248
+ }
6249
+ return false;
6250
+ }
5603
6251
  function hitTestSelection(featureGroups, selectionPolygon, options) {
5604
6252
  const selectionBounds = computeBounds(selectionPolygon.geometry.coordinates);
5605
6253
  const rectExactForPoints = (options == null ? void 0 : options.axisAlignedRectangle) === true;
5606
6254
  const selectedIds = [];
5607
- for (const features of featureGroups) {
5608
- for (const feature of features) {
6255
+ let visited = 0;
6256
+ let total = 0;
6257
+ for (const group of featureGroups) {
6258
+ const { features, index } = group;
6259
+ total += features.length;
6260
+ const useIndex = index !== void 0 && index.size === features.length;
6261
+ const candidates = useIndex ? queryCandidatePositions(index, selectionBounds) : null;
6262
+ const count = candidates ? candidates.length : features.length;
6263
+ visited += count;
6264
+ for (let i = 0; i < count; i++) {
6265
+ const feature = candidates ? features[candidates[i]] : features[i];
5609
6266
  try {
5610
- const geom = feature.geometry;
5611
- let isInside = false;
5612
- if ((geom == null ? void 0 : geom.type) === "Point") {
5613
- const lng = geom.coordinates[0];
5614
- const lat = geom.coordinates[1];
5615
- isInside = typeof lng === "number" && typeof lat === "number" && pointInBounds(lng, lat, selectionBounds) && (rectExactForPoints || turf__namespace.booleanPointInPolygon(geom.coordinates, selectionPolygon));
5616
- } 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") {
5617
- isInside = !boundsDisjoint(computeBounds(geom.coordinates), selectionBounds) && turf__namespace.booleanIntersects(feature, selectionPolygon);
5618
- }
5619
- if (isInside && feature.id) {
6267
+ if (featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) && feature.id) {
5620
6268
  selectedIds.push(String(feature.id));
5621
6269
  }
5622
6270
  } catch {
5623
6271
  }
5624
6272
  }
5625
6273
  }
6274
+ mapPerfLog("hit-test", "selection gesture", { visited, total, selected: selectedIds.length });
5626
6275
  return selectedIds;
5627
6276
  }
5628
6277
  const OTHER_BUCKET_KEY = "__other__";
@@ -5931,92 +6580,6 @@ function ClusterPieManager(props) {
5931
6580
  }, [visible, updateMarkers]);
5932
6581
  return null;
5933
6582
  }
5934
- 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");
5935
- 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");
5936
- proj4.defs("EPSG:32630", "+proj=utm +zone=30 +datum=WGS84 +units=m +no_defs");
5937
- proj4.defs("EPSG:32631", "+proj=utm +zone=31 +datum=WGS84 +units=m +no_defs");
5938
- function detectAndReprojectGeoJSON(geojson) {
5939
- var _a;
5940
- const crsProperty = geojson.crs;
5941
- let sourceCRS = null;
5942
- if ((_a = crsProperty == null ? void 0 : crsProperty.properties) == null ? void 0 : _a.name) {
5943
- const crsName = crsProperty.properties.name;
5944
- const epsgMatch = crsName.match(/EPSG::?(\d+)/i);
5945
- if (epsgMatch) {
5946
- sourceCRS = `EPSG:${epsgMatch[1]}`;
5947
- }
5948
- }
5949
- if (!sourceCRS && geojson.features.length > 0) {
5950
- const firstCoord = getFirstCoordinate(geojson.features[0].geometry);
5951
- if (firstCoord) {
5952
- const [x, y] = firstCoord;
5953
- const looksLikeWGS84 = Math.abs(x) <= 180 && Math.abs(y) <= 90;
5954
- if (looksLikeWGS84) {
5955
- return { features: geojson, reprojected: false, sourceCRS: "EPSG:4326" };
5956
- }
5957
- }
5958
- }
5959
- if (sourceCRS === "EPSG:4326") {
5960
- return { features: geojson, reprojected: false, sourceCRS };
5961
- }
5962
- if (sourceCRS && proj4.defs(sourceCRS)) {
5963
- try {
5964
- const reprojectedFeatures = geojson.features.map((feature) => ({
5965
- ...feature,
5966
- geometry: reprojectGeometry(feature.geometry, sourceCRS)
5967
- }));
5968
- return {
5969
- features: { ...geojson, type: "FeatureCollection", features: reprojectedFeatures },
5970
- reprojected: true,
5971
- sourceCRS
5972
- };
5973
- } catch (e) {
5974
- console.error("Reprojection failed:", e);
5975
- }
5976
- }
5977
- return { features: geojson, reprojected: false, sourceCRS };
5978
- }
5979
- function getFirstCoordinate(geometry) {
5980
- var _a, _b, _c;
5981
- if (!geometry) return null;
5982
- switch (geometry.type) {
5983
- case "Point":
5984
- return geometry.coordinates;
5985
- case "MultiPoint":
5986
- case "LineString":
5987
- return geometry.coordinates[0];
5988
- case "MultiLineString":
5989
- case "Polygon":
5990
- return (_a = geometry.coordinates[0]) == null ? void 0 : _a[0];
5991
- case "MultiPolygon":
5992
- return (_c = (_b = geometry.coordinates[0]) == null ? void 0 : _b[0]) == null ? void 0 : _c[0];
5993
- default:
5994
- return null;
5995
- }
5996
- }
5997
- function reprojectGeometry(geometry, fromCRS) {
5998
- const transform = (coord) => {
5999
- const [x, y] = proj4(fromCRS, "EPSG:4326", [coord[0], coord[1]]);
6000
- return coord.length > 2 ? [x, y, ...coord.slice(2)] : [x, y];
6001
- };
6002
- const reprojectCoords = (coords) => {
6003
- if (typeof coords[0] === "number") {
6004
- return transform(coords);
6005
- }
6006
- return coords.map(reprojectCoords);
6007
- };
6008
- if (geometry.type === "GeometryCollection") {
6009
- return {
6010
- type: "GeometryCollection",
6011
- geometries: geometry.geometries.map((g) => reprojectGeometry(g, fromCRS))
6012
- };
6013
- }
6014
- const geomWithCoords = geometry;
6015
- return {
6016
- ...geomWithCoords,
6017
- coordinates: reprojectCoords(geomWithCoords.coordinates)
6018
- };
6019
- }
6020
6583
  const EMOJI_CANVAS_SIZE = 48;
6021
6584
  function renderEmojiToCanvas(emoji, size = EMOJI_CANVAS_SIZE) {
6022
6585
  const ratio = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
@@ -6156,17 +6719,6 @@ function createFlightPath3DLayer(layerId, mapInstance, flightPaths) {
6156
6719
  }
6157
6720
  };
6158
6721
  }
6159
- function hasAltitudeData(feature) {
6160
- if (feature.geometry.type === "LineString") {
6161
- const coords = feature.geometry.coordinates;
6162
- return coords.some((c) => c.length >= 3 && c[2] !== 0);
6163
- }
6164
- if (feature.geometry.type === "MultiLineString") {
6165
- const coords = feature.geometry.coordinates;
6166
- return coords.some((line) => line.some((c) => c.length >= 3 && c[2] !== 0));
6167
- }
6168
- return false;
6169
- }
6170
6722
  function extract3DFlightPaths(features) {
6171
6723
  const paths = [];
6172
6724
  features.forEach((feature) => {
@@ -6432,7 +6984,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6432
6984
  const [visibleFeatureCount, setVisibleFeatureCount] = react.useState(Infinity);
6433
6985
  const lastLabelVisibility = react.useRef(false);
6434
6986
  const [labelsSuppressed, setLabelsSuppressed] = react.useState(true);
6435
- const [cursorCoords, setCursorCoords] = react.useState(null);
6436
6987
  const [contextMenu, setContextMenu] = react.useState(null);
6437
6988
  const [timelineStoreApi] = react.useState(createTimelineStore);
6438
6989
  const timelineStore = zustand.useStore(timelineStoreApi);
@@ -6649,19 +7200,32 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6649
7200
  const syncRef = react.useRef(() => {
6650
7201
  });
6651
7202
  const trySelectionFastPathRef = react.useRef(null);
7203
+ const tryTimelineFastPathRef = react.useRef(null);
6652
7204
  const syncCoalescerRef = react.useRef(null);
6653
7205
  if (syncCoalescerRef.current === null) {
6654
7206
  syncCoalescerRef.current = createRafCoalescer((reasons) => {
6655
- var _a;
6656
- if (reasons.size === 1 && reasons.has("selection") && ((_a = trySelectionFastPathRef.current) == null ? void 0 : _a.call(trySelectionFastPathRef))) {
6657
- return;
7207
+ var _a, _b;
7208
+ if (!reasons.has("full")) {
7209
+ let handled = true;
7210
+ if (reasons.has("timeline")) handled = ((_a = tryTimelineFastPathRef.current) == null ? void 0 : _a.call(tryTimelineFastPathRef)) ?? false;
7211
+ if (handled && reasons.has("selection")) handled = ((_b = trySelectionFastPathRef.current) == null ? void 0 : _b.call(trySelectionFastPathRef)) ?? false;
7212
+ if (handled) {
7213
+ mapPerfLog("sync", "frame handled by fast path(s)", reasons);
7214
+ return;
7215
+ }
7216
+ mapPerfLog("sync", "fast path bailed — full rebuild", reasons);
6658
7217
  }
6659
7218
  syncRef.current();
6660
7219
  });
6661
7220
  }
7221
+ const fullSyncCallersRef = react.useRef([]);
6662
7222
  const scheduleSync = react.useCallback((reason = "full") => {
6663
- var _a;
6664
- (_a = syncCoalescerRef.current) == null ? void 0 : _a.schedule(reason);
7223
+ var _a, _b;
7224
+ if (reason === "full" && mapPerfLogEnabled() && fullSyncCallersRef.current.length < 4) {
7225
+ const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n").slice(2, 5).map((line) => line.trim()).join(" ← ");
7226
+ if (stack) fullSyncCallersRef.current.push(stack);
7227
+ }
7228
+ (_b = syncCoalescerRef.current) == null ? void 0 : _b.schedule(reason);
6665
7229
  }, []);
6666
7230
  react.useEffect(() => {
6667
7231
  scheduleSync();
@@ -6752,10 +7316,106 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6752
7316
  }, []);
6753
7317
  const isSyncingRef = react.useRef(false);
6754
7318
  const selectionPaintCacheRef = react.useRef(null);
7319
+ const paintedArrowLinesRef = react.useRef([]);
7320
+ const renderArrowOverlays = react.useCallback((arrowLines) => {
7321
+ const mapInstance = map.current;
7322
+ if (!mapInstance) return;
7323
+ const arrowHeadSource = mapInstance.getSource("arrow-heads");
7324
+ if (arrowHeadSource) {
7325
+ const arrowHeadTriangles = [];
7326
+ const headLength = 16;
7327
+ const headWidth = 10;
7328
+ arrowLines.forEach((f) => {
7329
+ const coords = f.geometry.coordinates;
7330
+ if (coords.length < 2) return;
7331
+ const end = coords[coords.length - 1];
7332
+ const prev = coords[coords.length - 2];
7333
+ const endScreen = mapInstance.project(end);
7334
+ const prevScreen = mapInstance.project(prev);
7335
+ const dx = endScreen.x - prevScreen.x;
7336
+ const dy = endScreen.y - prevScreen.y;
7337
+ const len = Math.sqrt(dx * dx + dy * dy);
7338
+ if (len < 1e-3) return;
7339
+ const dirX = dx / len;
7340
+ const dirY = dy / len;
7341
+ const perpX = -dirY;
7342
+ const perpY = dirX;
7343
+ const tipScreen = { x: endScreen.x, y: endScreen.y };
7344
+ const baseLeftScreen = {
7345
+ x: endScreen.x - dirX * headLength - perpX * headWidth,
7346
+ y: endScreen.y - dirY * headLength - perpY * headWidth
7347
+ };
7348
+ const baseRightScreen = {
7349
+ x: endScreen.x - dirX * headLength + perpX * headWidth,
7350
+ y: endScreen.y - dirY * headLength + perpY * headWidth
7351
+ };
7352
+ const tipGeo = mapInstance.unproject([tipScreen.x, tipScreen.y]);
7353
+ const baseLeftGeo = mapInstance.unproject([baseLeftScreen.x, baseLeftScreen.y]);
7354
+ const baseRightGeo = mapInstance.unproject([baseRightScreen.x, baseRightScreen.y]);
7355
+ arrowHeadTriangles.push({
7356
+ type: "Feature",
7357
+ geometry: {
7358
+ type: "Polygon",
7359
+ coordinates: [[
7360
+ [tipGeo.lng, tipGeo.lat],
7361
+ [baseLeftGeo.lng, baseLeftGeo.lat],
7362
+ [baseRightGeo.lng, baseRightGeo.lat],
7363
+ [tipGeo.lng, tipGeo.lat]
7364
+ // Close the polygon
7365
+ ]]
7366
+ },
7367
+ properties: {
7368
+ ...f.properties
7369
+ }
7370
+ });
7371
+ });
7372
+ arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
7373
+ }
7374
+ const arrowLabelSource = mapInstance.getSource("arrow-labels");
7375
+ if (arrowLabelSource) {
7376
+ const arrowLabelPoints = [];
7377
+ arrowLines.forEach((f) => {
7378
+ var _a;
7379
+ const name = (_a = f.properties) == null ? void 0 : _a.name;
7380
+ if (!name) return;
7381
+ const coords = f.geometry.coordinates;
7382
+ if (coords.length < 2) return;
7383
+ const start = coords[0];
7384
+ const end = coords[coords.length - 1];
7385
+ const midPoint = [
7386
+ (start[0] + end[0]) / 2,
7387
+ (start[1] + end[1]) / 2
7388
+ ];
7389
+ const dLng = end[0] - start[0];
7390
+ const dLat = end[1] - start[1];
7391
+ const angleFromEast = Math.atan2(dLat, dLng) * (180 / Math.PI);
7392
+ let labelBearing = -angleFromEast;
7393
+ labelBearing = (labelBearing % 360 + 540) % 360 - 180;
7394
+ if (labelBearing > 90) {
7395
+ labelBearing -= 180;
7396
+ } else if (labelBearing < -90) {
7397
+ labelBearing += 180;
7398
+ }
7399
+ arrowLabelPoints.push({
7400
+ type: "Feature",
7401
+ geometry: {
7402
+ type: "Point",
7403
+ coordinates: midPoint
7404
+ },
7405
+ properties: {
7406
+ ...f.properties,
7407
+ labelBearing
7408
+ }
7409
+ });
7410
+ });
7411
+ arrowLabelSource.setData({ type: "FeatureCollection", features: arrowLabelPoints });
7412
+ }
7413
+ }, []);
6755
7414
  const syncFeaturesToCustomLayers = react.useCallback(() => {
6756
7415
  if (!map.current) return;
6757
7416
  if (isSyncingRef.current) return;
6758
7417
  isSyncingRef.current = true;
7418
+ const fullSyncStart = performance.now();
6759
7419
  try {
6760
7420
  const source = map.current.getSource("custom-features");
6761
7421
  if (!source) return;
@@ -6878,7 +7538,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6878
7538
  const layer = featureToLayer.get(featureId);
6879
7539
  const visualConfig = layer == null ? void 0 : layer.visualConfig;
6880
7540
  const isTimelineVisible = visibleSet === null || visibleSet.has(featureId);
6881
- const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? 1;
7541
+ const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? DEFAULT_VISIBLE_STROKE_OPACITY;
6882
7542
  let strokeColor = ((_b = f.properties) == null ? void 0 : _b.stroke) || "#3b82f6";
6883
7543
  const colorConfig = visualConfig == null ? void 0 : visualConfig.color;
6884
7544
  if (colorConfig) {
@@ -6980,7 +7640,17 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6980
7640
  basePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
6981
7641
  }
6982
7642
  const labelPriority = isFeatureSelected ? 0 : basePriority;
6983
- recordPaintedFeature(paintCache, featureId, basePriority, isFeatureSelected === 1);
7643
+ const visibleStrokeOpacity = hideFlatFor3DOnly ? 0 : baseOpacity;
7644
+ const visibleFillOpacity = hideFlatFor3DOnly ? 0 : ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? DEFAULT_VISIBLE_FILL_OPACITY;
7645
+ recordPaintedFeature(
7646
+ paintCache,
7647
+ featureId,
7648
+ basePriority,
7649
+ isFeatureSelected === 1,
7650
+ visibleStrokeOpacity,
7651
+ visibleFillOpacity,
7652
+ !isTimelineVisible
7653
+ );
6984
7654
  return {
6985
7655
  type: "Feature",
6986
7656
  id: featureId,
@@ -7001,9 +7671,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7001
7671
  iconSize: featureIconSize,
7002
7672
  stroke: strokeColor,
7003
7673
  "stroke-width": strokeWidth,
7004
- "stroke-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? baseOpacity : 0,
7674
+ "stroke-opacity": isTimelineVisible ? visibleStrokeOpacity : 0,
7005
7675
  fill: strokeColor,
7006
- "fill-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? 0.2 : 0,
7676
+ "fill-opacity": isTimelineVisible ? visibleFillOpacity : 0,
7007
7677
  pointRadius,
7008
7678
  isHiddenFor3DOnly: hideFlatFor3DOnly ? 1 : 0,
7009
7679
  isTimelineHidden: isTimelineVisible ? 0 : 1,
@@ -7102,104 +7772,19 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7102
7772
  });
7103
7773
  traceSource.setData({ type: "FeatureCollection", features: traceSegments });
7104
7774
  }
7105
- const arrowHeadSource = map.current.getSource("arrow-heads");
7106
- if (arrowHeadSource && map.current) {
7107
- const arrowHeadTriangles = [];
7108
- const mapInstance = map.current;
7775
+ {
7109
7776
  let sawArrowFeature = false;
7110
- const headLength = 16;
7111
- const headWidth = 10;
7777
+ const arrowLines = [];
7112
7778
  sourceData.features.forEach((f) => {
7113
7779
  var _a;
7114
7780
  const isArrow = ((_a = f.properties) == null ? void 0 : _a.kind) === "arrow" || arrowFeatureIdsRef.current.has(String(f.id));
7115
- if (isArrow) sawArrowFeature = true;
7116
- if (f.geometry.type !== "LineString" || !isArrow) return;
7117
- const coords = f.geometry.coordinates;
7118
- if (coords.length < 2) return;
7119
- const end = coords[coords.length - 1];
7120
- const prev = coords[coords.length - 2];
7121
- const endScreen = mapInstance.project(end);
7122
- const prevScreen = mapInstance.project(prev);
7123
- const dx = endScreen.x - prevScreen.x;
7124
- const dy = endScreen.y - prevScreen.y;
7125
- const len = Math.sqrt(dx * dx + dy * dy);
7126
- if (len < 1e-3) return;
7127
- const dirX = dx / len;
7128
- const dirY = dy / len;
7129
- const perpX = -dirY;
7130
- const perpY = dirX;
7131
- const tipScreen = { x: endScreen.x, y: endScreen.y };
7132
- const baseLeftScreen = {
7133
- x: endScreen.x - dirX * headLength - perpX * headWidth,
7134
- y: endScreen.y - dirY * headLength - perpY * headWidth
7135
- };
7136
- const baseRightScreen = {
7137
- x: endScreen.x - dirX * headLength + perpX * headWidth,
7138
- y: endScreen.y - dirY * headLength + perpY * headWidth
7139
- };
7140
- const tipGeo = mapInstance.unproject([tipScreen.x, tipScreen.y]);
7141
- const baseLeftGeo = mapInstance.unproject([baseLeftScreen.x, baseLeftScreen.y]);
7142
- const baseRightGeo = mapInstance.unproject([baseRightScreen.x, baseRightScreen.y]);
7143
- arrowHeadTriangles.push({
7144
- type: "Feature",
7145
- geometry: {
7146
- type: "Polygon",
7147
- coordinates: [[
7148
- [tipGeo.lng, tipGeo.lat],
7149
- [baseLeftGeo.lng, baseLeftGeo.lat],
7150
- [baseRightGeo.lng, baseRightGeo.lat],
7151
- [tipGeo.lng, tipGeo.lat]
7152
- // Close the polygon
7153
- ]]
7154
- },
7155
- properties: {
7156
- ...f.properties
7157
- }
7158
- });
7781
+ if (!isArrow) return;
7782
+ sawArrowFeature = true;
7783
+ if (f.geometry.type === "LineString") arrowLines.push(f);
7159
7784
  });
7160
- arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
7161
7785
  hasArrowFeaturesRef.current = sawArrowFeature;
7162
- }
7163
- const arrowLabelSource = map.current.getSource("arrow-labels");
7164
- if (arrowLabelSource) {
7165
- const arrowLabelPoints = [];
7166
- sourceData.features.forEach((f) => {
7167
- var _a, _b;
7168
- const isArrow = ((_a = f.properties) == null ? void 0 : _a.kind) === "arrow" || arrowFeatureIdsRef.current.has(String(f.id));
7169
- if (f.geometry.type !== "LineString" || !isArrow) return;
7170
- const name = (_b = f.properties) == null ? void 0 : _b.name;
7171
- if (!name) return;
7172
- const coords = f.geometry.coordinates;
7173
- if (coords.length < 2) return;
7174
- const start = coords[0];
7175
- const end = coords[coords.length - 1];
7176
- const midPoint = [
7177
- (start[0] + end[0]) / 2,
7178
- (start[1] + end[1]) / 2
7179
- ];
7180
- const dLng = end[0] - start[0];
7181
- const dLat = end[1] - start[1];
7182
- const angleFromEast = Math.atan2(dLat, dLng) * (180 / Math.PI);
7183
- let labelBearing = -angleFromEast;
7184
- labelBearing = (labelBearing % 360 + 540) % 360 - 180;
7185
- if (labelBearing > 90) {
7186
- labelBearing -= 180;
7187
- } else if (labelBearing < -90) {
7188
- labelBearing += 180;
7189
- }
7190
- arrowLabelPoints.push({
7191
- type: "Feature",
7192
- geometry: {
7193
- type: "Point",
7194
- coordinates: midPoint
7195
- },
7196
- properties: {
7197
- ...f.properties,
7198
- labelBearing
7199
- }
7200
- });
7201
- });
7202
- arrowLabelSource.setData({ type: "FeatureCollection", features: arrowLabelPoints });
7786
+ paintedArrowLinesRef.current = arrowLines;
7787
+ renderArrowOverlays(arrowLines);
7203
7788
  }
7204
7789
  if (update3DFlightPathsRef == null ? void 0 : update3DFlightPathsRef.current) {
7205
7790
  update3DFlightPathsRef.current();
@@ -7209,11 +7794,18 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7209
7794
  setVisibleFeatureCount(countVisibleFeatures(threshold));
7210
7795
  setLabelsSuppressed(false);
7211
7796
  }
7797
+ const requestedBy = fullSyncCallersRef.current.splice(0);
7798
+ mapPerfLog("sync", "full rebuild", {
7799
+ features: sourceData.features.length,
7800
+ ms: Math.round(performance.now() - fullSyncStart),
7801
+ requestedBy
7802
+ });
7212
7803
  } finally {
7213
7804
  isSyncingRef.current = false;
7214
7805
  }
7215
- }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures]);
7806
+ }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures, renderArrowOverlays]);
7216
7807
  const update3DFlightPaths = react.useCallback(() => {
7808
+ var _a;
7217
7809
  if (!map.current || !is3DTerrainEnabled) {
7218
7810
  if (map.current && flightPath3DLayerId.current) {
7219
7811
  try {
@@ -7234,20 +7826,21 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7234
7826
  const allFeatures = [];
7235
7827
  const currentLayers = layersRef.current;
7236
7828
  if (draw.current) {
7237
- const drawFeatures = draw.current.getAll().features.filter((feature) => {
7238
- var _a;
7239
- if (!isFeatureVisibleInTimeline(feature)) return false;
7240
- const featureId = feature.id;
7241
- const layer2 = currentLayers.find((l) => l.featureIds.includes(featureId));
7242
- return ((_a = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a.enabled) === true;
7243
- });
7829
+ const traceFeatureIds = /* @__PURE__ */ new Set();
7830
+ for (const l of currentLayers) {
7831
+ if (((_a = l.traceConfig) == null ? void 0 : _a.enabled) !== true) continue;
7832
+ for (const featureId of l.featureIds) traceFeatureIds.add(featureId);
7833
+ }
7834
+ const drawFeatures = draw.current.getAll().features.filter(
7835
+ (feature) => isFeatureVisibleInTimeline(feature) && traceFeatureIds.has(feature.id)
7836
+ );
7244
7837
  pushAll(allFeatures, drawFeatures);
7245
7838
  }
7246
7839
  readOnlyFeatures.current.forEach((features, layerId2) => {
7247
- var _a;
7840
+ var _a2;
7248
7841
  const layer2 = currentLayers.find((l) => l.id === layerId2);
7249
7842
  const altitudeMode = (layer2 == null ? void 0 : layer2.altitudeDisplayMode) ?? "both";
7250
- const traceEnabled = ((_a = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a.enabled) === true;
7843
+ const traceEnabled = ((_a2 = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a2.enabled) === true;
7251
7844
  if ((layer2 == null ? void 0 : layer2.visible) && traceEnabled && (altitudeMode === "3d" || altitudeMode === "both")) {
7252
7845
  const visibleFeatures = features.filter(isFeatureVisibleInTimeline);
7253
7846
  pushAll(allFeatures, visibleFeatures);
@@ -7302,52 +7895,24 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7302
7895
  featureToLayer.set(fid, layer.id);
7303
7896
  }
7304
7897
  }
7305
- const temporalFeatures = [];
7306
- const untimedIds = [];
7307
- for (const feature of drawFeatures) {
7308
- const props = feature.properties || {};
7309
- if (!hasAnyTemporalValue(props)) {
7310
- untimedIds.push(feature.id);
7311
- continue;
7312
- }
7313
- const { startDate, endDate } = normalizeTemporalProperties(props);
7314
- if (startDate || endDate) {
7315
- temporalFeatures.push({
7316
- id: feature.id,
7317
- startDate,
7318
- endDate,
7319
- layerId: featureToLayer.get(feature.id) || "default"
7320
- });
7321
- } else {
7322
- untimedIds.push(feature.id);
7323
- }
7324
- }
7898
+ const scan = { temporal: [], untimedIds: [] };
7899
+ scanTemporalFeatures(
7900
+ drawFeatures,
7901
+ (id) => featureToLayer.get(id) || "default",
7902
+ scan
7903
+ );
7325
7904
  readOnlyFeatures.current.forEach((features, layerId) => {
7326
7905
  const layer = currentLayers.find((l) => l.id === layerId);
7327
7906
  if (!(layer == null ? void 0 : layer.visible)) return;
7328
7907
  const cached = layerTemporalCacheRef.current.get(layerId);
7329
7908
  if (cached && cached.featureCount === features.length && !cached.hasTemporal) {
7330
- for (const f of features) untimedIds.push(f.id);
7909
+ for (const f of features) scan.untimedIds.push(f.id);
7331
7910
  return;
7332
7911
  }
7333
- let layerHasTemporal = false;
7334
- for (const feature of features) {
7335
- const props = feature.properties || {};
7336
- if (!hasAnyTemporalValue(props)) {
7337
- untimedIds.push(feature.id);
7338
- continue;
7339
- }
7340
- const { startDate, endDate } = normalizeTemporalProperties(props);
7341
- if (startDate || endDate) {
7342
- temporalFeatures.push({ id: feature.id, startDate, endDate, layerId });
7343
- layerHasTemporal = true;
7344
- } else {
7345
- untimedIds.push(feature.id);
7346
- }
7347
- }
7912
+ const layerHasTemporal = scanTemporalFeatures(features, () => layerId, scan);
7348
7913
  layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: layerHasTemporal });
7349
7914
  });
7350
- timelineStoreApi.getState().setTemporalFeatures(temporalFeatures, untimedIds);
7915
+ timelineStoreApi.getState().setTemporalFeatures(scan.temporal, scan.untimedIds);
7351
7916
  }, [timelineStoreApi]);
7352
7917
  const scheduleTimelineUpdate = react.useCallback(() => {
7353
7918
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
@@ -7623,6 +8188,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7623
8188
  }, [finalizeCapture]);
7624
8189
  react.useEffect(() => {
7625
8190
  if (!mapContainer.current || map.current) return;
8191
+ let removeDrawGateListeners;
7626
8192
  try {
7627
8193
  const baseStyle = createBaseStyle({
7628
8194
  glyphsUrl,
@@ -7681,12 +8247,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7681
8247
  ]
7682
8248
  });
7683
8249
  mapInstance.addControl(drawInstance);
7684
- mapInstance.on("mousemove", (e) => {
7685
- setCursorCoords({ lng: e.lngLat.lng, lat: e.lngLat.lat });
7686
- });
7687
- mapInstance.on("mouseout", () => {
7688
- setCursorCoords(null);
7689
- });
7690
8250
  requestAnimationFrame(() => {
7691
8251
  try {
7692
8252
  const container = mapInstance.getContainer();
@@ -8661,8 +9221,52 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8661
9221
  onFeatureCreate == null ? void 0 : onFeatureCreate(feature);
8662
9222
  });
8663
9223
  });
9224
+ let drawGatePointerDown = false;
9225
+ const onDrawGatePointerDown = () => {
9226
+ drawGatePointerDown = true;
9227
+ };
9228
+ const onDrawGatePointerUp = () => {
9229
+ drawGatePointerDown = false;
9230
+ };
9231
+ const drawGateCanvas = mapInstance.getCanvasContainer();
9232
+ drawGateCanvas.addEventListener("pointerdown", onDrawGatePointerDown);
9233
+ window.addEventListener("pointerup", onDrawGatePointerUp);
9234
+ window.addEventListener("pointercancel", onDrawGatePointerUp);
9235
+ window.addEventListener("blur", onDrawGatePointerUp);
9236
+ removeDrawGateListeners = () => {
9237
+ drawGateCanvas.removeEventListener("pointerdown", onDrawGatePointerDown);
9238
+ window.removeEventListener("pointerup", onDrawGatePointerUp);
9239
+ window.removeEventListener("pointercancel", onDrawGatePointerUp);
9240
+ window.removeEventListener("blur", onDrawGatePointerUp);
9241
+ };
9242
+ let lastDrawGeometries = /* @__PURE__ */ new Map();
9243
+ let drawGateSkips = 0;
8664
9244
  mapInstance.on("draw.render", () => {
8665
- scheduleSync();
9245
+ if (!shouldDiffDrawRender({
9246
+ mode: drawInstance.getMode(),
9247
+ pointerDown: drawGatePointerDown,
9248
+ hasSelection: drawInstance.getSelectedIds().length > 0
9249
+ })) {
9250
+ drawGateSkips++;
9251
+ return;
9252
+ }
9253
+ if (drawGateSkips > 0) {
9254
+ mapPerfLog("sync", "draw.render diff resumed", { skippedWhileIdle: drawGateSkips });
9255
+ drawGateSkips = 0;
9256
+ }
9257
+ const features = drawInstance.getAll().features;
9258
+ let changed = features.length !== lastDrawGeometries.size;
9259
+ const next = /* @__PURE__ */ new Map();
9260
+ features.forEach((f) => {
9261
+ const id = String(f.id);
9262
+ next.set(id, f.geometry);
9263
+ if (!changed) {
9264
+ const prev = lastDrawGeometries.get(id);
9265
+ if (!prev || !geometryEquals(prev, f.geometry)) changed = true;
9266
+ }
9267
+ });
9268
+ lastDrawGeometries = next;
9269
+ if (changed) scheduleSync();
8666
9270
  });
8667
9271
  mapInstance.on("draw.update", (e) => {
8668
9272
  const activeLayerId = activeEditingLayerIdRef.current;
@@ -8704,7 +9308,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8704
9308
  }
8705
9309
  });
8706
9310
  scheduleSync();
8707
- if (e.action === "change_coordinates" && !hasRevertedFeatures) {
9311
+ if ((e.action === "move" || e.action === "change_coordinates") && !hasRevertedFeatures) {
8708
9312
  scheduleTimelineUpdate();
8709
9313
  recordMoveFromPreDrag();
8710
9314
  }
@@ -8844,6 +9448,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8844
9448
  var _a;
8845
9449
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
8846
9450
  (_a = syncCoalescerRef.current) == null ? void 0 : _a.cancel();
9451
+ removeDrawGateListeners == null ? void 0 : removeDrawGateListeners();
8847
9452
  if (map.current) {
8848
9453
  map.current.remove();
8849
9454
  map.current = null;
@@ -9021,8 +9626,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9021
9626
  const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
9022
9627
  const currentLayers = layersRef.current;
9023
9628
  const targetLayerIds = layerIds ?? currentLayers.map((l) => l.id);
9024
- const targetFeatureIds = currentLayers.filter((l) => targetLayerIds.includes(l.id)).flatMap((l) => l.featureIds);
9025
- const targetFeatures = allFeatures.filter((f) => targetFeatureIds.includes(f.id));
9629
+ const targetFeatureIds = new Set(
9630
+ currentLayers.filter((l) => targetLayerIds.includes(l.id)).flatMap((l) => l.featureIds)
9631
+ );
9632
+ const targetFeatures = allFeatures.filter((f) => targetFeatureIds.has(f.id));
9026
9633
  if (targetFeatures.length === 0) return;
9027
9634
  const fc = turf__namespace.featureCollection(targetFeatures);
9028
9635
  const bbox = turf__namespace.bbox(fc);
@@ -9072,28 +9679,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9072
9679
  };
9073
9680
  if (geojson) {
9074
9681
  if (options == null ? void 0 : options.readOnly) {
9075
- let layerHasTemporal = false;
9076
- const featuresWithIds = geojson.features.map((f) => {
9077
- const id = f.id ? String(f.id) : crypto.randomUUID();
9078
- const props = f.properties || {};
9079
- if (!hasAnyTemporalValue(props)) {
9080
- return { ...f, id };
9081
- }
9082
- const { startDate, endDate } = normalizeTemporalProperties(props);
9083
- if (startDate || endDate) layerHasTemporal = true;
9084
- return {
9085
- ...f,
9086
- id,
9087
- properties: {
9088
- ...props,
9089
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9090
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9091
- }
9092
- };
9093
- });
9094
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9095
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: layerHasTemporal });
9096
- newLayer.featureIds = featuresWithIds.map((f) => String(f.id));
9682
+ const prepared = prepareFeaturesForLayer(geojson.features, "addLayer");
9683
+ readOnlyFeatures.current.set(layerId, prepared.features);
9684
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9685
+ newLayer.featureIds = prepared.featureIds;
9097
9686
  } else if (draw.current) {
9098
9687
  isApiAddingRef.current = true;
9099
9688
  try {
@@ -9219,29 +9808,12 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9219
9808
  if (options == null ? void 0 : options.recordHistory) saveStateForUndo("add features");
9220
9809
  if (layer.readOnly) {
9221
9810
  const existing = readOnlyFeatures.current.get(layerId) || [];
9222
- let layerHasTemporal = ((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false;
9223
- const newFeaturesWithIds = features.map((f) => {
9224
- const id = f.id ? String(f.id) : crypto.randomUUID();
9225
- const props = f.properties || {};
9226
- if (!hasAnyTemporalValue(props)) {
9227
- return { ...f, id };
9228
- }
9229
- const { startDate, endDate } = normalizeTemporalProperties(props);
9230
- if (startDate || endDate) layerHasTemporal = true;
9231
- return {
9232
- ...f,
9233
- id,
9234
- properties: {
9235
- ...props,
9236
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9237
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9238
- }
9239
- };
9240
- });
9241
- const combined = [...existing, ...newFeaturesWithIds];
9811
+ const prepared = prepareFeaturesForLayer(features, "addFeatures");
9812
+ const layerHasTemporal = (((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false) || prepared.hasTemporal;
9813
+ const combined = [...existing, ...prepared.features];
9242
9814
  readOnlyFeatures.current.set(layerId, combined);
9243
9815
  layerTemporalCacheRef.current.set(layerId, { featureCount: combined.length, hasTemporal: layerHasTemporal });
9244
- const addedIds2 = newFeaturesWithIds.map((f) => String(f.id));
9816
+ const addedIds2 = prepared.featureIds;
9245
9817
  const updatedLayers2 = layersRef.current.map(
9246
9818
  (l) => l.id === layerId ? { ...l, featureIds: [...l.featureIds, ...addedIds2] } : l
9247
9819
  );
@@ -9476,31 +10048,13 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9476
10048
  updateReadOnlyLayer: (layerId, features) => {
9477
10049
  const layer = layersRef.current.find((l) => l.id === layerId);
9478
10050
  if (!layer || !layer.readOnly || !isMapLoadedRef.current) return false;
9479
- let layerHasTemporal = false;
9480
- const featuresWithIds = features.map((f) => {
9481
- const id = f.id ? String(f.id) : crypto.randomUUID();
9482
- const props = f.properties || {};
9483
- if (!hasAnyTemporalValue(props)) {
9484
- return { ...f, id };
9485
- }
9486
- const { startDate, endDate } = normalizeTemporalProperties(props);
9487
- if (startDate || endDate) layerHasTemporal = true;
9488
- return {
9489
- ...f,
9490
- id,
9491
- properties: {
9492
- ...props,
9493
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9494
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9495
- }
9496
- };
9497
- });
9498
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9499
- layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: layerHasTemporal });
9500
- if (layerHasTemporal) {
10051
+ const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer");
10052
+ readOnlyFeatures.current.set(layerId, prepared.features);
10053
+ layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: prepared.hasTemporal });
10054
+ if (prepared.hasTemporal) {
9501
10055
  scheduleTimelineUpdate();
9502
10056
  }
9503
- const newFeatureIds = featuresWithIds.map((f) => String(f.id));
10057
+ const newFeatureIds = prepared.featureIds;
9504
10058
  const updatedLayers = layersRef.current.map(
9505
10059
  (l) => l.id === layerId ? { ...l, featureIds: newFeatureIds } : l
9506
10060
  );
@@ -9512,29 +10066,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9512
10066
  },
9513
10067
  setLayerData: (name, geojson, options) => {
9514
10068
  if (!isMapLoadedRef.current) return "";
9515
- let layerHasTemporal = false;
9516
- const featuresWithIds = geojson.features.map((f) => {
9517
- const id = f.id ? String(f.id) : crypto.randomUUID();
9518
- const props = f.properties || {};
9519
- if (!hasAnyTemporalValue(props)) {
9520
- return { ...f, id };
9521
- }
9522
- const { startDate, endDate } = normalizeTemporalProperties(props);
9523
- if (startDate || endDate) layerHasTemporal = true;
9524
- return {
9525
- ...f,
9526
- id,
9527
- properties: {
9528
- ...props,
9529
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
9530
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
9531
- }
9532
- };
9533
- });
9534
- const newFeatureIds = featuresWithIds.map((f) => String(f.id));
10069
+ const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData");
10070
+ const newFeatureIds = prepared.featureIds;
9535
10071
  const layerId = `managed-${name}`;
9536
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9537
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: layerHasTemporal });
10072
+ readOnlyFeatures.current.set(layerId, prepared.features);
10073
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9538
10074
  const buildLayerObj = (existing) => {
9539
10075
  const base = {
9540
10076
  id: layerId,
@@ -10765,18 +11301,23 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10765
11301
  react.useEffect(() => {
10766
11302
  if (!map.current || !isMapLoaded) return;
10767
11303
  const mapInstance = map.current;
11304
+ let rafId = null;
10768
11305
  const handleMove = () => {
10769
- if (!hasArrowFeaturesRef.current) return;
10770
- scheduleSync();
11306
+ if (!hasArrowFeaturesRef.current || rafId !== null) return;
11307
+ rafId = requestAnimationFrame(() => {
11308
+ rafId = null;
11309
+ renderArrowOverlays(paintedArrowLinesRef.current);
11310
+ });
10771
11311
  };
10772
11312
  mapInstance.on("move", handleMove);
10773
11313
  return () => {
11314
+ if (rafId !== null) cancelAnimationFrame(rafId);
10774
11315
  try {
10775
11316
  mapInstance.off("move", handleMove);
10776
11317
  } catch {
10777
11318
  }
10778
11319
  };
10779
- }, [isMapLoaded]);
11320
+ }, [isMapLoaded, renderArrowOverlays]);
10780
11321
  react.useEffect(() => {
10781
11322
  if (!map.current || !isMapLoaded || !onViewportChange) return;
10782
11323
  const mapInstance = map.current;
@@ -11099,6 +11640,29 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11099
11640
  return applySelectionFastPath(selectionPaintCacheRef.current, next, source);
11100
11641
  }, []);
11101
11642
  trySelectionFastPathRef.current = trySelectionFastPath;
11643
+ const tryTimelineFastPath = react.useCallback(() => {
11644
+ const m = map.current;
11645
+ if (!m) return true;
11646
+ if (hasArrowFeaturesRef.current) return false;
11647
+ if (layersRef.current.some((l) => {
11648
+ var _a;
11649
+ return l.visible && ((_a = l.traceConfig) == null ? void 0 : _a.enabled);
11650
+ })) return false;
11651
+ const source = m.getSource("custom-features");
11652
+ const { applied, toggled } = applyTimelineFastPath(
11653
+ selectionPaintCacheRef.current,
11654
+ timelineVisibleIdsRef.current,
11655
+ source
11656
+ );
11657
+ if (applied) {
11658
+ const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
11659
+ setVisibleFeatureCount(countVisibleFeatures(threshold));
11660
+ setLabelsSuppressed(false);
11661
+ mapPerfLog("timeline", "fast path applied", { toggled });
11662
+ }
11663
+ return applied;
11664
+ }, [autoLabelConfig, countVisibleFeatures]);
11665
+ tryTimelineFastPathRef.current = tryTimelineFastPath;
11102
11666
  const collectSelectionFeatureGroups = react.useCallback(() => {
11103
11667
  return collectVisibleFeatureGroups(
11104
11668
  draw.current ? draw.current.getAll().features : null,
@@ -11852,7 +12416,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11852
12416
  layerMetadata
11853
12417
  }
11854
12418
  };
11855
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/json" });
12419
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/json" });
11856
12420
  downloadBlob(blob, `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`);
11857
12421
  }, [layers]);
11858
12422
  const handleLoadLayerGeoJSON = react.useCallback((layerId) => {
@@ -11929,7 +12493,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11929
12493
  const handleSaveAllGeoJSON = react.useCallback(() => {
11930
12494
  if (!draw.current) return;
11931
12495
  const geojson = buildEnrichedGeoJSON();
11932
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/geo+json" });
12496
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/geo+json" });
11933
12497
  downloadBlob(blob, "map_export.geojson");
11934
12498
  }, [buildEnrichedGeoJSON]);
11935
12499
  const handleSearchAndAddToNewLayer = react.useCallback(async () => {
@@ -12120,26 +12684,14 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12120
12684
  }
12121
12685
  saveStateForUndo();
12122
12686
  const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12123
- let wsHasTemporal = false;
12124
- const featuresWithIds = result.features.map((f) => {
12125
- const props = f.properties || {};
12126
- const id = f.id ? String(f.id) : crypto.randomUUID();
12127
- if (!hasAnyTemporalValue(props)) return { ...f, id };
12128
- const { startDate, endDate } = normalizeTemporalProperties(props);
12129
- if (startDate || endDate) wsHasTemporal = true;
12130
- return {
12131
- ...f,
12132
- id,
12133
- properties: { ...props, startDate: (startDate == null ? void 0 : startDate.toISOString()) || null, endDate: (endDate == null ? void 0 : endDate.toISOString()) || null }
12134
- };
12135
- });
12136
- readOnlyFeatures.current.set(layerId, featuresWithIds);
12137
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: wsHasTemporal });
12687
+ const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad");
12688
+ readOnlyFeatures.current.set(layerId, prepared.features);
12689
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
12138
12690
  const newLayer = {
12139
12691
  id: layerId,
12140
12692
  name: "Loaded from workspace",
12141
12693
  visible: true,
12142
- featureIds: featuresWithIds.map((f) => String(f.id)),
12694
+ featureIds: prepared.featureIds,
12143
12695
  readOnly: true
12144
12696
  };
12145
12697
  setLayers((prev) => [...prev, newLayer]);
@@ -12148,7 +12700,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12148
12700
  scheduleSync();
12149
12701
  toast({
12150
12702
  title: "Features loaded",
12151
- description: `Created layer with ${featuresWithIds.length} features`
12703
+ description: `Created layer with ${prepared.features.length} features`
12152
12704
  });
12153
12705
  } catch (error) {
12154
12706
  toast({
@@ -12235,195 +12787,194 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12235
12787
  duration: 1e3
12236
12788
  });
12237
12789
  }, [layers, toast]);
12238
- const handleFileChange = react.useCallback((e) => {
12239
- var _a;
12240
- const file = (_a = e.target.files) == null ? void 0 : _a[0];
12241
- if (!file) return;
12242
- const requestedTargetLayerId = e.target.dataset.targetLayer || activeEditingLayerId;
12243
- const createNewLayer = e.target.dataset.createNewLayer === "true";
12244
- delete e.target.dataset.createNewLayer;
12245
- const reader = new FileReader();
12246
- reader.onload = (event) => {
12247
- var _a2, _b;
12248
- try {
12249
- const rawGeojson = JSON.parse((_a2 = event.target) == null ? void 0 : _a2.result);
12250
- if (rawGeojson.type !== "FeatureCollection" || !Array.isArray(rawGeojson.features)) {
12251
- throw new Error("Invalid GeoJSON format");
12252
- }
12253
- if (rawGeojson.features.length === 0) {
12254
- toast({
12255
- title: "Empty GeoJSON",
12256
- description: "The file contains no features",
12257
- variant: "destructive"
12258
- });
12259
- return;
12260
- }
12261
- if (rawGeojson["octostar:map"]) {
12262
- if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data: rawGeojson, file }) === true) {
12263
- return;
12264
- }
12265
- if (!draw.current) return;
12266
- restoreEnrichedGeoJSON(rawGeojson);
12267
- return;
12268
- }
12269
- if (!draw.current) return;
12270
- const { features: geojson, reprojected, sourceCRS } = detectAndReprojectGeoJSON(rawGeojson);
12271
- saveStateForUndo();
12272
- const layerMetadata = (_b = rawGeojson.properties) == null ? void 0 : _b.layerMetadata;
12273
- let fileHasTemporal = false;
12274
- const normalizedFeatures = geojson.features.map((f) => {
12275
- const props = f.properties || {};
12276
- if (!hasAnyTemporalValue(props)) return f;
12277
- const { startDate, endDate } = normalizeTemporalProperties(props);
12278
- if (startDate || endDate) fileHasTemporal = true;
12279
- return {
12280
- ...f,
12281
- properties: {
12282
- ...props,
12283
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
12284
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
12285
- }
12286
- };
12287
- });
12288
- if (createNewLayer) {
12289
- if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({
12290
- kind: "newLayer",
12291
- data: { type: "FeatureCollection", features: normalizedFeatures },
12292
- file,
12293
- reprojected,
12294
- sourceCRS: sourceCRS ?? void 0
12295
- }) === true) {
12296
- return;
12297
- }
12298
- const fileName = file.name.replace(/\.geojson$|\.json$/i, "");
12299
- const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12300
- const newLayer = {
12301
- id: layerId,
12302
- name: (layerMetadata == null ? void 0 : layerMetadata.name) || fileName,
12303
- visible: true,
12304
- featureIds: [],
12305
- readOnly: true,
12306
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12307
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12308
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12309
- };
12310
- const addedIds = [];
12311
- const featuresWithIds = [];
12312
- normalizedFeatures.forEach((f) => {
12313
- const featureId = f.id ? String(f.id) : crypto.randomUUID();
12314
- const normalizedFeature = { ...f, id: featureId };
12315
- featuresWithIds.push(normalizedFeature);
12316
- addedIds.push(featureId);
12317
- });
12318
- readOnlyFeatures.current.set(layerId, featuresWithIds);
12319
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: fileHasTemporal });
12320
- newLayer.featureIds = addedIds;
12321
- setLayers((prev) => [...prev, newLayer]);
12322
- updateFeatureCount();
12323
- scheduleTimelineUpdate();
12324
- scheduleSync();
12325
- if (map.current && geojson.features.length > 0) {
12326
- try {
12327
- const bbox = turf__namespace.bbox(geojson);
12328
- if (bbox && bbox.every((v) => isFinite(v))) {
12329
- map.current.fitBounds(
12330
- [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12331
- { padding: 50, maxZoom: 16, duration: 1e3 }
12332
- );
12333
- }
12334
- } catch (e2) {
12335
- }
12336
- }
12337
- const reprojectMsg2 = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12338
- toast({
12339
- title: "Layer created",
12340
- description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg2} (high-performance mode)`
12341
- });
12342
- return;
12343
- }
12344
- let targetLayer = layers.find((l) => l.id === requestedTargetLayerId && !l.readOnly);
12345
- if (!targetLayer) {
12346
- targetLayer = layers.find((l) => l.visible && !l.readOnly);
12347
- }
12348
- if (!targetLayer) {
12349
- targetLayer = layers.find((l) => !l.readOnly);
12350
- }
12351
- if (targetLayer == null ? void 0 : targetLayer.visible) {
12352
- const addedIds = [];
12353
- isApiAddingRef.current = true;
12354
- try {
12355
- normalizedFeatures.forEach((f) => {
12356
- const ids = draw.current.add(f);
12357
- addedIds.push(ids[0]);
12358
- });
12359
- } finally {
12360
- isApiAddingRef.current = false;
12361
- }
12362
- const targetId = targetLayer.id;
12363
- setLayers((prev) => prev.map((l) => {
12364
- if (l.id !== targetId) return l;
12365
- return {
12366
- ...l,
12367
- featureIds: [...l.featureIds, ...addedIds],
12368
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12369
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12370
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12371
- };
12372
- }));
12373
- } else if (targetLayer) {
12374
- const featuresWithIds = normalizedFeatures.map((f) => ({
12375
- ...f,
12376
- id: f.id || `feature-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`
12377
- }));
12378
- const targetId = targetLayer.id;
12379
- const addedIds = featuresWithIds.map((f) => f.id);
12380
- const existing = hiddenFeatures.current.get(targetId) || [];
12381
- hiddenFeatures.current.set(targetId, [...existing, ...featuresWithIds]);
12382
- setLayers((prev) => prev.map((l) => {
12383
- if (l.id !== targetId) return l;
12384
- return {
12385
- ...l,
12386
- featureIds: [...l.featureIds, ...addedIds],
12387
- ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12388
- ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12389
- ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12390
- };
12391
- }));
12392
- }
12393
- updateFeatureCount();
12394
- scheduleTimelineUpdate();
12395
- scheduleSync();
12396
- const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12790
+ const loadGeoJSONFile = react.useCallback(async (file, requestedTargetLayerId, createNewLayer) => {
12791
+ let result;
12792
+ try {
12793
+ result = await getSharedIngestClient().ingest(file, {
12794
+ idStrategy: "uuid-fallback",
12795
+ emptyIsError: true
12796
+ });
12797
+ } catch (error) {
12798
+ toast({
12799
+ title: "Failed to load GeoJSON",
12800
+ description: error instanceof Error ? error.message : "Invalid file",
12801
+ variant: "destructive"
12802
+ });
12803
+ return;
12804
+ }
12805
+ if (result.kind === "error") {
12806
+ if (result.code === "empty") {
12397
12807
  toast({
12398
- title: "GeoJSON loaded",
12399
- description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
12808
+ title: "Empty GeoJSON",
12809
+ description: result.message,
12810
+ variant: "destructive"
12400
12811
  });
12401
- } catch (error) {
12812
+ } else {
12402
12813
  toast({
12403
12814
  title: "Failed to load GeoJSON",
12404
- description: error instanceof Error ? error.message : "Invalid file",
12815
+ description: result.message,
12405
12816
  variant: "destructive"
12406
12817
  });
12407
12818
  }
12408
- };
12409
- reader.readAsText(file);
12410
- e.target.value = "";
12411
- }, [layers, activeEditingLayerId, saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12412
- const handleDropGeoJSON = react.useCallback((name, data) => {
12819
+ return;
12820
+ }
12821
+ if (result.kind === "enriched") {
12822
+ const rawGeojson = result.data;
12823
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data: rawGeojson, file }) === true) {
12824
+ return;
12825
+ }
12826
+ if (!draw.current) return;
12827
+ restoreEnrichedGeoJSON(rawGeojson);
12828
+ return;
12829
+ }
12830
+ if (!draw.current) return;
12831
+ const { features: normalizedFeatures, reprojected, sourceCRS, hasTemporal: fileHasTemporal } = result;
12832
+ const layerMetadata = result.layerMetadata;
12833
+ saveStateForUndo();
12834
+ if (createNewLayer) {
12835
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({
12836
+ kind: "newLayer",
12837
+ data: { type: "FeatureCollection", features: normalizedFeatures },
12838
+ file,
12839
+ reprojected,
12840
+ sourceCRS: sourceCRS ?? void 0
12841
+ }) === true) {
12842
+ return;
12843
+ }
12844
+ const fileName = file.name.replace(/\.geojson$|\.json$/i, "");
12845
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12846
+ const newLayer = {
12847
+ id: layerId,
12848
+ name: (layerMetadata == null ? void 0 : layerMetadata.name) || fileName,
12849
+ visible: true,
12850
+ featureIds: [],
12851
+ readOnly: true,
12852
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12853
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12854
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12855
+ };
12856
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
12857
+ readOnlyFeatures.current.set(layerId, normalizedFeatures);
12858
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: fileHasTemporal });
12859
+ newLayer.featureIds = addedIds;
12860
+ setLayers((prev) => [...prev, newLayer]);
12861
+ updateFeatureCount();
12862
+ scheduleTimelineUpdate();
12863
+ scheduleSync();
12864
+ if (map.current && result.bbox) {
12865
+ const bbox = result.bbox;
12866
+ map.current.fitBounds(
12867
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12868
+ { padding: 50, maxZoom: 16, duration: 1e3 }
12869
+ );
12870
+ }
12871
+ const reprojectMsg2 = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12872
+ toast({
12873
+ title: "Layer created",
12874
+ description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg2} (high-performance mode)`
12875
+ });
12876
+ return;
12877
+ }
12878
+ const currentLayers = layersRef.current;
12879
+ let targetLayer = currentLayers.find((l) => l.id === requestedTargetLayerId && !l.readOnly);
12880
+ if (!targetLayer) {
12881
+ targetLayer = currentLayers.find((l) => l.visible && !l.readOnly);
12882
+ }
12883
+ if (!targetLayer) {
12884
+ targetLayer = currentLayers.find((l) => !l.readOnly);
12885
+ }
12886
+ if (targetLayer == null ? void 0 : targetLayer.visible) {
12887
+ const addedIds = [];
12888
+ isApiAddingRef.current = true;
12889
+ try {
12890
+ normalizedFeatures.forEach((f) => {
12891
+ const ids = draw.current.add(f);
12892
+ addedIds.push(ids[0]);
12893
+ });
12894
+ } finally {
12895
+ isApiAddingRef.current = false;
12896
+ }
12897
+ const targetId = targetLayer.id;
12898
+ setLayers((prev) => prev.map((l) => {
12899
+ if (l.id !== targetId) return l;
12900
+ return {
12901
+ ...l,
12902
+ featureIds: [...l.featureIds, ...addedIds],
12903
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12904
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12905
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12906
+ };
12907
+ }));
12908
+ } else if (targetLayer) {
12909
+ const targetId = targetLayer.id;
12910
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
12911
+ const existing = hiddenFeatures.current.get(targetId) || [];
12912
+ hiddenFeatures.current.set(targetId, [...existing, ...normalizedFeatures]);
12913
+ setLayers((prev) => prev.map((l) => {
12914
+ if (l.id !== targetId) return l;
12915
+ return {
12916
+ ...l,
12917
+ featureIds: [...l.featureIds, ...addedIds],
12918
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12919
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12920
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
12921
+ };
12922
+ }));
12923
+ }
12924
+ updateFeatureCount();
12925
+ scheduleTimelineUpdate();
12926
+ scheduleSync();
12927
+ const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12928
+ toast({
12929
+ title: "GeoJSON loaded",
12930
+ description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
12931
+ });
12932
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
12933
+ const handleFileChange = react.useCallback((e) => {
12413
12934
  var _a;
12935
+ const file = (_a = e.target.files) == null ? void 0 : _a[0];
12936
+ if (!file) return;
12937
+ const requestedTargetLayerId = e.target.dataset.targetLayer || activeEditingLayerId;
12938
+ const createNewLayer = e.target.dataset.createNewLayer === "true";
12939
+ delete e.target.dataset.createNewLayer;
12940
+ e.target.value = "";
12941
+ void loadGeoJSONFile(file, requestedTargetLayerId, createNewLayer);
12942
+ }, [activeEditingLayerId, loadGeoJSONFile]);
12943
+ const ingestDroppedLayer = react.useCallback(async (name, input) => {
12944
+ if (!map.current) return;
12945
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12946
+ const startedAt = performance.now();
12947
+ let result;
12948
+ try {
12949
+ result = await getSharedIngestClient().ingest(input, { idStrategy: "layer-index", layerId });
12950
+ } catch (error) {
12951
+ toast({
12952
+ title: "Failed to load GeoJSON",
12953
+ description: error instanceof Error ? error.message : "Invalid file",
12954
+ variant: "destructive"
12955
+ });
12956
+ return;
12957
+ }
12414
12958
  if (!map.current) return;
12415
- if (data["octostar:map"]) {
12959
+ if (result.kind === "error") {
12960
+ toast({
12961
+ title: "Failed to load GeoJSON",
12962
+ description: result.message,
12963
+ variant: "destructive"
12964
+ });
12965
+ return;
12966
+ }
12967
+ if (result.kind === "enriched") {
12968
+ const data = result.data;
12416
12969
  if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data, sourceName: name }) === true) {
12417
12970
  return;
12418
12971
  }
12419
12972
  restoreEnrichedGeoJSON(data);
12420
12973
  return;
12421
12974
  }
12422
- const { features: reprojectedData, reprojected, sourceCRS } = detectAndReprojectGeoJSON(data);
12975
+ const { features: normalizedFeatures, reprojected, sourceCRS } = result;
12976
+ const layerMetadata = result.layerMetadata;
12423
12977
  saveStateForUndo();
12424
- const layerMetadata = (_a = data.properties) == null ? void 0 : _a.layerMetadata;
12425
- const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
12426
- const layerHasAltitudeData = reprojectedData.features.some((f) => hasAltitudeData(f));
12427
12978
  const newLayer = {
12428
12979
  id: layerId,
12429
12980
  name: (layerMetadata == null ? void 0 : layerMetadata.name) || name,
@@ -12434,34 +12985,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12434
12985
  ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12435
12986
  ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12436
12987
  ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig },
12437
- ...layerHasAltitudeData && { hasAltitudeData: true, altitudeDisplayMode: "both" }
12988
+ ...result.hasAltitude && { hasAltitudeData: true, altitudeDisplayMode: "both" }
12438
12989
  };
12439
- const normalizedFeatures = [];
12440
- const addedIds = [];
12441
- let dropHasTemporal = false;
12442
- reprojectedData.features.forEach((f, index) => {
12443
- const featureId = f.id !== void 0 && f.id !== null ? String(f.id) : `${layerId}-f${index}`;
12444
- const props = f.properties || {};
12445
- if (!hasAnyTemporalValue(props)) {
12446
- normalizedFeatures.push({ ...f, id: featureId });
12447
- addedIds.push(featureId);
12448
- return;
12449
- }
12450
- const { startDate, endDate } = normalizeTemporalProperties(props);
12451
- if (startDate || endDate) dropHasTemporal = true;
12452
- normalizedFeatures.push({
12453
- ...f,
12454
- id: featureId,
12455
- properties: {
12456
- ...props,
12457
- startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
12458
- endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
12459
- }
12460
- });
12461
- addedIds.push(featureId);
12462
- });
12990
+ const addedIds = normalizedFeatures.map((f) => f.id);
12463
12991
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
12464
- layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: dropHasTemporal });
12992
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: result.hasTemporal });
12465
12993
  newLayer.featureIds = addedIds;
12466
12994
  const nextLayers = [...layersRef.current, newLayer];
12467
12995
  layersRef.current = nextLayers;
@@ -12469,28 +12997,35 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12469
12997
  updateFeatureCount();
12470
12998
  scheduleTimelineUpdate();
12471
12999
  scheduleSync();
12472
- if (reprojectedData.features.length > 0) {
12473
- try {
12474
- const bbox = turf__namespace.bbox(reprojectedData);
12475
- if (bbox && bbox.every((v) => isFinite(v))) {
12476
- map.current.fitBounds(
12477
- [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
12478
- { padding: 50, maxZoom: 16, duration: 1e3 }
12479
- );
12480
- }
12481
- } catch (e) {
12482
- }
13000
+ if (result.bbox) {
13001
+ const bbox = result.bbox;
13002
+ map.current.fitBounds(
13003
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
13004
+ { padding: 50, maxZoom: 16, duration: 1e3 }
13005
+ );
12483
13006
  }
13007
+ mapPerfLog("ingest", `dropped layer "${newLayer.name}" applied`, {
13008
+ features: addedIds.length,
13009
+ totalMs: Math.round(performance.now() - startedAt)
13010
+ });
12484
13011
  const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12485
13012
  toast({
12486
13013
  title: "Layer added",
12487
13014
  description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg} (high-performance)`
12488
13015
  });
12489
13016
  }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
13017
+ const handleDropGeoJSON = react.useCallback((name, data) => {
13018
+ void ingestDroppedLayer(name, data);
13019
+ }, [ingestDroppedLayer]);
13020
+ const handleDropGeoJSONFile = react.useCallback((name, file) => {
13021
+ void ingestDroppedLayer(name, file);
13022
+ }, [ingestDroppedLayer]);
12490
13023
  const handleTimelineFilterChange = react.useCallback((visibleIds, hiddenIds, untimedIds) => {
12491
13024
  if (!draw.current || !map.current) return;
12492
- timelineVisibleIdsRef.current = /* @__PURE__ */ new Set([...visibleIds, ...untimedIds]);
12493
- scheduleSync();
13025
+ const nextVisible = new Set(visibleIds);
13026
+ untimedIds.forEach((id) => nextVisible.add(id));
13027
+ timelineVisibleIdsRef.current = nextVisible;
13028
+ scheduleSync("timeline");
12494
13029
  }, [scheduleSync]);
12495
13030
  const prevTimelineEnabledRef = react.useRef(timelineStore.isEnabled);
12496
13031
  react.useEffect(() => {
@@ -12874,7 +13409,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12874
13409
  ] }) });
12875
13410
  }
12876
13411
  const toastContextValue = toastProvider ?? null;
12877
- return /* @__PURE__ */ jsxRuntime.jsx(TimelineStoreContext.Provider, { value: timelineStoreApi, children: /* @__PURE__ */ jsxRuntime.jsx(ToastContext.Provider, { value: toastContextValue, children: /* @__PURE__ */ jsxRuntime.jsx(MapDropZone, { onDrop: handleDropGeoJSON, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `map-container w-full h-full min-w-0 relative overflow-hidden isolate ${className || ""}`, "data-testid": "map-editor-canvas", children: [
13412
+ return /* @__PURE__ */ jsxRuntime.jsx(TimelineStoreContext.Provider, { value: timelineStoreApi, children: /* @__PURE__ */ jsxRuntime.jsx(ToastContext.Provider, { value: toastContextValue, children: /* @__PURE__ */ jsxRuntime.jsx(MapDropZone, { onDrop: handleDropGeoJSON, onDropFile: handleDropGeoJSONFile, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: `map-container w-full h-full min-w-0 relative overflow-hidden isolate ${className || ""}`, "data-testid": "map-editor-canvas", children: [
12878
13413
  /* @__PURE__ */ jsxRuntime.jsx(
12879
13414
  "div",
12880
13415
  {
@@ -13353,18 +13888,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13353
13888
  ))
13354
13889
  }
13355
13890
  ),
13356
- cursorCoords && /* @__PURE__ */ jsxRuntime.jsxs(
13357
- "div",
13358
- {
13359
- className: "absolute bottom-1 right-12 z-10 pointer-events-none font-mono text-[10px] text-muted-foreground/70 select-none",
13360
- "data-testid": "cursor-coordinates",
13361
- children: [
13362
- cursorCoords.lat.toFixed(5),
13363
- ", ",
13364
- cursorCoords.lng.toFixed(5)
13365
- ]
13366
- }
13367
- ),
13891
+ /* @__PURE__ */ jsxRuntime.jsx(CursorCoordinatesOverlay, { map: isMapLoaded ? map.current : null }),
13368
13892
  /* @__PURE__ */ jsxRuntime.jsx(
13369
13893
  "input",
13370
13894
  {
@@ -14128,7 +14652,15 @@ function DebugSidebar({ onAddRandomPoints, onImportKML, onAddDomMarkers, onRemov
14128
14652
  const geojson = parseKMLToGeoJSON(content);
14129
14653
  if (geojson && onImportKML) {
14130
14654
  const layerName = file.name.replace(/\.(kml|kmz)$/i, "");
14131
- onImportKML(layerName, geojson);
14655
+ void getSharedIngestClient().ingest(geojson, { idStrategy: "preserve" }).then((result) => {
14656
+ onImportKML(
14657
+ layerName,
14658
+ result.kind === "features" ? { type: "FeatureCollection", features: result.features } : geojson
14659
+ );
14660
+ }).catch((err) => {
14661
+ console.warn("[map-component] KML ingest normalization failed:", err);
14662
+ onImportKML(layerName, geojson);
14663
+ });
14132
14664
  }
14133
14665
  };
14134
14666
  reader.readAsText(file);