@octostar/map-component 0.2.12 → 0.2.14

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 (52) hide show
  1. package/dist/index.cjs +1422 -644
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.mjs +1418 -640
  4. package/dist/index.mjs.map +1 -1
  5. package/dist/styles.css +5 -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/ingest-progress-overlay.d.ts +12 -0
  10. package/dist/types/components/ingest-progress-overlay.d.ts.map +1 -0
  11. package/dist/types/components/map-drop-zone.d.ts +7 -1
  12. package/dist/types/components/map-drop-zone.d.ts.map +1 -1
  13. package/dist/types/components/map-editor-canvas.d.ts.map +1 -1
  14. package/dist/types/index.d.ts +1 -0
  15. package/dist/types/index.d.ts.map +1 -1
  16. package/dist/types/lib/draw-render-gate.d.ts +10 -0
  17. package/dist/types/lib/draw-render-gate.d.ts.map +1 -0
  18. package/dist/types/lib/geojson-crs.d.ts +10 -0
  19. package/dist/types/lib/geojson-crs.d.ts.map +1 -0
  20. package/dist/types/lib/geojson-reproject.d.ts +15 -0
  21. package/dist/types/lib/geojson-reproject.d.ts.map +1 -0
  22. package/dist/types/lib/geojson-serialize.d.ts +21 -0
  23. package/dist/types/lib/geojson-serialize.d.ts.map +1 -0
  24. package/dist/types/lib/ingest-client.d.ts +43 -0
  25. package/dist/types/lib/ingest-client.d.ts.map +1 -0
  26. package/dist/types/lib/ingest-pipeline.d.ts +125 -0
  27. package/dist/types/lib/ingest-pipeline.d.ts.map +1 -0
  28. package/dist/types/lib/ingest-progress.d.ts +21 -0
  29. package/dist/types/lib/ingest-progress.d.ts.map +1 -0
  30. package/dist/types/lib/ingest-stream.d.ts +50 -0
  31. package/dist/types/lib/ingest-stream.d.ts.map +1 -0
  32. package/dist/types/lib/ingest.worker.d.ts +2 -0
  33. package/dist/types/lib/ingest.worker.d.ts.map +1 -0
  34. package/dist/types/lib/map-editor-api.d.ts +18 -0
  35. package/dist/types/lib/map-editor-api.d.ts.map +1 -1
  36. package/dist/types/lib/perf-log.d.ts +3 -0
  37. package/dist/types/lib/perf-log.d.ts.map +1 -0
  38. package/dist/types/lib/selection-diff.d.ts +24 -1
  39. package/dist/types/lib/selection-diff.d.ts.map +1 -1
  40. package/dist/types/lib/selection-hit-test.d.ts +25 -14
  41. package/dist/types/lib/selection-hit-test.d.ts.map +1 -1
  42. package/dist/types/lib/selection-spatial-index.d.ts +63 -0
  43. package/dist/types/lib/selection-spatial-index.d.ts.map +1 -0
  44. package/dist/types/lib/temporal-ingest.d.ts +53 -0
  45. package/dist/types/lib/temporal-ingest.d.ts.map +1 -0
  46. package/dist/types/lib/temporal-normalize.d.ts +11 -0
  47. package/dist/types/lib/temporal-normalize.d.ts.map +1 -0
  48. package/dist/types/lib/timeline-diff.d.ts +43 -0
  49. package/dist/types/lib/timeline-diff.d.ts.map +1 -0
  50. package/dist/types/lib/timeline-store.d.ts +1 -9
  51. package/dist/types/lib/timeline-store.d.ts.map +1 -1
  52. package/package.json +6 -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) {
@@ -28,13 +29,703 @@ function _interopNamespaceDefault(e) {
28
29
  });
29
30
  }
30
31
  }
31
- }
32
- n.default = e;
33
- return Object.freeze(n);
32
+ }
33
+ n.default = e;
34
+ return Object.freeze(n);
35
+ }
36
+ const turf__namespace = /* @__PURE__ */ _interopNamespaceDefault(turf);
37
+ const THREE__namespace = /* @__PURE__ */ _interopNamespaceDefault(THREE);
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 p(e){let t=e.crs?.properties?.name,n=null;if(t){let r=t.match(/EPSG::?(\\d+)/i);r&&(n=`EPSG:${r[1]}`)}if(!n&&e.features.length>0){let r=w(e.features[0].geometry);if(r){let[s,a]=r;if(Math.abs(s)<=180&&Math.abs(a)<=90)return{sourceCRS:"EPSG:4326",needsReprojection:!1}}return{sourceCRS:null,needsReprojection:!1}}return{sourceCRS:n,needsReprojection:n!==null&&n!=="EPSG:4326"}}function w(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 S(e){return e.geometry?.type==="LineString"?e.geometry.coordinates.some(n=>n.length>=3&&n[2]!==0):e.geometry?.type==="MultiLineString"?e.geometry.coordinates.some(n=>n.some(r=>r.length>=3&&r[2]!==0)):!1}function i(e){if(!e)return null;if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return isNaN(t.getTime())?null:t}return null}function b(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 I(e){let t=i(e.startDate)||i(e.startdate)||i(e.start_date)||i(e.start_time)||i(e.date)||i(e.timestamp)||i(e.flightDate)||i(e.time)||i(e.datetime),n=i(e.endDate)||i(e.enddate)||i(e.end_date)||i(e.end_time);return t&&n&&n<t&&([t,n]=[n,t]),{startDate:t,endDate:n}}function h(e){return"kind"in e&&e.kind==="ack"}function J(){let e=globalThis.crypto?.randomUUID?.bind(globalThis.crypto);return e?e():`f-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function D(e,t,n){switch(n.idStrategy){case"preserve":return e.id;case"layer-index":return e.id!==void 0&&e.id!==null?String(e.id):`${n.layerId}-f${t}`;case"uuid-fallback":return e.id?String(e.id):J()}}function C(e,t){if(Array.isArray(e)){if(typeof e[0]=="number"){let n=e[0],r=e[1];t[0]=Math.min(t[0],n),t[1]=Math.min(t[1],r),t[2]=Math.max(t[2],n),t[3]=Math.max(t[3],r);return}for(let n of e)C(n,t)}}function R(e,t){if(e){if(e.type==="GeometryCollection"){for(let n of e.geometries)R(n,t);return}C(e.coordinates,t)}}function M(e){let t=[1/0,1/0,-1/0,-1/0];for(let n of e)R(n.geometry,t);return t.every(n=>isFinite(n))?t:null}function x(e,t){let n;if(e.type==="text")try{n=JSON.parse(e.text)}catch(d){return{kind:"error",code:"parse-error",message:d instanceof Error?d.message:"Invalid file"}}else n=e.data;if(n&&n.type==="Feature"&&(n={type:"FeatureCollection",features:[n]}),!n||n.type!=="FeatureCollection"||!Array.isArray(n.features))return{kind:"error",code:"invalid-format",message:"Invalid GeoJSON format"};if(t.emptyIsError&&n.features.length===0)return{kind:"error",code:"empty",message:"The file contains no features"};if(n["octostar:map"])return{kind:"enriched",data:n};let{sourceCRS:r,needsReprojection:s}=p(n),a=!1,o=!1,u=[];n.features.forEach((d,G)=>{let m=D(d,G,t);!o&&S(d)&&(o=!0);let g=d.properties||{};if(!b(g)){u.push(t.idStrategy==="preserve"?d:{...d,id:m});return}let{startDate:y,endDate:k}=I(g);(y||k)&&(a=!0),u.push({...d,...m!==void 0&&{id:m},properties:{...g,startDate:y?.toISOString()||null,endDate:k?.toISOString()||null}})});let c=n.properties?.layerMetadata;return{kind:"features",features:u,featureCount:u.length,bbox:M(u),hasTemporal:a,hasAltitude:o,reprojected:!1,sourceCRS:r,...s&&{needsReprojection:s},...c&&{layerMetadata:c}}}var O=5e3;function P(e,t){let n=Number.isNaN(t)?O:Math.max(1,Math.floor(t)),r=[];for(let s=0;s<e.length;s+=n)r.push(e.slice(s,s+n));return r}function f(e){if(e===void 0)return!1;if(typeof e=="number")return Number.isFinite(e)&&!Object.is(e,-0);if(e===null||typeof e!="object")return!0;if(Array.isArray(e)){for(let t=0;t<e.length;t++)if(!f(e[t]))return!1;return!0}for(let t in e)if(!f(e[t]))return!1;return!0}function A(e){for(let t=0;t<e.length;t++)if(!f(e[t]))return e;try{return JSON.stringify(e)}catch{return e}}function E(e){let{kind:t,features:n,...r}=e;return r}async function N(e,t,n,r){let s;try{s=x(t,n)}catch(a){r.post({kind:"result",id:e,ok:!1,error:a instanceof Error?a.message:String(a)});return}if(s.kind!=="features"){r.post({kind:"result",id:e,ok:!0,result:s});return}try{let a=r.encode??A,o=P(s.features,r.chunkSize??O);r.post({kind:"head",id:e,summary:E(s)});let u=o.length>0?a(o[0]):null;for(let c=0;c<o.length;c++){let d=r.waitAck(c);r.post({kind:"chunk",id:e,seq:c,payload:u}),u=c+1<o.length?a(o[c+1]):null,await d}r.post({kind:"done",id:e,chunkCount:o.length})}catch(a){r.post({kind:"error",id:e,message:a instanceof Error?a.message:String(a)})}}var F=e=>self.postMessage(e),l=new Map;self.onmessage=async e=>{let t=e.data;if(h(t)){let o=`${t.id}:${t.seq}`,u=l.get(o);l.delete(o),u?.();return}let{id:n,source:r,options:s,tuning:a}=t;try{let o=r.type==="blob"?{type:"text",text:await r.blob.text()}:r;await N(n,o,s,{post:F,waitAck:u=>new Promise(c=>{l.set(`${n}:${u}`,c)}),...a?.chunkSize!==void 0&&{chunkSize:a.chunkSize},...a?.featureArrayChunks&&{encode:u=>u}})}catch(o){F({kind:"result",id:n,ok:!1,error:o instanceof Error?o.message:String(o)})}finally{l.forEach((o,u)=>{u.startsWith(`${n}:`)&&l.delete(u)})}};})();\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
+ // Omit the key rather than set `id: undefined` ('preserve' + id-less
270
+ // feature): an own undefined key survives structured clone but is
271
+ // dropped by JSON chunks, so it would make the transfer encoding
272
+ // observable. Never undefined for the other strategies.
273
+ ...id !== void 0 && { id },
274
+ properties: {
275
+ ...props,
276
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
277
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
278
+ }
279
+ });
280
+ });
281
+ const layerMetadata = (_a = data.properties) == null ? void 0 : _a.layerMetadata;
282
+ return {
283
+ kind: "features",
284
+ features,
285
+ featureCount: features.length,
286
+ bbox: computeFeatureCollectionBbox(features),
287
+ hasTemporal,
288
+ hasAltitude,
289
+ reprojected: false,
290
+ sourceCRS,
291
+ ...needsReprojection && { needsReprojection },
292
+ ...layerMetadata && { layerMetadata }
293
+ };
294
+ }
295
+ function decodeChunkPayload(payload) {
296
+ return typeof payload === "string" ? JSON.parse(payload) : payload;
297
+ }
298
+ const fromStorage = (() => {
299
+ var _a;
300
+ try {
301
+ return ((_a = globalThis.localStorage) == null ? void 0 : _a.getItem("octostar-map-perf-log")) === "1";
302
+ } catch {
303
+ return false;
304
+ }
305
+ })();
306
+ function mapPerfLogEnabled() {
307
+ return fromStorage || globalThis.__octostarMapPerfLog === true;
308
+ }
309
+ function mapPerfLog(area, message, data) {
310
+ if (!mapPerfLogEnabled()) return;
311
+ if (data === void 0) {
312
+ console.info(`[map-perf:${area}] ${message}`);
313
+ } else {
314
+ console.info(`[map-perf:${area}] ${message}`, data);
315
+ }
316
+ }
317
+ function finalizeReprojection(result) {
318
+ if (result.kind !== "features" || !result.needsReprojection || !result.sourceCRS) return result;
319
+ const reprojected = reprojectFeatures(result.features, result.sourceCRS);
320
+ if (!reprojected) {
321
+ return { ...result, needsReprojection: false };
322
+ }
323
+ return {
324
+ ...result,
325
+ features: reprojected,
326
+ reprojected: true,
327
+ needsReprojection: false,
328
+ bbox: computeFeatureCollectionBbox(reprojected)
329
+ };
330
+ }
331
+ function createWorkerPort() {
332
+ if (typeof Worker === "undefined") {
333
+ mapPerfLog("ingest", "Worker unavailable in this environment — using main-thread pipeline");
334
+ return null;
335
+ }
336
+ let url = null;
337
+ try {
338
+ url = URL.createObjectURL(new Blob([ingestWorkerSource], { type: "text/javascript" }));
339
+ const worker = new Worker(url);
340
+ let pendingUrl = url;
341
+ const revokePendingUrl = () => {
342
+ if (pendingUrl) URL.revokeObjectURL(pendingUrl);
343
+ pendingUrl = null;
344
+ };
345
+ mapPerfLog("ingest", "worker spawned");
346
+ return {
347
+ post: (msg) => worker.postMessage(msg),
348
+ onMessage: (cb) => {
349
+ worker.onmessage = (e) => {
350
+ revokePendingUrl();
351
+ cb(e.data);
352
+ };
353
+ },
354
+ onError: (cb) => {
355
+ worker.onerror = (e) => {
356
+ revokePendingUrl();
357
+ cb(e);
358
+ };
359
+ worker.onmessageerror = (e) => cb(e);
360
+ },
361
+ terminate: () => {
362
+ revokePendingUrl();
363
+ worker.terminate();
364
+ }
365
+ };
366
+ } catch (err) {
367
+ if (url) URL.revokeObjectURL(url);
368
+ console.warn(
369
+ "[map-component] Ingest worker could not be spawned (CSP may block blob: workers); file parsing will run on the main thread.",
370
+ err
371
+ );
372
+ return null;
373
+ }
374
+ }
375
+ const INGEST_STALL_TIMEOUT_MS = 12e4;
376
+ function assembleStreamResult(stream) {
377
+ return finalizeReprojection({ kind: "features", ...stream.summary, features: stream.features });
378
+ }
379
+ function createIngestClient(portFactory = createWorkerPort) {
380
+ let port = null;
381
+ let portUnavailable = false;
382
+ let nextId = 0;
383
+ const pending = /* @__PURE__ */ new Map();
384
+ const rejectAllPending = (reason) => {
385
+ pending.forEach((request) => {
386
+ clearTimeout(request.timeout);
387
+ request.reject(new Error(reason));
388
+ });
389
+ pending.clear();
390
+ };
391
+ const abandonPort = (reason) => {
392
+ rejectAllPending(reason);
393
+ port == null ? void 0 : port.terminate();
394
+ port = null;
395
+ };
396
+ const armWatchdog = (request) => {
397
+ clearTimeout(request.timeout);
398
+ request.timeout = setTimeout(() => {
399
+ console.warn(
400
+ `[map-component] Ingest worker unresponsive for "${request.label}" after ${INGEST_STALL_TIMEOUT_MS}ms; it will be respawned on next use.`
401
+ );
402
+ abandonPort("Ingest worker unresponsive — the file could not be parsed");
403
+ }, INGEST_STALL_TIMEOUT_MS);
404
+ };
405
+ const callHook = (request, invoke) => {
406
+ if (!request.hooks) return;
407
+ try {
408
+ invoke(request.hooks);
409
+ } catch (err) {
410
+ console.warn("[map-component] Ingest stream hook threw; progress reporting disabled for this request.", err);
411
+ request.hooks = void 0;
412
+ }
413
+ };
414
+ const settle = (id, request) => {
415
+ pending.delete(id);
416
+ clearTimeout(request.timeout);
417
+ };
418
+ const handleChunk = (activePort, request, msg) => {
419
+ const stream = request.stream;
420
+ if (!stream || msg.seq !== stream.nextSeq) {
421
+ abandonPort("Ingest worker sent an out-of-order chunk");
422
+ return;
423
+ }
424
+ armWatchdog(request);
425
+ const features = decodeChunkPayload(msg.payload);
426
+ features.forEach((f) => stream.features.push(f));
427
+ stream.nextSeq += 1;
428
+ callHook(request, (hooks) => {
429
+ var _a;
430
+ return (_a = hooks.onProgress) == null ? void 0 : _a.call(hooks, stream.features.length, stream.summary.featureCount);
431
+ });
432
+ activePort.post({ kind: "ack", id: msg.id, seq: msg.seq });
433
+ };
434
+ const handleMessage = (activePort, msg) => {
435
+ const request = pending.get(msg.id);
436
+ if (!request) return;
437
+ switch (msg.kind) {
438
+ case "result": {
439
+ if (request.stream) {
440
+ abandonPort("Ingest worker sent a single-shot result mid-stream");
441
+ return;
442
+ }
443
+ if (!msg.ok) {
444
+ settle(msg.id, request);
445
+ mapPerfLog("ingest", `worker request "${request.label}" finished`, {
446
+ ms: Math.round(performance.now() - request.startedAt),
447
+ ok: false
448
+ });
449
+ request.reject(new Error(msg.error));
450
+ return;
451
+ }
452
+ let finalized;
453
+ try {
454
+ finalized = finalizeReprojection(msg.result);
455
+ } catch (err) {
456
+ settle(msg.id, request);
457
+ request.reject(err instanceof Error ? err : new Error(String(err)));
458
+ return;
459
+ }
460
+ settle(msg.id, request);
461
+ mapPerfLog("ingest", `worker request "${request.label}" finished`, {
462
+ ms: Math.round(performance.now() - request.startedAt),
463
+ ok: true
464
+ });
465
+ request.resolve(finalized);
466
+ return;
467
+ }
468
+ case "head":
469
+ if (request.stream) {
470
+ abandonPort("Ingest worker restarted a stream mid-request");
471
+ return;
472
+ }
473
+ armWatchdog(request);
474
+ request.stream = {
475
+ summary: msg.summary,
476
+ features: [],
477
+ nextSeq: 0
478
+ };
479
+ callHook(request, (hooks) => {
480
+ var _a;
481
+ return (_a = hooks.onHead) == null ? void 0 : _a.call(hooks, msg.summary);
482
+ });
483
+ return;
484
+ case "chunk":
485
+ try {
486
+ handleChunk(activePort, request, msg);
487
+ } catch (err) {
488
+ console.warn("[map-component] Ingest chunk could not be processed; abandoning the worker.", err);
489
+ abandonPort("Ingest worker sent an unreadable chunk");
490
+ }
491
+ return;
492
+ case "done": {
493
+ const stream = request.stream;
494
+ if (!stream) {
495
+ abandonPort("Ingest worker completed a stream that never started");
496
+ return;
497
+ }
498
+ if (msg.chunkCount !== stream.nextSeq) {
499
+ abandonPort("Ingest worker stream ended with missing chunks");
500
+ return;
501
+ }
502
+ let assembled;
503
+ try {
504
+ assembled = assembleStreamResult(stream);
505
+ } catch (err) {
506
+ settle(msg.id, request);
507
+ request.reject(err instanceof Error ? err : new Error(String(err)));
508
+ return;
509
+ }
510
+ settle(msg.id, request);
511
+ mapPerfLog("ingest", `worker request "${request.label}" streamed`, {
512
+ ms: Math.round(performance.now() - request.startedAt),
513
+ features: stream.features.length,
514
+ chunks: msg.chunkCount
515
+ });
516
+ request.resolve(assembled);
517
+ return;
518
+ }
519
+ case "error":
520
+ settle(msg.id, request);
521
+ mapPerfLog("ingest", `worker request "${request.label}" failed mid-stream`, {
522
+ ms: Math.round(performance.now() - request.startedAt)
523
+ });
524
+ request.reject(new Error(msg.message));
525
+ return;
526
+ }
527
+ };
528
+ const ensurePort = () => {
529
+ if (portUnavailable || port) return port;
530
+ try {
531
+ port = portFactory();
532
+ } catch {
533
+ port = null;
534
+ }
535
+ if (!port) {
536
+ portUnavailable = true;
537
+ return null;
538
+ }
539
+ const activePort = port;
540
+ activePort.onMessage((msg) => handleMessage(activePort, msg));
541
+ activePort.onError((err) => {
542
+ console.warn("[map-component] Ingest worker crashed; it will be respawned on next use.", err);
543
+ abandonPort("Ingest worker crashed");
544
+ });
545
+ return port;
546
+ };
547
+ const runInline = async (input, options) => {
548
+ const text = typeof input === "string" ? input : await input.text();
549
+ const startedAt = performance.now();
550
+ const result = finalizeReprojection(runIngestPipeline({ type: "text", text }, options));
551
+ mapPerfLog("ingest", "main-thread pipeline finished (no worker)", {
552
+ ms: Math.round(performance.now() - startedAt)
553
+ });
554
+ return result;
555
+ };
556
+ return {
557
+ ingest(input, options, stream, tuning) {
558
+ if (typeof input === "object" && !(input instanceof Blob)) {
559
+ return Promise.resolve().then(
560
+ () => finalizeReprojection(runIngestPipeline({ type: "parsed", data: input }, options))
561
+ );
562
+ }
563
+ const activePort = ensurePort();
564
+ if (!activePort) return runInline(input, options);
565
+ const id = nextId++;
566
+ const label = input instanceof File ? input.name : typeof input === "string" ? "text" : "blob";
567
+ return new Promise((resolve, reject) => {
568
+ const request = {
569
+ resolve,
570
+ reject,
571
+ startedAt: performance.now(),
572
+ label,
573
+ hooks: stream
574
+ };
575
+ armWatchdog(request);
576
+ pending.set(id, request);
577
+ try {
578
+ activePort.post({
579
+ id,
580
+ source: typeof input === "string" ? { type: "text", text: input } : { type: "blob", blob: input },
581
+ options,
582
+ ...tuning && { tuning }
583
+ });
584
+ } catch (err) {
585
+ settle(id, request);
586
+ throw err;
587
+ }
588
+ });
589
+ },
590
+ dispose() {
591
+ abandonPort("Ingest client disposed");
592
+ portUnavailable = false;
593
+ }
594
+ };
595
+ }
596
+ let sharedClient = null;
597
+ function getSharedIngestClient() {
598
+ if (!sharedClient) sharedClient = createIngestClient();
599
+ return sharedClient;
600
+ }
601
+ function createIngestProgressStore() {
602
+ const entries = /* @__PURE__ */ new Map();
603
+ const listeners = /* @__PURE__ */ new Set();
604
+ let nextId = 0;
605
+ let snapshot = [];
606
+ let dirty = false;
607
+ const notify = () => {
608
+ dirty = true;
609
+ listeners.forEach((listener) => listener());
610
+ };
611
+ return {
612
+ begin(label) {
613
+ const id = nextId++;
614
+ entries.set(id, { label, received: 0, total: null });
615
+ notify();
616
+ return {
617
+ setTotal(total) {
618
+ const entry = entries.get(id);
619
+ if (!entry || entry.total === total) return;
620
+ entry.total = total;
621
+ notify();
622
+ },
623
+ update(received) {
624
+ const entry = entries.get(id);
625
+ if (!entry || entry.received === received) return;
626
+ entry.received = received;
627
+ notify();
628
+ },
629
+ end() {
630
+ if (entries.delete(id)) notify();
631
+ }
632
+ };
633
+ },
634
+ subscribe(listener) {
635
+ listeners.add(listener);
636
+ return () => listeners.delete(listener);
637
+ },
638
+ getSnapshot() {
639
+ if (dirty) {
640
+ const next = [];
641
+ entries.forEach((entry, id) => next.push({ id, ...entry }));
642
+ snapshot = next;
643
+ dirty = false;
644
+ }
645
+ return snapshot;
646
+ }
647
+ };
648
+ }
649
+ function CursorCoordinatesOverlay({ map }) {
650
+ const [coords, setCoords] = react.useState(null);
651
+ react.useEffect(() => {
652
+ if (!map) return;
653
+ let pending = null;
654
+ let frame = 0;
655
+ const flush = () => {
656
+ frame = 0;
657
+ setCoords(pending);
658
+ };
659
+ const schedule = (next) => {
660
+ pending = next;
661
+ if (!frame) frame = requestAnimationFrame(flush);
662
+ };
663
+ const onMove = (e) => schedule({ lng: e.lngLat.lng, lat: e.lngLat.lat });
664
+ const onOut = () => schedule(null);
665
+ map.on("mousemove", onMove);
666
+ map.on("mouseout", onOut);
667
+ return () => {
668
+ if (frame) cancelAnimationFrame(frame);
669
+ try {
670
+ map.off("mousemove", onMove);
671
+ map.off("mouseout", onOut);
672
+ } catch {
673
+ }
674
+ };
675
+ }, [map]);
676
+ if (!coords) return null;
677
+ return /* @__PURE__ */ jsxRuntime.jsxs(
678
+ "div",
679
+ {
680
+ className: "absolute bottom-1 right-12 z-10 pointer-events-none font-mono text-[10px] text-muted-foreground/70 select-none",
681
+ "data-testid": "cursor-coordinates",
682
+ children: [
683
+ coords.lat.toFixed(5),
684
+ ", ",
685
+ coords.lng.toFixed(5)
686
+ ]
687
+ }
688
+ );
689
+ }
690
+ const NO_IMPORTS = Object.freeze([]);
691
+ const getServerSnapshot = () => NO_IMPORTS;
692
+ function IngestProgressOverlay({
693
+ store,
694
+ bottomPx
695
+ }) {
696
+ const entries = react.useSyncExternalStore(store.subscribe, store.getSnapshot, getServerSnapshot);
697
+ if (entries.length === 0) return null;
698
+ return /* @__PURE__ */ jsxRuntime.jsx(
699
+ "div",
700
+ {
701
+ className: "absolute left-1/2 z-10 flex -translate-x-1/2 flex-col gap-1 pointer-events-none",
702
+ style: { bottom: bottomPx },
703
+ "data-testid": "ingest-progress",
704
+ children: entries.map((entry) => /* @__PURE__ */ jsxRuntime.jsxs(
705
+ "div",
706
+ {
707
+ className: "rounded-md border bg-background/90 px-3 py-1.5 text-xs text-muted-foreground shadow-md",
708
+ children: [
709
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
710
+ "Importing ",
711
+ entry.label,
712
+ "…",
713
+ entry.total !== null ? ` ${entry.received.toLocaleString()} / ${entry.total.toLocaleString()} features` : ""
714
+ ] }),
715
+ entry.total !== null && entry.total > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-1 h-1 w-48 overflow-hidden rounded bg-muted", children: /* @__PURE__ */ jsxRuntime.jsx(
716
+ "div",
717
+ {
718
+ className: "h-full bg-primary",
719
+ style: { width: `${Math.min(100, entry.received / entry.total * 100)}%` }
720
+ }
721
+ ) })
722
+ ]
723
+ },
724
+ entry.id
725
+ ))
726
+ }
727
+ );
34
728
  }
35
- const turf__namespace = /* @__PURE__ */ _interopNamespaceDefault(turf);
36
- const THREE__namespace = /* @__PURE__ */ _interopNamespaceDefault(THREE);
37
- const toGeoJSON__namespace = /* @__PURE__ */ _interopNamespaceDefault(toGeoJSON);
38
729
  const ICONS = [
39
730
  // Location & Places
40
731
  { id: "map-pin", emoji: "📍", name: "Map Pin", category: "places" },
@@ -4524,26 +5215,6 @@ function StatusIndicator({ featureCount, selectedCount = 0 }) {
4524
5215
  }
4525
5216
  );
4526
5217
  }
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
5218
  function isFeatureInRange(feature, rangeStart, rangeEnd) {
4548
5219
  if (!feature.startDate && !feature.endDate) return true;
4549
5220
  if (!rangeStart || !rangeEnd) return true;
@@ -4637,7 +5308,8 @@ const timelineStoreInitializer = (set, get) => ({
4637
5308
  const computedMax = maxDate;
4638
5309
  const sameFeatureIds = state.temporalFeatures.length === timedFeatures.length && timedFeatures.every((f, i) => f.id === state.temporalFeatures[i].id);
4639
5310
  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;
5311
+ const sameUntimed = state.untimedFeatureIds.length === untimedIds.length && untimedIds.every((id, i) => id === state.untimedFeatureIds[i]);
5312
+ if (sameFeatureIds && sameDates && sameUntimed && state.hasTemporalData) return;
4641
5313
  const histogramBins = minDate && maxDate ? computeHistogramBins(timedFeatures, minDate, maxDate) : [];
4642
5314
  set({
4643
5315
  hasTemporalData: true,
@@ -5162,7 +5834,7 @@ function Timebar({ onFilterChange, selectedFeatureIds = [], selectedFeatureColor
5162
5834
  }
5163
5835
  );
5164
5836
  }
5165
- function MapDropZone({ onDrop, children }) {
5837
+ function MapDropZone({ onDrop, onDropFile, children }) {
5166
5838
  const [isDragOver, setIsDragOver] = react.useState(false);
5167
5839
  const handleDragOver = react.useCallback((e) => {
5168
5840
  e.preventDefault();
@@ -5197,13 +5869,17 @@ function MapDropZone({ onDrop, children }) {
5197
5869
  for (let i = 0; i < files.length; i++) {
5198
5870
  const file = files[i];
5199
5871
  if (!file.name.match(/\.(geojson|json)$/i)) continue;
5872
+ const name = file.name.replace(/\.(geojson|json)$/i, "");
5873
+ if (onDropFile) {
5874
+ onDropFile(name, file);
5875
+ continue;
5876
+ }
5200
5877
  const reader = new FileReader();
5201
5878
  reader.onload = (evt) => {
5202
5879
  var _a;
5203
5880
  try {
5204
5881
  const parsed = JSON.parse((_a = evt.target) == null ? void 0 : _a.result);
5205
5882
  if (parsed.type === "FeatureCollection" && Array.isArray(parsed.features)) {
5206
- const name = file.name.replace(/\.(geojson|json)$/i, "");
5207
5883
  onDrop(name, parsed);
5208
5884
  }
5209
5885
  } catch (err) {
@@ -5213,7 +5889,7 @@ function MapDropZone({ onDrop, children }) {
5213
5889
  reader.readAsText(file);
5214
5890
  }
5215
5891
  }
5216
- }, [onDrop]);
5892
+ }, [onDrop, onDropFile]);
5217
5893
  return /* @__PURE__ */ jsxRuntime.jsxs(
5218
5894
  "div",
5219
5895
  {
@@ -5451,15 +6127,20 @@ function createRafCoalescer(run, scheduler = rafScheduler) {
5451
6127
  };
5452
6128
  }
5453
6129
  const DEFAULT_LABEL_PRIORITY = 100;
6130
+ const DEFAULT_VISIBLE_STROKE_OPACITY = 1;
6131
+ const DEFAULT_VISIBLE_FILL_OPACITY = 0.2;
5454
6132
  function createSelectionPaintCache() {
5455
6133
  return {
5456
6134
  presentIds: /* @__PURE__ */ new Set(),
5457
6135
  appliedSelectedIds: /* @__PURE__ */ new Set(),
5458
6136
  basePriorityById: /* @__PURE__ */ new Map(),
6137
+ appliedHiddenIds: /* @__PURE__ */ new Set(),
6138
+ visibleStrokeOpacityById: /* @__PURE__ */ new Map(),
6139
+ visibleFillOpacityById: /* @__PURE__ */ new Map(),
5459
6140
  updatable: true
5460
6141
  };
5461
6142
  }
5462
- function recordPaintedFeature(cache, featureId, basePriority, isSelected) {
6143
+ function recordPaintedFeature(cache, featureId, basePriority, isSelected, visibleStrokeOpacity, visibleFillOpacity, isTimelineHidden) {
5463
6144
  if (cache.presentIds.has(featureId)) {
5464
6145
  cache.updatable = false;
5465
6146
  } else {
@@ -5467,6 +6148,13 @@ function recordPaintedFeature(cache, featureId, basePriority, isSelected) {
5467
6148
  }
5468
6149
  cache.basePriorityById.set(featureId, basePriority);
5469
6150
  if (isSelected) cache.appliedSelectedIds.add(featureId);
6151
+ if (visibleStrokeOpacity !== DEFAULT_VISIBLE_STROKE_OPACITY) {
6152
+ cache.visibleStrokeOpacityById.set(featureId, visibleStrokeOpacity);
6153
+ }
6154
+ if (visibleFillOpacity !== DEFAULT_VISIBLE_FILL_OPACITY) {
6155
+ cache.visibleFillOpacityById.set(featureId, visibleFillOpacity);
6156
+ }
6157
+ if (isTimelineHidden) cache.appliedHiddenIds.add(featureId);
5470
6158
  }
5471
6159
  function applySelectionFastPath(cache, nextSelectedIds, source) {
5472
6160
  if (!cache || !cache.updatable || !source) return false;
@@ -5514,6 +6202,49 @@ function buildSelectionDiff(cache, nextSelectedIds) {
5514
6202
  });
5515
6203
  return update.length > 0 ? { update } : null;
5516
6204
  }
6205
+ function buildTimelineVisibilityDiff(cache, nextVisibleSet) {
6206
+ const update = [];
6207
+ const nextHiddenIds = /* @__PURE__ */ new Set();
6208
+ cache.presentIds.forEach((id) => {
6209
+ const nextHidden = nextVisibleSet !== null && !nextVisibleSet.has(id);
6210
+ if (nextHidden) nextHiddenIds.add(id);
6211
+ if (nextHidden === cache.appliedHiddenIds.has(id)) return;
6212
+ if (nextHidden) {
6213
+ update.push({
6214
+ id,
6215
+ addOrUpdateProperties: [
6216
+ { key: "stroke-opacity", value: 0 },
6217
+ { key: "fill-opacity", value: 0 },
6218
+ { key: "isTimelineHidden", value: 1 }
6219
+ ]
6220
+ });
6221
+ } else {
6222
+ update.push({
6223
+ id,
6224
+ addOrUpdateProperties: [
6225
+ { key: "stroke-opacity", value: cache.visibleStrokeOpacityById.get(id) ?? DEFAULT_VISIBLE_STROKE_OPACITY },
6226
+ { key: "fill-opacity", value: cache.visibleFillOpacityById.get(id) ?? DEFAULT_VISIBLE_FILL_OPACITY },
6227
+ { key: "isTimelineHidden", value: 0 }
6228
+ ]
6229
+ });
6230
+ }
6231
+ });
6232
+ return { diff: update.length > 0 ? { update } : null, nextHiddenIds };
6233
+ }
6234
+ function applyTimelineFastPath(cache, nextVisibleSet, source) {
6235
+ var _a;
6236
+ if (!cache || !cache.updatable || !source) return { applied: false, toggled: 0 };
6237
+ const { diff, nextHiddenIds } = buildTimelineVisibilityDiff(cache, nextVisibleSet);
6238
+ if (diff) {
6239
+ try {
6240
+ source.updateData(diff);
6241
+ } catch {
6242
+ return { applied: false, toggled: 0 };
6243
+ }
6244
+ }
6245
+ cache.appliedHiddenIds = nextHiddenIds;
6246
+ return { applied: true, toggled: ((_a = diff == null ? void 0 : diff.update) == null ? void 0 : _a.length) ?? 0 };
6247
+ }
5517
6248
  function deepClone(value) {
5518
6249
  try {
5519
6250
  return structuredClone(value);
@@ -5566,15 +6297,80 @@ function geometryEquals(a, b) {
5566
6297
  b.coordinates
5567
6298
  );
5568
6299
  }
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;
6300
+ function prepareFeaturesForLayer(input, caller) {
6301
+ const logging = mapPerfLogEnabled();
6302
+ const started = logging ? performance.now() : 0;
6303
+ const count = input.length;
6304
+ const features = new Array(count);
6305
+ const featureIds = new Array(count);
6306
+ let hasTemporal = false;
6307
+ let temporalCount = 0;
6308
+ let reused = 0;
6309
+ for (let i = 0; i < count; i++) {
6310
+ const f = input[i];
6311
+ const props = f.properties || {};
6312
+ if (!hasAnyTemporalValue(props)) {
6313
+ if (typeof f.id === "string" && f.id) {
6314
+ features[i] = f;
6315
+ featureIds[i] = f.id;
6316
+ reused++;
6317
+ } else {
6318
+ const id2 = f.id ? String(f.id) : crypto.randomUUID();
6319
+ features[i] = { ...f, id: id2 };
6320
+ featureIds[i] = id2;
6321
+ }
6322
+ continue;
6323
+ }
6324
+ const id = f.id ? String(f.id) : crypto.randomUUID();
6325
+ featureIds[i] = id;
6326
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6327
+ if (startDate || endDate) hasTemporal = true;
6328
+ temporalCount++;
6329
+ features[i] = {
6330
+ ...f,
6331
+ id,
6332
+ properties: {
6333
+ ...props,
6334
+ startDate: (startDate == null ? void 0 : startDate.toISOString()) || null,
6335
+ endDate: (endDate == null ? void 0 : endDate.toISOString()) || null
6336
+ }
6337
+ };
6338
+ }
6339
+ if (logging) {
6340
+ mapPerfLog("normalize", `${caller ?? "prepareFeaturesForLayer"} normalized ${count} features`, {
6341
+ ms: Math.round((performance.now() - started) * 10) / 10,
6342
+ withTemporalKeys: temporalCount,
6343
+ hasTemporal,
6344
+ reused,
6345
+ copied: count - reused
6346
+ });
6347
+ }
6348
+ return { features, featureIds, hasTemporal };
6349
+ }
6350
+ function scanTemporalFeatures(features, resolveLayerId, out) {
6351
+ let foundTemporal = false;
6352
+ for (let i = 0; i < features.length; i++) {
6353
+ const feature = features[i];
6354
+ const id = feature.id;
6355
+ const props = feature.properties || {};
6356
+ if (!hasAnyTemporalValue(props)) {
6357
+ out.untimedIds.push(id);
6358
+ continue;
6359
+ }
6360
+ const { startDate, endDate } = normalizeTemporalProperties(props);
6361
+ if (startDate || endDate) {
6362
+ out.temporal.push({ id, startDate, endDate, layerId: resolveLayerId(id) });
6363
+ foundTemporal = true;
6364
+ } else {
6365
+ out.untimedIds.push(id);
6366
+ }
6367
+ }
6368
+ return foundTemporal;
6369
+ }
6370
+ function shouldDiffDrawRender({ mode, pointerDown, hasSelection }) {
6371
+ if (mode === "view_select") return false;
6372
+ if (mode === "simple_select" || mode === "direct_select") return pointerDown && hasSelection;
6373
+ return true;
5578
6374
  }
5579
6375
  function extendBounds(bounds, coords) {
5580
6376
  if (!Array.isArray(coords) || coords.length === 0) return;
@@ -5600,29 +6396,106 @@ function boundsDisjoint(a, b) {
5600
6396
  function pointInBounds(lng, lat, b) {
5601
6397
  return lng >= b.minLng && lng <= b.maxLng && lat >= b.minLat && lat <= b.maxLat;
5602
6398
  }
6399
+ function buildGroupSpatialIndex(features) {
6400
+ var _a;
6401
+ const boxes = [];
6402
+ const positions = [];
6403
+ for (let p = 0; p < features.length; p++) {
6404
+ const geom = (_a = features[p]) == null ? void 0 : _a.geometry;
6405
+ const b = computeBounds(geom == null ? void 0 : geom.coordinates);
6406
+ if (!isFinite(b.minLng) || !isFinite(b.minLat) || !isFinite(b.maxLng) || !isFinite(b.maxLat)) {
6407
+ continue;
6408
+ }
6409
+ boxes.push(b.minLng, b.minLat, b.maxLng, b.maxLat);
6410
+ positions.push(p);
6411
+ }
6412
+ if (positions.length === 0) {
6413
+ return { tree: null, positions, size: features.length };
6414
+ }
6415
+ const startedAt = performance.now();
6416
+ const tree = new Flatbush(positions.length);
6417
+ for (let i = 0; i < boxes.length; i += 4) {
6418
+ tree.add(boxes[i], boxes[i + 1], boxes[i + 2], boxes[i + 3]);
6419
+ }
6420
+ tree.finish();
6421
+ mapPerfLog("spatial-index", "built group index", {
6422
+ indexed: positions.length,
6423
+ of: features.length,
6424
+ ms: Math.round(performance.now() - startedAt)
6425
+ });
6426
+ return { tree, positions, size: features.length };
6427
+ }
6428
+ const indexCache = /* @__PURE__ */ new WeakMap();
6429
+ const failedBuilds = /* @__PURE__ */ new WeakSet();
6430
+ function getGroupSpatialIndex(features) {
6431
+ if (failedBuilds.has(features)) return void 0;
6432
+ let index = indexCache.get(features);
6433
+ if (!index) {
6434
+ try {
6435
+ index = buildGroupSpatialIndex(features);
6436
+ } catch {
6437
+ failedBuilds.add(features);
6438
+ return void 0;
6439
+ }
6440
+ indexCache.set(features, index);
6441
+ }
6442
+ return index;
6443
+ }
6444
+ function queryCandidatePositions(index, bounds) {
6445
+ if (!index.tree) return [];
6446
+ const items = index.tree.search(bounds.minLng, bounds.minLat, bounds.maxLng, bounds.maxLat);
6447
+ const positions = items.map((i) => index.positions[i]);
6448
+ positions.sort((a, b) => a - b);
6449
+ return positions;
6450
+ }
6451
+ function collectVisibleFeatureGroups(drawFeatures, readOnlyByLayer, layers) {
6452
+ const groups = [];
6453
+ if (drawFeatures) groups.push({ features: drawFeatures });
6454
+ const layerById = new Map(layers.map((l) => [l.id, l]));
6455
+ readOnlyByLayer.forEach((features, layerId) => {
6456
+ var _a;
6457
+ if ((_a = layerById.get(layerId)) == null ? void 0 : _a.visible) {
6458
+ groups.push({ features, index: getGroupSpatialIndex(features) });
6459
+ }
6460
+ });
6461
+ return groups;
6462
+ }
6463
+ function featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) {
6464
+ const geom = feature.geometry;
6465
+ if ((geom == null ? void 0 : geom.type) === "Point") {
6466
+ const lng = geom.coordinates[0];
6467
+ const lat = geom.coordinates[1];
6468
+ return typeof lng === "number" && typeof lat === "number" && pointInBounds(lng, lat, selectionBounds) && (rectExactForPoints || turf__namespace.booleanPointInPolygon(geom.coordinates, selectionPolygon));
6469
+ }
6470
+ 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") {
6471
+ return !boundsDisjoint(computeBounds(geom.coordinates), selectionBounds) && turf__namespace.booleanIntersects(feature, selectionPolygon);
6472
+ }
6473
+ return false;
6474
+ }
5603
6475
  function hitTestSelection(featureGroups, selectionPolygon, options) {
5604
6476
  const selectionBounds = computeBounds(selectionPolygon.geometry.coordinates);
5605
6477
  const rectExactForPoints = (options == null ? void 0 : options.axisAlignedRectangle) === true;
5606
6478
  const selectedIds = [];
5607
- for (const features of featureGroups) {
5608
- for (const feature of features) {
6479
+ let visited = 0;
6480
+ let total = 0;
6481
+ for (const group of featureGroups) {
6482
+ const { features, index } = group;
6483
+ total += features.length;
6484
+ const useIndex = index !== void 0 && index.size === features.length;
6485
+ const candidates = useIndex ? queryCandidatePositions(index, selectionBounds) : null;
6486
+ const count = candidates ? candidates.length : features.length;
6487
+ visited += count;
6488
+ for (let i = 0; i < count; i++) {
6489
+ const feature = candidates ? features[candidates[i]] : features[i];
5609
6490
  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) {
6491
+ if (featureHitsSelection(feature, selectionPolygon, selectionBounds, rectExactForPoints) && feature.id) {
5620
6492
  selectedIds.push(String(feature.id));
5621
6493
  }
5622
6494
  } catch {
5623
6495
  }
5624
6496
  }
5625
6497
  }
6498
+ mapPerfLog("hit-test", "selection gesture", { visited, total, selected: selectedIds.length });
5626
6499
  return selectedIds;
5627
6500
  }
5628
6501
  const OTHER_BUCKET_KEY = "__other__";
@@ -5931,92 +6804,6 @@ function ClusterPieManager(props) {
5931
6804
  }, [visible, updateMarkers]);
5932
6805
  return null;
5933
6806
  }
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
6807
  const EMOJI_CANVAS_SIZE = 48;
6021
6808
  function renderEmojiToCanvas(emoji, size = EMOJI_CANVAS_SIZE) {
6022
6809
  const ratio = typeof window !== "undefined" ? window.devicePixelRatio || 1 : 1;
@@ -6156,17 +6943,6 @@ function createFlightPath3DLayer(layerId, mapInstance, flightPaths) {
6156
6943
  }
6157
6944
  };
6158
6945
  }
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
6946
  function extract3DFlightPaths(features) {
6171
6947
  const paths = [];
6172
6948
  features.forEach((feature) => {
@@ -6432,7 +7208,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6432
7208
  const [visibleFeatureCount, setVisibleFeatureCount] = react.useState(Infinity);
6433
7209
  const lastLabelVisibility = react.useRef(false);
6434
7210
  const [labelsSuppressed, setLabelsSuppressed] = react.useState(true);
6435
- const [cursorCoords, setCursorCoords] = react.useState(null);
6436
7211
  const [contextMenu, setContextMenu] = react.useState(null);
6437
7212
  const [timelineStoreApi] = react.useState(createTimelineStore);
6438
7213
  const timelineStore = zustand.useStore(timelineStoreApi);
@@ -6649,19 +7424,32 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6649
7424
  const syncRef = react.useRef(() => {
6650
7425
  });
6651
7426
  const trySelectionFastPathRef = react.useRef(null);
7427
+ const tryTimelineFastPathRef = react.useRef(null);
6652
7428
  const syncCoalescerRef = react.useRef(null);
6653
7429
  if (syncCoalescerRef.current === null) {
6654
7430
  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;
7431
+ var _a, _b;
7432
+ if (!reasons.has("full")) {
7433
+ let handled = true;
7434
+ if (reasons.has("timeline")) handled = ((_a = tryTimelineFastPathRef.current) == null ? void 0 : _a.call(tryTimelineFastPathRef)) ?? false;
7435
+ if (handled && reasons.has("selection")) handled = ((_b = trySelectionFastPathRef.current) == null ? void 0 : _b.call(trySelectionFastPathRef)) ?? false;
7436
+ if (handled) {
7437
+ mapPerfLog("sync", "frame handled by fast path(s)", reasons);
7438
+ return;
7439
+ }
7440
+ mapPerfLog("sync", "fast path bailed — full rebuild", reasons);
6658
7441
  }
6659
7442
  syncRef.current();
6660
7443
  });
6661
7444
  }
7445
+ const fullSyncCallersRef = react.useRef([]);
6662
7446
  const scheduleSync = react.useCallback((reason = "full") => {
6663
- var _a;
6664
- (_a = syncCoalescerRef.current) == null ? void 0 : _a.schedule(reason);
7447
+ var _a, _b;
7448
+ if (reason === "full" && mapPerfLogEnabled() && fullSyncCallersRef.current.length < 4) {
7449
+ const stack = (_a = new Error().stack) == null ? void 0 : _a.split("\n").slice(2, 5).map((line) => line.trim()).join(" ← ");
7450
+ if (stack) fullSyncCallersRef.current.push(stack);
7451
+ }
7452
+ (_b = syncCoalescerRef.current) == null ? void 0 : _b.schedule(reason);
6665
7453
  }, []);
6666
7454
  react.useEffect(() => {
6667
7455
  scheduleSync();
@@ -6752,10 +7540,106 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6752
7540
  }, []);
6753
7541
  const isSyncingRef = react.useRef(false);
6754
7542
  const selectionPaintCacheRef = react.useRef(null);
7543
+ const paintedArrowLinesRef = react.useRef([]);
7544
+ const renderArrowOverlays = react.useCallback((arrowLines) => {
7545
+ const mapInstance = map.current;
7546
+ if (!mapInstance) return;
7547
+ const arrowHeadSource = mapInstance.getSource("arrow-heads");
7548
+ if (arrowHeadSource) {
7549
+ const arrowHeadTriangles = [];
7550
+ const headLength = 16;
7551
+ const headWidth = 10;
7552
+ arrowLines.forEach((f) => {
7553
+ const coords = f.geometry.coordinates;
7554
+ if (coords.length < 2) return;
7555
+ const end = coords[coords.length - 1];
7556
+ const prev = coords[coords.length - 2];
7557
+ const endScreen = mapInstance.project(end);
7558
+ const prevScreen = mapInstance.project(prev);
7559
+ const dx = endScreen.x - prevScreen.x;
7560
+ const dy = endScreen.y - prevScreen.y;
7561
+ const len = Math.sqrt(dx * dx + dy * dy);
7562
+ if (len < 1e-3) return;
7563
+ const dirX = dx / len;
7564
+ const dirY = dy / len;
7565
+ const perpX = -dirY;
7566
+ const perpY = dirX;
7567
+ const tipScreen = { x: endScreen.x, y: endScreen.y };
7568
+ const baseLeftScreen = {
7569
+ x: endScreen.x - dirX * headLength - perpX * headWidth,
7570
+ y: endScreen.y - dirY * headLength - perpY * headWidth
7571
+ };
7572
+ const baseRightScreen = {
7573
+ x: endScreen.x - dirX * headLength + perpX * headWidth,
7574
+ y: endScreen.y - dirY * headLength + perpY * headWidth
7575
+ };
7576
+ const tipGeo = mapInstance.unproject([tipScreen.x, tipScreen.y]);
7577
+ const baseLeftGeo = mapInstance.unproject([baseLeftScreen.x, baseLeftScreen.y]);
7578
+ const baseRightGeo = mapInstance.unproject([baseRightScreen.x, baseRightScreen.y]);
7579
+ arrowHeadTriangles.push({
7580
+ type: "Feature",
7581
+ geometry: {
7582
+ type: "Polygon",
7583
+ coordinates: [[
7584
+ [tipGeo.lng, tipGeo.lat],
7585
+ [baseLeftGeo.lng, baseLeftGeo.lat],
7586
+ [baseRightGeo.lng, baseRightGeo.lat],
7587
+ [tipGeo.lng, tipGeo.lat]
7588
+ // Close the polygon
7589
+ ]]
7590
+ },
7591
+ properties: {
7592
+ ...f.properties
7593
+ }
7594
+ });
7595
+ });
7596
+ arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
7597
+ }
7598
+ const arrowLabelSource = mapInstance.getSource("arrow-labels");
7599
+ if (arrowLabelSource) {
7600
+ const arrowLabelPoints = [];
7601
+ arrowLines.forEach((f) => {
7602
+ var _a;
7603
+ const name = (_a = f.properties) == null ? void 0 : _a.name;
7604
+ if (!name) return;
7605
+ const coords = f.geometry.coordinates;
7606
+ if (coords.length < 2) return;
7607
+ const start = coords[0];
7608
+ const end = coords[coords.length - 1];
7609
+ const midPoint = [
7610
+ (start[0] + end[0]) / 2,
7611
+ (start[1] + end[1]) / 2
7612
+ ];
7613
+ const dLng = end[0] - start[0];
7614
+ const dLat = end[1] - start[1];
7615
+ const angleFromEast = Math.atan2(dLat, dLng) * (180 / Math.PI);
7616
+ let labelBearing = -angleFromEast;
7617
+ labelBearing = (labelBearing % 360 + 540) % 360 - 180;
7618
+ if (labelBearing > 90) {
7619
+ labelBearing -= 180;
7620
+ } else if (labelBearing < -90) {
7621
+ labelBearing += 180;
7622
+ }
7623
+ arrowLabelPoints.push({
7624
+ type: "Feature",
7625
+ geometry: {
7626
+ type: "Point",
7627
+ coordinates: midPoint
7628
+ },
7629
+ properties: {
7630
+ ...f.properties,
7631
+ labelBearing
7632
+ }
7633
+ });
7634
+ });
7635
+ arrowLabelSource.setData({ type: "FeatureCollection", features: arrowLabelPoints });
7636
+ }
7637
+ }, []);
6755
7638
  const syncFeaturesToCustomLayers = react.useCallback(() => {
6756
7639
  if (!map.current) return;
6757
7640
  if (isSyncingRef.current) return;
6758
7641
  isSyncingRef.current = true;
7642
+ const fullSyncStart = performance.now();
6759
7643
  try {
6760
7644
  const source = map.current.getSource("custom-features");
6761
7645
  if (!source) return;
@@ -6878,7 +7762,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6878
7762
  const layer = featureToLayer.get(featureId);
6879
7763
  const visualConfig = layer == null ? void 0 : layer.visualConfig;
6880
7764
  const isTimelineVisible = visibleSet === null || visibleSet.has(featureId);
6881
- const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? 1;
7765
+ const baseOpacity = ((_a = f.properties) == null ? void 0 : _a["stroke-opacity"]) ?? DEFAULT_VISIBLE_STROKE_OPACITY;
6882
7766
  let strokeColor = ((_b = f.properties) == null ? void 0 : _b.stroke) || "#3b82f6";
6883
7767
  const colorConfig = visualConfig == null ? void 0 : visualConfig.color;
6884
7768
  if (colorConfig) {
@@ -6980,7 +7864,17 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
6980
7864
  basePriority = DEFAULT_LABEL_PRIORITY + Math.abs(h) % 1e3;
6981
7865
  }
6982
7866
  const labelPriority = isFeatureSelected ? 0 : basePriority;
6983
- recordPaintedFeature(paintCache, featureId, basePriority, isFeatureSelected === 1);
7867
+ const visibleStrokeOpacity = hideFlatFor3DOnly ? 0 : baseOpacity;
7868
+ const visibleFillOpacity = hideFlatFor3DOnly ? 0 : ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? DEFAULT_VISIBLE_FILL_OPACITY;
7869
+ recordPaintedFeature(
7870
+ paintCache,
7871
+ featureId,
7872
+ basePriority,
7873
+ isFeatureSelected === 1,
7874
+ visibleStrokeOpacity,
7875
+ visibleFillOpacity,
7876
+ !isTimelineVisible
7877
+ );
6984
7878
  return {
6985
7879
  type: "Feature",
6986
7880
  id: featureId,
@@ -7001,9 +7895,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7001
7895
  iconSize: featureIconSize,
7002
7896
  stroke: strokeColor,
7003
7897
  "stroke-width": strokeWidth,
7004
- "stroke-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? baseOpacity : 0,
7898
+ "stroke-opacity": isTimelineVisible ? visibleStrokeOpacity : 0,
7005
7899
  fill: strokeColor,
7006
- "fill-opacity": hideFlatFor3DOnly ? 0 : isTimelineVisible ? ((_n = f.properties) == null ? void 0 : _n["fill-opacity"]) ?? 0.2 : 0,
7900
+ "fill-opacity": isTimelineVisible ? visibleFillOpacity : 0,
7007
7901
  pointRadius,
7008
7902
  isHiddenFor3DOnly: hideFlatFor3DOnly ? 1 : 0,
7009
7903
  isTimelineHidden: isTimelineVisible ? 0 : 1,
@@ -7102,104 +7996,19 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7102
7996
  });
7103
7997
  traceSource.setData({ type: "FeatureCollection", features: traceSegments });
7104
7998
  }
7105
- const arrowHeadSource = map.current.getSource("arrow-heads");
7106
- if (arrowHeadSource && map.current) {
7107
- const arrowHeadTriangles = [];
7108
- const mapInstance = map.current;
7999
+ {
7109
8000
  let sawArrowFeature = false;
7110
- const headLength = 16;
7111
- const headWidth = 10;
8001
+ const arrowLines = [];
7112
8002
  sourceData.features.forEach((f) => {
7113
8003
  var _a;
7114
8004
  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
- });
8005
+ if (!isArrow) return;
8006
+ sawArrowFeature = true;
8007
+ if (f.geometry.type === "LineString") arrowLines.push(f);
7159
8008
  });
7160
- arrowHeadSource.setData({ type: "FeatureCollection", features: arrowHeadTriangles });
7161
8009
  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 });
8010
+ paintedArrowLinesRef.current = arrowLines;
8011
+ renderArrowOverlays(arrowLines);
7203
8012
  }
7204
8013
  if (update3DFlightPathsRef == null ? void 0 : update3DFlightPathsRef.current) {
7205
8014
  update3DFlightPathsRef.current();
@@ -7209,11 +8018,18 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7209
8018
  setVisibleFeatureCount(countVisibleFeatures(threshold));
7210
8019
  setLabelsSuppressed(false);
7211
8020
  }
8021
+ const requestedBy = fullSyncCallersRef.current.splice(0);
8022
+ mapPerfLog("sync", "full rebuild", {
8023
+ features: sourceData.features.length,
8024
+ ms: Math.round(performance.now() - fullSyncStart),
8025
+ requestedBy
8026
+ });
7212
8027
  } finally {
7213
8028
  isSyncingRef.current = false;
7214
8029
  }
7215
- }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures]);
8030
+ }, [layers, hashStringToColor$1, autoLabelConfig, countVisibleFeatures, renderArrowOverlays]);
7216
8031
  const update3DFlightPaths = react.useCallback(() => {
8032
+ var _a;
7217
8033
  if (!map.current || !is3DTerrainEnabled) {
7218
8034
  if (map.current && flightPath3DLayerId.current) {
7219
8035
  try {
@@ -7234,20 +8050,21 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7234
8050
  const allFeatures = [];
7235
8051
  const currentLayers = layersRef.current;
7236
8052
  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
- });
8053
+ const traceFeatureIds = /* @__PURE__ */ new Set();
8054
+ for (const l of currentLayers) {
8055
+ if (((_a = l.traceConfig) == null ? void 0 : _a.enabled) !== true) continue;
8056
+ for (const featureId of l.featureIds) traceFeatureIds.add(featureId);
8057
+ }
8058
+ const drawFeatures = draw.current.getAll().features.filter(
8059
+ (feature) => isFeatureVisibleInTimeline(feature) && traceFeatureIds.has(feature.id)
8060
+ );
7244
8061
  pushAll(allFeatures, drawFeatures);
7245
8062
  }
7246
8063
  readOnlyFeatures.current.forEach((features, layerId2) => {
7247
- var _a;
8064
+ var _a2;
7248
8065
  const layer2 = currentLayers.find((l) => l.id === layerId2);
7249
8066
  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;
8067
+ const traceEnabled = ((_a2 = layer2 == null ? void 0 : layer2.traceConfig) == null ? void 0 : _a2.enabled) === true;
7251
8068
  if ((layer2 == null ? void 0 : layer2.visible) && traceEnabled && (altitudeMode === "3d" || altitudeMode === "both")) {
7252
8069
  const visibleFeatures = features.filter(isFeatureVisibleInTimeline);
7253
8070
  pushAll(allFeatures, visibleFeatures);
@@ -7302,52 +8119,24 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7302
8119
  featureToLayer.set(fid, layer.id);
7303
8120
  }
7304
8121
  }
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
- }
8122
+ const scan = { temporal: [], untimedIds: [] };
8123
+ scanTemporalFeatures(
8124
+ drawFeatures,
8125
+ (id) => featureToLayer.get(id) || "default",
8126
+ scan
8127
+ );
7325
8128
  readOnlyFeatures.current.forEach((features, layerId) => {
7326
8129
  const layer = currentLayers.find((l) => l.id === layerId);
7327
8130
  if (!(layer == null ? void 0 : layer.visible)) return;
7328
8131
  const cached = layerTemporalCacheRef.current.get(layerId);
7329
8132
  if (cached && cached.featureCount === features.length && !cached.hasTemporal) {
7330
- for (const f of features) untimedIds.push(f.id);
8133
+ for (const f of features) scan.untimedIds.push(f.id);
7331
8134
  return;
7332
8135
  }
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
- }
8136
+ const layerHasTemporal = scanTemporalFeatures(features, () => layerId, scan);
7348
8137
  layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: layerHasTemporal });
7349
8138
  });
7350
- timelineStoreApi.getState().setTemporalFeatures(temporalFeatures, untimedIds);
8139
+ timelineStoreApi.getState().setTemporalFeatures(scan.temporal, scan.untimedIds);
7351
8140
  }, [timelineStoreApi]);
7352
8141
  const scheduleTimelineUpdate = react.useCallback(() => {
7353
8142
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
@@ -7623,6 +8412,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7623
8412
  }, [finalizeCapture]);
7624
8413
  react.useEffect(() => {
7625
8414
  if (!mapContainer.current || map.current) return;
8415
+ let removeDrawGateListeners;
7626
8416
  try {
7627
8417
  const baseStyle = createBaseStyle({
7628
8418
  glyphsUrl,
@@ -7681,12 +8471,6 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
7681
8471
  ]
7682
8472
  });
7683
8473
  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
8474
  requestAnimationFrame(() => {
7691
8475
  try {
7692
8476
  const container = mapInstance.getContainer();
@@ -8661,8 +9445,52 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8661
9445
  onFeatureCreate == null ? void 0 : onFeatureCreate(feature);
8662
9446
  });
8663
9447
  });
9448
+ let drawGatePointerDown = false;
9449
+ const onDrawGatePointerDown = () => {
9450
+ drawGatePointerDown = true;
9451
+ };
9452
+ const onDrawGatePointerUp = () => {
9453
+ drawGatePointerDown = false;
9454
+ };
9455
+ const drawGateCanvas = mapInstance.getCanvasContainer();
9456
+ drawGateCanvas.addEventListener("pointerdown", onDrawGatePointerDown);
9457
+ window.addEventListener("pointerup", onDrawGatePointerUp);
9458
+ window.addEventListener("pointercancel", onDrawGatePointerUp);
9459
+ window.addEventListener("blur", onDrawGatePointerUp);
9460
+ removeDrawGateListeners = () => {
9461
+ drawGateCanvas.removeEventListener("pointerdown", onDrawGatePointerDown);
9462
+ window.removeEventListener("pointerup", onDrawGatePointerUp);
9463
+ window.removeEventListener("pointercancel", onDrawGatePointerUp);
9464
+ window.removeEventListener("blur", onDrawGatePointerUp);
9465
+ };
9466
+ let lastDrawGeometries = /* @__PURE__ */ new Map();
9467
+ let drawGateSkips = 0;
8664
9468
  mapInstance.on("draw.render", () => {
8665
- scheduleSync();
9469
+ if (!shouldDiffDrawRender({
9470
+ mode: drawInstance.getMode(),
9471
+ pointerDown: drawGatePointerDown,
9472
+ hasSelection: drawInstance.getSelectedIds().length > 0
9473
+ })) {
9474
+ drawGateSkips++;
9475
+ return;
9476
+ }
9477
+ if (drawGateSkips > 0) {
9478
+ mapPerfLog("sync", "draw.render diff resumed", { skippedWhileIdle: drawGateSkips });
9479
+ drawGateSkips = 0;
9480
+ }
9481
+ const features = drawInstance.getAll().features;
9482
+ let changed = features.length !== lastDrawGeometries.size;
9483
+ const next = /* @__PURE__ */ new Map();
9484
+ features.forEach((f) => {
9485
+ const id = String(f.id);
9486
+ next.set(id, f.geometry);
9487
+ if (!changed) {
9488
+ const prev = lastDrawGeometries.get(id);
9489
+ if (!prev || !geometryEquals(prev, f.geometry)) changed = true;
9490
+ }
9491
+ });
9492
+ lastDrawGeometries = next;
9493
+ if (changed) scheduleSync();
8666
9494
  });
8667
9495
  mapInstance.on("draw.update", (e) => {
8668
9496
  const activeLayerId = activeEditingLayerIdRef.current;
@@ -8704,7 +9532,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8704
9532
  }
8705
9533
  });
8706
9534
  scheduleSync();
8707
- if (e.action === "change_coordinates" && !hasRevertedFeatures) {
9535
+ if ((e.action === "move" || e.action === "change_coordinates") && !hasRevertedFeatures) {
8708
9536
  scheduleTimelineUpdate();
8709
9537
  recordMoveFromPreDrag();
8710
9538
  }
@@ -8844,6 +9672,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
8844
9672
  var _a;
8845
9673
  if (timelineUpdateTimerRef.current) clearTimeout(timelineUpdateTimerRef.current);
8846
9674
  (_a = syncCoalescerRef.current) == null ? void 0 : _a.cancel();
9675
+ removeDrawGateListeners == null ? void 0 : removeDrawGateListeners();
8847
9676
  if (map.current) {
8848
9677
  map.current.remove();
8849
9678
  map.current = null;
@@ -9021,8 +9850,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9021
9850
  const allFeatures = [...drawFeatures, ...readOnlyFeaturesList];
9022
9851
  const currentLayers = layersRef.current;
9023
9852
  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));
9853
+ const targetFeatureIds = new Set(
9854
+ currentLayers.filter((l) => targetLayerIds.includes(l.id)).flatMap((l) => l.featureIds)
9855
+ );
9856
+ const targetFeatures = allFeatures.filter((f) => targetFeatureIds.has(f.id));
9026
9857
  if (targetFeatures.length === 0) return;
9027
9858
  const fc = turf__namespace.featureCollection(targetFeatures);
9028
9859
  const bbox = turf__namespace.bbox(fc);
@@ -9043,6 +9874,9 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9043
9874
  map.current.flyTo({ center: center.geometry.coordinates });
9044
9875
  },
9045
9876
  listLayers: () => [...layersRef.current],
9877
+ // Worker parse + streamed transfer + the canvas progress overlay, with
9878
+ // layer creation left to the host (see MapEditorHandle docs).
9879
+ parseGeoJSONText: (label, text) => ingestWithProgress(label, text, { idStrategy: "preserve" }),
9046
9880
  addLayer: (name, geojson, options) => {
9047
9881
  if (!isMapLoadedRef.current) return "";
9048
9882
  if (options == null ? void 0 : options.recordHistory) saveStateForUndo(`add layer "${name}"`);
@@ -9072,28 +9906,10 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9072
9906
  };
9073
9907
  if (geojson) {
9074
9908
  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));
9909
+ const prepared = prepareFeaturesForLayer(geojson.features, "addLayer");
9910
+ readOnlyFeatures.current.set(layerId, prepared.features);
9911
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9912
+ newLayer.featureIds = prepared.featureIds;
9097
9913
  } else if (draw.current) {
9098
9914
  isApiAddingRef.current = true;
9099
9915
  try {
@@ -9219,29 +10035,12 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9219
10035
  if (options == null ? void 0 : options.recordHistory) saveStateForUndo("add features");
9220
10036
  if (layer.readOnly) {
9221
10037
  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];
10038
+ const prepared = prepareFeaturesForLayer(features, "addFeatures");
10039
+ const layerHasTemporal = (((_a = layerTemporalCacheRef.current.get(layerId)) == null ? void 0 : _a.hasTemporal) ?? false) || prepared.hasTemporal;
10040
+ const combined = [...existing, ...prepared.features];
9242
10041
  readOnlyFeatures.current.set(layerId, combined);
9243
10042
  layerTemporalCacheRef.current.set(layerId, { featureCount: combined.length, hasTemporal: layerHasTemporal });
9244
- const addedIds2 = newFeaturesWithIds.map((f) => String(f.id));
10043
+ const addedIds2 = prepared.featureIds;
9245
10044
  const updatedLayers2 = layersRef.current.map(
9246
10045
  (l) => l.id === layerId ? { ...l, featureIds: [...l.featureIds, ...addedIds2] } : l
9247
10046
  );
@@ -9476,31 +10275,13 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9476
10275
  updateReadOnlyLayer: (layerId, features) => {
9477
10276
  const layer = layersRef.current.find((l) => l.id === layerId);
9478
10277
  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) {
10278
+ const prepared = prepareFeaturesForLayer(features, "updateReadOnlyLayer");
10279
+ readOnlyFeatures.current.set(layerId, prepared.features);
10280
+ layerTemporalCacheRef.current.set(layerId, { featureCount: features.length, hasTemporal: prepared.hasTemporal });
10281
+ if (prepared.hasTemporal) {
9501
10282
  scheduleTimelineUpdate();
9502
10283
  }
9503
- const newFeatureIds = featuresWithIds.map((f) => String(f.id));
10284
+ const newFeatureIds = prepared.featureIds;
9504
10285
  const updatedLayers = layersRef.current.map(
9505
10286
  (l) => l.id === layerId ? { ...l, featureIds: newFeatureIds } : l
9506
10287
  );
@@ -9512,29 +10293,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
9512
10293
  },
9513
10294
  setLayerData: (name, geojson, options) => {
9514
10295
  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));
10296
+ const prepared = prepareFeaturesForLayer(geojson.features, "setLayerData");
10297
+ const newFeatureIds = prepared.featureIds;
9535
10298
  const layerId = `managed-${name}`;
9536
- readOnlyFeatures.current.set(layerId, featuresWithIds);
9537
- layerTemporalCacheRef.current.set(layerId, { featureCount: featuresWithIds.length, hasTemporal: layerHasTemporal });
10299
+ readOnlyFeatures.current.set(layerId, prepared.features);
10300
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
9538
10301
  const buildLayerObj = (existing) => {
9539
10302
  const base = {
9540
10303
  id: layerId,
@@ -10765,18 +11528,23 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
10765
11528
  react.useEffect(() => {
10766
11529
  if (!map.current || !isMapLoaded) return;
10767
11530
  const mapInstance = map.current;
11531
+ let rafId = null;
10768
11532
  const handleMove = () => {
10769
- if (!hasArrowFeaturesRef.current) return;
10770
- scheduleSync();
11533
+ if (!hasArrowFeaturesRef.current || rafId !== null) return;
11534
+ rafId = requestAnimationFrame(() => {
11535
+ rafId = null;
11536
+ renderArrowOverlays(paintedArrowLinesRef.current);
11537
+ });
10771
11538
  };
10772
11539
  mapInstance.on("move", handleMove);
10773
11540
  return () => {
11541
+ if (rafId !== null) cancelAnimationFrame(rafId);
10774
11542
  try {
10775
11543
  mapInstance.off("move", handleMove);
10776
11544
  } catch {
10777
11545
  }
10778
11546
  };
10779
- }, [isMapLoaded]);
11547
+ }, [isMapLoaded, renderArrowOverlays]);
10780
11548
  react.useEffect(() => {
10781
11549
  if (!map.current || !isMapLoaded || !onViewportChange) return;
10782
11550
  const mapInstance = map.current;
@@ -11099,6 +11867,29 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11099
11867
  return applySelectionFastPath(selectionPaintCacheRef.current, next, source);
11100
11868
  }, []);
11101
11869
  trySelectionFastPathRef.current = trySelectionFastPath;
11870
+ const tryTimelineFastPath = react.useCallback(() => {
11871
+ const m = map.current;
11872
+ if (!m) return true;
11873
+ if (hasArrowFeaturesRef.current) return false;
11874
+ if (layersRef.current.some((l) => {
11875
+ var _a;
11876
+ return l.visible && ((_a = l.traceConfig) == null ? void 0 : _a.enabled);
11877
+ })) return false;
11878
+ const source = m.getSource("custom-features");
11879
+ const { applied, toggled } = applyTimelineFastPath(
11880
+ selectionPaintCacheRef.current,
11881
+ timelineVisibleIdsRef.current,
11882
+ source
11883
+ );
11884
+ if (applied) {
11885
+ const threshold = autoLabelConfig.enabled ? autoLabelConfig.threshold : 220;
11886
+ setVisibleFeatureCount(countVisibleFeatures(threshold));
11887
+ setLabelsSuppressed(false);
11888
+ mapPerfLog("timeline", "fast path applied", { toggled });
11889
+ }
11890
+ return applied;
11891
+ }, [autoLabelConfig, countVisibleFeatures]);
11892
+ tryTimelineFastPathRef.current = tryTimelineFastPath;
11102
11893
  const collectSelectionFeatureGroups = react.useCallback(() => {
11103
11894
  return collectVisibleFeatureGroups(
11104
11895
  draw.current ? draw.current.getAll().features : null,
@@ -11852,7 +12643,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11852
12643
  layerMetadata
11853
12644
  }
11854
12645
  };
11855
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/json" });
12646
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/json" });
11856
12647
  downloadBlob(blob, `${layer.name.replace(/[^a-z0-9]/gi, "_")}.geojson`);
11857
12648
  }, [layers]);
11858
12649
  const handleLoadLayerGeoJSON = react.useCallback((layerId) => {
@@ -11929,7 +12720,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
11929
12720
  const handleSaveAllGeoJSON = react.useCallback(() => {
11930
12721
  if (!draw.current) return;
11931
12722
  const geojson = buildEnrichedGeoJSON();
11932
- const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: "application/geo+json" });
12723
+ const blob = new Blob(featureCollectionBlobParts(geojson), { type: "application/geo+json" });
11933
12724
  downloadBlob(blob, "map_export.geojson");
11934
12725
  }, [buildEnrichedGeoJSON]);
11935
12726
  const handleSearchAndAddToNewLayer = react.useCallback(async () => {
@@ -12120,26 +12911,14 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12120
12911
  }
12121
12912
  saveStateForUndo();
12122
12913
  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 });
12914
+ const prepared = prepareFeaturesForLayer(result.features, "workspaceLoad");
12915
+ readOnlyFeatures.current.set(layerId, prepared.features);
12916
+ layerTemporalCacheRef.current.set(layerId, { featureCount: prepared.features.length, hasTemporal: prepared.hasTemporal });
12138
12917
  const newLayer = {
12139
12918
  id: layerId,
12140
12919
  name: "Loaded from workspace",
12141
12920
  visible: true,
12142
- featureIds: featuresWithIds.map((f) => String(f.id)),
12921
+ featureIds: prepared.featureIds,
12143
12922
  readOnly: true
12144
12923
  };
12145
12924
  setLayers((prev) => [...prev, newLayer]);
@@ -12148,7 +12927,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12148
12927
  scheduleSync();
12149
12928
  toast({
12150
12929
  title: "Features loaded",
12151
- description: `Created layer with ${featuresWithIds.length} features`
12930
+ description: `Created layer with ${prepared.features.length} features`
12152
12931
  });
12153
12932
  } catch (error) {
12154
12933
  toast({
@@ -12235,195 +13014,206 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12235
13014
  duration: 1e3
12236
13015
  });
12237
13016
  }, [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})` : "";
13017
+ const [ingestProgressStore] = react.useState(createIngestProgressStore);
13018
+ const ingestWithProgress = react.useCallback(async (label, input, options) => {
13019
+ const progress = ingestProgressStore.begin(label);
13020
+ try {
13021
+ return await getSharedIngestClient().ingest(input, options, {
13022
+ onHead: (summary) => progress.setTotal(summary.featureCount),
13023
+ onProgress: (received) => progress.update(received)
13024
+ });
13025
+ } finally {
13026
+ progress.end();
13027
+ }
13028
+ }, [ingestProgressStore]);
13029
+ const loadGeoJSONFile = react.useCallback(async (file, requestedTargetLayerId, createNewLayer) => {
13030
+ let result;
13031
+ try {
13032
+ result = await ingestWithProgress(file.name, file, {
13033
+ idStrategy: "uuid-fallback",
13034
+ emptyIsError: true
13035
+ });
13036
+ } catch (error) {
13037
+ toast({
13038
+ title: "Failed to load GeoJSON",
13039
+ description: error instanceof Error ? error.message : "Invalid file",
13040
+ variant: "destructive"
13041
+ });
13042
+ return;
13043
+ }
13044
+ if (result.kind === "error") {
13045
+ if (result.code === "empty") {
12397
13046
  toast({
12398
- title: "GeoJSON loaded",
12399
- description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
13047
+ title: "Empty GeoJSON",
13048
+ description: result.message,
13049
+ variant: "destructive"
12400
13050
  });
12401
- } catch (error) {
13051
+ } else {
12402
13052
  toast({
12403
13053
  title: "Failed to load GeoJSON",
12404
- description: error instanceof Error ? error.message : "Invalid file",
13054
+ description: result.message,
12405
13055
  variant: "destructive"
12406
13056
  });
12407
13057
  }
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) => {
13058
+ return;
13059
+ }
13060
+ if (result.kind === "enriched") {
13061
+ const rawGeojson = result.data;
13062
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data: rawGeojson, file }) === true) {
13063
+ return;
13064
+ }
13065
+ if (!draw.current) return;
13066
+ restoreEnrichedGeoJSON(rawGeojson);
13067
+ return;
13068
+ }
13069
+ if (!draw.current) return;
13070
+ const { features: normalizedFeatures, reprojected, sourceCRS, hasTemporal: fileHasTemporal } = result;
13071
+ const layerMetadata = result.layerMetadata;
13072
+ saveStateForUndo();
13073
+ if (createNewLayer) {
13074
+ if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({
13075
+ kind: "newLayer",
13076
+ data: { type: "FeatureCollection", features: normalizedFeatures },
13077
+ file,
13078
+ reprojected,
13079
+ sourceCRS: sourceCRS ?? void 0
13080
+ }) === true) {
13081
+ return;
13082
+ }
13083
+ const fileName = file.name.replace(/\.geojson$|\.json$/i, "");
13084
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
13085
+ const newLayer = {
13086
+ id: layerId,
13087
+ name: (layerMetadata == null ? void 0 : layerMetadata.name) || fileName,
13088
+ visible: true,
13089
+ featureIds: [],
13090
+ readOnly: true,
13091
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
13092
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
13093
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
13094
+ };
13095
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
13096
+ readOnlyFeatures.current.set(layerId, normalizedFeatures);
13097
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: fileHasTemporal });
13098
+ newLayer.featureIds = addedIds;
13099
+ setLayers((prev) => [...prev, newLayer]);
13100
+ updateFeatureCount();
13101
+ scheduleTimelineUpdate();
13102
+ scheduleSync();
13103
+ if (map.current && result.bbox) {
13104
+ const bbox = result.bbox;
13105
+ map.current.fitBounds(
13106
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
13107
+ { padding: 50, maxZoom: 16, duration: 1e3 }
13108
+ );
13109
+ }
13110
+ const reprojectMsg2 = reprojected ? ` (reprojected from ${sourceCRS})` : "";
13111
+ toast({
13112
+ title: "Layer created",
13113
+ description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg2} (high-performance mode)`
13114
+ });
13115
+ return;
13116
+ }
13117
+ const currentLayers = layersRef.current;
13118
+ let targetLayer = currentLayers.find((l) => l.id === requestedTargetLayerId && !l.readOnly);
13119
+ if (!targetLayer) {
13120
+ targetLayer = currentLayers.find((l) => l.visible && !l.readOnly);
13121
+ }
13122
+ if (!targetLayer) {
13123
+ targetLayer = currentLayers.find((l) => !l.readOnly);
13124
+ }
13125
+ if (targetLayer == null ? void 0 : targetLayer.visible) {
13126
+ const addedIds = [];
13127
+ isApiAddingRef.current = true;
13128
+ try {
13129
+ normalizedFeatures.forEach((f) => {
13130
+ const ids = draw.current.add(f);
13131
+ addedIds.push(ids[0]);
13132
+ });
13133
+ } finally {
13134
+ isApiAddingRef.current = false;
13135
+ }
13136
+ const targetId = targetLayer.id;
13137
+ setLayers((prev) => prev.map((l) => {
13138
+ if (l.id !== targetId) return l;
13139
+ return {
13140
+ ...l,
13141
+ featureIds: [...l.featureIds, ...addedIds],
13142
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
13143
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
13144
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
13145
+ };
13146
+ }));
13147
+ } else if (targetLayer) {
13148
+ const targetId = targetLayer.id;
13149
+ const addedIds = normalizedFeatures.map((f) => String(f.id));
13150
+ const existing = hiddenFeatures.current.get(targetId) || [];
13151
+ hiddenFeatures.current.set(targetId, [...existing, ...normalizedFeatures]);
13152
+ setLayers((prev) => prev.map((l) => {
13153
+ if (l.id !== targetId) return l;
13154
+ return {
13155
+ ...l,
13156
+ featureIds: [...l.featureIds, ...addedIds],
13157
+ ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
13158
+ ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
13159
+ ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig }
13160
+ };
13161
+ }));
13162
+ }
13163
+ updateFeatureCount();
13164
+ scheduleTimelineUpdate();
13165
+ scheduleSync();
13166
+ const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
13167
+ toast({
13168
+ title: "GeoJSON loaded",
13169
+ description: `Added ${normalizedFeatures.length} features${reprojectMsg}${!(targetLayer == null ? void 0 : targetLayer.visible) ? " (layer hidden)" : ""}`
13170
+ });
13171
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress]);
13172
+ const handleFileChange = react.useCallback((e) => {
12413
13173
  var _a;
13174
+ const file = (_a = e.target.files) == null ? void 0 : _a[0];
13175
+ if (!file) return;
13176
+ const requestedTargetLayerId = e.target.dataset.targetLayer || activeEditingLayerId;
13177
+ const createNewLayer = e.target.dataset.createNewLayer === "true";
13178
+ delete e.target.dataset.createNewLayer;
13179
+ e.target.value = "";
13180
+ void loadGeoJSONFile(file, requestedTargetLayerId, createNewLayer);
13181
+ }, [activeEditingLayerId, loadGeoJSONFile]);
13182
+ const ingestDroppedLayer = react.useCallback(async (name, input) => {
13183
+ if (!map.current) return;
13184
+ const layerId = `layer-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
13185
+ const startedAt = performance.now();
13186
+ let result;
13187
+ try {
13188
+ result = await ingestWithProgress(name, input, { idStrategy: "layer-index", layerId });
13189
+ } catch (error) {
13190
+ toast({
13191
+ title: "Failed to load GeoJSON",
13192
+ description: error instanceof Error ? error.message : "Invalid file",
13193
+ variant: "destructive"
13194
+ });
13195
+ return;
13196
+ }
12414
13197
  if (!map.current) return;
12415
- if (data["octostar:map"]) {
13198
+ if (result.kind === "error") {
13199
+ toast({
13200
+ title: "Failed to load GeoJSON",
13201
+ description: result.message,
13202
+ variant: "destructive"
13203
+ });
13204
+ return;
13205
+ }
13206
+ if (result.kind === "enriched") {
13207
+ const data = result.data;
12416
13208
  if (interceptGeoJSONFileLoad != null && interceptGeoJSONFileLoad({ kind: "enriched", data, sourceName: name }) === true) {
12417
13209
  return;
12418
13210
  }
12419
13211
  restoreEnrichedGeoJSON(data);
12420
13212
  return;
12421
13213
  }
12422
- const { features: reprojectedData, reprojected, sourceCRS } = detectAndReprojectGeoJSON(data);
13214
+ const { features: normalizedFeatures, reprojected, sourceCRS } = result;
13215
+ const layerMetadata = result.layerMetadata;
12423
13216
  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
13217
  const newLayer = {
12428
13218
  id: layerId,
12429
13219
  name: (layerMetadata == null ? void 0 : layerMetadata.name) || name,
@@ -12434,34 +13224,11 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12434
13224
  ...(layerMetadata == null ? void 0 : layerMetadata.traceConfig) && { traceConfig: layerMetadata.traceConfig },
12435
13225
  ...(layerMetadata == null ? void 0 : layerMetadata.heatmapConfig) && { heatmapConfig: layerMetadata.heatmapConfig },
12436
13226
  ...(layerMetadata == null ? void 0 : layerMetadata.visualConfig) && { visualConfig: layerMetadata.visualConfig },
12437
- ...layerHasAltitudeData && { hasAltitudeData: true, altitudeDisplayMode: "both" }
13227
+ ...result.hasAltitude && { hasAltitudeData: true, altitudeDisplayMode: "both" }
12438
13228
  };
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
- });
13229
+ const addedIds = normalizedFeatures.map((f) => f.id);
12463
13230
  readOnlyFeatures.current.set(layerId, normalizedFeatures);
12464
- layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: dropHasTemporal });
13231
+ layerTemporalCacheRef.current.set(layerId, { featureCount: normalizedFeatures.length, hasTemporal: result.hasTemporal });
12465
13232
  newLayer.featureIds = addedIds;
12466
13233
  const nextLayers = [...layersRef.current, newLayer];
12467
13234
  layersRef.current = nextLayers;
@@ -12469,28 +13236,35 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12469
13236
  updateFeatureCount();
12470
13237
  scheduleTimelineUpdate();
12471
13238
  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
- }
13239
+ if (result.bbox) {
13240
+ const bbox = result.bbox;
13241
+ map.current.fitBounds(
13242
+ [[bbox[0], bbox[1]], [bbox[2], bbox[3]]],
13243
+ { padding: 50, maxZoom: 16, duration: 1e3 }
13244
+ );
12483
13245
  }
13246
+ mapPerfLog("ingest", `dropped layer "${newLayer.name}" applied`, {
13247
+ features: addedIds.length,
13248
+ totalMs: Math.round(performance.now() - startedAt)
13249
+ });
12484
13250
  const reprojectMsg = reprojected ? ` (reprojected from ${sourceCRS})` : "";
12485
13251
  toast({
12486
13252
  title: "Layer added",
12487
13253
  description: `Created "${newLayer.name}" with ${addedIds.length} features${reprojectMsg} (high-performance)`
12488
13254
  });
12489
- }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad]);
13255
+ }, [saveStateForUndo, updateFeatureCount, scheduleTimelineUpdate, scheduleSync, restoreEnrichedGeoJSON, toast, interceptGeoJSONFileLoad, ingestWithProgress]);
13256
+ const handleDropGeoJSON = react.useCallback((name, data) => {
13257
+ void ingestDroppedLayer(name, data);
13258
+ }, [ingestDroppedLayer]);
13259
+ const handleDropGeoJSONFile = react.useCallback((name, file) => {
13260
+ void ingestDroppedLayer(name, file);
13261
+ }, [ingestDroppedLayer]);
12490
13262
  const handleTimelineFilterChange = react.useCallback((visibleIds, hiddenIds, untimedIds) => {
12491
13263
  if (!draw.current || !map.current) return;
12492
- timelineVisibleIdsRef.current = /* @__PURE__ */ new Set([...visibleIds, ...untimedIds]);
12493
- scheduleSync();
13264
+ const nextVisible = new Set(visibleIds);
13265
+ untimedIds.forEach((id) => nextVisible.add(id));
13266
+ timelineVisibleIdsRef.current = nextVisible;
13267
+ scheduleSync("timeline");
12494
13268
  }, [scheduleSync]);
12495
13269
  const prevTimelineEnabledRef = react.useRef(timelineStore.isEnabled);
12496
13270
  react.useEffect(() => {
@@ -12499,7 +13273,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12499
13273
  prevTimelineEnabledRef.current = isNowEnabled;
12500
13274
  if (!isNowEnabled || !timelineStore.hasTemporalData) {
12501
13275
  timelineVisibleIdsRef.current = null;
12502
- scheduleSync();
13276
+ scheduleSync("timeline");
12503
13277
  } else if (!wasEnabled && isNowEnabled) {
12504
13278
  updateTimelineStore();
12505
13279
  }
@@ -12874,7 +13648,7 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
12874
13648
  ] }) });
12875
13649
  }
12876
13650
  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: [
13651
+ 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
13652
  /* @__PURE__ */ jsxRuntime.jsx(
12879
13653
  "div",
12880
13654
  {
@@ -13353,16 +14127,12 @@ const MapEditorCanvas = react.forwardRef(function MapEditorCanvas2({
13353
14127
  ))
13354
14128
  }
13355
14129
  ),
13356
- cursorCoords && /* @__PURE__ */ jsxRuntime.jsxs(
13357
- "div",
14130
+ /* @__PURE__ */ jsxRuntime.jsx(CursorCoordinatesOverlay, { map: isMapLoaded ? map.current : null }),
14131
+ /* @__PURE__ */ jsxRuntime.jsx(
14132
+ IngestProgressOverlay,
13358
14133
  {
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
- ]
14134
+ store: ingestProgressStore,
14135
+ bottomPx: timelineStore.isEnabled ? TIMEBAR_HEIGHT + TIMEBAR_BOTTOM_OFFSET + 8 : 32
13366
14136
  }
13367
14137
  ),
13368
14138
  /* @__PURE__ */ jsxRuntime.jsx(
@@ -14128,7 +14898,15 @@ function DebugSidebar({ onAddRandomPoints, onImportKML, onAddDomMarkers, onRemov
14128
14898
  const geojson = parseKMLToGeoJSON(content);
14129
14899
  if (geojson && onImportKML) {
14130
14900
  const layerName = file.name.replace(/\.(kml|kmz)$/i, "");
14131
- onImportKML(layerName, geojson);
14901
+ void getSharedIngestClient().ingest(geojson, { idStrategy: "preserve" }).then((result) => {
14902
+ onImportKML(
14903
+ layerName,
14904
+ result.kind === "features" ? { type: "FeatureCollection", features: result.features } : geojson
14905
+ );
14906
+ }).catch((err) => {
14907
+ console.warn("[map-component] KML ingest normalization failed:", err);
14908
+ onImportKML(layerName, geojson);
14909
+ });
14132
14910
  }
14133
14911
  };
14134
14912
  reader.readAsText(file);